updated-packages

This commit is contained in:
RafficMohammed
2023-01-08 00:13:22 +05:30
parent 3ff7df7487
commit da241bacb6
12659 changed files with 563377 additions and 510538 deletions

View File

@@ -0,0 +1,161 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Reader;
use PhpOffice\PhpSpreadsheet\Reader\Exception as ReaderException;
use PhpOffice\PhpSpreadsheet\Reader\Security\XmlScanner;
use PhpOffice\PhpSpreadsheet\Shared\File;
abstract class BaseReader implements IReader
{
/**
* Read data only?
* Identifies whether the Reader should only read data values for cells, and ignore any formatting information;
* or whether it should read both data and formatting.
*
* @var bool
*/
protected $readDataOnly = false;
/**
* Read empty cells?
* Identifies whether the Reader should read data values for cells all cells, or should ignore cells containing
* null value or empty string.
*
* @var bool
*/
protected $readEmptyCells = true;
/**
* Read charts that are defined in the workbook?
* Identifies whether the Reader should read the definitions for any charts that exist in the workbook;.
*
* @var bool
*/
protected $includeCharts = false;
/**
* Restrict which sheets should be loaded?
* This property holds an array of worksheet names to be loaded. If null, then all worksheets will be loaded.
*
* @var array of string
*/
protected $loadSheetsOnly;
/**
* IReadFilter instance.
*
* @var IReadFilter
*/
protected $readFilter;
protected $fileHandle;
/**
* @var XmlScanner
*/
protected $securityScanner;
public function __construct()
{
$this->readFilter = new DefaultReadFilter();
}
public function getReadDataOnly()
{
return $this->readDataOnly;
}
public function setReadDataOnly($pValue)
{
$this->readDataOnly = (bool) $pValue;
return $this;
}
public function getReadEmptyCells()
{
return $this->readEmptyCells;
}
public function setReadEmptyCells($pValue)
{
$this->readEmptyCells = (bool) $pValue;
return $this;
}
public function getIncludeCharts()
{
return $this->includeCharts;
}
public function setIncludeCharts($pValue)
{
$this->includeCharts = (bool) $pValue;
return $this;
}
public function getLoadSheetsOnly()
{
return $this->loadSheetsOnly;
}
public function setLoadSheetsOnly($value)
{
if ($value === null) {
return $this->setLoadAllSheets();
}
$this->loadSheetsOnly = is_array($value) ? $value : [$value];
return $this;
}
public function setLoadAllSheets()
{
$this->loadSheetsOnly = null;
return $this;
}
public function getReadFilter()
{
return $this->readFilter;
}
public function setReadFilter(IReadFilter $pValue)
{
$this->readFilter = $pValue;
return $this;
}
public function getSecurityScanner()
{
return $this->securityScanner;
}
/**
* Open file for reading.
*
* @param string $pFilename
*/
protected function openFile($pFilename): void
{
if ($pFilename) {
File::assertFile($pFilename);
// Open file
$fileHandle = fopen($pFilename, 'rb');
} else {
$fileHandle = false;
}
if ($fileHandle !== false) {
$this->fileHandle = $fileHandle;
} else {
throw new ReaderException('Could not open file ' . $pFilename . ' for reading.');
}
}
}

View File

@@ -0,0 +1,606 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Reader;
use InvalidArgumentException;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
class Csv extends BaseReader
{
const UTF8_BOM = "\xEF\xBB\xBF";
const UTF8_BOM_LEN = 3;
const UTF16BE_BOM = "\xfe\xff";
const UTF16BE_BOM_LEN = 2;
const UTF16BE_LF = "\x00\x0a";
const UTF16LE_BOM = "\xff\xfe";
const UTF16LE_BOM_LEN = 2;
const UTF16LE_LF = "\x0a\x00";
const UTF32BE_BOM = "\x00\x00\xfe\xff";
const UTF32BE_BOM_LEN = 4;
const UTF32BE_LF = "\x00\x00\x00\x0a";
const UTF32LE_BOM = "\xff\xfe\x00\x00";
const UTF32LE_BOM_LEN = 4;
const UTF32LE_LF = "\x0a\x00\x00\x00";
/**
* Input encoding.
*
* @var string
*/
private $inputEncoding = 'UTF-8';
/**
* Delimiter.
*
* @var string
*/
private $delimiter;
/**
* Enclosure.
*
* @var string
*/
private $enclosure = '"';
/**
* Sheet index to read.
*
* @var int
*/
private $sheetIndex = 0;
/**
* Load rows contiguously.
*
* @var bool
*/
private $contiguous = false;
/**
* The character that can escape the enclosure.
*
* @var string
*/
private $escapeCharacter = '\\';
/**
* Create a new CSV Reader instance.
*/
public function __construct()
{
parent::__construct();
}
/**
* Set input encoding.
*
* @param string $pValue Input encoding, eg: 'UTF-8'
*
* @return $this
*/
public function setInputEncoding($pValue)
{
$this->inputEncoding = $pValue;
return $this;
}
/**
* Get input encoding.
*
* @return string
*/
public function getInputEncoding()
{
return $this->inputEncoding;
}
/**
* Move filepointer past any BOM marker.
*/
protected function skipBOM(): void
{
rewind($this->fileHandle);
if (fgets($this->fileHandle, self::UTF8_BOM_LEN + 1) !== self::UTF8_BOM) {
rewind($this->fileHandle);
}
}
/**
* Identify any separator that is explicitly set in the file.
*/
protected function checkSeparator(): void
{
$line = fgets($this->fileHandle);
if ($line === false) {
return;
}
if ((strlen(trim($line, "\r\n")) == 5) && (stripos($line, 'sep=') === 0)) {
$this->delimiter = substr($line, 4, 1);
return;
}
$this->skipBOM();
}
/**
* Infer the separator if it isn't explicitly set in the file or specified by the user.
*/
protected function inferSeparator(): void
{
if ($this->delimiter !== null) {
return;
}
$potentialDelimiters = [',', ';', "\t", '|', ':', ' ', '~'];
$counts = [];
foreach ($potentialDelimiters as $delimiter) {
$counts[$delimiter] = [];
}
// Count how many times each of the potential delimiters appears in each line
$numberLines = 0;
while (($line = $this->getNextLine()) !== false && (++$numberLines < 1000)) {
$countLine = [];
for ($i = strlen($line) - 1; $i >= 0; --$i) {
$char = $line[$i];
if (isset($counts[$char])) {
if (!isset($countLine[$char])) {
$countLine[$char] = 0;
}
++$countLine[$char];
}
}
foreach ($potentialDelimiters as $delimiter) {
$counts[$delimiter][] = $countLine[$delimiter]
?? 0;
}
}
// If number of lines is 0, nothing to infer : fall back to the default
if ($numberLines === 0) {
$this->delimiter = reset($potentialDelimiters);
$this->skipBOM();
return;
}
// Calculate the mean square deviations for each delimiter (ignoring delimiters that haven't been found consistently)
$meanSquareDeviations = [];
$middleIdx = floor(($numberLines - 1) / 2);
foreach ($potentialDelimiters as $delimiter) {
$series = $counts[$delimiter];
sort($series);
$median = ($numberLines % 2)
? $series[$middleIdx]
: ($series[$middleIdx] + $series[$middleIdx + 1]) / 2;
if ($median === 0) {
continue;
}
$meanSquareDeviations[$delimiter] = array_reduce(
$series,
function ($sum, $value) use ($median) {
return $sum + ($value - $median) ** 2;
}
) / count($series);
}
// ... and pick the delimiter with the smallest mean square deviation (in case of ties, the order in potentialDelimiters is respected)
$min = INF;
foreach ($potentialDelimiters as $delimiter) {
if (!isset($meanSquareDeviations[$delimiter])) {
continue;
}
if ($meanSquareDeviations[$delimiter] < $min) {
$min = $meanSquareDeviations[$delimiter];
$this->delimiter = $delimiter;
}
}
// If no delimiter could be detected, fall back to the default
if ($this->delimiter === null) {
$this->delimiter = reset($potentialDelimiters);
}
$this->skipBOM();
}
/**
* Get the next full line from the file.
*
* @return false|string
*/
private function getNextLine()
{
$line = '';
$enclosure = ($this->escapeCharacter === '' ? ''
: ('(?<!' . preg_quote($this->escapeCharacter, '/') . ')'))
. preg_quote($this->enclosure, '/');
do {
// Get the next line in the file
$newLine = fgets($this->fileHandle);
// Return false if there is no next line
if ($newLine === false) {
return false;
}
// Add the new line to the line passed in
$line = $line . $newLine;
// Drop everything that is enclosed to avoid counting false positives in enclosures
$line = preg_replace('/(' . $enclosure . '.*' . $enclosure . ')/Us', '', $line);
// See if we have any enclosures left in the line
// if we still have an enclosure then we need to read the next line as well
} while (preg_match('/(' . $enclosure . ')/', $line) > 0);
return $line;
}
/**
* Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns).
*
* @param string $pFilename
*
* @return array
*/
public function listWorksheetInfo($pFilename)
{
// Open file
$this->openFileOrMemory($pFilename);
$fileHandle = $this->fileHandle;
// Skip BOM, if any
$this->skipBOM();
$this->checkSeparator();
$this->inferSeparator();
$worksheetInfo = [];
$worksheetInfo[0]['worksheetName'] = 'Worksheet';
$worksheetInfo[0]['lastColumnLetter'] = 'A';
$worksheetInfo[0]['lastColumnIndex'] = 0;
$worksheetInfo[0]['totalRows'] = 0;
$worksheetInfo[0]['totalColumns'] = 0;
// Loop through each line of the file in turn
while (($rowData = fgetcsv($fileHandle, 0, $this->delimiter, $this->enclosure, $this->escapeCharacter)) !== false) {
++$worksheetInfo[0]['totalRows'];
$worksheetInfo[0]['lastColumnIndex'] = max($worksheetInfo[0]['lastColumnIndex'], count($rowData) - 1);
}
$worksheetInfo[0]['lastColumnLetter'] = Coordinate::stringFromColumnIndex($worksheetInfo[0]['lastColumnIndex'] + 1);
$worksheetInfo[0]['totalColumns'] = $worksheetInfo[0]['lastColumnIndex'] + 1;
// Close file
fclose($fileHandle);
return $worksheetInfo;
}
/**
* Loads Spreadsheet from file.
*
* @param string $pFilename
*
* @return Spreadsheet
*/
public function load($pFilename)
{
// Create new Spreadsheet
$spreadsheet = new Spreadsheet();
// Load into this instance
return $this->loadIntoExisting($pFilename, $spreadsheet);
}
private function openFileOrMemory($pFilename): void
{
// Open file
$fhandle = $this->canRead($pFilename);
if (!$fhandle) {
throw new Exception($pFilename . ' is an Invalid Spreadsheet file.');
}
$this->openFile($pFilename);
if ($this->inputEncoding !== 'UTF-8') {
fclose($this->fileHandle);
$entireFile = file_get_contents($pFilename);
$this->fileHandle = fopen('php://memory', 'r+b');
$data = StringHelper::convertEncoding($entireFile, 'UTF-8', $this->inputEncoding);
fwrite($this->fileHandle, $data);
$this->skipBOM();
}
}
/**
* Loads PhpSpreadsheet from file into PhpSpreadsheet instance.
*
* @param string $pFilename
*
* @return Spreadsheet
*/
public function loadIntoExisting($pFilename, Spreadsheet $spreadsheet)
{
$lineEnding = ini_get('auto_detect_line_endings');
ini_set('auto_detect_line_endings', true);
// Open file
$this->openFileOrMemory($pFilename);
$fileHandle = $this->fileHandle;
// Skip BOM, if any
$this->skipBOM();
$this->checkSeparator();
$this->inferSeparator();
// Create new PhpSpreadsheet object
while ($spreadsheet->getSheetCount() <= $this->sheetIndex) {
$spreadsheet->createSheet();
}
$sheet = $spreadsheet->setActiveSheetIndex($this->sheetIndex);
// Set our starting row based on whether we're in contiguous mode or not
$currentRow = 1;
$outRow = 0;
// Loop through each line of the file in turn
while (($rowData = fgetcsv($fileHandle, 0, $this->delimiter, $this->enclosure, $this->escapeCharacter)) !== false) {
$noOutputYet = true;
$columnLetter = 'A';
foreach ($rowData as $rowDatum) {
if ($rowDatum != '' && $this->readFilter->readCell($columnLetter, $currentRow)) {
if ($this->contiguous) {
if ($noOutputYet) {
$noOutputYet = false;
++$outRow;
}
} else {
$outRow = $currentRow;
}
// Set cell value
$sheet->getCell($columnLetter . $outRow)->setValue($rowDatum);
}
++$columnLetter;
}
++$currentRow;
}
// Close file
fclose($fileHandle);
ini_set('auto_detect_line_endings', $lineEnding);
// Return
return $spreadsheet;
}
/**
* Get delimiter.
*
* @return string
*/
public function getDelimiter()
{
return $this->delimiter;
}
/**
* Set delimiter.
*
* @param string $delimiter Delimiter, eg: ','
*
* @return $this
*/
public function setDelimiter($delimiter)
{
$this->delimiter = $delimiter;
return $this;
}
/**
* Get enclosure.
*
* @return string
*/
public function getEnclosure()
{
return $this->enclosure;
}
/**
* Set enclosure.
*
* @param string $enclosure Enclosure, defaults to "
*
* @return $this
*/
public function setEnclosure($enclosure)
{
if ($enclosure == '') {
$enclosure = '"';
}
$this->enclosure = $enclosure;
return $this;
}
/**
* Get sheet index.
*
* @return int
*/
public function getSheetIndex()
{
return $this->sheetIndex;
}
/**
* Set sheet index.
*
* @param int $pValue Sheet index
*
* @return $this
*/
public function setSheetIndex($pValue)
{
$this->sheetIndex = $pValue;
return $this;
}
/**
* Set Contiguous.
*
* @param bool $contiguous
*
* @return $this
*/
public function setContiguous($contiguous)
{
$this->contiguous = (bool) $contiguous;
return $this;
}
/**
* Get Contiguous.
*
* @return bool
*/
public function getContiguous()
{
return $this->contiguous;
}
/**
* Set escape backslashes.
*
* @param string $escapeCharacter
*
* @return $this
*/
public function setEscapeCharacter($escapeCharacter)
{
$this->escapeCharacter = $escapeCharacter;
return $this;
}
/**
* Get escape backslashes.
*
* @return string
*/
public function getEscapeCharacter()
{
return $this->escapeCharacter;
}
/**
* Can the current IReader read the file?
*
* @param string $pFilename
*
* @return bool
*/
public function canRead($pFilename)
{
// Check if file exists
try {
$this->openFile($pFilename);
} catch (InvalidArgumentException $e) {
return false;
}
fclose($this->fileHandle);
// Trust file extension if any
$extension = strtolower(pathinfo($pFilename, PATHINFO_EXTENSION));
if (in_array($extension, ['csv', 'tsv'])) {
return true;
}
// Attempt to guess mimetype
$type = mime_content_type($pFilename);
$supportedTypes = [
'application/csv',
'text/csv',
'text/plain',
'inode/x-empty',
];
return in_array($type, $supportedTypes, true);
}
private static function guessEncodingTestNoBom(string &$encoding, string &$contents, string $compare, string $setEncoding): void
{
if ($encoding === '') {
$pos = strpos($contents, $compare);
if ($pos !== false && $pos % strlen($compare) === 0) {
$encoding = $setEncoding;
}
}
}
private static function guessEncodingNoBom(string $filename): string
{
$encoding = '';
$contents = file_get_contents($filename);
self::guessEncodingTestNoBom($encoding, $contents, self::UTF32BE_LF, 'UTF-32BE');
self::guessEncodingTestNoBom($encoding, $contents, self::UTF32LE_LF, 'UTF-32LE');
self::guessEncodingTestNoBom($encoding, $contents, self::UTF16BE_LF, 'UTF-16BE');
self::guessEncodingTestNoBom($encoding, $contents, self::UTF16LE_LF, 'UTF-16LE');
if ($encoding === '' && preg_match('//u', $contents) === 1) {
$encoding = 'UTF-8';
}
return $encoding;
}
private static function guessEncodingTestBom(string &$encoding, string $first4, string $compare, string $setEncoding): void
{
if ($encoding === '') {
if ($compare === substr($first4, 0, strlen($compare))) {
$encoding = $setEncoding;
}
}
}
private static function guessEncodingBom(string $filename): string
{
$encoding = '';
$first4 = file_get_contents($filename, false, null, 0, 4);
if ($first4 !== false) {
self::guessEncodingTestBom($encoding, $first4, self::UTF8_BOM, 'UTF-8');
self::guessEncodingTestBom($encoding, $first4, self::UTF16BE_BOM, 'UTF-16BE');
self::guessEncodingTestBom($encoding, $first4, self::UTF32BE_BOM, 'UTF-32BE');
self::guessEncodingTestBom($encoding, $first4, self::UTF32LE_BOM, 'UTF-32LE');
self::guessEncodingTestBom($encoding, $first4, self::UTF16LE_BOM, 'UTF-16LE');
}
return $encoding;
}
public static function guessEncoding(string $filename, string $dflt = 'CP1252'): string
{
$encoding = self::guessEncodingBom($filename);
if ($encoding === '') {
$encoding = self::guessEncodingNoBom($filename);
}
return ($encoding === '') ? $dflt : $encoding;
}
}

View File

@@ -0,0 +1,20 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Reader;
class DefaultReadFilter implements IReadFilter
{
/**
* Should this cell be read?
*
* @param string $column Column address (as a string value like "A", or "IV")
* @param int $row Row number
* @param string $worksheetName Optional worksheet name
*
* @return bool
*/
public function readCell($column, $row, $worksheetName = '')
{
return true;
}
}

View File

@@ -0,0 +1,9 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Reader;
use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException;
class Exception extends PhpSpreadsheetException
{
}

View File

@@ -0,0 +1,831 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Reader;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\DefinedName;
use PhpOffice\PhpSpreadsheet\Reader\Gnumeric\PageSetup;
use PhpOffice\PhpSpreadsheet\Reader\Security\XmlScanner;
use PhpOffice\PhpSpreadsheet\ReferenceHelper;
use PhpOffice\PhpSpreadsheet\RichText\RichText;
use PhpOffice\PhpSpreadsheet\Settings;
use PhpOffice\PhpSpreadsheet\Shared\Date;
use PhpOffice\PhpSpreadsheet\Shared\File;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\Borders;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Style\Font;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use SimpleXMLElement;
use XMLReader;
class Gnumeric extends BaseReader
{
private const UOM_CONVERSION_POINTS_TO_CENTIMETERS = 0.03527777778;
/**
* Shared Expressions.
*
* @var array
*/
private $expressions = [];
/**
* Spreadsheet shared across all functions.
*
* @var Spreadsheet
*/
private $spreadsheet;
private $referenceHelper;
/**
* Namespace shared across all functions.
* It is 'gnm', except for really old sheets which use 'gmr'.
*
* @var string
*/
private $gnm = 'gnm';
/**
* Create a new Gnumeric.
*/
public function __construct()
{
parent::__construct();
$this->referenceHelper = ReferenceHelper::getInstance();
$this->securityScanner = XmlScanner::getInstance($this);
}
/**
* Can the current IReader read the file?
*
* @param string $pFilename
*
* @return bool
*/
public function canRead($pFilename)
{
File::assertFile($pFilename);
// Check if gzlib functions are available
$data = '';
if (function_exists('gzread')) {
// Read signature data (first 3 bytes)
$fh = fopen($pFilename, 'rb');
$data = fread($fh, 2);
fclose($fh);
}
return $data == chr(0x1F) . chr(0x8B);
}
private static function matchXml(string $name, string $field): bool
{
return 1 === preg_match("/^(gnm|gmr):$field$/", $name);
}
/**
* Reads names of the worksheets from a file, without parsing the whole file to a Spreadsheet object.
*
* @param string $pFilename
*
* @return array
*/
public function listWorksheetNames($pFilename)
{
File::assertFile($pFilename);
$xml = new XMLReader();
$xml->xml($this->securityScanner->scanFile('compress.zlib://' . realpath($pFilename)), null, Settings::getLibXmlLoaderOptions());
$xml->setParserProperty(2, true);
$worksheetNames = [];
while ($xml->read()) {
if (self::matchXml($xml->name, 'SheetName') && $xml->nodeType == XMLReader::ELEMENT) {
$xml->read(); // Move onto the value node
$worksheetNames[] = (string) $xml->value;
} elseif (self::matchXml($xml->name, 'Sheets')) {
// break out of the loop once we've got our sheet names rather than parse the entire file
break;
}
}
return $worksheetNames;
}
/**
* Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns).
*
* @param string $pFilename
*
* @return array
*/
public function listWorksheetInfo($pFilename)
{
File::assertFile($pFilename);
$xml = new XMLReader();
$xml->xml($this->securityScanner->scanFile('compress.zlib://' . realpath($pFilename)), null, Settings::getLibXmlLoaderOptions());
$xml->setParserProperty(2, true);
$worksheetInfo = [];
while ($xml->read()) {
if (self::matchXml($xml->name, 'Sheet') && $xml->nodeType == XMLReader::ELEMENT) {
$tmpInfo = [
'worksheetName' => '',
'lastColumnLetter' => 'A',
'lastColumnIndex' => 0,
'totalRows' => 0,
'totalColumns' => 0,
];
while ($xml->read()) {
if ($xml->nodeType == XMLReader::ELEMENT) {
if (self::matchXml($xml->name, 'Name')) {
$xml->read(); // Move onto the value node
$tmpInfo['worksheetName'] = (string) $xml->value;
} elseif (self::matchXml($xml->name, 'MaxCol')) {
$xml->read(); // Move onto the value node
$tmpInfo['lastColumnIndex'] = (int) $xml->value;
$tmpInfo['totalColumns'] = (int) $xml->value + 1;
} elseif (self::matchXml($xml->name, 'MaxRow')) {
$xml->read(); // Move onto the value node
$tmpInfo['totalRows'] = (int) $xml->value + 1;
break;
}
}
}
$tmpInfo['lastColumnLetter'] = Coordinate::stringFromColumnIndex($tmpInfo['lastColumnIndex'] + 1);
$worksheetInfo[] = $tmpInfo;
}
}
return $worksheetInfo;
}
/**
* @param string $filename
*
* @return string
*/
private function gzfileGetContents($filename)
{
$file = @gzopen($filename, 'rb');
$data = '';
if ($file !== false) {
while (!gzeof($file)) {
$data .= gzread($file, 1024);
}
gzclose($file);
}
return $data;
}
private static $mappings = [
'borderStyle' => [
'0' => Border::BORDER_NONE,
'1' => Border::BORDER_THIN,
'2' => Border::BORDER_MEDIUM,
'3' => Border::BORDER_SLANTDASHDOT,
'4' => Border::BORDER_DASHED,
'5' => Border::BORDER_THICK,
'6' => Border::BORDER_DOUBLE,
'7' => Border::BORDER_DOTTED,
'8' => Border::BORDER_MEDIUMDASHED,
'9' => Border::BORDER_DASHDOT,
'10' => Border::BORDER_MEDIUMDASHDOT,
'11' => Border::BORDER_DASHDOTDOT,
'12' => Border::BORDER_MEDIUMDASHDOTDOT,
'13' => Border::BORDER_MEDIUMDASHDOTDOT,
],
'dataType' => [
'10' => DataType::TYPE_NULL,
'20' => DataType::TYPE_BOOL,
'30' => DataType::TYPE_NUMERIC, // Integer doesn't exist in Excel
'40' => DataType::TYPE_NUMERIC, // Float
'50' => DataType::TYPE_ERROR,
'60' => DataType::TYPE_STRING,
//'70': // Cell Range
//'80': // Array
],
'fillType' => [
'1' => Fill::FILL_SOLID,
'2' => Fill::FILL_PATTERN_DARKGRAY,
'3' => Fill::FILL_PATTERN_MEDIUMGRAY,
'4' => Fill::FILL_PATTERN_LIGHTGRAY,
'5' => Fill::FILL_PATTERN_GRAY125,
'6' => Fill::FILL_PATTERN_GRAY0625,
'7' => Fill::FILL_PATTERN_DARKHORIZONTAL, // horizontal stripe
'8' => Fill::FILL_PATTERN_DARKVERTICAL, // vertical stripe
'9' => Fill::FILL_PATTERN_DARKDOWN, // diagonal stripe
'10' => Fill::FILL_PATTERN_DARKUP, // reverse diagonal stripe
'11' => Fill::FILL_PATTERN_DARKGRID, // diagoanl crosshatch
'12' => Fill::FILL_PATTERN_DARKTRELLIS, // thick diagonal crosshatch
'13' => Fill::FILL_PATTERN_LIGHTHORIZONTAL,
'14' => Fill::FILL_PATTERN_LIGHTVERTICAL,
'15' => Fill::FILL_PATTERN_LIGHTUP,
'16' => Fill::FILL_PATTERN_LIGHTDOWN,
'17' => Fill::FILL_PATTERN_LIGHTGRID, // thin horizontal crosshatch
'18' => Fill::FILL_PATTERN_LIGHTTRELLIS, // thin diagonal crosshatch
],
'horizontal' => [
'1' => Alignment::HORIZONTAL_GENERAL,
'2' => Alignment::HORIZONTAL_LEFT,
'4' => Alignment::HORIZONTAL_RIGHT,
'8' => Alignment::HORIZONTAL_CENTER,
'16' => Alignment::HORIZONTAL_CENTER_CONTINUOUS,
'32' => Alignment::HORIZONTAL_JUSTIFY,
'64' => Alignment::HORIZONTAL_CENTER_CONTINUOUS,
],
'underline' => [
'1' => Font::UNDERLINE_SINGLE,
'2' => Font::UNDERLINE_DOUBLE,
'3' => Font::UNDERLINE_SINGLEACCOUNTING,
'4' => Font::UNDERLINE_DOUBLEACCOUNTING,
],
'vertical' => [
'1' => Alignment::VERTICAL_TOP,
'2' => Alignment::VERTICAL_BOTTOM,
'4' => Alignment::VERTICAL_CENTER,
'8' => Alignment::VERTICAL_JUSTIFY,
],
];
public static function gnumericMappings(): array
{
return self::$mappings;
}
private function docPropertiesOld(SimpleXMLElement $gnmXML): void
{
$docProps = $this->spreadsheet->getProperties();
foreach ($gnmXML->Summary->Item as $summaryItem) {
$propertyName = $summaryItem->name;
$propertyValue = $summaryItem->{'val-string'};
switch ($propertyName) {
case 'title':
$docProps->setTitle(trim($propertyValue));
break;
case 'comments':
$docProps->setDescription(trim($propertyValue));
break;
case 'keywords':
$docProps->setKeywords(trim($propertyValue));
break;
case 'category':
$docProps->setCategory(trim($propertyValue));
break;
case 'manager':
$docProps->setManager(trim($propertyValue));
break;
case 'author':
$docProps->setCreator(trim($propertyValue));
$docProps->setLastModifiedBy(trim($propertyValue));
break;
case 'company':
$docProps->setCompany(trim($propertyValue));
break;
}
}
}
private function docPropertiesDC(SimpleXMLElement $officePropertyDC): void
{
$docProps = $this->spreadsheet->getProperties();
foreach ($officePropertyDC as $propertyName => $propertyValue) {
$propertyValue = trim((string) $propertyValue);
switch ($propertyName) {
case 'title':
$docProps->setTitle($propertyValue);
break;
case 'subject':
$docProps->setSubject($propertyValue);
break;
case 'creator':
$docProps->setCreator($propertyValue);
$docProps->setLastModifiedBy($propertyValue);
break;
case 'date':
$creationDate = strtotime($propertyValue);
$docProps->setCreated($creationDate);
$docProps->setModified($creationDate);
break;
case 'description':
$docProps->setDescription($propertyValue);
break;
}
}
}
private function docPropertiesMeta(SimpleXMLElement $officePropertyMeta, array $namespacesMeta): void
{
$docProps = $this->spreadsheet->getProperties();
foreach ($officePropertyMeta as $propertyName => $propertyValue) {
$attributes = $propertyValue->attributes($namespacesMeta['meta']);
$propertyValue = trim((string) $propertyValue);
switch ($propertyName) {
case 'keyword':
$docProps->setKeywords($propertyValue);
break;
case 'initial-creator':
$docProps->setCreator($propertyValue);
$docProps->setLastModifiedBy($propertyValue);
break;
case 'creation-date':
$creationDate = strtotime($propertyValue);
$docProps->setCreated($creationDate);
$docProps->setModified($creationDate);
break;
case 'user-defined':
[, $attrName] = explode(':', $attributes['name']);
switch ($attrName) {
case 'publisher':
$docProps->setCompany($propertyValue);
break;
case 'category':
$docProps->setCategory($propertyValue);
break;
case 'manager':
$docProps->setManager($propertyValue);
break;
}
break;
}
}
}
private function docProperties(SimpleXMLElement $xml, SimpleXMLElement $gnmXML, array $namespacesMeta): void
{
if (isset($namespacesMeta['office'])) {
$officeXML = $xml->children($namespacesMeta['office']);
$officeDocXML = $officeXML->{'document-meta'};
$officeDocMetaXML = $officeDocXML->meta;
foreach ($officeDocMetaXML as $officePropertyData) {
$officePropertyDC = [];
if (isset($namespacesMeta['dc'])) {
$officePropertyDC = $officePropertyData->children($namespacesMeta['dc']);
}
$this->docPropertiesDC($officePropertyDC);
$officePropertyMeta = [];
if (isset($namespacesMeta['meta'])) {
$officePropertyMeta = $officePropertyData->children($namespacesMeta['meta']);
}
$this->docPropertiesMeta($officePropertyMeta, $namespacesMeta);
}
} elseif (isset($gnmXML->Summary)) {
$this->docPropertiesOld($gnmXML);
}
}
private function processComments(SimpleXMLElement $sheet): void
{
if ((!$this->readDataOnly) && (isset($sheet->Objects))) {
foreach ($sheet->Objects->children($this->gnm, true) as $key => $comment) {
$commentAttributes = $comment->attributes();
// Only comment objects are handled at the moment
if ($commentAttributes->Text) {
$this->spreadsheet->getActiveSheet()->getComment((string) $commentAttributes->ObjectBound)->setAuthor((string) $commentAttributes->Author)->setText($this->parseRichText((string) $commentAttributes->Text));
}
}
}
}
/**
* Loads Spreadsheet from file.
*
* @param string $pFilename
*
* @return Spreadsheet
*/
public function load($pFilename)
{
// Create new Spreadsheet
$spreadsheet = new Spreadsheet();
$spreadsheet->removeSheetByIndex(0);
// Load into this instance
return $this->loadIntoExisting($pFilename, $spreadsheet);
}
/**
* Loads from file into Spreadsheet instance.
*/
public function loadIntoExisting(string $pFilename, Spreadsheet $spreadsheet): Spreadsheet
{
$this->spreadsheet = $spreadsheet;
File::assertFile($pFilename);
$gFileData = $this->gzfileGetContents($pFilename);
$xml2 = simplexml_load_string($this->securityScanner->scan($gFileData), 'SimpleXMLElement', Settings::getLibXmlLoaderOptions());
$xml = ($xml2 !== false) ? $xml2 : new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><root></root>');
$namespacesMeta = $xml->getNamespaces(true);
$this->gnm = array_key_exists('gmr', $namespacesMeta) ? 'gmr' : 'gnm';
$gnmXML = $xml->children($namespacesMeta[$this->gnm]);
$this->docProperties($xml, $gnmXML, $namespacesMeta);
$worksheetID = 0;
foreach ($gnmXML->Sheets->Sheet as $sheet) {
$worksheetName = (string) $sheet->Name;
if ((isset($this->loadSheetsOnly)) && (!in_array($worksheetName, $this->loadSheetsOnly))) {
continue;
}
$maxRow = $maxCol = 0;
// Create new Worksheet
$this->spreadsheet->createSheet();
$this->spreadsheet->setActiveSheetIndex($worksheetID);
// 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
$this->spreadsheet->getActiveSheet()->setTitle($worksheetName, false, false);
if (!$this->readDataOnly) {
(new PageSetup($this->spreadsheet, $this->gnm))
->printInformation($sheet)
->sheetMargins($sheet);
}
foreach ($sheet->Cells->Cell as $cell) {
$cellAttributes = $cell->attributes();
$row = (int) $cellAttributes->Row + 1;
$column = (int) $cellAttributes->Col;
if ($row > $maxRow) {
$maxRow = $row;
}
if ($column > $maxCol) {
$maxCol = $column;
}
$column = Coordinate::stringFromColumnIndex($column + 1);
// Read cell?
if ($this->getReadFilter() !== null) {
if (!$this->getReadFilter()->readCell($column, $row, $worksheetName)) {
continue;
}
}
$ValueType = $cellAttributes->ValueType;
$ExprID = (string) $cellAttributes->ExprID;
$type = DataType::TYPE_FORMULA;
if ($ExprID > '') {
if (((string) $cell) > '') {
$this->expressions[$ExprID] = [
'column' => $cellAttributes->Col,
'row' => $cellAttributes->Row,
'formula' => (string) $cell,
];
} else {
$expression = $this->expressions[$ExprID];
$cell = $this->referenceHelper->updateFormulaReferences(
$expression['formula'],
'A1',
$cellAttributes->Col - $expression['column'],
$cellAttributes->Row - $expression['row'],
$worksheetName
);
}
$type = DataType::TYPE_FORMULA;
} else {
$vtype = (string) $ValueType;
if (array_key_exists($vtype, self::$mappings['dataType'])) {
$type = self::$mappings['dataType'][$vtype];
}
if ($vtype == '20') { // Boolean
$cell = $cell == 'TRUE';
}
}
$this->spreadsheet->getActiveSheet()->getCell($column . $row)->setValueExplicit((string) $cell, $type);
}
$this->processComments($sheet);
foreach ($sheet->Styles->StyleRegion as $styleRegion) {
$styleAttributes = $styleRegion->attributes();
if (
($styleAttributes['startRow'] <= $maxRow) &&
($styleAttributes['startCol'] <= $maxCol)
) {
$startColumn = Coordinate::stringFromColumnIndex((int) $styleAttributes['startCol'] + 1);
$startRow = $styleAttributes['startRow'] + 1;
$endColumn = ($styleAttributes['endCol'] > $maxCol) ? $maxCol : (int) $styleAttributes['endCol'];
$endColumn = Coordinate::stringFromColumnIndex($endColumn + 1);
$endRow = 1 + (($styleAttributes['endRow'] > $maxRow) ? $maxRow : (int) $styleAttributes['endRow']);
$cellRange = $startColumn . $startRow . ':' . $endColumn . $endRow;
$styleAttributes = $styleRegion->Style->attributes();
$styleArray = [];
// We still set the number format mask for date/time values, even if readDataOnly is true
$formatCode = (string) $styleAttributes['Format'];
if (Date::isDateTimeFormatCode($formatCode)) {
$styleArray['numberFormat']['formatCode'] = $formatCode;
}
if (!$this->readDataOnly) {
// If readDataOnly is false, we set all formatting information
$styleArray['numberFormat']['formatCode'] = $formatCode;
self::addStyle2($styleArray, 'alignment', 'horizontal', $styleAttributes['HAlign']);
self::addStyle2($styleArray, 'alignment', 'vertical', $styleAttributes['VAlign']);
$styleArray['alignment']['wrapText'] = $styleAttributes['WrapText'] == '1';
$styleArray['alignment']['textRotation'] = $this->calcRotation($styleAttributes);
$styleArray['alignment']['shrinkToFit'] = $styleAttributes['ShrinkToFit'] == '1';
$styleArray['alignment']['indent'] = ((int) ($styleAttributes['Indent']) > 0) ? $styleAttributes['indent'] : 0;
$this->addColors($styleArray, $styleAttributes);
$fontAttributes = $styleRegion->Style->Font->attributes();
$styleArray['font']['name'] = (string) $styleRegion->Style->Font;
$styleArray['font']['size'] = (int) ($fontAttributes['Unit']);
$styleArray['font']['bold'] = $fontAttributes['Bold'] == '1';
$styleArray['font']['italic'] = $fontAttributes['Italic'] == '1';
$styleArray['font']['strikethrough'] = $fontAttributes['StrikeThrough'] == '1';
self::addStyle2($styleArray, 'font', 'underline', $fontAttributes['Underline']);
switch ($fontAttributes['Script']) {
case '1':
$styleArray['font']['superscript'] = true;
break;
case '-1':
$styleArray['font']['subscript'] = true;
break;
}
if (isset($styleRegion->Style->StyleBorder)) {
$srssb = $styleRegion->Style->StyleBorder;
$this->addBorderStyle($srssb, $styleArray, 'top');
$this->addBorderStyle($srssb, $styleArray, 'bottom');
$this->addBorderStyle($srssb, $styleArray, 'left');
$this->addBorderStyle($srssb, $styleArray, 'right');
$this->addBorderDiagonal($srssb, $styleArray);
}
if (isset($styleRegion->Style->HyperLink)) {
// TO DO
$hyperlink = $styleRegion->Style->HyperLink->attributes();
}
}
$this->spreadsheet->getActiveSheet()->getStyle($cellRange)->applyFromArray($styleArray);
}
}
$this->processColumnWidths($sheet, $maxCol);
$this->processRowHeights($sheet, $maxRow);
$this->processMergedCells($sheet);
++$worksheetID;
}
$this->processDefinedNames($gnmXML);
// Return
return $this->spreadsheet;
}
private function addBorderDiagonal(SimpleXMLElement $srssb, array &$styleArray): void
{
if (isset($srssb->Diagonal, $srssb->{'Rev-Diagonal'})) {
$styleArray['borders']['diagonal'] = self::parseBorderAttributes($srssb->Diagonal->attributes());
$styleArray['borders']['diagonalDirection'] = Borders::DIAGONAL_BOTH;
} elseif (isset($srssb->Diagonal)) {
$styleArray['borders']['diagonal'] = self::parseBorderAttributes($srssb->Diagonal->attributes());
$styleArray['borders']['diagonalDirection'] = Borders::DIAGONAL_UP;
} elseif (isset($srssb->{'Rev-Diagonal'})) {
$styleArray['borders']['diagonal'] = self::parseBorderAttributes($srssb->{'Rev-Diagonal'}->attributes());
$styleArray['borders']['diagonalDirection'] = Borders::DIAGONAL_DOWN;
}
}
private function addBorderStyle(SimpleXMLElement $srssb, array &$styleArray, string $direction): void
{
$ucDirection = ucfirst($direction);
if (isset($srssb->$ucDirection)) {
$styleArray['borders'][$direction] = self::parseBorderAttributes($srssb->$ucDirection->attributes());
}
}
private function processMergedCells(SimpleXMLElement $sheet): void
{
// Handle Merged Cells in this worksheet
if (isset($sheet->MergedRegions)) {
foreach ($sheet->MergedRegions->Merge as $mergeCells) {
if (strpos($mergeCells, ':') !== false) {
$this->spreadsheet->getActiveSheet()->mergeCells($mergeCells);
}
}
}
}
private function processColumnLoop(int $c, int $maxCol, SimpleXMLElement $columnOverride, float $defaultWidth): int
{
$columnAttributes = $columnOverride->attributes();
$column = $columnAttributes['No'];
$columnWidth = ((float) $columnAttributes['Unit']) / 5.4;
$hidden = (isset($columnAttributes['Hidden'])) && ((string) $columnAttributes['Hidden'] == '1');
$columnCount = (isset($columnAttributes['Count'])) ? $columnAttributes['Count'] : 1;
while ($c < $column) {
$this->spreadsheet->getActiveSheet()->getColumnDimension(Coordinate::stringFromColumnIndex($c + 1))->setWidth($defaultWidth);
++$c;
}
while (($c < ($column + $columnCount)) && ($c <= $maxCol)) {
$this->spreadsheet->getActiveSheet()->getColumnDimension(Coordinate::stringFromColumnIndex($c + 1))->setWidth($columnWidth);
if ($hidden) {
$this->spreadsheet->getActiveSheet()->getColumnDimension(Coordinate::stringFromColumnIndex($c + 1))->setVisible(false);
}
++$c;
}
return $c;
}
private function processColumnWidths(SimpleXMLElement $sheet, int $maxCol): void
{
if ((!$this->readDataOnly) && (isset($sheet->Cols))) {
// Column Widths
$columnAttributes = $sheet->Cols->attributes();
$defaultWidth = $columnAttributes['DefaultSizePts'] / 5.4;
$c = 0;
foreach ($sheet->Cols->ColInfo as $columnOverride) {
$c = $this->processColumnLoop($c, $maxCol, $columnOverride, $defaultWidth);
}
while ($c <= $maxCol) {
$this->spreadsheet->getActiveSheet()->getColumnDimension(Coordinate::stringFromColumnIndex($c + 1))->setWidth($defaultWidth);
++$c;
}
}
}
private function processRowLoop(int $r, int $maxRow, SimpleXMLElement $rowOverride, float $defaultHeight): int
{
$rowAttributes = $rowOverride->attributes();
$row = $rowAttributes['No'];
$rowHeight = (float) $rowAttributes['Unit'];
$hidden = (isset($rowAttributes['Hidden'])) && ((string) $rowAttributes['Hidden'] == '1');
$rowCount = (isset($rowAttributes['Count'])) ? $rowAttributes['Count'] : 1;
while ($r < $row) {
++$r;
$this->spreadsheet->getActiveSheet()->getRowDimension($r)->setRowHeight($defaultHeight);
}
while (($r < ($row + $rowCount)) && ($r < $maxRow)) {
++$r;
$this->spreadsheet->getActiveSheet()->getRowDimension($r)->setRowHeight($rowHeight);
if ($hidden) {
$this->spreadsheet->getActiveSheet()->getRowDimension($r)->setVisible(false);
}
}
return $r;
}
private function processRowHeights(SimpleXMLElement $sheet, int $maxRow): void
{
if ((!$this->readDataOnly) && (isset($sheet->Rows))) {
// Row Heights
$rowAttributes = $sheet->Rows->attributes();
$defaultHeight = (float) $rowAttributes['DefaultSizePts'];
$r = 0;
foreach ($sheet->Rows->RowInfo as $rowOverride) {
$r = $this->processRowLoop($r, $maxRow, $rowOverride, $defaultHeight);
}
// never executed, I can't figure out any circumstances
// under which it would be executed, and, even if
// such exist, I'm not convinced this is needed.
//while ($r < $maxRow) {
// ++$r;
// $this->spreadsheet->getActiveSheet()->getRowDimension($r)->setRowHeight($defaultHeight);
//}
}
}
private function processDefinedNames(SimpleXMLElement $gnmXML): void
{
// Loop through definedNames (global named ranges)
if (isset($gnmXML->Names)) {
foreach ($gnmXML->Names->Name as $definedName) {
$name = (string) $definedName->name;
$value = (string) $definedName->value;
if (stripos($value, '#REF!') !== false) {
continue;
}
[$worksheetName] = Worksheet::extractSheetTitle($value, true);
$worksheetName = trim($worksheetName, "'");
$worksheet = $this->spreadsheet->getSheetByName($worksheetName);
// Worksheet might still be null if we're only loading selected sheets rather than the full spreadsheet
if ($worksheet !== null) {
$this->spreadsheet->addDefinedName(DefinedName::createInstance($name, $worksheet, $value));
}
}
}
}
private function calcRotation(SimpleXMLElement $styleAttributes): int
{
$rotation = (int) $styleAttributes->Rotation;
if ($rotation >= 270 && $rotation <= 360) {
$rotation -= 360;
}
$rotation = (abs($rotation) > 90) ? 0 : $rotation;
return $rotation;
}
private static function addStyle(array &$styleArray, string $key, string $value): void
{
if (array_key_exists($value, self::$mappings[$key])) {
$styleArray[$key] = self::$mappings[$key][$value];
}
}
private static function addStyle2(array &$styleArray, string $key1, string $key, string $value): void
{
if (array_key_exists($value, self::$mappings[$key])) {
$styleArray[$key1][$key] = self::$mappings[$key][$value];
}
}
private static function parseBorderAttributes($borderAttributes)
{
$styleArray = [];
if (isset($borderAttributes['Color'])) {
$styleArray['color']['rgb'] = self::parseGnumericColour($borderAttributes['Color']);
}
self::addStyle($styleArray, 'borderStyle', $borderAttributes['Style']);
return $styleArray;
}
private function parseRichText($is)
{
$value = new RichText();
$value->createText($is);
return $value;
}
private static function parseGnumericColour($gnmColour)
{
[$gnmR, $gnmG, $gnmB] = explode(':', $gnmColour);
$gnmR = substr(str_pad($gnmR, 4, '0', STR_PAD_RIGHT), 0, 2);
$gnmG = substr(str_pad($gnmG, 4, '0', STR_PAD_RIGHT), 0, 2);
$gnmB = substr(str_pad($gnmB, 4, '0', STR_PAD_RIGHT), 0, 2);
return $gnmR . $gnmG . $gnmB;
}
private function addColors(array &$styleArray, SimpleXMLElement $styleAttributes): void
{
$RGB = self::parseGnumericColour($styleAttributes['Fore']);
$styleArray['font']['color']['rgb'] = $RGB;
$RGB = self::parseGnumericColour($styleAttributes['Back']);
$shade = (string) $styleAttributes['Shade'];
if (($RGB != '000000') || ($shade != '0')) {
$RGB2 = self::parseGnumericColour($styleAttributes['PatternColor']);
if ($shade == '1') {
$styleArray['fill']['startColor']['rgb'] = $RGB;
$styleArray['fill']['endColor']['rgb'] = $RGB2;
} else {
$styleArray['fill']['endColor']['rgb'] = $RGB;
$styleArray['fill']['startColor']['rgb'] = $RGB2;
}
self::addStyle2($styleArray, 'fill', 'fillType', $shade);
}
}
}

View File

@@ -0,0 +1,143 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Reader\Gnumeric;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\PageMargins;
use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup as WorksheetPageSetup;
use SimpleXMLElement;
class PageSetup
{
/**
* @var Spreadsheet
*/
private $spreadsheet;
/**
* @var string
*/
private $gnm;
public function __construct(Spreadsheet $spreadsheet, string $gnm)
{
$this->spreadsheet = $spreadsheet;
$this->gnm = $gnm;
}
public function printInformation(SimpleXMLElement $sheet): self
{
if (isset($sheet->PrintInformation)) {
$printInformation = $sheet->PrintInformation[0];
$scale = (string) $printInformation->Scale->attributes()['percentage'];
$pageOrder = (string) $printInformation->order;
$orientation = (string) $printInformation->orientation;
$horizontalCentered = (string) $printInformation->hcenter->attributes()['value'];
$verticalCentered = (string) $printInformation->vcenter->attributes()['value'];
$this->spreadsheet->getActiveSheet()->getPageSetup()
->setPageOrder($pageOrder === 'r_then_d' ? WorksheetPageSetup::PAGEORDER_OVER_THEN_DOWN : WorksheetPageSetup::PAGEORDER_DOWN_THEN_OVER)
->setScale((int) $scale)
->setOrientation($orientation ?? WorksheetPageSetup::ORIENTATION_DEFAULT)
->setHorizontalCentered((bool) $horizontalCentered)
->setVerticalCentered((bool) $verticalCentered);
}
return $this;
}
public function sheetMargins(SimpleXMLElement $sheet): self
{
if (isset($sheet->PrintInformation, $sheet->PrintInformation->Margins)) {
$marginSet = [
// Default Settings
'top' => 0.75,
'header' => 0.3,
'left' => 0.7,
'right' => 0.7,
'bottom' => 0.75,
'footer' => 0.3,
];
$marginSet = $this->buildMarginSet($sheet, $marginSet);
$this->adjustMargins($marginSet);
}
return $this;
}
private function buildMarginSet(SimpleXMLElement $sheet, array $marginSet): array
{
foreach ($sheet->PrintInformation->Margins->children($this->gnm, true) as $key => $margin) {
$marginAttributes = $margin->attributes();
$marginSize = ($marginAttributes['Points']) ?? 72; // Default is 72pt
// Convert value in points to inches
$marginSize = PageMargins::fromPoints((float) $marginSize);
$marginSet[$key] = $marginSize;
}
return $marginSet;
}
private function adjustMargins(array $marginSet): void
{
foreach ($marginSet as $key => $marginSize) {
// Gnumeric is quirky in the way it displays the header/footer values:
// header is actually the sum of top and header; footer is actually the sum of bottom and footer
// then top is actually the header value, and bottom is actually the footer value
switch ($key) {
case 'left':
case 'right':
$this->sheetMargin($key, $marginSize);
break;
case 'top':
$this->sheetMargin($key, $marginSet['header'] ?? 0);
break;
case 'bottom':
$this->sheetMargin($key, $marginSet['footer'] ?? 0);
break;
case 'header':
$this->sheetMargin($key, ($marginSet['top'] ?? 0) - $marginSize);
break;
case 'footer':
$this->sheetMargin($key, ($marginSet['bottom'] ?? 0) - $marginSize);
break;
}
}
}
private function sheetMargin(string $key, float $marginSize): void
{
switch ($key) {
case 'top':
$this->spreadsheet->getActiveSheet()->getPageMargins()->setTop($marginSize);
break;
case 'bottom':
$this->spreadsheet->getActiveSheet()->getPageMargins()->setBottom($marginSize);
break;
case 'left':
$this->spreadsheet->getActiveSheet()->getPageMargins()->setLeft($marginSize);
break;
case 'right':
$this->spreadsheet->getActiveSheet()->getPageMargins()->setRight($marginSize);
break;
case 'header':
$this->spreadsheet->getActiveSheet()->getPageMargins()->setHeader($marginSize);
break;
case 'footer':
$this->spreadsheet->getActiveSheet()->getPageMargins()->setFooter($marginSize);
break;
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,17 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Reader;
interface IReadFilter
{
/**
* Should this cell be read?
*
* @param string $column Column address (as a string value like "A", or "IV")
* @param int $row Row number
* @param string $worksheetName Optional worksheet name
*
* @return bool
*/
public function readCell($column, $row, $worksheetName = '');
}

View File

@@ -0,0 +1,133 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Reader;
interface IReader
{
/**
* IReader constructor.
*/
public function __construct();
/**
* Can the current IReader read the file?
*
* @param string $pFilename
*
* @return bool
*/
public function canRead($pFilename);
/**
* Read data only?
* If this is true, then the Reader will only read data values for cells, it will not read any formatting information.
* If false (the default) it will read data and formatting.
*
* @return bool
*/
public function getReadDataOnly();
/**
* Set read data only
* Set to true, to advise the Reader only to read data values for cells, and to ignore any formatting information.
* Set to false (the default) to advise the Reader to read both data and formatting for cells.
*
* @param bool $pValue
*
* @return IReader
*/
public function setReadDataOnly($pValue);
/**
* Read empty cells?
* If this is true (the default), then the Reader will read data values for all cells, irrespective of value.
* If false it will not read data for cells containing a null value or an empty string.
*
* @return bool
*/
public function getReadEmptyCells();
/**
* Set read empty cells
* Set to true (the default) to advise the Reader read data values for all cells, irrespective of value.
* Set to false to advise the Reader to ignore cells containing a null value or an empty string.
*
* @param bool $pValue
*
* @return IReader
*/
public function setReadEmptyCells($pValue);
/**
* Read charts in workbook?
* If this is true, then the Reader will include any charts that exist in the workbook.
* Note that a ReadDataOnly value of false overrides, and charts won't be read regardless of the IncludeCharts value.
* If false (the default) it will ignore any charts defined in the workbook file.
*
* @return bool
*/
public function getIncludeCharts();
/**
* Set read charts in workbook
* Set to true, to advise the Reader to include any charts that exist in the workbook.
* Note that a ReadDataOnly value of false overrides, and charts won't be read regardless of the IncludeCharts value.
* Set to false (the default) to discard charts.
*
* @param bool $pValue
*
* @return IReader
*/
public function setIncludeCharts($pValue);
/**
* Get which sheets to load
* Returns either an array of worksheet names (the list of worksheets that should be loaded), or a null
* indicating that all worksheets in the workbook should be loaded.
*
* @return mixed
*/
public function getLoadSheetsOnly();
/**
* Set which sheets to load.
*
* @param mixed $value
* This should be either an array of worksheet names to be loaded, or a string containing a single worksheet name.
* If NULL, then it tells the Reader to read all worksheets in the workbook
*
* @return IReader
*/
public function setLoadSheetsOnly($value);
/**
* Set all sheets to load
* Tells the Reader to load all worksheets from the workbook.
*
* @return IReader
*/
public function setLoadAllSheets();
/**
* Read filter.
*
* @return IReadFilter
*/
public function getReadFilter();
/**
* Set read filter.
*
* @return IReader
*/
public function setReadFilter(IReadFilter $pValue);
/**
* Loads PhpSpreadsheet from file.
*
* @param string $pFilename
*
* @return \PhpOffice\PhpSpreadsheet\Spreadsheet
*/
public function load($pFilename);
}

View File

@@ -0,0 +1,795 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Reader;
use DateTime;
use DateTimeZone;
use DOMAttr;
use DOMDocument;
use DOMElement;
use DOMNode;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\DefinedName;
use PhpOffice\PhpSpreadsheet\Reader\Exception as ReaderException;
use PhpOffice\PhpSpreadsheet\Reader\Ods\PageSettings;
use PhpOffice\PhpSpreadsheet\Reader\Ods\Properties as DocumentProperties;
use PhpOffice\PhpSpreadsheet\Reader\Security\XmlScanner;
use PhpOffice\PhpSpreadsheet\RichText\RichText;
use PhpOffice\PhpSpreadsheet\Settings;
use PhpOffice\PhpSpreadsheet\Shared\Date;
use PhpOffice\PhpSpreadsheet\Shared\File;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use XMLReader;
use ZipArchive;
class Ods extends BaseReader
{
/**
* Create a new Ods Reader instance.
*/
public function __construct()
{
parent::__construct();
$this->securityScanner = XmlScanner::getInstance($this);
}
/**
* Can the current IReader read the file?
*
* @param string $pFilename
*
* @return bool
*/
public function canRead($pFilename)
{
File::assertFile($pFilename);
$mimeType = 'UNKNOWN';
// Load file
$zip = new ZipArchive();
if ($zip->open($pFilename) === true) {
// check if it is an OOXML archive
$stat = $zip->statName('mimetype');
if ($stat && ($stat['size'] <= 255)) {
$mimeType = $zip->getFromName($stat['name']);
} elseif ($zip->statName('META-INF/manifest.xml')) {
$xml = simplexml_load_string(
$this->securityScanner->scan($zip->getFromName('META-INF/manifest.xml')),
'SimpleXMLElement',
Settings::getLibXmlLoaderOptions()
);
$namespacesContent = $xml->getNamespaces(true);
if (isset($namespacesContent['manifest'])) {
$manifest = $xml->children($namespacesContent['manifest']);
foreach ($manifest as $manifestDataSet) {
$manifestAttributes = $manifestDataSet->attributes($namespacesContent['manifest']);
if ($manifestAttributes->{'full-path'} == '/') {
$mimeType = (string) $manifestAttributes->{'media-type'};
break;
}
}
}
}
$zip->close();
}
return $mimeType === 'application/vnd.oasis.opendocument.spreadsheet';
}
/**
* Reads names of the worksheets from a file, without parsing the whole file to a PhpSpreadsheet object.
*
* @param string $pFilename
*
* @return string[]
*/
public function listWorksheetNames($pFilename)
{
File::assertFile($pFilename);
$zip = new ZipArchive();
if ($zip->open($pFilename) !== true) {
throw new ReaderException('Could not open ' . $pFilename . ' for reading! Error opening file.');
}
$worksheetNames = [];
$xml = new XMLReader();
$xml->xml(
$this->securityScanner->scanFile('zip://' . realpath($pFilename) . '#content.xml'),
null,
Settings::getLibXmlLoaderOptions()
);
$xml->setParserProperty(2, true);
// Step into the first level of content of the XML
$xml->read();
while ($xml->read()) {
// Quickly jump through to the office:body node
while ($xml->name !== 'office:body') {
if ($xml->isEmptyElement) {
$xml->read();
} else {
$xml->next();
}
}
// Now read each node until we find our first table:table node
while ($xml->read()) {
if ($xml->name == 'table:table' && $xml->nodeType == XMLReader::ELEMENT) {
// Loop through each table:table node reading the table:name attribute for each worksheet name
do {
$worksheetNames[] = $xml->getAttribute('table:name');
$xml->next();
} while ($xml->name == 'table:table' && $xml->nodeType == XMLReader::ELEMENT);
}
}
}
return $worksheetNames;
}
/**
* Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns).
*
* @param string $pFilename
*
* @return array
*/
public function listWorksheetInfo($pFilename)
{
File::assertFile($pFilename);
$worksheetInfo = [];
$zip = new ZipArchive();
if ($zip->open($pFilename) !== true) {
throw new ReaderException('Could not open ' . $pFilename . ' for reading! Error opening file.');
}
$xml = new XMLReader();
$xml->xml(
$this->securityScanner->scanFile('zip://' . realpath($pFilename) . '#content.xml'),
null,
Settings::getLibXmlLoaderOptions()
);
$xml->setParserProperty(2, true);
// Step into the first level of content of the XML
$xml->read();
while ($xml->read()) {
// Quickly jump through to the office:body node
while ($xml->name !== 'office:body') {
if ($xml->isEmptyElement) {
$xml->read();
} else {
$xml->next();
}
}
// Now read each node until we find our first table:table node
while ($xml->read()) {
if ($xml->name == 'table:table' && $xml->nodeType == XMLReader::ELEMENT) {
$worksheetNames[] = $xml->getAttribute('table:name');
$tmpInfo = [
'worksheetName' => $xml->getAttribute('table:name'),
'lastColumnLetter' => 'A',
'lastColumnIndex' => 0,
'totalRows' => 0,
'totalColumns' => 0,
];
// Loop through each child node of the table:table element reading
$currCells = 0;
do {
$xml->read();
if ($xml->name == 'table:table-row' && $xml->nodeType == XMLReader::ELEMENT) {
$rowspan = $xml->getAttribute('table:number-rows-repeated');
$rowspan = empty($rowspan) ? 1 : $rowspan;
$tmpInfo['totalRows'] += $rowspan;
$tmpInfo['totalColumns'] = max($tmpInfo['totalColumns'], $currCells);
$currCells = 0;
// Step into the row
$xml->read();
do {
$doread = true;
if ($xml->name == 'table:table-cell' && $xml->nodeType == XMLReader::ELEMENT) {
if (!$xml->isEmptyElement) {
++$currCells;
$xml->next();
$doread = false;
}
} elseif ($xml->name == 'table:covered-table-cell' && $xml->nodeType == XMLReader::ELEMENT) {
$mergeSize = $xml->getAttribute('table:number-columns-repeated');
$currCells += (int) $mergeSize;
}
if ($doread) {
$xml->read();
}
} while ($xml->name != 'table:table-row');
}
} while ($xml->name != 'table:table');
$tmpInfo['totalColumns'] = max($tmpInfo['totalColumns'], $currCells);
$tmpInfo['lastColumnIndex'] = $tmpInfo['totalColumns'] - 1;
$tmpInfo['lastColumnLetter'] = Coordinate::stringFromColumnIndex($tmpInfo['lastColumnIndex'] + 1);
$worksheetInfo[] = $tmpInfo;
}
}
}
return $worksheetInfo;
}
/**
* Loads PhpSpreadsheet from file.
*
* @param string $pFilename
*
* @return Spreadsheet
*/
public function load($pFilename)
{
// Create new Spreadsheet
$spreadsheet = new Spreadsheet();
// Load into this instance
return $this->loadIntoExisting($pFilename, $spreadsheet);
}
/**
* Loads PhpSpreadsheet from file into PhpSpreadsheet instance.
*
* @param string $pFilename
*
* @return Spreadsheet
*/
public function loadIntoExisting($pFilename, Spreadsheet $spreadsheet)
{
File::assertFile($pFilename);
$timezoneObj = new DateTimeZone('Europe/London');
$GMT = new DateTimeZone('UTC');
$zip = new ZipArchive();
if ($zip->open($pFilename) !== true) {
throw new Exception("Could not open {$pFilename} for reading! Error opening file.");
}
// Meta
$xml = @simplexml_load_string(
$this->securityScanner->scan($zip->getFromName('meta.xml')),
'SimpleXMLElement',
Settings::getLibXmlLoaderOptions()
);
if ($xml === false) {
throw new Exception('Unable to read data from {$pFilename}');
}
$namespacesMeta = $xml->getNamespaces(true);
(new DocumentProperties($spreadsheet))->load($xml, $namespacesMeta);
// Styles
$dom = new DOMDocument('1.01', 'UTF-8');
$dom->loadXML(
$this->securityScanner->scan($zip->getFromName('styles.xml')),
Settings::getLibXmlLoaderOptions()
);
$pageSettings = new PageSettings($dom);
// Main Content
$dom = new DOMDocument('1.01', 'UTF-8');
$dom->loadXML(
$this->securityScanner->scan($zip->getFromName('content.xml')),
Settings::getLibXmlLoaderOptions()
);
$officeNs = $dom->lookupNamespaceUri('office');
$tableNs = $dom->lookupNamespaceUri('table');
$textNs = $dom->lookupNamespaceUri('text');
$xlinkNs = $dom->lookupNamespaceUri('xlink');
$pageSettings->readStyleCrossReferences($dom);
// Content
$spreadsheets = $dom->getElementsByTagNameNS($officeNs, 'body')
->item(0)
->getElementsByTagNameNS($officeNs, 'spreadsheet');
foreach ($spreadsheets as $workbookData) {
/** @var DOMElement $workbookData */
$tables = $workbookData->getElementsByTagNameNS($tableNs, 'table');
$worksheetID = 0;
foreach ($tables as $worksheetDataSet) {
/** @var DOMElement $worksheetDataSet */
$worksheetName = $worksheetDataSet->getAttributeNS($tableNs, 'name');
// Check loadSheetsOnly
if (
isset($this->loadSheetsOnly)
&& $worksheetName
&& !in_array($worksheetName, $this->loadSheetsOnly)
) {
continue;
}
$worksheetStyleName = $worksheetDataSet->getAttributeNS($tableNs, 'style-name');
// Create sheet
if ($worksheetID > 0) {
$spreadsheet->createSheet(); // First sheet is added by default
}
$spreadsheet->setActiveSheetIndex($worksheetID);
if ($worksheetName) {
// 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
$spreadsheet->getActiveSheet()->setTitle((string) $worksheetName, false, false);
}
// Go through every child of table element
$rowID = 1;
foreach ($worksheetDataSet->childNodes as $childNode) {
/** @var DOMElement $childNode */
// Filter elements which are not under the "table" ns
if ($childNode->namespaceURI != $tableNs) {
continue;
}
$key = $childNode->nodeName;
// Remove ns from node name
if (strpos($key, ':') !== false) {
$keyChunks = explode(':', $key);
$key = array_pop($keyChunks);
}
switch ($key) {
case 'table-header-rows':
/// TODO :: Figure this out. This is only a partial implementation I guess.
// ($rowData it's not used at all and I'm not sure that PHPExcel
// has an API for this)
// foreach ($rowData as $keyRowData => $cellData) {
// $rowData = $cellData;
// break;
// }
break;
case 'table-row':
if ($childNode->hasAttributeNS($tableNs, 'number-rows-repeated')) {
$rowRepeats = $childNode->getAttributeNS($tableNs, 'number-rows-repeated');
} else {
$rowRepeats = 1;
}
$columnID = 'A';
foreach ($childNode->childNodes as $key => $cellData) {
// @var \DOMElement $cellData
if ($this->getReadFilter() !== null) {
if (!$this->getReadFilter()->readCell($columnID, $rowID, $worksheetName)) {
++$columnID;
continue;
}
}
// Initialize variables
$formatting = $hyperlink = null;
$hasCalculatedValue = false;
$cellDataFormula = '';
if ($cellData->hasAttributeNS($tableNs, 'formula')) {
$cellDataFormula = $cellData->getAttributeNS($tableNs, 'formula');
$hasCalculatedValue = true;
}
// Annotations
$annotation = $cellData->getElementsByTagNameNS($officeNs, 'annotation');
if ($annotation->length > 0) {
$textNode = $annotation->item(0)->getElementsByTagNameNS($textNs, 'p');
if ($textNode->length > 0) {
$text = $this->scanElementForText($textNode->item(0));
$spreadsheet->getActiveSheet()
->getComment($columnID . $rowID)
->setText($this->parseRichText($text));
// ->setAuthor( $author )
}
}
// Content
/** @var DOMElement[] $paragraphs */
$paragraphs = [];
foreach ($cellData->childNodes as $item) {
/** @var DOMElement $item */
// Filter text:p elements
if ($item->nodeName == 'text:p') {
$paragraphs[] = $item;
}
}
if (count($paragraphs) > 0) {
// Consolidate if there are multiple p records (maybe with spans as well)
$dataArray = [];
// Text can have multiple text:p and within those, multiple text:span.
// text:p newlines, but text:span does not.
// Also, here we assume there is no text data is span fields are specified, since
// we have no way of knowing proper positioning anyway.
foreach ($paragraphs as $pData) {
$dataArray[] = $this->scanElementForText($pData);
}
$allCellDataText = implode("\n", $dataArray);
$type = $cellData->getAttributeNS($officeNs, 'value-type');
switch ($type) {
case 'string':
$type = DataType::TYPE_STRING;
$dataValue = $allCellDataText;
foreach ($paragraphs as $paragraph) {
$link = $paragraph->getElementsByTagNameNS($textNs, 'a');
if ($link->length > 0) {
$hyperlink = $link->item(0)->getAttributeNS($xlinkNs, 'href');
}
}
break;
case 'boolean':
$type = DataType::TYPE_BOOL;
$dataValue = ($allCellDataText == 'TRUE') ? true : false;
break;
case 'percentage':
$type = DataType::TYPE_NUMERIC;
$dataValue = (float) $cellData->getAttributeNS($officeNs, 'value');
// percentage should always be float
//if (floor($dataValue) == $dataValue) {
// $dataValue = (int) $dataValue;
//}
$formatting = NumberFormat::FORMAT_PERCENTAGE_00;
break;
case 'currency':
$type = DataType::TYPE_NUMERIC;
$dataValue = (float) $cellData->getAttributeNS($officeNs, 'value');
if (floor($dataValue) == $dataValue) {
$dataValue = (int) $dataValue;
}
$formatting = NumberFormat::FORMAT_CURRENCY_USD_SIMPLE;
break;
case 'float':
$type = DataType::TYPE_NUMERIC;
$dataValue = (float) $cellData->getAttributeNS($officeNs, 'value');
if (floor($dataValue) == $dataValue) {
if ($dataValue == (int) $dataValue) {
$dataValue = (int) $dataValue;
}
}
break;
case 'date':
$type = DataType::TYPE_NUMERIC;
$value = $cellData->getAttributeNS($officeNs, 'date-value');
$dateObj = new DateTime($value, $GMT);
$dateObj->setTimeZone($timezoneObj);
[$year, $month, $day, $hour, $minute, $second] = explode(
' ',
$dateObj->format('Y m d H i s')
);
$dataValue = Date::formattedPHPToExcel(
(int) $year,
(int) $month,
(int) $day,
(int) $hour,
(int) $minute,
(int) $second
);
if ($dataValue != floor($dataValue)) {
$formatting = NumberFormat::FORMAT_DATE_XLSX15
. ' '
. NumberFormat::FORMAT_DATE_TIME4;
} else {
$formatting = NumberFormat::FORMAT_DATE_XLSX15;
}
break;
case 'time':
$type = DataType::TYPE_NUMERIC;
$timeValue = $cellData->getAttributeNS($officeNs, 'time-value');
$dataValue = Date::PHPToExcel(
strtotime(
'01-01-1970 ' . implode(':', sscanf($timeValue, 'PT%dH%dM%dS'))
)
);
$formatting = NumberFormat::FORMAT_DATE_TIME4;
break;
default:
$dataValue = null;
}
} else {
$type = DataType::TYPE_NULL;
$dataValue = null;
}
if ($hasCalculatedValue) {
$type = DataType::TYPE_FORMULA;
$cellDataFormula = substr($cellDataFormula, strpos($cellDataFormula, ':=') + 1);
$cellDataFormula = $this->convertToExcelFormulaValue($cellDataFormula);
}
if ($cellData->hasAttributeNS($tableNs, 'number-columns-repeated')) {
$colRepeats = (int) $cellData->getAttributeNS($tableNs, 'number-columns-repeated');
} else {
$colRepeats = 1;
}
if ($type !== null) {
for ($i = 0; $i < $colRepeats; ++$i) {
if ($i > 0) {
++$columnID;
}
if ($type !== DataType::TYPE_NULL) {
for ($rowAdjust = 0; $rowAdjust < $rowRepeats; ++$rowAdjust) {
$rID = $rowID + $rowAdjust;
$cell = $spreadsheet->getActiveSheet()
->getCell($columnID . $rID);
// Set value
if ($hasCalculatedValue) {
$cell->setValueExplicit($cellDataFormula, $type);
} else {
$cell->setValueExplicit($dataValue, $type);
}
if ($hasCalculatedValue) {
$cell->setCalculatedValue($dataValue);
}
// Set other properties
if ($formatting !== null) {
$spreadsheet->getActiveSheet()
->getStyle($columnID . $rID)
->getNumberFormat()
->setFormatCode($formatting);
} else {
$spreadsheet->getActiveSheet()
->getStyle($columnID . $rID)
->getNumberFormat()
->setFormatCode(NumberFormat::FORMAT_GENERAL);
}
if ($hyperlink !== null) {
$cell->getHyperlink()
->setUrl($hyperlink);
}
}
}
}
}
// Merged cells
if (
$cellData->hasAttributeNS($tableNs, 'number-columns-spanned')
|| $cellData->hasAttributeNS($tableNs, 'number-rows-spanned')
) {
if (($type !== DataType::TYPE_NULL) || (!$this->readDataOnly)) {
$columnTo = $columnID;
if ($cellData->hasAttributeNS($tableNs, 'number-columns-spanned')) {
$columnIndex = Coordinate::columnIndexFromString($columnID);
$columnIndex += (int) $cellData->getAttributeNS($tableNs, 'number-columns-spanned');
$columnIndex -= 2;
$columnTo = Coordinate::stringFromColumnIndex($columnIndex + 1);
}
$rowTo = $rowID;
if ($cellData->hasAttributeNS($tableNs, 'number-rows-spanned')) {
$rowTo = $rowTo + (int) $cellData->getAttributeNS($tableNs, 'number-rows-spanned') - 1;
}
$cellRange = $columnID . $rowID . ':' . $columnTo . $rowTo;
$spreadsheet->getActiveSheet()->mergeCells($cellRange);
}
}
++$columnID;
}
$rowID += $rowRepeats;
break;
}
}
$pageSettings->setPrintSettingsForWorksheet($spreadsheet->getActiveSheet(), $worksheetStyleName);
++$worksheetID;
}
$this->readDefinedRanges($spreadsheet, $workbookData, $tableNs);
$this->readDefinedExpressions($spreadsheet, $workbookData, $tableNs);
}
$spreadsheet->setActiveSheetIndex(0);
// Return
return $spreadsheet;
}
/**
* Recursively scan element.
*
* @return string
*/
protected function scanElementForText(DOMNode $element)
{
$str = '';
foreach ($element->childNodes as $child) {
/** @var DOMNode $child */
if ($child->nodeType == XML_TEXT_NODE) {
$str .= $child->nodeValue;
} elseif ($child->nodeType == XML_ELEMENT_NODE && $child->nodeName == 'text:s') {
// It's a space
// Multiple spaces?
/** @var DOMAttr $cAttr */
$cAttr = $child->attributes->getNamedItem('c');
if ($cAttr) {
$multiplier = (int) $cAttr->nodeValue;
} else {
$multiplier = 1;
}
$str .= str_repeat(' ', $multiplier);
}
if ($child->hasChildNodes()) {
$str .= $this->scanElementForText($child);
}
}
return $str;
}
/**
* @param string $is
*
* @return RichText
*/
private function parseRichText($is)
{
$value = new RichText();
$value->createText($is);
return $value;
}
private function convertToExcelAddressValue(string $openOfficeAddress): string
{
$excelAddress = $openOfficeAddress;
// Cell range 3-d reference
// As we don't support 3-d ranges, we're just going to take a quick and dirty approach
// and assume that the second worksheet reference is the same as the first
$excelAddress = preg_replace('/\$?([^\.]+)\.([^\.]+):\$?([^\.]+)\.([^\.]+)/miu', '$1!$2:$4', $excelAddress);
// Cell range reference in another sheet
$excelAddress = preg_replace('/\$?([^\.]+)\.([^\.]+):\.([^\.]+)/miu', '$1!$2:$3', $excelAddress);
// Cell reference in another sheet
$excelAddress = preg_replace('/\$?([^\.]+)\.([^\.]+)/miu', '$1!$2', $excelAddress);
// Cell range reference
$excelAddress = preg_replace('/\.([^\.]+):\.([^\.]+)/miu', '$1:$2', $excelAddress);
// Simple cell reference
$excelAddress = preg_replace('/\.([^\.]+)/miu', '$1', $excelAddress);
return $excelAddress;
}
private function convertToExcelFormulaValue(string $openOfficeFormula): string
{
$temp = explode('"', $openOfficeFormula);
$tKey = false;
foreach ($temp as &$value) {
// Only replace in alternate array entries (i.e. non-quoted blocks)
if ($tKey = !$tKey) {
// Cell range reference in another sheet
$value = preg_replace('/\[\$?([^\.]+)\.([^\.]+):\.([^\.]+)\]/miu', '$1!$2:$3', $value);
// Cell reference in another sheet
$value = preg_replace('/\[\$?([^\.]+)\.([^\.]+)\]/miu', '$1!$2', $value);
// Cell range reference
$value = preg_replace('/\[\.([^\.]+):\.([^\.]+)\]/miu', '$1:$2', $value);
// Simple cell reference
$value = preg_replace('/\[\.([^\.]+)\]/miu', '$1', $value);
$value = Calculation::translateSeparator(';', ',', $value, $inBraces);
}
}
// Then rebuild the formula string
$excelFormula = implode('"', $temp);
return $excelFormula;
}
/**
* Read any Named Ranges that are defined in this spreadsheet.
*/
private function readDefinedRanges(Spreadsheet $spreadsheet, DOMElement $workbookData, string $tableNs): void
{
$namedRanges = $workbookData->getElementsByTagNameNS($tableNs, 'named-range');
foreach ($namedRanges as $definedNameElement) {
$definedName = $definedNameElement->getAttributeNS($tableNs, 'name');
$baseAddress = $definedNameElement->getAttributeNS($tableNs, 'base-cell-address');
$range = $definedNameElement->getAttributeNS($tableNs, 'cell-range-address');
$baseAddress = $this->convertToExcelAddressValue($baseAddress);
$range = $this->convertToExcelAddressValue($range);
$this->addDefinedName($spreadsheet, $baseAddress, $definedName, $range);
}
}
/**
* Read any Named Formulae that are defined in this spreadsheet.
*/
private function readDefinedExpressions(Spreadsheet $spreadsheet, DOMElement $workbookData, string $tableNs): void
{
$namedExpressions = $workbookData->getElementsByTagNameNS($tableNs, 'named-expression');
foreach ($namedExpressions as $definedNameElement) {
$definedName = $definedNameElement->getAttributeNS($tableNs, 'name');
$baseAddress = $definedNameElement->getAttributeNS($tableNs, 'base-cell-address');
$expression = $definedNameElement->getAttributeNS($tableNs, 'expression');
$baseAddress = $this->convertToExcelAddressValue($baseAddress);
$expression = $this->convertToExcelFormulaValue($expression);
$this->addDefinedName($spreadsheet, $baseAddress, $definedName, $expression);
}
}
/**
* Assess scope and store the Defined Name.
*/
private function addDefinedName(Spreadsheet $spreadsheet, string $baseAddress, string $definedName, string $value): void
{
[$sheetReference] = Worksheet::extractSheetTitle($baseAddress, true);
$worksheet = $spreadsheet->getSheetByName($sheetReference);
// Worksheet might still be null if we're only loading selected sheets rather than the full spreadsheet
if ($worksheet !== null) {
$spreadsheet->addDefinedName(DefinedName::createInstance((string) $definedName, $worksheet, $value));
}
}
}

View File

@@ -0,0 +1,139 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Reader\Ods;
use DOMDocument;
use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
class PageSettings
{
private $officeNs;
private $stylesNs;
private $stylesFo;
private $pageLayoutStyles = [];
private $masterStylesCrossReference = [];
private $masterPrintStylesCrossReference = [];
public function __construct(DOMDocument $styleDom)
{
$this->setDomNameSpaces($styleDom);
$this->readPageSettingStyles($styleDom);
$this->readStyleMasterLookup($styleDom);
}
private function setDomNameSpaces(DOMDocument $styleDom): void
{
$this->officeNs = $styleDom->lookupNamespaceUri('office');
$this->stylesNs = $styleDom->lookupNamespaceUri('style');
$this->stylesFo = $styleDom->lookupNamespaceUri('fo');
}
private function readPageSettingStyles(DOMDocument $styleDom): void
{
$styles = $styleDom->getElementsByTagNameNS($this->officeNs, 'automatic-styles')
->item(0)
->getElementsByTagNameNS($this->stylesNs, 'page-layout');
foreach ($styles as $styleSet) {
$styleName = $styleSet->getAttributeNS($this->stylesNs, 'name');
$pageLayoutProperties = $styleSet->getElementsByTagNameNS($this->stylesNs, 'page-layout-properties')[0];
$styleOrientation = $pageLayoutProperties->getAttributeNS($this->stylesNs, 'print-orientation');
$styleScale = $pageLayoutProperties->getAttributeNS($this->stylesNs, 'scale-to');
$stylePrintOrder = $pageLayoutProperties->getAttributeNS($this->stylesNs, 'print-page-order');
$centered = $pageLayoutProperties->getAttributeNS($this->stylesNs, 'table-centering');
$marginLeft = $pageLayoutProperties->getAttributeNS($this->stylesFo, 'margin-left');
$marginRight = $pageLayoutProperties->getAttributeNS($this->stylesFo, 'margin-right');
$marginTop = $pageLayoutProperties->getAttributeNS($this->stylesFo, 'margin-top');
$marginBottom = $pageLayoutProperties->getAttributeNS($this->stylesFo, 'margin-bottom');
$header = $styleSet->getElementsByTagNameNS($this->stylesNs, 'header-style')[0];
$headerProperties = $header->getElementsByTagNameNS($this->stylesNs, 'header-footer-properties')[0];
$marginHeader = $headerProperties->getAttributeNS($this->stylesFo, 'min-height');
$footer = $styleSet->getElementsByTagNameNS($this->stylesNs, 'footer-style')[0];
$footerProperties = $footer->getElementsByTagNameNS($this->stylesNs, 'header-footer-properties')[0];
$marginFooter = $footerProperties->getAttributeNS($this->stylesFo, 'min-height');
$this->pageLayoutStyles[$styleName] = (object) [
'orientation' => $styleOrientation ?: PageSetup::ORIENTATION_DEFAULT,
'scale' => $styleScale ?: 100,
'printOrder' => $stylePrintOrder,
'horizontalCentered' => $centered === 'horizontal' || $centered === 'both',
'verticalCentered' => $centered === 'vertical' || $centered === 'both',
// margin size is already stored in inches, so no UOM conversion is required
'marginLeft' => (float) $marginLeft ?? 0.7,
'marginRight' => (float) $marginRight ?? 0.7,
'marginTop' => (float) $marginTop ?? 0.3,
'marginBottom' => (float) $marginBottom ?? 0.3,
'marginHeader' => (float) $marginHeader ?? 0.45,
'marginFooter' => (float) $marginFooter ?? 0.45,
];
}
}
private function readStyleMasterLookup(DOMDocument $styleDom): void
{
$styleMasterLookup = $styleDom->getElementsByTagNameNS($this->officeNs, 'master-styles')
->item(0)
->getElementsByTagNameNS($this->stylesNs, 'master-page');
foreach ($styleMasterLookup as $styleMasterSet) {
$styleMasterName = $styleMasterSet->getAttributeNS($this->stylesNs, 'name');
$pageLayoutName = $styleMasterSet->getAttributeNS($this->stylesNs, 'page-layout-name');
$this->masterPrintStylesCrossReference[$styleMasterName] = $pageLayoutName;
}
}
public function readStyleCrossReferences(DOMDocument $contentDom): void
{
$styleXReferences = $contentDom->getElementsByTagNameNS($this->officeNs, 'automatic-styles')
->item(0)
->getElementsByTagNameNS($this->stylesNs, 'style');
foreach ($styleXReferences as $styleXreferenceSet) {
$styleXRefName = $styleXreferenceSet->getAttributeNS($this->stylesNs, 'name');
$stylePageLayoutName = $styleXreferenceSet->getAttributeNS($this->stylesNs, 'master-page-name');
if (!empty($stylePageLayoutName)) {
$this->masterStylesCrossReference[$styleXRefName] = $stylePageLayoutName;
}
}
}
public function setPrintSettingsForWorksheet(Worksheet $worksheet, string $styleName): void
{
if (!array_key_exists($styleName, $this->masterStylesCrossReference)) {
return;
}
$masterStyleName = $this->masterStylesCrossReference[$styleName];
if (!array_key_exists($masterStyleName, $this->masterPrintStylesCrossReference)) {
return;
}
$printSettingsIndex = $this->masterPrintStylesCrossReference[$masterStyleName];
if (!array_key_exists($printSettingsIndex, $this->pageLayoutStyles)) {
return;
}
$printSettings = $this->pageLayoutStyles[$printSettingsIndex];
$worksheet->getPageSetup()
->setOrientation($printSettings->orientation ?? PageSetup::ORIENTATION_DEFAULT)
->setPageOrder($printSettings->printOrder === 'ltr' ? PageSetup::PAGEORDER_OVER_THEN_DOWN : PageSetup::PAGEORDER_DOWN_THEN_OVER)
->setScale((int) trim($printSettings->scale, '%'))
->setHorizontalCentered($printSettings->horizontalCentered)
->setVerticalCentered($printSettings->verticalCentered);
$worksheet->getPageMargins()
->setLeft($printSettings->marginLeft)
->setRight($printSettings->marginRight)
->setTop($printSettings->marginTop)
->setBottom($printSettings->marginBottom)
->setHeader($printSettings->marginHeader)
->setFooter($printSettings->marginFooter);
}
}

View File

@@ -0,0 +1,132 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Reader\Ods;
use PhpOffice\PhpSpreadsheet\Document\Properties as DocumentProperties;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use SimpleXMLElement;
class Properties
{
private $spreadsheet;
public function __construct(Spreadsheet $spreadsheet)
{
$this->spreadsheet = $spreadsheet;
}
public function load(SimpleXMLElement $xml, $namespacesMeta): void
{
$docProps = $this->spreadsheet->getProperties();
$officeProperty = $xml->children($namespacesMeta['office']);
foreach ($officeProperty as $officePropertyData) {
// @var \SimpleXMLElement $officePropertyData
if (isset($namespacesMeta['dc'])) {
$officePropertiesDC = $officePropertyData->children($namespacesMeta['dc']);
$this->setCoreProperties($docProps, $officePropertiesDC);
}
$officePropertyMeta = (object) [];
if (isset($namespacesMeta['dc'])) {
$officePropertyMeta = $officePropertyData->children($namespacesMeta['meta']);
}
foreach ($officePropertyMeta as $propertyName => $propertyValue) {
$this->setMetaProperties($namespacesMeta, $propertyValue, $propertyName, $docProps);
}
}
}
private function setCoreProperties(DocumentProperties $docProps, SimpleXMLElement $officePropertyDC): void
{
foreach ($officePropertyDC as $propertyName => $propertyValue) {
$propertyValue = (string) $propertyValue;
switch ($propertyName) {
case 'title':
$docProps->setTitle($propertyValue);
break;
case 'subject':
$docProps->setSubject($propertyValue);
break;
case 'creator':
$docProps->setCreator($propertyValue);
$docProps->setLastModifiedBy($propertyValue);
break;
case 'date':
$creationDate = strtotime($propertyValue);
$docProps->setCreated($creationDate);
$docProps->setModified($creationDate);
break;
case 'description':
$docProps->setDescription($propertyValue);
break;
}
}
}
private function setMetaProperties(
$namespacesMeta,
SimpleXMLElement $propertyValue,
$propertyName,
DocumentProperties $docProps
): void {
$propertyValueAttributes = $propertyValue->attributes($namespacesMeta['meta']);
$propertyValue = (string) $propertyValue;
switch ($propertyName) {
case 'initial-creator':
$docProps->setCreator($propertyValue);
break;
case 'keyword':
$docProps->setKeywords($propertyValue);
break;
case 'creation-date':
$creationDate = strtotime($propertyValue);
$docProps->setCreated($creationDate);
break;
case 'user-defined':
$this->setUserDefinedProperty($propertyValueAttributes, $propertyValue, $docProps);
break;
}
}
private function setUserDefinedProperty($propertyValueAttributes, $propertyValue, DocumentProperties $docProps): void
{
$propertyValueName = '';
$propertyValueType = DocumentProperties::PROPERTY_TYPE_STRING;
foreach ($propertyValueAttributes as $key => $value) {
if ($key == 'name') {
$propertyValueName = (string) $value;
} elseif ($key == 'value-type') {
switch ($value) {
case 'date':
$propertyValue = DocumentProperties::convertProperty($propertyValue, 'date');
$propertyValueType = DocumentProperties::PROPERTY_TYPE_DATE;
break;
case 'boolean':
$propertyValue = DocumentProperties::convertProperty($propertyValue, 'bool');
$propertyValueType = DocumentProperties::PROPERTY_TYPE_BOOLEAN;
break;
case 'float':
$propertyValue = DocumentProperties::convertProperty($propertyValue, 'r4');
$propertyValueType = DocumentProperties::PROPERTY_TYPE_FLOAT;
break;
default:
$propertyValueType = DocumentProperties::PROPERTY_TYPE_STRING;
}
}
}
$docProps->setCustomProperty($propertyValueName, $propertyValue, $propertyValueType);
}
}

View File

@@ -0,0 +1,150 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Reader\Security;
use PhpOffice\PhpSpreadsheet\Reader;
use PhpOffice\PhpSpreadsheet\Settings;
class XmlScanner
{
/**
* String used to identify risky xml elements.
*
* @var string
*/
private $pattern;
private $callback;
private static $libxmlDisableEntityLoaderValue;
public function __construct($pattern = '<!DOCTYPE')
{
$this->pattern = $pattern;
$this->disableEntityLoaderCheck();
// A fatal error will bypass the destructor, so we register a shutdown here
register_shutdown_function([__CLASS__, 'shutdown']);
}
public static function getInstance(Reader\IReader $reader)
{
switch (true) {
case $reader instanceof Reader\Html:
return new self('<!ENTITY');
case $reader instanceof Reader\Xlsx:
case $reader instanceof Reader\Xml:
case $reader instanceof Reader\Ods:
case $reader instanceof Reader\Gnumeric:
return new self('<!DOCTYPE');
default:
return new self('<!DOCTYPE');
}
}
public static function threadSafeLibxmlDisableEntityLoaderAvailability()
{
if (PHP_MAJOR_VERSION == 7) {
switch (PHP_MINOR_VERSION) {
case 2:
return PHP_RELEASE_VERSION >= 1;
case 1:
return PHP_RELEASE_VERSION >= 13;
case 0:
return PHP_RELEASE_VERSION >= 27;
}
return true;
}
return false;
}
private function disableEntityLoaderCheck(): void
{
if (Settings::getLibXmlDisableEntityLoader() && \PHP_VERSION_ID < 80000) {
$libxmlDisableEntityLoaderValue = libxml_disable_entity_loader(true);
if (self::$libxmlDisableEntityLoaderValue === null) {
self::$libxmlDisableEntityLoaderValue = $libxmlDisableEntityLoaderValue;
}
}
}
public static function shutdown(): void
{
if (self::$libxmlDisableEntityLoaderValue !== null && \PHP_VERSION_ID < 80000) {
libxml_disable_entity_loader(self::$libxmlDisableEntityLoaderValue);
self::$libxmlDisableEntityLoaderValue = null;
}
}
public function __destruct()
{
self::shutdown();
}
public function setAdditionalCallback(callable $callback): void
{
$this->callback = $callback;
}
private function toUtf8($xml)
{
$pattern = '/encoding="(.*?)"/';
$result = preg_match($pattern, $xml, $matches);
$charset = strtoupper($result ? $matches[1] : 'UTF-8');
if ($charset !== 'UTF-8') {
$xml = mb_convert_encoding($xml, 'UTF-8', $charset);
$result = preg_match($pattern, $xml, $matches);
$charset = strtoupper($result ? $matches[1] : 'UTF-8');
if ($charset !== 'UTF-8') {
throw new Reader\Exception('Suspicious Double-encoded XML, spreadsheet file load() aborted to prevent XXE/XEE attacks');
}
}
return $xml;
}
/**
* Scan the XML for use of <!ENTITY to prevent XXE/XEE attacks.
*
* @param mixed $xml
*
* @return string
*/
public function scan($xml)
{
$this->disableEntityLoaderCheck();
$xml = $this->toUtf8($xml);
// Don't rely purely on libxml_disable_entity_loader()
$pattern = '/\\0?' . implode('\\0?', str_split($this->pattern)) . '\\0?/';
if (preg_match($pattern, $xml)) {
throw new Reader\Exception('Detected use of ENTITY in XML, spreadsheet file load() aborted to prevent XXE/XEE attacks');
}
if ($this->callback !== null && is_callable($this->callback)) {
$xml = call_user_func($this->callback, $xml);
}
return $xml;
}
/**
* Scan theXML for use of <!ENTITY to prevent XXE/XEE attacks.
*
* @param string $filestream
*
* @return string
*/
public function scanFile($filestream)
{
return $this->scan(file_get_contents($filestream));
}
}

View File

@@ -0,0 +1,591 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Reader;
use InvalidArgumentException;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Exception as ReaderException;
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
class Slk extends BaseReader
{
/**
* Input encoding.
*
* @var string
*/
private $inputEncoding = 'ANSI';
/**
* Sheet index to read.
*
* @var int
*/
private $sheetIndex = 0;
/**
* Formats.
*
* @var array
*/
private $formats = [];
/**
* Format Count.
*
* @var int
*/
private $format = 0;
/**
* Fonts.
*
* @var array
*/
private $fonts = [];
/**
* Font Count.
*
* @var int
*/
private $fontcount = 0;
/**
* Create a new SYLK Reader instance.
*/
public function __construct()
{
parent::__construct();
}
/**
* Validate that the current file is a SYLK file.
*
* @param string $pFilename
*
* @return bool
*/
public function canRead($pFilename)
{
try {
$this->openFile($pFilename);
} catch (InvalidArgumentException $e) {
return false;
}
// Read sample data (first 2 KB will do)
$data = fread($this->fileHandle, 2048);
// Count delimiters in file
$delimiterCount = substr_count($data, ';');
$hasDelimiter = $delimiterCount > 0;
// Analyze first line looking for ID; signature
$lines = explode("\n", $data);
$hasId = substr($lines[0], 0, 4) === 'ID;P';
fclose($this->fileHandle);
return $hasDelimiter && $hasId;
}
private function canReadOrBust(string $pFilename): void
{
if (!$this->canRead($pFilename)) {
throw new ReaderException($pFilename . ' is an Invalid SYLK file.');
}
$this->openFile($pFilename);
}
/**
* Set input encoding.
*
* @deprecated no use is made of this property
*
* @param string $pValue Input encoding, eg: 'ANSI'
*
* @return $this
*
* @codeCoverageIgnore
*/
public function setInputEncoding($pValue)
{
$this->inputEncoding = $pValue;
return $this;
}
/**
* Get input encoding.
*
* @deprecated no use is made of this property
*
* @return string
*
* @codeCoverageIgnore
*/
public function getInputEncoding()
{
return $this->inputEncoding;
}
/**
* Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns).
*
* @param string $pFilename
*
* @return array
*/
public function listWorksheetInfo($pFilename)
{
// Open file
$this->canReadOrBust($pFilename);
$fileHandle = $this->fileHandle;
rewind($fileHandle);
$worksheetInfo = [];
$worksheetInfo[0]['worksheetName'] = basename($pFilename, '.slk');
// loop through one row (line) at a time in the file
$rowIndex = 0;
$columnIndex = 0;
while (($rowData = fgets($fileHandle)) !== false) {
$columnIndex = 0;
// convert SYLK encoded $rowData to UTF-8
$rowData = StringHelper::SYLKtoUTF8($rowData);
// explode each row at semicolons while taking into account that literal semicolon (;)
// is escaped like this (;;)
$rowData = explode("\t", str_replace('¤', ';', str_replace(';', "\t", str_replace(';;', '¤', rtrim($rowData)))));
$dataType = array_shift($rowData);
if ($dataType == 'B') {
foreach ($rowData as $rowDatum) {
switch ($rowDatum[0]) {
case 'X':
$columnIndex = substr($rowDatum, 1) - 1;
break;
case 'Y':
$rowIndex = substr($rowDatum, 1);
break;
}
}
break;
}
}
$worksheetInfo[0]['lastColumnIndex'] = $columnIndex;
$worksheetInfo[0]['totalRows'] = $rowIndex;
$worksheetInfo[0]['lastColumnLetter'] = Coordinate::stringFromColumnIndex($worksheetInfo[0]['lastColumnIndex'] + 1);
$worksheetInfo[0]['totalColumns'] = $worksheetInfo[0]['lastColumnIndex'] + 1;
// Close file
fclose($fileHandle);
return $worksheetInfo;
}
/**
* Loads PhpSpreadsheet from file.
*
* @param string $pFilename
*
* @return Spreadsheet
*/
public function load($pFilename)
{
// Create new Spreadsheet
$spreadsheet = new Spreadsheet();
// Load into this instance
return $this->loadIntoExisting($pFilename, $spreadsheet);
}
private $colorArray = [
'FF00FFFF', // 0 - cyan
'FF000000', // 1 - black
'FFFFFFFF', // 2 - white
'FFFF0000', // 3 - red
'FF00FF00', // 4 - green
'FF0000FF', // 5 - blue
'FFFFFF00', // 6 - yellow
'FFFF00FF', // 7 - magenta
];
private $fontStyleMappings = [
'B' => 'bold',
'I' => 'italic',
'U' => 'underline',
];
private function processFormula(string $rowDatum, bool &$hasCalculatedValue, string &$cellDataFormula, string $row, string $column): void
{
$cellDataFormula = '=' . substr($rowDatum, 1);
// Convert R1C1 style references to A1 style references (but only when not quoted)
$temp = explode('"', $cellDataFormula);
$key = false;
foreach ($temp as &$value) {
// Only count/replace in alternate array entries
if ($key = !$key) {
preg_match_all('/(R(\[?-?\d*\]?))(C(\[?-?\d*\]?))/', $value, $cellReferences, PREG_SET_ORDER + PREG_OFFSET_CAPTURE);
// Reverse the matches array, otherwise all our offsets will become incorrect if we modify our way
// through the formula from left to right. Reversing means that we work right to left.through
// the formula
$cellReferences = array_reverse($cellReferences);
// Loop through each R1C1 style reference in turn, converting it to its A1 style equivalent,
// then modify the formula to use that new reference
foreach ($cellReferences as $cellReference) {
$rowReference = $cellReference[2][0];
// Empty R reference is the current row
if ($rowReference == '') {
$rowReference = $row;
}
// Bracketed R references are relative to the current row
if ($rowReference[0] == '[') {
$rowReference = $row + trim($rowReference, '[]');
}
$columnReference = $cellReference[4][0];
// Empty C reference is the current column
if ($columnReference == '') {
$columnReference = $column;
}
// Bracketed C references are relative to the current column
if ($columnReference[0] == '[') {
$columnReference = $column + trim($columnReference, '[]');
}
$A1CellReference = Coordinate::stringFromColumnIndex($columnReference) . $rowReference;
$value = substr_replace($value, $A1CellReference, $cellReference[0][1], strlen($cellReference[0][0]));
}
}
}
unset($value);
// Then rebuild the formula string
$cellDataFormula = implode('"', $temp);
$hasCalculatedValue = true;
}
private function processCRecord(array $rowData, Spreadsheet &$spreadsheet, string &$row, string &$column): void
{
// Read cell value data
$hasCalculatedValue = false;
$cellDataFormula = $cellData = '';
foreach ($rowData as $rowDatum) {
switch ($rowDatum[0]) {
case 'C':
case 'X':
$column = substr($rowDatum, 1);
break;
case 'R':
case 'Y':
$row = substr($rowDatum, 1);
break;
case 'K':
$cellData = substr($rowDatum, 1);
break;
case 'E':
$this->processFormula($rowDatum, $hasCalculatedValue, $cellDataFormula, $row, $column);
break;
}
}
$columnLetter = Coordinate::stringFromColumnIndex((int) $column);
$cellData = Calculation::unwrapResult($cellData);
// Set cell value
$this->processCFinal($spreadsheet, $hasCalculatedValue, $cellDataFormula, $cellData, "$columnLetter$row");
}
private function processCFinal(Spreadsheet &$spreadsheet, bool $hasCalculatedValue, string $cellDataFormula, string $cellData, string $coordinate): void
{
// Set cell value
$spreadsheet->getActiveSheet()->getCell($coordinate)->setValue(($hasCalculatedValue) ? $cellDataFormula : $cellData);
if ($hasCalculatedValue) {
$cellData = Calculation::unwrapResult($cellData);
$spreadsheet->getActiveSheet()->getCell($coordinate)->setCalculatedValue($cellData);
}
}
private function processFRecord(array $rowData, Spreadsheet &$spreadsheet, string &$row, string &$column): void
{
// Read cell formatting
$formatStyle = $columnWidth = '';
$startCol = $endCol = '';
$fontStyle = '';
$styleData = [];
foreach ($rowData as $rowDatum) {
switch ($rowDatum[0]) {
case 'C':
case 'X':
$column = substr($rowDatum, 1);
break;
case 'R':
case 'Y':
$row = substr($rowDatum, 1);
break;
case 'P':
$formatStyle = $rowDatum;
break;
case 'W':
[$startCol, $endCol, $columnWidth] = explode(' ', substr($rowDatum, 1));
break;
case 'S':
$this->styleSettings($rowDatum, $styleData, $fontStyle);
break;
}
}
$this->addFormats($spreadsheet, $formatStyle, $row, $column);
$this->addFonts($spreadsheet, $fontStyle, $row, $column);
$this->addStyle($spreadsheet, $styleData, $row, $column);
$this->addWidth($spreadsheet, $columnWidth, $startCol, $endCol);
}
private $styleSettingsFont = ['D' => 'bold', 'I' => 'italic'];
private $styleSettingsBorder = [
'B' => 'bottom',
'L' => 'left',
'R' => 'right',
'T' => 'top',
];
private function styleSettings(string $rowDatum, array &$styleData, string &$fontStyle): void
{
$styleSettings = substr($rowDatum, 1);
$iMax = strlen($styleSettings);
for ($i = 0; $i < $iMax; ++$i) {
$char = $styleSettings[$i];
if (array_key_exists($char, $this->styleSettingsFont)) {
$styleData['font'][$this->styleSettingsFont[$char]] = true;
} elseif (array_key_exists($char, $this->styleSettingsBorder)) {
$styleData['borders'][$this->styleSettingsBorder[$char]]['borderStyle'] = Border::BORDER_THIN;
} elseif ($char == 'S') {
$styleData['fill']['fillType'] = \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_PATTERN_GRAY125;
} elseif ($char == 'M') {
if (preg_match('/M([1-9]\\d*)/', $styleSettings, $matches)) {
$fontStyle = $matches[1];
}
}
}
}
private function addFormats(Spreadsheet &$spreadsheet, string $formatStyle, string $row, string $column): void
{
if ($formatStyle && $column > '' && $row > '') {
$columnLetter = Coordinate::stringFromColumnIndex((int) $column);
if (isset($this->formats[$formatStyle])) {
$spreadsheet->getActiveSheet()->getStyle($columnLetter . $row)->applyFromArray($this->formats[$formatStyle]);
}
}
}
private function addFonts(Spreadsheet &$spreadsheet, string $fontStyle, string $row, string $column): void
{
if ($fontStyle && $column > '' && $row > '') {
$columnLetter = Coordinate::stringFromColumnIndex((int) $column);
if (isset($this->fonts[$fontStyle])) {
$spreadsheet->getActiveSheet()->getStyle($columnLetter . $row)->applyFromArray($this->fonts[$fontStyle]);
}
}
}
private function addStyle(Spreadsheet &$spreadsheet, array $styleData, string $row, string $column): void
{
if ((!empty($styleData)) && $column > '' && $row > '') {
$columnLetter = Coordinate::stringFromColumnIndex($column);
$spreadsheet->getActiveSheet()->getStyle($columnLetter . $row)->applyFromArray($styleData);
}
}
private function addWidth(Spreadsheet $spreadsheet, string $columnWidth, string $startCol, string $endCol): void
{
if ($columnWidth > '') {
if ($startCol == $endCol) {
$startCol = Coordinate::stringFromColumnIndex((int) $startCol);
$spreadsheet->getActiveSheet()->getColumnDimension($startCol)->setWidth($columnWidth);
} else {
$startCol = Coordinate::stringFromColumnIndex($startCol);
$endCol = Coordinate::stringFromColumnIndex($endCol);
$spreadsheet->getActiveSheet()->getColumnDimension($startCol)->setWidth((float) $columnWidth);
do {
$spreadsheet->getActiveSheet()->getColumnDimension(++$startCol)->setWidth($columnWidth);
} while ($startCol != $endCol);
}
}
}
private function processPRecord(array $rowData, Spreadsheet &$spreadsheet): void
{
// Read shared styles
$formatArray = [];
$fromFormats = ['\-', '\ '];
$toFormats = ['-', ' '];
foreach ($rowData as $rowDatum) {
switch ($rowDatum[0]) {
case 'P':
$formatArray['numberFormat']['formatCode'] = str_replace($fromFormats, $toFormats, substr($rowDatum, 1));
break;
case 'E':
case 'F':
$formatArray['font']['name'] = substr($rowDatum, 1);
break;
case 'M':
$formatArray['font']['size'] = substr($rowDatum, 1) / 20;
break;
case 'L':
$this->processPColors($rowDatum, $formatArray);
break;
case 'S':
$this->processPFontStyles($rowDatum, $formatArray);
break;
}
}
$this->processPFinal($spreadsheet, $formatArray);
}
private function processPColors(string $rowDatum, array &$formatArray): void
{
if (preg_match('/L([1-9]\\d*)/', $rowDatum, $matches)) {
$fontColor = $matches[1] % 8;
$formatArray['font']['color']['argb'] = $this->colorArray[$fontColor];
}
}
private function processPFontStyles(string $rowDatum, array &$formatArray): void
{
$styleSettings = substr($rowDatum, 1);
$iMax = strlen($styleSettings);
for ($i = 0; $i < $iMax; ++$i) {
if (array_key_exists($styleSettings[$i], $this->fontStyleMappings)) {
$formatArray['font'][$this->fontStyleMappings[$styleSettings[$i]]] = true;
}
}
}
private function processPFinal(Spreadsheet &$spreadsheet, array $formatArray): void
{
if (array_key_exists('numberFormat', $formatArray)) {
$this->formats['P' . $this->format] = $formatArray;
++$this->format;
} elseif (array_key_exists('font', $formatArray)) {
++$this->fontcount;
$this->fonts[$this->fontcount] = $formatArray;
if ($this->fontcount === 1) {
$spreadsheet->getDefaultStyle()->applyFromArray($formatArray);
}
}
}
/**
* Loads PhpSpreadsheet from file into PhpSpreadsheet instance.
*
* @param string $pFilename
*
* @return Spreadsheet
*/
public function loadIntoExisting($pFilename, Spreadsheet $spreadsheet)
{
// Open file
$this->canReadOrBust($pFilename);
$fileHandle = $this->fileHandle;
rewind($fileHandle);
// Create new Worksheets
while ($spreadsheet->getSheetCount() <= $this->sheetIndex) {
$spreadsheet->createSheet();
}
$spreadsheet->setActiveSheetIndex($this->sheetIndex);
$spreadsheet->getActiveSheet()->setTitle(substr(basename($pFilename, '.slk'), 0, Worksheet::SHEET_TITLE_MAXIMUM_LENGTH));
// Loop through file
$column = $row = '';
// loop through one row (line) at a time in the file
while (($rowDataTxt = fgets($fileHandle)) !== false) {
// convert SYLK encoded $rowData to UTF-8
$rowDataTxt = StringHelper::SYLKtoUTF8($rowDataTxt);
// explode each row at semicolons while taking into account that literal semicolon (;)
// is escaped like this (;;)
$rowData = explode("\t", str_replace('¤', ';', str_replace(';', "\t", str_replace(';;', '¤', rtrim($rowDataTxt)))));
$dataType = array_shift($rowData);
if ($dataType == 'P') {
// Read shared styles
$this->processPRecord($rowData, $spreadsheet);
} elseif ($dataType == 'C') {
// Read cell value data
$this->processCRecord($rowData, $spreadsheet, $row, $column);
} elseif ($dataType == 'F') {
// Read cell formatting
$this->processFRecord($rowData, $spreadsheet, $row, $column);
} else {
$this->columnRowFromRowData($rowData, $column, $row);
}
}
// Close file
fclose($fileHandle);
// Return
return $spreadsheet;
}
private function columnRowFromRowData(array $rowData, string &$column, string &$row): void
{
foreach ($rowData as $rowDatum) {
$char0 = $rowDatum[0];
if ($char0 === 'X' || $char0 == 'C') {
$column = substr($rowDatum, 1);
} elseif ($char0 === 'Y' || $char0 == 'R') {
$row = substr($rowDatum, 1);
}
}
}
/**
* Get sheet index.
*
* @return int
*/
public function getSheetIndex()
{
return $this->sheetIndex;
}
/**
* Set sheet index.
*
* @param int $pValue Sheet index
*
* @return $this
*/
public function setSheetIndex($pValue)
{
$this->sheetIndex = $pValue;
return $this;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,36 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
class Color
{
/**
* Read color.
*
* @param int $color Indexed color
* @param array $palette Color palette
* @param int $version
*
* @return array RGB color value, example: ['rgb' => 'FF0000']
*/
public static function map($color, $palette, $version)
{
if ($color <= 0x07 || $color >= 0x40) {
// special built-in color
return Color\BuiltIn::lookup($color);
} elseif (isset($palette, $palette[$color - 8])) {
// palette color, color index 0x08 maps to pallete index 0
return $palette[$color - 8];
}
// default color table
if ($version == Xls::XLS_BIFF8) {
return Color\BIFF8::lookup($color);
}
// BIFF5
return Color\BIFF5::lookup($color);
}
}

View File

@@ -0,0 +1,81 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Reader\Xls\Color;
class BIFF5
{
protected static $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.
*
* @param int $color
*
* @return array
*/
public static function lookup($color)
{
if (isset(self::$map[$color])) {
return ['rgb' => self::$map[$color]];
}
return ['rgb' => '000000'];
}
}

View File

@@ -0,0 +1,81 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Reader\Xls\Color;
class BIFF8
{
protected static $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.
*
* @param int $color
*
* @return array
*/
public static function lookup($color)
{
if (isset(self::$map[$color])) {
return ['rgb' => self::$map[$color]];
}
return ['rgb' => '000000'];
}
}

View File

@@ -0,0 +1,35 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Reader\Xls\Color;
class BuiltIn
{
protected static $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
*/
public static function lookup($color)
{
if (isset(self::$map[$color])) {
return ['rgb' => self::$map[$color]];
}
return ['rgb' => '000000'];
}
}

View File

@@ -0,0 +1,32 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Reader\Xls;
class ErrorCode
{
protected static $map = [
0x00 => '#NULL!',
0x07 => '#DIV/0!',
0x0F => '#VALUE!',
0x17 => '#REF!',
0x1D => '#NAME?',
0x24 => '#NUM!',
0x2A => '#N/A',
];
/**
* Map error code, e.g. '#N/A'.
*
* @param int $code
*
* @return bool|string
*/
public static function lookup($code)
{
if (isset(self::$map[$code])) {
return self::$map[$code];
}
return false;
}
}

View File

@@ -0,0 +1,677 @@
<?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;
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).
*
* @var string
*/
private $data;
/**
* Size in bytes of the Escher stream data.
*
* @var int
*/
private $dataSize;
/**
* Current position of stream pointer in Escher stream data.
*
* @var int
*/
private $pos;
/**
* The object to be returned by the reader. Modified during load.
*
* @var BSE|BstoreContainer|DgContainer|DggContainer|\PhpOffice\PhpSpreadsheet\Shared\Escher|SpContainer|SpgrContainer
*/
private $object;
/**
* Create a new Escher instance.
*
* @param mixed $object
*/
public function __construct($object)
{
$this->object = $object;
}
/**
* Load Escher stream data. May be a partial Escher stream.
*
* @param string $data
*
* @return BSE|BstoreContainer|DgContainer|DggContainer|\PhpOffice\PhpSpreadsheet\Shared\Escher|SpContainer|SpgrContainer
*/
public function load($data)
{
$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);
switch ($fbt) {
case self::DGGCONTAINER:
$this->readDggContainer();
break;
case self::DGG:
$this->readDgg();
break;
case self::BSTORECONTAINER:
$this->readBstoreContainer();
break;
case self::BSE:
$this->readBSE();
break;
case self::BLIPJPEG:
$this->readBlipJPEG();
break;
case self::BLIPPNG:
$this->readBlipPNG();
break;
case self::OPT:
$this->readOPT();
break;
case self::TERTIARYOPT:
$this->readTertiaryOPT();
break;
case self::SPLITMENUCOLORS:
$this->readSplitMenuColors();
break;
case self::DGCONTAINER:
$this->readDgContainer();
break;
case self::DG:
$this->readDg();
break;
case self::SPGRCONTAINER:
$this->readSpgrContainer();
break;
case self::SPCONTAINER:
$this->readSpContainer();
break;
case self::SPGR:
$this->readSpgr();
break;
case self::SP:
$this->readSp();
break;
case self::CLIENTTEXTBOX:
$this->readClientTextbox();
break;
case self::CLIENTANCHOR:
$this->readClientAnchor();
break;
case self::CLIENTDATA:
$this->readClientData();
break;
default:
$this->readDefault();
break;
}
}
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->object->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->object->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->object->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->object->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->object->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->object->setDgContainer($dgContainer);
$reader = new self($dgContainer);
$escher = $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);
} else {
// SpgrContainer
$this->object->addChild($spgrContainer);
}
$reader = new self($spgrContainer);
$escher = $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->object->addChild($spContainer);
// move stream pointer to next record
$this->pos += 8 + $length;
// record is a container, read contents
$reader = new self($spContainer);
$escher = $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);
// set the start coordinates
$this->object->setStartCoordinates(Coordinate::stringFromColumnIndex($c1 + 1) . ($r1 + 1));
// set the start offsetX
$this->object->setStartOffsetX($startOffsetX);
// set the start offsetY
$this->object->setStartOffsetY($startOffsetY);
// set the end coordinates
$this->object->setEndCoordinates(Coordinate::stringFromColumnIndex($c2 + 1) . ($r2 + 1));
// set the end offsetX
$this->object->setEndOffsetX($endOffsetX);
// set the end offsetY
$this->object->setEndOffsetY($endOffsetY);
}
/**
* 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($data, $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;
}
$this->object->setOPT($opidOpid, $value);
}
}
}

View File

@@ -0,0 +1,184 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Reader\Xls;
class MD5
{
// Context
private $a;
private $b;
private $c;
private $d;
/**
* MD5 stream constructor.
*/
public function __construct()
{
$this->reset();
}
/**
* Reset the MD5 stream context.
*/
public function reset(): void
{
$this->a = 0x67452301;
$this->b = 0xEFCDAB89;
$this->c = 0x98BADCFE;
$this->d = 0x10325476;
}
/**
* Get MD5 stream context.
*
* @return string
*/
public function getContext()
{
$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($data): void
{
$words = array_values(unpack('V16', $data));
$A = $this->a;
$B = $this->b;
$C = $this->c;
$D = $this->d;
$F = ['self', 'f'];
$G = ['self', 'g'];
$H = ['self', 'h'];
$I = ['self', '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) & 0xffffffff;
$this->b = ($this->b + $B) & 0xffffffff;
$this->c = ($this->c + $C) & 0xffffffff;
$this->d = ($this->d + $D) & 0xffffffff;
}
private static function f($X, $Y, $Z)
{
return ($X & $Y) | ((~$X) & $Z); // X AND Y OR NOT X AND Z
}
private static function g($X, $Y, $Z)
{
return ($X & $Z) | ($Y & (~$Z)); // X AND Z OR Y AND NOT Z
}
private static function h($X, $Y, $Z)
{
return $X ^ $Y ^ $Z; // X XOR Y XOR Z
}
private static function i($X, $Y, $Z)
{
return $Y ^ ($X | (~$Z)); // Y XOR (X OR NOT Z)
}
private static function step($func, &$A, $B, $C, $D, $M, $s, $t): void
{
$A = ($A + call_user_func($func, $B, $C, $D) + $M + $t) & 0xffffffff;
$A = self::rotate($A, $s);
$A = ($B + $A) & 0xffffffff;
}
private static function rotate($decimal, $bits)
{
$binary = str_pad(decbin($decimal), 32, '0', STR_PAD_LEFT);
return bindec(substr($binary, $bits) . substr($binary, 0, $bits));
}
}

View File

@@ -0,0 +1,61 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Reader\Xls;
class RC4
{
// Context
protected $s = [];
protected $i = 0;
protected $j = 0;
/**
* RC4 stream decryption/encryption constrcutor.
*
* @param string $key Encryption key/passphrase
*/
public function __construct($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
*
* @return string
*/
public function RC4($data)
{
$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;
}
}

View File

@@ -0,0 +1,42 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Reader\Xls\Style;
use PhpOffice\PhpSpreadsheet\Style\Border as StyleBorder;
class Border
{
protected static $map = [
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,
];
/**
* Map border style
* OpenOffice documentation: 2.5.11.
*
* @param int $index
*
* @return string
*/
public static function lookup($index)
{
if (isset(self::$map[$index])) {
return self::$map[$index];
}
return StyleBorder::BORDER_NONE;
}
}

View File

@@ -0,0 +1,47 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Reader\Xls\Style;
use PhpOffice\PhpSpreadsheet\Style\Fill;
class FillPattern
{
protected static $map = [
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.
*
* @param int $index
*
* @return string
*/
public static function lookup($index)
{
if (isset(self::$map[$index])) {
return self::$map[$index];
}
return Fill::FILL_NONE;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,146 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column;
use PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use SimpleXMLElement;
class AutoFilter
{
private $worksheet;
private $worksheetXml;
public function __construct(Worksheet $workSheet, SimpleXMLElement $worksheetXml)
{
$this->worksheet = $workSheet;
$this->worksheetXml = $worksheetXml;
}
public function load(): void
{
// Remove all "$" in the auto filter range
$autoFilterRange = preg_replace('/\$/', '', $this->worksheetXml->autoFilter['ref']);
if (strpos($autoFilterRange, ':') !== false) {
$this->readAutoFilter($autoFilterRange, $this->worksheetXml);
}
}
private function readAutoFilter($autoFilterRange, $xmlSheet): void
{
$autoFilter = $this->worksheet->getAutoFilter();
$autoFilter->setRange($autoFilterRange);
foreach ($xmlSheet->autoFilter->filterColumn as $filterColumn) {
$column = $autoFilter->getColumnByOffset((int) $filterColumn['colId']);
// Check for standard filters
if ($filterColumn->filters) {
$column->setFilterType(Column::AUTOFILTER_FILTERTYPE_FILTER);
$filters = $filterColumn->filters;
if ((isset($filters['blank'])) && ($filters['blank'] == 1)) {
// Operator is undefined, but always treated as EQUAL
$column->createRule()->setRule(null, '')->setRuleType(Rule::AUTOFILTER_RULETYPE_FILTER);
}
// Standard filters are always an OR join, so no join rule needs to be set
// Entries can be either filter elements
foreach ($filters->filter as $filterRule) {
// Operator is undefined, but always treated as EQUAL
$column->createRule()->setRule(null, (string) $filterRule['val'])->setRuleType(Rule::AUTOFILTER_RULETYPE_FILTER);
}
// Or Date Group elements
$this->readDateRangeAutoFilter($filters, $column);
}
// Check for custom filters
$this->readCustomAutoFilter($filterColumn, $column);
// Check for dynamic filters
$this->readDynamicAutoFilter($filterColumn, $column);
// Check for dynamic filters
$this->readTopTenAutoFilter($filterColumn, $column);
}
}
private function readDateRangeAutoFilter(SimpleXMLElement $filters, Column $column): void
{
foreach ($filters->dateGroupItem as $dateGroupItem) {
// Operator is undefined, but always treated as EQUAL
$column->createRule()->setRule(
null,
[
'year' => (string) $dateGroupItem['year'],
'month' => (string) $dateGroupItem['month'],
'day' => (string) $dateGroupItem['day'],
'hour' => (string) $dateGroupItem['hour'],
'minute' => (string) $dateGroupItem['minute'],
'second' => (string) $dateGroupItem['second'],
],
(string) $dateGroupItem['dateTimeGrouping']
)->setRuleType(Rule::AUTOFILTER_RULETYPE_DATEGROUP);
}
}
private function readCustomAutoFilter(SimpleXMLElement $filterColumn, Column $column): void
{
if ($filterColumn->customFilters) {
$column->setFilterType(Column::AUTOFILTER_FILTERTYPE_CUSTOMFILTER);
$customFilters = $filterColumn->customFilters;
// Custom filters can an AND or an OR join;
// and there should only ever be one or two entries
if ((isset($customFilters['and'])) && ($customFilters['and'] == 1)) {
$column->setJoin(Column::AUTOFILTER_COLUMN_JOIN_AND);
}
foreach ($customFilters->customFilter as $filterRule) {
$column->createRule()->setRule(
(string) $filterRule['operator'],
(string) $filterRule['val']
)->setRuleType(Rule::AUTOFILTER_RULETYPE_CUSTOMFILTER);
}
}
}
private function readDynamicAutoFilter(SimpleXMLElement $filterColumn, Column $column): void
{
if ($filterColumn->dynamicFilter) {
$column->setFilterType(Column::AUTOFILTER_FILTERTYPE_DYNAMICFILTER);
// We should only ever have one dynamic filter
foreach ($filterColumn->dynamicFilter as $filterRule) {
// Operator is undefined, but always treated as EQUAL
$column->createRule()->setRule(
null,
(string) $filterRule['val'],
(string) $filterRule['type']
)->setRuleType(Rule::AUTOFILTER_RULETYPE_DYNAMICFILTER);
if (isset($filterRule['val'])) {
$column->setAttribute('val', (string) $filterRule['val']);
}
if (isset($filterRule['maxVal'])) {
$column->setAttribute('maxVal', (string) $filterRule['maxVal']);
}
}
}
}
private function readTopTenAutoFilter(SimpleXMLElement $filterColumn, Column $column): void
{
if ($filterColumn->top10) {
$column->setFilterType(Column::AUTOFILTER_FILTERTYPE_TOPTENFILTER);
// We should only ever have one top10 filter
foreach ($filterColumn->top10 as $filterRule) {
$column->createRule()->setRule(
(((isset($filterRule['percent'])) && ($filterRule['percent'] == 1))
? Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT
: Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_BY_VALUE
),
(string) $filterRule['val'],
(((isset($filterRule['top'])) && ($filterRule['top'] == 1))
? Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP
: Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_BOTTOM
)
)->setRuleType(Rule::AUTOFILTER_RULETYPE_TOPTENFILTER);
}
}
}
}

View File

@@ -0,0 +1,19 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx;
class BaseParserClass
{
protected static function boolean($value)
{
if (is_object($value)) {
$value = (string) $value;
}
if (is_numeric($value)) {
return (bool) $value;
}
return $value === strtolower('true');
}
}

View File

@@ -0,0 +1,567 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Calculation\Functions;
use PhpOffice\PhpSpreadsheet\Chart\DataSeries;
use PhpOffice\PhpSpreadsheet\Chart\DataSeriesValues;
use PhpOffice\PhpSpreadsheet\Chart\Layout;
use PhpOffice\PhpSpreadsheet\Chart\Legend;
use PhpOffice\PhpSpreadsheet\Chart\PlotArea;
use PhpOffice\PhpSpreadsheet\Chart\Title;
use PhpOffice\PhpSpreadsheet\RichText\RichText;
use PhpOffice\PhpSpreadsheet\Style\Color;
use PhpOffice\PhpSpreadsheet\Style\Font;
use SimpleXMLElement;
class Chart
{
/**
* @param string $name
* @param string $format
*
* @return null|bool|float|int|string
*/
private static function getAttribute(SimpleXMLElement $component, $name, $format)
{
$attributes = $component->attributes();
if (isset($attributes[$name])) {
if ($format == 'string') {
return (string) $attributes[$name];
} elseif ($format == 'integer') {
return (int) $attributes[$name];
} elseif ($format == 'boolean') {
return (bool) ($attributes[$name] === '0' || $attributes[$name] !== 'true') ? false : true;
}
return (float) $attributes[$name];
}
return null;
}
private static function readColor($color, $background = false)
{
if (isset($color['rgb'])) {
return (string) $color['rgb'];
} elseif (isset($color['indexed'])) {
return Color::indexedColor($color['indexed'] - 7, $background)->getARGB();
}
}
/**
* @param string $chartName
*
* @return \PhpOffice\PhpSpreadsheet\Chart\Chart
*/
public static function readChart(SimpleXMLElement $chartElements, $chartName)
{
$namespacesChartMeta = $chartElements->getNamespaces(true);
$chartElementsC = $chartElements->children($namespacesChartMeta['c']);
$XaxisLabel = $YaxisLabel = $legend = $title = null;
$dispBlanksAs = $plotVisOnly = null;
foreach ($chartElementsC as $chartElementKey => $chartElement) {
switch ($chartElementKey) {
case 'chart':
foreach ($chartElement as $chartDetailsKey => $chartDetails) {
$chartDetailsC = $chartDetails->children($namespacesChartMeta['c']);
switch ($chartDetailsKey) {
case 'plotArea':
$plotAreaLayout = $XaxisLable = $YaxisLable = null;
$plotSeries = $plotAttributes = [];
foreach ($chartDetails as $chartDetailKey => $chartDetail) {
switch ($chartDetailKey) {
case 'layout':
$plotAreaLayout = self::chartLayoutDetails($chartDetail, $namespacesChartMeta);
break;
case 'catAx':
if (isset($chartDetail->title)) {
$XaxisLabel = self::chartTitle($chartDetail->title->children($namespacesChartMeta['c']), $namespacesChartMeta);
}
break;
case 'dateAx':
if (isset($chartDetail->title)) {
$XaxisLabel = self::chartTitle($chartDetail->title->children($namespacesChartMeta['c']), $namespacesChartMeta);
}
break;
case 'valAx':
if (isset($chartDetail->title)) {
$YaxisLabel = self::chartTitle($chartDetail->title->children($namespacesChartMeta['c']), $namespacesChartMeta);
}
break;
case 'barChart':
case 'bar3DChart':
$barDirection = self::getAttribute($chartDetail->barDir, 'val', 'string');
$plotSer = self::chartDataSeries($chartDetail, $namespacesChartMeta, $chartDetailKey);
$plotSer->setPlotDirection($barDirection);
$plotSeries[] = $plotSer;
$plotAttributes = self::readChartAttributes($chartDetail);
break;
case 'lineChart':
case 'line3DChart':
$plotSeries[] = self::chartDataSeries($chartDetail, $namespacesChartMeta, $chartDetailKey);
$plotAttributes = self::readChartAttributes($chartDetail);
break;
case 'areaChart':
case 'area3DChart':
$plotSeries[] = self::chartDataSeries($chartDetail, $namespacesChartMeta, $chartDetailKey);
$plotAttributes = self::readChartAttributes($chartDetail);
break;
case 'doughnutChart':
case 'pieChart':
case 'pie3DChart':
$explosion = isset($chartDetail->ser->explosion);
$plotSer = self::chartDataSeries($chartDetail, $namespacesChartMeta, $chartDetailKey);
$plotSer->setPlotStyle($explosion);
$plotSeries[] = $plotSer;
$plotAttributes = self::readChartAttributes($chartDetail);
break;
case 'scatterChart':
$scatterStyle = self::getAttribute($chartDetail->scatterStyle, 'val', 'string');
$plotSer = self::chartDataSeries($chartDetail, $namespacesChartMeta, $chartDetailKey);
$plotSer->setPlotStyle($scatterStyle);
$plotSeries[] = $plotSer;
$plotAttributes = self::readChartAttributes($chartDetail);
break;
case 'bubbleChart':
$bubbleScale = self::getAttribute($chartDetail->bubbleScale, 'val', 'integer');
$plotSer = self::chartDataSeries($chartDetail, $namespacesChartMeta, $chartDetailKey);
$plotSer->setPlotStyle($bubbleScale);
$plotSeries[] = $plotSer;
$plotAttributes = self::readChartAttributes($chartDetail);
break;
case 'radarChart':
$radarStyle = self::getAttribute($chartDetail->radarStyle, 'val', 'string');
$plotSer = self::chartDataSeries($chartDetail, $namespacesChartMeta, $chartDetailKey);
$plotSer->setPlotStyle($radarStyle);
$plotSeries[] = $plotSer;
$plotAttributes = self::readChartAttributes($chartDetail);
break;
case 'surfaceChart':
case 'surface3DChart':
$wireFrame = self::getAttribute($chartDetail->wireframe, 'val', 'boolean');
$plotSer = self::chartDataSeries($chartDetail, $namespacesChartMeta, $chartDetailKey);
$plotSer->setPlotStyle($wireFrame);
$plotSeries[] = $plotSer;
$plotAttributes = self::readChartAttributes($chartDetail);
break;
case 'stockChart':
$plotSeries[] = self::chartDataSeries($chartDetail, $namespacesChartMeta, $chartDetailKey);
$plotAttributes = self::readChartAttributes($plotAreaLayout);
break;
}
}
if ($plotAreaLayout == null) {
$plotAreaLayout = new Layout();
}
$plotArea = new PlotArea($plotAreaLayout, $plotSeries);
self::setChartAttributes($plotAreaLayout, $plotAttributes);
break;
case 'plotVisOnly':
$plotVisOnly = self::getAttribute($chartDetails, 'val', 'string');
break;
case 'dispBlanksAs':
$dispBlanksAs = self::getAttribute($chartDetails, 'val', 'string');
break;
case 'title':
$title = self::chartTitle($chartDetails, $namespacesChartMeta);
break;
case 'legend':
$legendPos = 'r';
$legendLayout = null;
$legendOverlay = false;
foreach ($chartDetails as $chartDetailKey => $chartDetail) {
switch ($chartDetailKey) {
case 'legendPos':
$legendPos = self::getAttribute($chartDetail, 'val', 'string');
break;
case 'overlay':
$legendOverlay = self::getAttribute($chartDetail, 'val', 'boolean');
break;
case 'layout':
$legendLayout = self::chartLayoutDetails($chartDetail, $namespacesChartMeta);
break;
}
}
$legend = new Legend($legendPos, $legendLayout, $legendOverlay);
break;
}
}
}
}
$chart = new \PhpOffice\PhpSpreadsheet\Chart\Chart($chartName, $title, $legend, $plotArea, $plotVisOnly, $dispBlanksAs, $XaxisLabel, $YaxisLabel);
return $chart;
}
private static function chartTitle(SimpleXMLElement $titleDetails, array $namespacesChartMeta)
{
$caption = [];
$titleLayout = null;
foreach ($titleDetails as $titleDetailKey => $chartDetail) {
switch ($titleDetailKey) {
case 'tx':
$titleDetails = $chartDetail->rich->children($namespacesChartMeta['a']);
foreach ($titleDetails as $titleKey => $titleDetail) {
switch ($titleKey) {
case 'p':
$titleDetailPart = $titleDetail->children($namespacesChartMeta['a']);
$caption[] = self::parseRichText($titleDetailPart);
}
}
break;
case 'layout':
$titleLayout = self::chartLayoutDetails($chartDetail, $namespacesChartMeta);
break;
}
}
return new Title($caption, $titleLayout);
}
private static function chartLayoutDetails($chartDetail, $namespacesChartMeta)
{
if (!isset($chartDetail->manualLayout)) {
return null;
}
$details = $chartDetail->manualLayout->children($namespacesChartMeta['c']);
if ($details === null) {
return null;
}
$layout = [];
foreach ($details as $detailKey => $detail) {
$layout[$detailKey] = self::getAttribute($detail, 'val', 'string');
}
return new Layout($layout);
}
private static function chartDataSeries($chartDetail, $namespacesChartMeta, $plotType)
{
$multiSeriesType = null;
$smoothLine = false;
$seriesLabel = $seriesCategory = $seriesValues = $plotOrder = [];
$seriesDetailSet = $chartDetail->children($namespacesChartMeta['c']);
foreach ($seriesDetailSet as $seriesDetailKey => $seriesDetails) {
switch ($seriesDetailKey) {
case 'grouping':
$multiSeriesType = self::getAttribute($chartDetail->grouping, 'val', 'string');
break;
case 'ser':
$marker = null;
$seriesIndex = '';
foreach ($seriesDetails as $seriesKey => $seriesDetail) {
switch ($seriesKey) {
case 'idx':
$seriesIndex = self::getAttribute($seriesDetail, 'val', 'integer');
break;
case 'order':
$seriesOrder = self::getAttribute($seriesDetail, 'val', 'integer');
$plotOrder[$seriesIndex] = $seriesOrder;
break;
case 'tx':
$seriesLabel[$seriesIndex] = self::chartDataSeriesValueSet($seriesDetail, $namespacesChartMeta);
break;
case 'marker':
$marker = self::getAttribute($seriesDetail->symbol, 'val', 'string');
break;
case 'smooth':
$smoothLine = self::getAttribute($seriesDetail, 'val', 'boolean');
break;
case 'cat':
$seriesCategory[$seriesIndex] = self::chartDataSeriesValueSet($seriesDetail, $namespacesChartMeta);
break;
case 'val':
$seriesValues[$seriesIndex] = self::chartDataSeriesValueSet($seriesDetail, $namespacesChartMeta, $marker);
break;
case 'xVal':
$seriesCategory[$seriesIndex] = self::chartDataSeriesValueSet($seriesDetail, $namespacesChartMeta, $marker);
break;
case 'yVal':
$seriesValues[$seriesIndex] = self::chartDataSeriesValueSet($seriesDetail, $namespacesChartMeta, $marker);
break;
}
}
}
}
return new DataSeries($plotType, $multiSeriesType, $plotOrder, $seriesLabel, $seriesCategory, $seriesValues, $smoothLine);
}
private static function chartDataSeriesValueSet($seriesDetail, $namespacesChartMeta, $marker = null)
{
if (isset($seriesDetail->strRef)) {
$seriesSource = (string) $seriesDetail->strRef->f;
$seriesData = self::chartDataSeriesValues($seriesDetail->strRef->strCache->children($namespacesChartMeta['c']), 's');
return new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, $seriesSource, $seriesData['formatCode'], $seriesData['pointCount'], $seriesData['dataValues'], $marker);
} elseif (isset($seriesDetail->numRef)) {
$seriesSource = (string) $seriesDetail->numRef->f;
$seriesData = self::chartDataSeriesValues($seriesDetail->numRef->numCache->children($namespacesChartMeta['c']));
return new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, $seriesSource, $seriesData['formatCode'], $seriesData['pointCount'], $seriesData['dataValues'], $marker);
} elseif (isset($seriesDetail->multiLvlStrRef)) {
$seriesSource = (string) $seriesDetail->multiLvlStrRef->f;
$seriesData = self::chartDataSeriesValuesMultiLevel($seriesDetail->multiLvlStrRef->multiLvlStrCache->children($namespacesChartMeta['c']), 's');
$seriesData['pointCount'] = count($seriesData['dataValues']);
return new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, $seriesSource, $seriesData['formatCode'], $seriesData['pointCount'], $seriesData['dataValues'], $marker);
} elseif (isset($seriesDetail->multiLvlNumRef)) {
$seriesSource = (string) $seriesDetail->multiLvlNumRef->f;
$seriesData = self::chartDataSeriesValuesMultiLevel($seriesDetail->multiLvlNumRef->multiLvlNumCache->children($namespacesChartMeta['c']), 's');
$seriesData['pointCount'] = count($seriesData['dataValues']);
return new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, $seriesSource, $seriesData['formatCode'], $seriesData['pointCount'], $seriesData['dataValues'], $marker);
}
return null;
}
private static function chartDataSeriesValues($seriesValueSet, $dataType = 'n')
{
$seriesVal = [];
$formatCode = '';
$pointCount = 0;
foreach ($seriesValueSet as $seriesValueIdx => $seriesValue) {
switch ($seriesValueIdx) {
case 'ptCount':
$pointCount = self::getAttribute($seriesValue, 'val', 'integer');
break;
case 'formatCode':
$formatCode = (string) $seriesValue;
break;
case 'pt':
$pointVal = self::getAttribute($seriesValue, 'idx', 'integer');
if ($dataType == 's') {
$seriesVal[$pointVal] = (string) $seriesValue->v;
} elseif ($seriesValue->v === Functions::NA()) {
$seriesVal[$pointVal] = null;
} else {
$seriesVal[$pointVal] = (float) $seriesValue->v;
}
break;
}
}
return [
'formatCode' => $formatCode,
'pointCount' => $pointCount,
'dataValues' => $seriesVal,
];
}
private static function chartDataSeriesValuesMultiLevel($seriesValueSet, $dataType = 'n')
{
$seriesVal = [];
$formatCode = '';
$pointCount = 0;
foreach ($seriesValueSet->lvl as $seriesLevelIdx => $seriesLevel) {
foreach ($seriesLevel as $seriesValueIdx => $seriesValue) {
switch ($seriesValueIdx) {
case 'ptCount':
$pointCount = self::getAttribute($seriesValue, 'val', 'integer');
break;
case 'formatCode':
$formatCode = (string) $seriesValue;
break;
case 'pt':
$pointVal = self::getAttribute($seriesValue, 'idx', 'integer');
if ($dataType == 's') {
$seriesVal[$pointVal][] = (string) $seriesValue->v;
} elseif ($seriesValue->v === Functions::NA()) {
$seriesVal[$pointVal] = null;
} else {
$seriesVal[$pointVal][] = (float) $seriesValue->v;
}
break;
}
}
}
return [
'formatCode' => $formatCode,
'pointCount' => $pointCount,
'dataValues' => $seriesVal,
];
}
private static function parseRichText(SimpleXMLElement $titleDetailPart)
{
$value = new RichText();
$objText = null;
foreach ($titleDetailPart as $titleDetailElementKey => $titleDetailElement) {
if (isset($titleDetailElement->t)) {
$objText = $value->createTextRun((string) $titleDetailElement->t);
}
if (isset($titleDetailElement->rPr)) {
if (isset($titleDetailElement->rPr->rFont['val'])) {
$objText->getFont()->setName((string) $titleDetailElement->rPr->rFont['val']);
}
$fontSize = (self::getAttribute($titleDetailElement->rPr, 'sz', 'integer'));
if ($fontSize !== null) {
$objText->getFont()->setSize(floor($fontSize / 100));
}
$fontColor = (self::getAttribute($titleDetailElement->rPr, 'color', 'string'));
if ($fontColor !== null) {
$objText->getFont()->setColor(new Color(self::readColor($fontColor)));
}
$bold = self::getAttribute($titleDetailElement->rPr, 'b', 'boolean');
if ($bold !== null) {
$objText->getFont()->setBold($bold);
}
$italic = self::getAttribute($titleDetailElement->rPr, 'i', 'boolean');
if ($italic !== null) {
$objText->getFont()->setItalic($italic);
}
$baseline = self::getAttribute($titleDetailElement->rPr, 'baseline', 'integer');
if ($baseline !== null) {
if ($baseline > 0) {
$objText->getFont()->setSuperscript(true);
} elseif ($baseline < 0) {
$objText->getFont()->setSubscript(true);
}
}
$underscore = (self::getAttribute($titleDetailElement->rPr, 'u', 'string'));
if ($underscore !== null) {
if ($underscore == 'sng') {
$objText->getFont()->setUnderline(Font::UNDERLINE_SINGLE);
} elseif ($underscore == 'dbl') {
$objText->getFont()->setUnderline(Font::UNDERLINE_DOUBLE);
} else {
$objText->getFont()->setUnderline(Font::UNDERLINE_NONE);
}
}
$strikethrough = (self::getAttribute($titleDetailElement->rPr, 's', 'string'));
if ($strikethrough !== null) {
if ($strikethrough == 'noStrike') {
$objText->getFont()->setStrikethrough(false);
} else {
$objText->getFont()->setStrikethrough(true);
}
}
}
}
return $value;
}
private static function readChartAttributes($chartDetail)
{
$plotAttributes = [];
if (isset($chartDetail->dLbls)) {
if (isset($chartDetail->dLbls->howLegendKey)) {
$plotAttributes['showLegendKey'] = self::getAttribute($chartDetail->dLbls->showLegendKey, 'val', 'string');
}
if (isset($chartDetail->dLbls->showVal)) {
$plotAttributes['showVal'] = self::getAttribute($chartDetail->dLbls->showVal, 'val', 'string');
}
if (isset($chartDetail->dLbls->showCatName)) {
$plotAttributes['showCatName'] = self::getAttribute($chartDetail->dLbls->showCatName, 'val', 'string');
}
if (isset($chartDetail->dLbls->showSerName)) {
$plotAttributes['showSerName'] = self::getAttribute($chartDetail->dLbls->showSerName, 'val', 'string');
}
if (isset($chartDetail->dLbls->showPercent)) {
$plotAttributes['showPercent'] = self::getAttribute($chartDetail->dLbls->showPercent, 'val', 'string');
}
if (isset($chartDetail->dLbls->showBubbleSize)) {
$plotAttributes['showBubbleSize'] = self::getAttribute($chartDetail->dLbls->showBubbleSize, 'val', 'string');
}
if (isset($chartDetail->dLbls->showLeaderLines)) {
$plotAttributes['showLeaderLines'] = self::getAttribute($chartDetail->dLbls->showLeaderLines, 'val', 'string');
}
}
return $plotAttributes;
}
/**
* @param mixed $plotAttributes
*/
private static function setChartAttributes(Layout $plotArea, $plotAttributes): void
{
foreach ($plotAttributes as $plotAttributeKey => $plotAttributeValue) {
switch ($plotAttributeKey) {
case 'showLegendKey':
$plotArea->setShowLegendKey($plotAttributeValue);
break;
case 'showVal':
$plotArea->setShowVal($plotAttributeValue);
break;
case 'showCatName':
$plotArea->setShowCatName($plotAttributeValue);
break;
case 'showSerName':
$plotArea->setShowSerName($plotAttributeValue);
break;
case 'showPercent':
$plotArea->setShowPercent($plotAttributeValue);
break;
case 'showBubbleSize':
$plotArea->setShowBubbleSize($plotAttributeValue);
break;
case 'showLeaderLines':
$plotArea->setShowLeaderLines($plotAttributeValue);
break;
}
}
}
}

View File

@@ -0,0 +1,209 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\IReadFilter;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use SimpleXMLElement;
class ColumnAndRowAttributes extends BaseParserClass
{
private $worksheet;
private $worksheetXml;
public function __construct(Worksheet $workSheet, ?SimpleXMLElement $worksheetXml = null)
{
$this->worksheet = $workSheet;
$this->worksheetXml = $worksheetXml;
}
/**
* Set Worksheet column attributes by attributes array passed.
*
* @param string $columnAddress A, B, ... DX, ...
* @param array $columnAttributes array of attributes (indexes are attribute name, values are value)
* 'xfIndex', 'visible', 'collapsed', 'outlineLevel', 'width', ... ?
*/
private function setColumnAttributes($columnAddress, array $columnAttributes): void
{
if (isset($columnAttributes['xfIndex'])) {
$this->worksheet->getColumnDimension($columnAddress)->setXfIndex($columnAttributes['xfIndex']);
}
if (isset($columnAttributes['visible'])) {
$this->worksheet->getColumnDimension($columnAddress)->setVisible($columnAttributes['visible']);
}
if (isset($columnAttributes['collapsed'])) {
$this->worksheet->getColumnDimension($columnAddress)->setCollapsed($columnAttributes['collapsed']);
}
if (isset($columnAttributes['outlineLevel'])) {
$this->worksheet->getColumnDimension($columnAddress)->setOutlineLevel($columnAttributes['outlineLevel']);
}
if (isset($columnAttributes['width'])) {
$this->worksheet->getColumnDimension($columnAddress)->setWidth($columnAttributes['width']);
}
}
/**
* Set Worksheet row attributes by attributes array passed.
*
* @param int $rowNumber 1, 2, 3, ... 99, ...
* @param array $rowAttributes array of attributes (indexes are attribute name, values are value)
* 'xfIndex', 'visible', 'collapsed', 'outlineLevel', 'rowHeight', ... ?
*/
private function setRowAttributes($rowNumber, array $rowAttributes): void
{
if (isset($rowAttributes['xfIndex'])) {
$this->worksheet->getRowDimension($rowNumber)->setXfIndex($rowAttributes['xfIndex']);
}
if (isset($rowAttributes['visible'])) {
$this->worksheet->getRowDimension($rowNumber)->setVisible($rowAttributes['visible']);
}
if (isset($rowAttributes['collapsed'])) {
$this->worksheet->getRowDimension($rowNumber)->setCollapsed($rowAttributes['collapsed']);
}
if (isset($rowAttributes['outlineLevel'])) {
$this->worksheet->getRowDimension($rowNumber)->setOutlineLevel($rowAttributes['outlineLevel']);
}
if (isset($rowAttributes['rowHeight'])) {
$this->worksheet->getRowDimension($rowNumber)->setRowHeight($rowAttributes['rowHeight']);
}
}
/**
* @param IReadFilter $readFilter
* @param bool $readDataOnly
*/
public function load(?IReadFilter $readFilter = null, $readDataOnly = false): void
{
if ($this->worksheetXml === null) {
return;
}
$columnsAttributes = [];
$rowsAttributes = [];
if (isset($this->worksheetXml->cols)) {
$columnsAttributes = $this->readColumnAttributes($this->worksheetXml->cols, $readDataOnly);
}
if ($this->worksheetXml->sheetData && $this->worksheetXml->sheetData->row) {
$rowsAttributes = $this->readRowAttributes($this->worksheetXml->sheetData->row, $readDataOnly);
}
// set columns/rows attributes
$columnsAttributesAreSet = [];
foreach ($columnsAttributes as $columnCoordinate => $columnAttributes) {
if (
$readFilter === null ||
!$this->isFilteredColumn($readFilter, $columnCoordinate, $rowsAttributes)
) {
if (!isset($columnsAttributesAreSet[$columnCoordinate])) {
$this->setColumnAttributes($columnCoordinate, $columnAttributes);
$columnsAttributesAreSet[$columnCoordinate] = true;
}
}
}
$rowsAttributesAreSet = [];
foreach ($rowsAttributes as $rowCoordinate => $rowAttributes) {
if (
$readFilter === null ||
!$this->isFilteredRow($readFilter, $rowCoordinate, $columnsAttributes)
) {
if (!isset($rowsAttributesAreSet[$rowCoordinate])) {
$this->setRowAttributes($rowCoordinate, $rowAttributes);
$rowsAttributesAreSet[$rowCoordinate] = true;
}
}
}
}
private function isFilteredColumn(IReadFilter $readFilter, $columnCoordinate, array $rowsAttributes)
{
foreach ($rowsAttributes as $rowCoordinate => $rowAttributes) {
if (!$readFilter->readCell($columnCoordinate, $rowCoordinate, $this->worksheet->getTitle())) {
return true;
}
}
return false;
}
private function readColumnAttributes(SimpleXMLElement $worksheetCols, $readDataOnly)
{
$columnAttributes = [];
foreach ($worksheetCols->col as $column) {
$startColumn = Coordinate::stringFromColumnIndex((int) $column['min']);
$endColumn = Coordinate::stringFromColumnIndex((int) $column['max']);
++$endColumn;
for ($columnAddress = $startColumn; $columnAddress !== $endColumn; ++$columnAddress) {
$columnAttributes[$columnAddress] = $this->readColumnRangeAttributes($column, $readDataOnly);
if ((int) ($column['max']) == 16384) {
break;
}
}
}
return $columnAttributes;
}
private function readColumnRangeAttributes(SimpleXMLElement $column, $readDataOnly)
{
$columnAttributes = [];
if ($column['style'] && !$readDataOnly) {
$columnAttributes['xfIndex'] = (int) $column['style'];
}
if (self::boolean($column['hidden'])) {
$columnAttributes['visible'] = false;
}
if (self::boolean($column['collapsed'])) {
$columnAttributes['collapsed'] = true;
}
if (((int) $column['outlineLevel']) > 0) {
$columnAttributes['outlineLevel'] = (int) $column['outlineLevel'];
}
$columnAttributes['width'] = (float) $column['width'];
return $columnAttributes;
}
private function isFilteredRow(IReadFilter $readFilter, $rowCoordinate, array $columnsAttributes)
{
foreach ($columnsAttributes as $columnCoordinate => $columnAttributes) {
if (!$readFilter->readCell($columnCoordinate, $rowCoordinate, $this->worksheet->getTitle())) {
return true;
}
}
return false;
}
private function readRowAttributes(SimpleXMLElement $worksheetRow, $readDataOnly)
{
$rowAttributes = [];
foreach ($worksheetRow as $row) {
if ($row['ht'] && !$readDataOnly) {
$rowAttributes[(int) $row['r']]['rowHeight'] = (float) $row['ht'];
}
if (self::boolean($row['hidden'])) {
$rowAttributes[(int) $row['r']]['visible'] = false;
}
if (self::boolean($row['collapsed'])) {
$rowAttributes[(int) $row['r']]['collapsed'] = true;
}
if ((int) $row['outlineLevel'] > 0) {
$rowAttributes[(int) $row['r']]['outlineLevel'] = (int) $row['outlineLevel'];
}
if ($row['s'] && !$readDataOnly) {
$rowAttributes[(int) $row['r']]['xfIndex'] = (int) $row['s'];
}
}
return $rowAttributes;
}
}

View File

@@ -0,0 +1,97 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Style\Conditional;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use SimpleXMLElement;
class ConditionalStyles
{
private $worksheet;
private $worksheetXml;
private $dxfs;
public function __construct(Worksheet $workSheet, SimpleXMLElement $worksheetXml, array $dxfs = [])
{
$this->worksheet = $workSheet;
$this->worksheetXml = $worksheetXml;
$this->dxfs = $dxfs;
}
public function load(): void
{
$this->setConditionalStyles(
$this->worksheet,
$this->readConditionalStyles($this->worksheetXml)
);
}
private function readConditionalStyles($xmlSheet)
{
$conditionals = [];
foreach ($xmlSheet->conditionalFormatting as $conditional) {
foreach ($conditional->cfRule as $cfRule) {
if (
((string) $cfRule['type'] == Conditional::CONDITION_NONE
|| (string) $cfRule['type'] == Conditional::CONDITION_CELLIS
|| (string) $cfRule['type'] == Conditional::CONDITION_CONTAINSTEXT
|| (string) $cfRule['type'] == Conditional::CONDITION_CONTAINSBLANKS
|| (string) $cfRule['type'] == Conditional::CONDITION_NOTCONTAINSBLANKS
|| (string) $cfRule['type'] == Conditional::CONDITION_EXPRESSION)
&& isset($this->dxfs[(int) ($cfRule['dxfId'])])
) {
$conditionals[(string) $conditional['sqref']][(int) ($cfRule['priority'])] = $cfRule;
}
}
}
return $conditionals;
}
private function setConditionalStyles(Worksheet $worksheet, array $conditionals): void
{
foreach ($conditionals as $ref => $cfRules) {
ksort($cfRules);
$conditionalStyles = $this->readStyleRules($cfRules);
// Extract all cell references in $ref
$cellBlocks = explode(' ', str_replace('$', '', strtoupper($ref)));
foreach ($cellBlocks as $cellBlock) {
$worksheet->getStyle($cellBlock)->setConditionalStyles($conditionalStyles);
}
}
}
private function readStyleRules($cfRules)
{
$conditionalStyles = [];
foreach ($cfRules as $cfRule) {
$objConditional = new Conditional();
$objConditional->setConditionType((string) $cfRule['type']);
$objConditional->setOperatorType((string) $cfRule['operator']);
if ((string) $cfRule['text'] != '') {
$objConditional->setText((string) $cfRule['text']);
}
if (isset($cfRule['stopIfTrue']) && (int) $cfRule['stopIfTrue'] === 1) {
$objConditional->setStopIfTrue(true);
}
if (count($cfRule->formula) > 1) {
foreach ($cfRule->formula as $formula) {
$objConditional->addCondition((string) $formula);
}
} else {
$objConditional->addCondition((string) $cfRule->formula);
}
$objConditional->setStyle(clone $this->dxfs[(int) ($cfRule['dxfId'])]);
$conditionalStyles[] = $objConditional;
}
return $conditionalStyles;
}
}

View File

@@ -0,0 +1,51 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use SimpleXMLElement;
class DataValidations
{
private $worksheet;
private $worksheetXml;
public function __construct(Worksheet $workSheet, SimpleXMLElement $worksheetXml)
{
$this->worksheet = $workSheet;
$this->worksheetXml = $worksheetXml;
}
public function load(): void
{
foreach ($this->worksheetXml->dataValidations->dataValidation as $dataValidation) {
// Uppercase coordinate
$range = strtoupper($dataValidation['sqref']);
$rangeSet = explode(' ', $range);
foreach ($rangeSet as $range) {
$stRange = $this->worksheet->shrinkRangeToFit($range);
// Extract all cell references in $range
foreach (Coordinate::extractAllCellReferencesInRange($stRange) as $reference) {
// Create validation
$docValidation = $this->worksheet->getCell($reference)->getDataValidation();
$docValidation->setType((string) $dataValidation['type']);
$docValidation->setErrorStyle((string) $dataValidation['errorStyle']);
$docValidation->setOperator((string) $dataValidation['operator']);
$docValidation->setAllowBlank($dataValidation['allowBlank'] != 0);
$docValidation->setShowDropDown($dataValidation['showDropDown'] == 0);
$docValidation->setShowInputMessage($dataValidation['showInputMessage'] != 0);
$docValidation->setShowErrorMessage($dataValidation['showErrorMessage'] != 0);
$docValidation->setErrorTitle((string) $dataValidation['errorTitle']);
$docValidation->setError((string) $dataValidation['error']);
$docValidation->setPromptTitle((string) $dataValidation['promptTitle']);
$docValidation->setPrompt((string) $dataValidation['prompt']);
$docValidation->setFormula1((string) $dataValidation->formula1);
$docValidation->setFormula2((string) $dataValidation->formula2);
}
}
}
}
}

View File

@@ -0,0 +1,59 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use SimpleXMLElement;
class Hyperlinks
{
private $worksheet;
private $hyperlinks = [];
public function __construct(Worksheet $workSheet)
{
$this->worksheet = $workSheet;
}
public function readHyperlinks(SimpleXMLElement $relsWorksheet): void
{
foreach ($relsWorksheet->Relationship as $element) {
if ($element['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink') {
$this->hyperlinks[(string) $element['Id']] = (string) $element['Target'];
}
}
}
public function setHyperlinks(SimpleXMLElement $worksheetXml): void
{
foreach ($worksheetXml->hyperlink as $hyperlink) {
$this->setHyperlink($hyperlink, $this->worksheet);
}
}
private function setHyperlink(SimpleXMLElement $hyperlink, Worksheet $worksheet): void
{
// Link url
$linkRel = $hyperlink->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships');
foreach (Coordinate::extractAllCellReferencesInRange($hyperlink['ref']) as $cellReference) {
$cell = $worksheet->getCell($cellReference);
if (isset($linkRel['id'])) {
$hyperlinkUrl = $this->hyperlinks[(string) $linkRel['id']] ?? null;
if (isset($hyperlink['location'])) {
$hyperlinkUrl .= '#' . (string) $hyperlink['location'];
}
$cell->getHyperlink()->setUrl($hyperlinkUrl);
} elseif (isset($hyperlink['location'])) {
$cell->getHyperlink()->setUrl('sheet://' . (string) $hyperlink['location']);
}
// Tooltip
if (isset($hyperlink['tooltip'])) {
$cell->getHyperlink()->setTooltip((string) $hyperlink['tooltip']);
}
}
}
}

View File

@@ -0,0 +1,164 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use SimpleXMLElement;
class PageSetup extends BaseParserClass
{
private $worksheet;
private $worksheetXml;
public function __construct(Worksheet $workSheet, ?SimpleXMLElement $worksheetXml = null)
{
$this->worksheet = $workSheet;
$this->worksheetXml = $worksheetXml;
}
public function load(array $unparsedLoadedData)
{
if (!$this->worksheetXml) {
return $unparsedLoadedData;
}
$this->margins($this->worksheetXml, $this->worksheet);
$unparsedLoadedData = $this->pageSetup($this->worksheetXml, $this->worksheet, $unparsedLoadedData);
$this->headerFooter($this->worksheetXml, $this->worksheet);
$this->pageBreaks($this->worksheetXml, $this->worksheet);
return $unparsedLoadedData;
}
private function margins(SimpleXMLElement $xmlSheet, Worksheet $worksheet): void
{
if ($xmlSheet->pageMargins) {
$docPageMargins = $worksheet->getPageMargins();
$docPageMargins->setLeft((float) ($xmlSheet->pageMargins['left']));
$docPageMargins->setRight((float) ($xmlSheet->pageMargins['right']));
$docPageMargins->setTop((float) ($xmlSheet->pageMargins['top']));
$docPageMargins->setBottom((float) ($xmlSheet->pageMargins['bottom']));
$docPageMargins->setHeader((float) ($xmlSheet->pageMargins['header']));
$docPageMargins->setFooter((float) ($xmlSheet->pageMargins['footer']));
}
}
private function pageSetup(SimpleXMLElement $xmlSheet, Worksheet $worksheet, array $unparsedLoadedData)
{
if ($xmlSheet->pageSetup) {
$docPageSetup = $worksheet->getPageSetup();
if (isset($xmlSheet->pageSetup['orientation'])) {
$docPageSetup->setOrientation((string) $xmlSheet->pageSetup['orientation']);
}
if (isset($xmlSheet->pageSetup['paperSize'])) {
$docPageSetup->setPaperSize((int) ($xmlSheet->pageSetup['paperSize']));
}
if (isset($xmlSheet->pageSetup['scale'])) {
$docPageSetup->setScale((int) ($xmlSheet->pageSetup['scale']), false);
}
if (isset($xmlSheet->pageSetup['fitToHeight']) && (int) ($xmlSheet->pageSetup['fitToHeight']) >= 0) {
$docPageSetup->setFitToHeight((int) ($xmlSheet->pageSetup['fitToHeight']), false);
}
if (isset($xmlSheet->pageSetup['fitToWidth']) && (int) ($xmlSheet->pageSetup['fitToWidth']) >= 0) {
$docPageSetup->setFitToWidth((int) ($xmlSheet->pageSetup['fitToWidth']), false);
}
if (
isset($xmlSheet->pageSetup['firstPageNumber'], $xmlSheet->pageSetup['useFirstPageNumber']) &&
self::boolean((string) $xmlSheet->pageSetup['useFirstPageNumber'])
) {
$docPageSetup->setFirstPageNumber((int) ($xmlSheet->pageSetup['firstPageNumber']));
}
if (isset($xmlSheet->pageSetup['pageOrder'])) {
$docPageSetup->setPageOrder((string) $xmlSheet->pageSetup['pageOrder']);
}
$relAttributes = $xmlSheet->pageSetup->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships');
if (isset($relAttributes['id'])) {
$unparsedLoadedData['sheets'][$worksheet->getCodeName()]['pageSetupRelId'] = (string) $relAttributes['id'];
}
}
return $unparsedLoadedData;
}
private function headerFooter(SimpleXMLElement $xmlSheet, Worksheet $worksheet): void
{
if ($xmlSheet->headerFooter) {
$docHeaderFooter = $worksheet->getHeaderFooter();
if (
isset($xmlSheet->headerFooter['differentOddEven']) &&
self::boolean((string) $xmlSheet->headerFooter['differentOddEven'])
) {
$docHeaderFooter->setDifferentOddEven(true);
} else {
$docHeaderFooter->setDifferentOddEven(false);
}
if (
isset($xmlSheet->headerFooter['differentFirst']) &&
self::boolean((string) $xmlSheet->headerFooter['differentFirst'])
) {
$docHeaderFooter->setDifferentFirst(true);
} else {
$docHeaderFooter->setDifferentFirst(false);
}
if (
isset($xmlSheet->headerFooter['scaleWithDoc']) &&
!self::boolean((string) $xmlSheet->headerFooter['scaleWithDoc'])
) {
$docHeaderFooter->setScaleWithDocument(false);
} else {
$docHeaderFooter->setScaleWithDocument(true);
}
if (
isset($xmlSheet->headerFooter['alignWithMargins']) &&
!self::boolean((string) $xmlSheet->headerFooter['alignWithMargins'])
) {
$docHeaderFooter->setAlignWithMargins(false);
} else {
$docHeaderFooter->setAlignWithMargins(true);
}
$docHeaderFooter->setOddHeader((string) $xmlSheet->headerFooter->oddHeader);
$docHeaderFooter->setOddFooter((string) $xmlSheet->headerFooter->oddFooter);
$docHeaderFooter->setEvenHeader((string) $xmlSheet->headerFooter->evenHeader);
$docHeaderFooter->setEvenFooter((string) $xmlSheet->headerFooter->evenFooter);
$docHeaderFooter->setFirstHeader((string) $xmlSheet->headerFooter->firstHeader);
$docHeaderFooter->setFirstFooter((string) $xmlSheet->headerFooter->firstFooter);
}
}
private function pageBreaks(SimpleXMLElement $xmlSheet, Worksheet $worksheet): void
{
if ($xmlSheet->rowBreaks && $xmlSheet->rowBreaks->brk) {
$this->rowBreaks($xmlSheet, $worksheet);
}
if ($xmlSheet->colBreaks && $xmlSheet->colBreaks->brk) {
$this->columnBreaks($xmlSheet, $worksheet);
}
}
private function rowBreaks(SimpleXMLElement $xmlSheet, Worksheet $worksheet): void
{
foreach ($xmlSheet->rowBreaks->brk as $brk) {
if ($brk['man']) {
$worksheet->setBreak("A{$brk['id']}", Worksheet::BREAK_ROW);
}
}
}
private function columnBreaks(SimpleXMLElement $xmlSheet, Worksheet $worksheet): void
{
foreach ($xmlSheet->colBreaks->brk as $brk) {
if ($brk['man']) {
$worksheet->setBreak(
Coordinate::stringFromColumnIndex(((int) $brk['id']) + 1) . '1',
Worksheet::BREAK_COLUMN
);
}
}
}
}

View File

@@ -0,0 +1,92 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Document\Properties as DocumentProperties;
use PhpOffice\PhpSpreadsheet\Reader\Security\XmlScanner;
use PhpOffice\PhpSpreadsheet\Settings;
use SimpleXMLElement;
class Properties
{
private $securityScanner;
private $docProps;
public function __construct(XmlScanner $securityScanner, DocumentProperties $docProps)
{
$this->securityScanner = $securityScanner;
$this->docProps = $docProps;
}
private function extractPropertyData($propertyData)
{
return simplexml_load_string(
$this->securityScanner->scan($propertyData),
'SimpleXMLElement',
Settings::getLibXmlLoaderOptions()
);
}
public function readCoreProperties($propertyData): void
{
$xmlCore = $this->extractPropertyData($propertyData);
if (is_object($xmlCore)) {
$xmlCore->registerXPathNamespace('dc', 'http://purl.org/dc/elements/1.1/');
$xmlCore->registerXPathNamespace('dcterms', 'http://purl.org/dc/terms/');
$xmlCore->registerXPathNamespace('cp', 'http://schemas.openxmlformats.org/package/2006/metadata/core-properties');
$this->docProps->setCreator((string) self::getArrayItem($xmlCore->xpath('dc:creator')));
$this->docProps->setLastModifiedBy((string) self::getArrayItem($xmlCore->xpath('cp:lastModifiedBy')));
$this->docProps->setCreated(strtotime(self::getArrayItem($xmlCore->xpath('dcterms:created')))); //! respect xsi:type
$this->docProps->setModified(strtotime(self::getArrayItem($xmlCore->xpath('dcterms:modified')))); //! respect xsi:type
$this->docProps->setTitle((string) self::getArrayItem($xmlCore->xpath('dc:title')));
$this->docProps->setDescription((string) self::getArrayItem($xmlCore->xpath('dc:description')));
$this->docProps->setSubject((string) self::getArrayItem($xmlCore->xpath('dc:subject')));
$this->docProps->setKeywords((string) self::getArrayItem($xmlCore->xpath('cp:keywords')));
$this->docProps->setCategory((string) self::getArrayItem($xmlCore->xpath('cp:category')));
}
}
public function readExtendedProperties($propertyData): void
{
$xmlCore = $this->extractPropertyData($propertyData);
if (is_object($xmlCore)) {
if (isset($xmlCore->Company)) {
$this->docProps->setCompany((string) $xmlCore->Company);
}
if (isset($xmlCore->Manager)) {
$this->docProps->setManager((string) $xmlCore->Manager);
}
}
}
public function readCustomProperties($propertyData): void
{
$xmlCore = $this->extractPropertyData($propertyData);
if (is_object($xmlCore)) {
foreach ($xmlCore as $xmlProperty) {
/** @var SimpleXMLElement $xmlProperty */
$cellDataOfficeAttributes = $xmlProperty->attributes();
if (isset($cellDataOfficeAttributes['name'])) {
$propertyName = (string) $cellDataOfficeAttributes['name'];
$cellDataOfficeChildren = $xmlProperty->children('http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes');
$attributeType = $cellDataOfficeChildren->getName();
$attributeValue = (string) $cellDataOfficeChildren->{$attributeType};
$attributeValue = DocumentProperties::convertProperty($attributeValue, $attributeType);
$attributeType = DocumentProperties::convertPropertyType($attributeType);
$this->docProps->setCustomProperty($propertyName, $attributeValue, $attributeType);
}
}
}
}
private static function getArrayItem(array $array, $key = 0)
{
return $array[$key] ?? null;
}
}

View File

@@ -0,0 +1,135 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use SimpleXMLElement;
class SheetViewOptions extends BaseParserClass
{
private $worksheet;
private $worksheetXml;
public function __construct(Worksheet $workSheet, ?SimpleXMLElement $worksheetXml = null)
{
$this->worksheet = $workSheet;
$this->worksheetXml = $worksheetXml;
}
/**
* @param bool $readDataOnly
*/
public function load($readDataOnly = false): void
{
if ($this->worksheetXml === null) {
return;
}
if (isset($this->worksheetXml->sheetPr)) {
$this->tabColor($this->worksheetXml->sheetPr);
$this->codeName($this->worksheetXml->sheetPr);
$this->outlines($this->worksheetXml->sheetPr);
$this->pageSetup($this->worksheetXml->sheetPr);
}
if (isset($this->worksheetXml->sheetFormatPr)) {
$this->sheetFormat($this->worksheetXml->sheetFormatPr);
}
if (!$readDataOnly && isset($this->worksheetXml->printOptions)) {
$this->printOptions($this->worksheetXml->printOptions);
}
}
private function tabColor(SimpleXMLElement $sheetPr): void
{
if (isset($sheetPr->tabColor, $sheetPr->tabColor['rgb'])) {
$this->worksheet->getTabColor()->setARGB((string) $sheetPr->tabColor['rgb']);
}
}
private function codeName(SimpleXMLElement $sheetPr): void
{
if (isset($sheetPr['codeName'])) {
$this->worksheet->setCodeName((string) $sheetPr['codeName'], false);
}
}
private function outlines(SimpleXMLElement $sheetPr): void
{
if (isset($sheetPr->outlinePr)) {
if (
isset($sheetPr->outlinePr['summaryRight']) &&
!self::boolean((string) $sheetPr->outlinePr['summaryRight'])
) {
$this->worksheet->setShowSummaryRight(false);
} else {
$this->worksheet->setShowSummaryRight(true);
}
if (
isset($sheetPr->outlinePr['summaryBelow']) &&
!self::boolean((string) $sheetPr->outlinePr['summaryBelow'])
) {
$this->worksheet->setShowSummaryBelow(false);
} else {
$this->worksheet->setShowSummaryBelow(true);
}
}
}
private function pageSetup(SimpleXMLElement $sheetPr): void
{
if (isset($sheetPr->pageSetUpPr)) {
if (
isset($sheetPr->pageSetUpPr['fitToPage']) &&
!self::boolean((string) $sheetPr->pageSetUpPr['fitToPage'])
) {
$this->worksheet->getPageSetup()->setFitToPage(false);
} else {
$this->worksheet->getPageSetup()->setFitToPage(true);
}
}
}
private function sheetFormat(SimpleXMLElement $sheetFormatPr): void
{
if (
isset($sheetFormatPr['customHeight']) &&
self::boolean((string) $sheetFormatPr['customHeight']) &&
isset($sheetFormatPr['defaultRowHeight'])
) {
$this->worksheet->getDefaultRowDimension()
->setRowHeight((float) $sheetFormatPr['defaultRowHeight']);
}
if (isset($sheetFormatPr['defaultColWidth'])) {
$this->worksheet->getDefaultColumnDimension()
->setWidth((float) $sheetFormatPr['defaultColWidth']);
}
if (
isset($sheetFormatPr['zeroHeight']) &&
((string) $sheetFormatPr['zeroHeight'] === '1')
) {
$this->worksheet->getDefaultRowDimension()->setZeroHeight(true);
}
}
private function printOptions(SimpleXMLElement $printOptions): void
{
if (self::boolean((string) $printOptions['gridLinesSet'])) {
$this->worksheet->setShowGridlines(true);
}
if (self::boolean((string) $printOptions['gridLines'])) {
$this->worksheet->setPrintGridlines(true);
}
if (self::boolean((string) $printOptions['horizontalCentered'])) {
$this->worksheet->getPageSetup()->setHorizontalCentered(true);
}
if (self::boolean((string) $printOptions['verticalCentered'])) {
$this->worksheet->getPageSetup()->setVerticalCentered(true);
}
}
}

View File

@@ -0,0 +1,138 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use SimpleXMLElement;
class SheetViews extends BaseParserClass
{
private $sheetViewXml;
private $worksheet;
public function __construct(SimpleXMLElement $sheetViewXml, Worksheet $workSheet)
{
$this->sheetViewXml = $sheetViewXml;
$this->worksheet = $workSheet;
}
public function load(): void
{
$this->zoomScale();
$this->view();
$this->gridLines();
$this->headers();
$this->direction();
$this->showZeros();
if (isset($this->sheetViewXml->pane)) {
$this->pane();
}
if (isset($this->sheetViewXml->selection, $this->sheetViewXml->selection['sqref'])) {
$this->selection();
}
}
private function zoomScale(): void
{
if (isset($this->sheetViewXml['zoomScale'])) {
$zoomScale = (int) ($this->sheetViewXml['zoomScale']);
if ($zoomScale <= 0) {
// setZoomScale will throw an Exception if the scale is less than or equals 0
// that is OK when manually creating documents, but we should be able to read all documents
$zoomScale = 100;
}
$this->worksheet->getSheetView()->setZoomScale($zoomScale);
}
if (isset($this->sheetViewXml['zoomScaleNormal'])) {
$zoomScaleNormal = (int) ($this->sheetViewXml['zoomScaleNormal']);
if ($zoomScaleNormal <= 0) {
// setZoomScaleNormal will throw an Exception if the scale is less than or equals 0
// that is OK when manually creating documents, but we should be able to read all documents
$zoomScaleNormal = 100;
}
$this->worksheet->getSheetView()->setZoomScaleNormal($zoomScaleNormal);
}
}
private function view(): void
{
if (isset($this->sheetViewXml['view'])) {
$this->worksheet->getSheetView()->setView((string) $this->sheetViewXml['view']);
}
}
private function gridLines(): void
{
if (isset($this->sheetViewXml['showGridLines'])) {
$this->worksheet->setShowGridLines(
self::boolean((string) $this->sheetViewXml['showGridLines'])
);
}
}
private function headers(): void
{
if (isset($this->sheetViewXml['showRowColHeaders'])) {
$this->worksheet->setShowRowColHeaders(
self::boolean((string) $this->sheetViewXml['showRowColHeaders'])
);
}
}
private function direction(): void
{
if (isset($this->sheetViewXml['rightToLeft'])) {
$this->worksheet->setRightToLeft(
self::boolean((string) $this->sheetViewXml['rightToLeft'])
);
}
}
private function showZeros(): void
{
if (isset($this->sheetViewXml['showZeros'])) {
$this->worksheet->getSheetView()->setShowZeros(
self::boolean((string) $this->sheetViewXml['showZeros'])
);
}
}
private function pane(): void
{
$xSplit = 0;
$ySplit = 0;
$topLeftCell = null;
if (isset($this->sheetViewXml->pane['xSplit'])) {
$xSplit = (int) ($this->sheetViewXml->pane['xSplit']);
}
if (isset($this->sheetViewXml->pane['ySplit'])) {
$ySplit = (int) ($this->sheetViewXml->pane['ySplit']);
}
if (isset($this->sheetViewXml->pane['topLeftCell'])) {
$topLeftCell = (string) $this->sheetViewXml->pane['topLeftCell'];
}
$this->worksheet->freezePane(
Coordinate::stringFromColumnIndex($xSplit + 1) . ($ySplit + 1),
$topLeftCell
);
}
private function selection(): void
{
$sqref = (string) $this->sheetViewXml->selection['sqref'];
$sqref = explode(' ', $sqref);
$sqref = $sqref[0];
$this->worksheet->setSelectedCells($sqref);
}
}

View File

@@ -0,0 +1,282 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\Borders;
use PhpOffice\PhpSpreadsheet\Style\Color;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Style\Font;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use PhpOffice\PhpSpreadsheet\Style\Protection;
use PhpOffice\PhpSpreadsheet\Style\Style;
use SimpleXMLElement;
class Styles extends BaseParserClass
{
/**
* Theme instance.
*
* @var Theme
*/
private static $theme = null;
private $styles = [];
private $cellStyles = [];
private $styleXml;
public function __construct(SimpleXMLElement $styleXml)
{
$this->styleXml = $styleXml;
}
public function setStyleBaseData(?Theme $theme = null, $styles = [], $cellStyles = []): void
{
self::$theme = $theme;
$this->styles = $styles;
$this->cellStyles = $cellStyles;
}
private static function readFontStyle(Font $fontStyle, SimpleXMLElement $fontStyleXml): void
{
$fontStyle->setName((string) $fontStyleXml->name['val']);
$fontStyle->setSize((float) $fontStyleXml->sz['val']);
if (isset($fontStyleXml->b)) {
$fontStyle->setBold(!isset($fontStyleXml->b['val']) || self::boolean((string) $fontStyleXml->b['val']));
}
if (isset($fontStyleXml->i)) {
$fontStyle->setItalic(!isset($fontStyleXml->i['val']) || self::boolean((string) $fontStyleXml->i['val']));
}
if (isset($fontStyleXml->strike)) {
$fontStyle->setStrikethrough(!isset($fontStyleXml->strike['val']) || self::boolean((string) $fontStyleXml->strike['val']));
}
$fontStyle->getColor()->setARGB(self::readColor($fontStyleXml->color));
if (isset($fontStyleXml->u) && !isset($fontStyleXml->u['val'])) {
$fontStyle->setUnderline(Font::UNDERLINE_SINGLE);
} elseif (isset($fontStyleXml->u, $fontStyleXml->u['val'])) {
$fontStyle->setUnderline((string) $fontStyleXml->u['val']);
}
if (isset($fontStyleXml->vertAlign, $fontStyleXml->vertAlign['val'])) {
$verticalAlign = strtolower((string) $fontStyleXml->vertAlign['val']);
if ($verticalAlign === 'superscript') {
$fontStyle->setSuperscript(true);
}
if ($verticalAlign === 'subscript') {
$fontStyle->setSubscript(true);
}
}
}
private static function readNumberFormat(NumberFormat $numfmtStyle, SimpleXMLElement $numfmtStyleXml): void
{
if ($numfmtStyleXml->count() === 0) {
return;
}
$numfmt = $numfmtStyleXml->attributes();
if ($numfmt->count() > 0 && isset($numfmt['formatCode'])) {
$numfmtStyle->setFormatCode((string) $numfmt['formatCode']);
}
}
private static function readFillStyle(Fill $fillStyle, SimpleXMLElement $fillStyleXml): void
{
if ($fillStyleXml->gradientFill) {
/** @var SimpleXMLElement $gradientFill */
$gradientFill = $fillStyleXml->gradientFill[0];
if (!empty($gradientFill['type'])) {
$fillStyle->setFillType((string) $gradientFill['type']);
}
$fillStyle->setRotation((float) ($gradientFill['degree']));
$gradientFill->registerXPathNamespace('sml', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main');
$fillStyle->getStartColor()->setARGB(self::readColor(self::getArrayItem($gradientFill->xpath('sml:stop[@position=0]'))->color));
$fillStyle->getEndColor()->setARGB(self::readColor(self::getArrayItem($gradientFill->xpath('sml:stop[@position=1]'))->color));
} elseif ($fillStyleXml->patternFill) {
$patternType = (string) $fillStyleXml->patternFill['patternType'] != '' ? (string) $fillStyleXml->patternFill['patternType'] : 'solid';
$fillStyle->setFillType($patternType);
if ($fillStyleXml->patternFill->fgColor) {
$fillStyle->getStartColor()->setARGB(self::readColor($fillStyleXml->patternFill->fgColor, true));
} else {
$fillStyle->getStartColor()->setARGB('FF000000');
}
if ($fillStyleXml->patternFill->bgColor) {
$fillStyle->getEndColor()->setARGB(self::readColor($fillStyleXml->patternFill->bgColor, true));
}
}
}
private static function readBorderStyle(Borders $borderStyle, SimpleXMLElement $borderStyleXml): void
{
$diagonalUp = self::boolean((string) $borderStyleXml['diagonalUp']);
$diagonalDown = self::boolean((string) $borderStyleXml['diagonalDown']);
if (!$diagonalUp && !$diagonalDown) {
$borderStyle->setDiagonalDirection(Borders::DIAGONAL_NONE);
} elseif ($diagonalUp && !$diagonalDown) {
$borderStyle->setDiagonalDirection(Borders::DIAGONAL_UP);
} elseif (!$diagonalUp && $diagonalDown) {
$borderStyle->setDiagonalDirection(Borders::DIAGONAL_DOWN);
} else {
$borderStyle->setDiagonalDirection(Borders::DIAGONAL_BOTH);
}
self::readBorder($borderStyle->getLeft(), $borderStyleXml->left);
self::readBorder($borderStyle->getRight(), $borderStyleXml->right);
self::readBorder($borderStyle->getTop(), $borderStyleXml->top);
self::readBorder($borderStyle->getBottom(), $borderStyleXml->bottom);
self::readBorder($borderStyle->getDiagonal(), $borderStyleXml->diagonal);
}
private static function readBorder(Border $border, SimpleXMLElement $borderXml): void
{
if (isset($borderXml['style'])) {
$border->setBorderStyle((string) $borderXml['style']);
}
if (isset($borderXml->color)) {
$border->getColor()->setARGB(self::readColor($borderXml->color));
}
}
private static function readAlignmentStyle(Alignment $alignment, SimpleXMLElement $alignmentXml): void
{
$alignment->setHorizontal((string) $alignmentXml->alignment['horizontal']);
$alignment->setVertical((string) $alignmentXml->alignment['vertical']);
$textRotation = 0;
if ((int) $alignmentXml->alignment['textRotation'] <= 90) {
$textRotation = (int) $alignmentXml->alignment['textRotation'];
} elseif ((int) $alignmentXml->alignment['textRotation'] > 90) {
$textRotation = 90 - (int) $alignmentXml->alignment['textRotation'];
}
$alignment->setTextRotation((int) $textRotation);
$alignment->setWrapText(self::boolean((string) $alignmentXml->alignment['wrapText']));
$alignment->setShrinkToFit(self::boolean((string) $alignmentXml->alignment['shrinkToFit']));
$alignment->setIndent((int) ((string) $alignmentXml->alignment['indent']) > 0 ? (int) ((string) $alignmentXml->alignment['indent']) : 0);
$alignment->setReadOrder((int) ((string) $alignmentXml->alignment['readingOrder']) > 0 ? (int) ((string) $alignmentXml->alignment['readingOrder']) : 0);
}
private function readStyle(Style $docStyle, $style): void
{
if ($style->numFmt instanceof SimpleXMLElement) {
self::readNumberFormat($docStyle->getNumberFormat(), $style->numFmt);
} else {
$docStyle->getNumberFormat()->setFormatCode($style->numFmt);
}
if (isset($style->font)) {
self::readFontStyle($docStyle->getFont(), $style->font);
}
if (isset($style->fill)) {
self::readFillStyle($docStyle->getFill(), $style->fill);
}
if (isset($style->border)) {
self::readBorderStyle($docStyle->getBorders(), $style->border);
}
if (isset($style->alignment->alignment)) {
self::readAlignmentStyle($docStyle->getAlignment(), $style->alignment);
}
// protection
if (isset($style->protection)) {
$this->readProtectionLocked($docStyle, $style);
$this->readProtectionHidden($docStyle, $style);
}
// top-level style settings
if (isset($style->quotePrefix)) {
$docStyle->setQuotePrefix(true);
}
}
private function readProtectionLocked(Style $docStyle, $style): void
{
if (isset($style->protection['locked'])) {
if (self::boolean((string) $style->protection['locked'])) {
$docStyle->getProtection()->setLocked(Protection::PROTECTION_PROTECTED);
} else {
$docStyle->getProtection()->setLocked(Protection::PROTECTION_UNPROTECTED);
}
}
}
private function readProtectionHidden(Style $docStyle, $style): void
{
if (isset($style->protection['hidden'])) {
if (self::boolean((string) $style->protection['hidden'])) {
$docStyle->getProtection()->setHidden(Protection::PROTECTION_PROTECTED);
} else {
$docStyle->getProtection()->setHidden(Protection::PROTECTION_UNPROTECTED);
}
}
}
private static function readColor($color, $background = false)
{
if (isset($color['rgb'])) {
return (string) $color['rgb'];
} elseif (isset($color['indexed'])) {
return Color::indexedColor($color['indexed'] - 7, $background)->getARGB();
} elseif (isset($color['theme'])) {
if (self::$theme !== null) {
$returnColour = self::$theme->getColourByIndex((int) $color['theme']);
if (isset($color['tint'])) {
$tintAdjust = (float) $color['tint'];
$returnColour = Color::changeBrightness($returnColour, $tintAdjust);
}
return 'FF' . $returnColour;
}
}
return ($background) ? 'FFFFFFFF' : 'FF000000';
}
public function dxfs($readDataOnly = false)
{
$dxfs = [];
if (!$readDataOnly && $this->styleXml) {
// Conditional Styles
if ($this->styleXml->dxfs) {
foreach ($this->styleXml->dxfs->dxf as $dxf) {
$style = new Style(false, true);
$this->readStyle($style, $dxf);
$dxfs[] = $style;
}
}
// Cell Styles
if ($this->styleXml->cellStyles) {
foreach ($this->styleXml->cellStyles->cellStyle as $cellStyle) {
if ((int) ($cellStyle['builtinId']) == 0) {
if (isset($this->cellStyles[(int) ($cellStyle['xfId'])])) {
// Set default style
$style = new Style();
$this->readStyle($style, $this->cellStyles[(int) ($cellStyle['xfId'])]);
// normal style, currently not using it for anything
}
}
}
}
}
return $dxfs;
}
public function styles()
{
return $this->styles;
}
private static function getArrayItem($array, $key = 0)
{
return $array[$key] ?? null;
}
}

View File

@@ -0,0 +1,93 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx;
class Theme
{
/**
* Theme Name.
*
* @var string
*/
private $themeName;
/**
* Colour Scheme Name.
*
* @var string
*/
private $colourSchemeName;
/**
* Colour Map.
*
* @var array of string
*/
private $colourMap;
/**
* Create a new Theme.
*
* @param mixed $themeName
* @param mixed $colourSchemeName
* @param mixed $colourMap
*/
public function __construct($themeName, $colourSchemeName, $colourMap)
{
// Initialise values
$this->themeName = $themeName;
$this->colourSchemeName = $colourSchemeName;
$this->colourMap = $colourMap;
}
/**
* Get Theme Name.
*
* @return string
*/
public function getThemeName()
{
return $this->themeName;
}
/**
* Get colour Scheme Name.
*
* @return string
*/
public function getColourSchemeName()
{
return $this->colourSchemeName;
}
/**
* Get colour Map Value by Position.
*
* @param mixed $index
*
* @return string
*/
public function getColourByIndex($index)
{
if (isset($this->colourMap[$index])) {
return $this->colourMap[$index];
}
return null;
}
/**
* Implement PHP __clone to create a deep clone, not just a shallow copy.
*/
public function __clone()
{
$vars = get_object_vars($this);
foreach ($vars as $key => $value) {
if ((is_object($value)) && ($key != '_parent')) {
$this->$key = clone $value;
} else {
$this->$key = $value;
}
}
}
}

View File

@@ -0,0 +1,899 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Reader;
use PhpOffice\PhpSpreadsheet\Cell\AddressHelper;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\DefinedName;
use PhpOffice\PhpSpreadsheet\Document\Properties;
use PhpOffice\PhpSpreadsheet\Reader\Security\XmlScanner;
use PhpOffice\PhpSpreadsheet\Reader\Xml\PageSettings;
use PhpOffice\PhpSpreadsheet\RichText\RichText;
use PhpOffice\PhpSpreadsheet\Settings;
use PhpOffice\PhpSpreadsheet\Shared\Date;
use PhpOffice\PhpSpreadsheet\Shared\File;
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\Borders;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Style\Font;
use SimpleXMLElement;
/**
* Reader for SpreadsheetML, the XML schema for Microsoft Office Excel 2003.
*/
class Xml extends BaseReader
{
/**
* Formats.
*
* @var array
*/
protected $styles = [];
/**
* Create a new Excel2003XML Reader instance.
*/
public function __construct()
{
parent::__construct();
$this->securityScanner = XmlScanner::getInstance($this);
}
private $fileContents = '';
private static $mappings = [
'borderStyle' => [
'1continuous' => Border::BORDER_THIN,
'1dash' => Border::BORDER_DASHED,
'1dashdot' => Border::BORDER_DASHDOT,
'1dashdotdot' => Border::BORDER_DASHDOTDOT,
'1dot' => Border::BORDER_DOTTED,
'1double' => Border::BORDER_DOUBLE,
'2continuous' => Border::BORDER_MEDIUM,
'2dash' => Border::BORDER_MEDIUMDASHED,
'2dashdot' => Border::BORDER_MEDIUMDASHDOT,
'2dashdotdot' => Border::BORDER_MEDIUMDASHDOTDOT,
'2dot' => Border::BORDER_DOTTED,
'2double' => Border::BORDER_DOUBLE,
'3continuous' => Border::BORDER_THICK,
'3dash' => Border::BORDER_MEDIUMDASHED,
'3dashdot' => Border::BORDER_MEDIUMDASHDOT,
'3dashdotdot' => Border::BORDER_MEDIUMDASHDOTDOT,
'3dot' => Border::BORDER_DOTTED,
'3double' => Border::BORDER_DOUBLE,
],
'fillType' => [
'solid' => Fill::FILL_SOLID,
'gray75' => Fill::FILL_PATTERN_DARKGRAY,
'gray50' => Fill::FILL_PATTERN_MEDIUMGRAY,
'gray25' => Fill::FILL_PATTERN_LIGHTGRAY,
'gray125' => Fill::FILL_PATTERN_GRAY125,
'gray0625' => Fill::FILL_PATTERN_GRAY0625,
'horzstripe' => Fill::FILL_PATTERN_DARKHORIZONTAL, // horizontal stripe
'vertstripe' => Fill::FILL_PATTERN_DARKVERTICAL, // vertical stripe
'reversediagstripe' => Fill::FILL_PATTERN_DARKUP, // reverse diagonal stripe
'diagstripe' => Fill::FILL_PATTERN_DARKDOWN, // diagonal stripe
'diagcross' => Fill::FILL_PATTERN_DARKGRID, // diagoanl crosshatch
'thickdiagcross' => Fill::FILL_PATTERN_DARKTRELLIS, // thick diagonal crosshatch
'thinhorzstripe' => Fill::FILL_PATTERN_LIGHTHORIZONTAL,
'thinvertstripe' => Fill::FILL_PATTERN_LIGHTVERTICAL,
'thinreversediagstripe' => Fill::FILL_PATTERN_LIGHTUP,
'thindiagstripe' => Fill::FILL_PATTERN_LIGHTDOWN,
'thinhorzcross' => Fill::FILL_PATTERN_LIGHTGRID, // thin horizontal crosshatch
'thindiagcross' => Fill::FILL_PATTERN_LIGHTTRELLIS, // thin diagonal crosshatch
],
];
public static function xmlMappings(): array
{
return self::$mappings;
}
/**
* Can the current IReader read the file?
*
* @param string $pFilename
*
* @return bool
*/
public function canRead($pFilename)
{
// Office xmlns:o="urn:schemas-microsoft-com:office:office"
// Excel xmlns:x="urn:schemas-microsoft-com:office:excel"
// XML Spreadsheet xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
// Spreadsheet component xmlns:c="urn:schemas-microsoft-com:office:component:spreadsheet"
// XML schema xmlns:s="uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882"
// XML data type xmlns:dt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882"
// MS-persist recordset xmlns:rs="urn:schemas-microsoft-com:rowset"
// Rowset xmlns:z="#RowsetSchema"
//
$signature = [
'<?xml version="1.0"',
'<?mso-application progid="Excel.Sheet"?>',
];
// Open file
$data = file_get_contents($pFilename);
// Why?
//$data = str_replace("'", '"', $data); // fix headers with single quote
$valid = true;
foreach ($signature as $match) {
// every part of the signature must be present
if (strpos($data, $match) === false) {
$valid = false;
break;
}
}
// Retrieve charset encoding
if (preg_match('/<?xml.*encoding=[\'"](.*?)[\'"].*?>/m', $data, $matches)) {
$charSet = strtoupper($matches[1]);
if (1 == preg_match('/^ISO-8859-\d[\dL]?$/i', $charSet)) {
$data = StringHelper::convertEncoding($data, 'UTF-8', $charSet);
$data = preg_replace('/(<?xml.*encoding=[\'"]).*?([\'"].*?>)/um', '$1' . 'UTF-8' . '$2', $data, 1);
}
}
$this->fileContents = $data;
return $valid;
}
/**
* Check if the file is a valid SimpleXML.
*
* @param string $pFilename
*
* @return false|SimpleXMLElement
*/
public function trySimpleXMLLoadString($pFilename)
{
try {
$xml = simplexml_load_string(
$this->securityScanner->scan($this->fileContents ?: file_get_contents($pFilename)),
'SimpleXMLElement',
Settings::getLibXmlLoaderOptions()
);
} catch (\Exception $e) {
throw new Exception('Cannot load invalid XML file: ' . $pFilename, 0, $e);
}
$this->fileContents = '';
return $xml;
}
/**
* Reads names of the worksheets from a file, without parsing the whole file to a Spreadsheet object.
*
* @param string $pFilename
*
* @return array
*/
public function listWorksheetNames($pFilename)
{
File::assertFile($pFilename);
if (!$this->canRead($pFilename)) {
throw new Exception($pFilename . ' is an Invalid Spreadsheet file.');
}
$worksheetNames = [];
$xml = $this->trySimpleXMLLoadString($pFilename);
$namespaces = $xml->getNamespaces(true);
$xml_ss = $xml->children($namespaces['ss']);
foreach ($xml_ss->Worksheet as $worksheet) {
$worksheet_ss = $worksheet->attributes($namespaces['ss']);
$worksheetNames[] = (string) $worksheet_ss['Name'];
}
return $worksheetNames;
}
/**
* Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns).
*
* @param string $pFilename
*
* @return array
*/
public function listWorksheetInfo($pFilename)
{
File::assertFile($pFilename);
if (!$this->canRead($pFilename)) {
throw new Exception($pFilename . ' is an Invalid Spreadsheet file.');
}
$worksheetInfo = [];
$xml = $this->trySimpleXMLLoadString($pFilename);
$namespaces = $xml->getNamespaces(true);
$worksheetID = 1;
$xml_ss = $xml->children($namespaces['ss']);
foreach ($xml_ss->Worksheet as $worksheet) {
$worksheet_ss = $worksheet->attributes($namespaces['ss']);
$tmpInfo = [];
$tmpInfo['worksheetName'] = '';
$tmpInfo['lastColumnLetter'] = 'A';
$tmpInfo['lastColumnIndex'] = 0;
$tmpInfo['totalRows'] = 0;
$tmpInfo['totalColumns'] = 0;
$tmpInfo['worksheetName'] = "Worksheet_{$worksheetID}";
if (isset($worksheet_ss['Name'])) {
$tmpInfo['worksheetName'] = (string) $worksheet_ss['Name'];
}
if (isset($worksheet->Table->Row)) {
$rowIndex = 0;
foreach ($worksheet->Table->Row as $rowData) {
$columnIndex = 0;
$rowHasData = false;
foreach ($rowData->Cell as $cell) {
if (isset($cell->Data)) {
$tmpInfo['lastColumnIndex'] = max($tmpInfo['lastColumnIndex'], $columnIndex);
$rowHasData = true;
}
++$columnIndex;
}
++$rowIndex;
if ($rowHasData) {
$tmpInfo['totalRows'] = max($tmpInfo['totalRows'], $rowIndex);
}
}
}
$tmpInfo['lastColumnLetter'] = Coordinate::stringFromColumnIndex($tmpInfo['lastColumnIndex'] + 1);
$tmpInfo['totalColumns'] = $tmpInfo['lastColumnIndex'] + 1;
$worksheetInfo[] = $tmpInfo;
++$worksheetID;
}
return $worksheetInfo;
}
/**
* Loads Spreadsheet from file.
*
* @param string $pFilename
*
* @return Spreadsheet
*/
public function load($pFilename)
{
// Create new Spreadsheet
$spreadsheet = new Spreadsheet();
$spreadsheet->removeSheetByIndex(0);
// Load into this instance
return $this->loadIntoExisting($pFilename, $spreadsheet);
}
private static function identifyFixedStyleValue($styleList, &$styleAttributeValue)
{
$returnValue = false;
$styleAttributeValue = strtolower($styleAttributeValue);
foreach ($styleList as $style) {
if ($styleAttributeValue == strtolower($style)) {
$styleAttributeValue = $style;
$returnValue = true;
break;
}
}
return $returnValue;
}
protected static function hex2str($hex)
{
return mb_chr((int) hexdec($hex[1]), 'UTF-8');
}
/**
* Loads from file into Spreadsheet instance.
*
* @param string $pFilename
*
* @return Spreadsheet
*/
public function loadIntoExisting($pFilename, Spreadsheet $spreadsheet)
{
File::assertFile($pFilename);
if (!$this->canRead($pFilename)) {
throw new Exception($pFilename . ' is an Invalid Spreadsheet file.');
}
$xml = $this->trySimpleXMLLoadString($pFilename);
$namespaces = $xml->getNamespaces(true);
$docProps = $spreadsheet->getProperties();
if (isset($xml->DocumentProperties[0])) {
foreach ($xml->DocumentProperties[0] as $propertyName => $propertyValue) {
$stringValue = (string) $propertyValue;
switch ($propertyName) {
case 'Title':
$docProps->setTitle($stringValue);
break;
case 'Subject':
$docProps->setSubject($stringValue);
break;
case 'Author':
$docProps->setCreator($stringValue);
break;
case 'Created':
$creationDate = strtotime($stringValue);
$docProps->setCreated($creationDate);
break;
case 'LastAuthor':
$docProps->setLastModifiedBy($stringValue);
break;
case 'LastSaved':
$lastSaveDate = strtotime($stringValue);
$docProps->setModified($lastSaveDate);
break;
case 'Company':
$docProps->setCompany($stringValue);
break;
case 'Category':
$docProps->setCategory($stringValue);
break;
case 'Manager':
$docProps->setManager($stringValue);
break;
case 'Keywords':
$docProps->setKeywords($stringValue);
break;
case 'Description':
$docProps->setDescription($stringValue);
break;
}
}
}
if (isset($xml->CustomDocumentProperties)) {
foreach ($xml->CustomDocumentProperties[0] as $propertyName => $propertyValue) {
$propertyAttributes = $propertyValue->attributes($namespaces['dt']);
$propertyName = preg_replace_callback('/_x([0-9a-f]{4})_/i', ['self', 'hex2str'], $propertyName);
$propertyType = Properties::PROPERTY_TYPE_UNKNOWN;
switch ((string) $propertyAttributes) {
case 'string':
$propertyType = Properties::PROPERTY_TYPE_STRING;
$propertyValue = trim($propertyValue);
break;
case 'boolean':
$propertyType = Properties::PROPERTY_TYPE_BOOLEAN;
$propertyValue = (bool) $propertyValue;
break;
case 'integer':
$propertyType = Properties::PROPERTY_TYPE_INTEGER;
$propertyValue = (int) $propertyValue;
break;
case 'float':
$propertyType = Properties::PROPERTY_TYPE_FLOAT;
$propertyValue = (float) $propertyValue;
break;
case 'dateTime.tz':
$propertyType = Properties::PROPERTY_TYPE_DATE;
$propertyValue = strtotime(trim($propertyValue));
break;
}
$docProps->setCustomProperty($propertyName, $propertyValue, $propertyType);
}
}
$this->parseStyles($xml, $namespaces);
$worksheetID = 0;
$xml_ss = $xml->children($namespaces['ss']);
foreach ($xml_ss->Worksheet as $worksheet) {
$worksheet_ss = $worksheet->attributes($namespaces['ss']);
if (
(isset($this->loadSheetsOnly)) && (isset($worksheet_ss['Name'])) &&
(!in_array($worksheet_ss['Name'], $this->loadSheetsOnly))
) {
continue;
}
// Create new Worksheet
$spreadsheet->createSheet();
$spreadsheet->setActiveSheetIndex($worksheetID);
if (isset($worksheet_ss['Name'])) {
$worksheetName = (string) $worksheet_ss['Name'];
// 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
$spreadsheet->getActiveSheet()->setTitle($worksheetName, false, false);
}
// locally scoped defined names
if (isset($worksheet->Names[0])) {
foreach ($worksheet->Names[0] as $definedName) {
$definedName_ss = $definedName->attributes($namespaces['ss']);
$name = (string) $definedName_ss['Name'];
$definedValue = (string) $definedName_ss['RefersTo'];
$convertedValue = AddressHelper::convertFormulaToA1($definedValue);
if ($convertedValue[0] === '=') {
$convertedValue = substr($convertedValue, 1);
}
$spreadsheet->addDefinedName(DefinedName::createInstance($name, $spreadsheet->getActiveSheet(), $convertedValue, true));
}
}
$columnID = 'A';
if (isset($worksheet->Table->Column)) {
foreach ($worksheet->Table->Column as $columnData) {
$columnData_ss = $columnData->attributes($namespaces['ss']);
if (isset($columnData_ss['Index'])) {
$columnID = Coordinate::stringFromColumnIndex((int) $columnData_ss['Index']);
}
if (isset($columnData_ss['Width'])) {
$columnWidth = $columnData_ss['Width'];
$spreadsheet->getActiveSheet()->getColumnDimension($columnID)->setWidth($columnWidth / 5.4);
}
++$columnID;
}
}
$rowID = 1;
if (isset($worksheet->Table->Row)) {
$additionalMergedCells = 0;
foreach ($worksheet->Table->Row as $rowData) {
$rowHasData = false;
$row_ss = $rowData->attributes($namespaces['ss']);
if (isset($row_ss['Index'])) {
$rowID = (int) $row_ss['Index'];
}
$columnID = 'A';
foreach ($rowData->Cell as $cell) {
$cell_ss = $cell->attributes($namespaces['ss']);
if (isset($cell_ss['Index'])) {
$columnID = Coordinate::stringFromColumnIndex((int) $cell_ss['Index']);
}
$cellRange = $columnID . $rowID;
if ($this->getReadFilter() !== null) {
if (!$this->getReadFilter()->readCell($columnID, $rowID, $worksheetName)) {
++$columnID;
continue;
}
}
if (isset($cell_ss['HRef'])) {
$spreadsheet->getActiveSheet()->getCell($cellRange)->getHyperlink()->setUrl((string) $cell_ss['HRef']);
}
if ((isset($cell_ss['MergeAcross'])) || (isset($cell_ss['MergeDown']))) {
$columnTo = $columnID;
if (isset($cell_ss['MergeAcross'])) {
$additionalMergedCells += (int) $cell_ss['MergeAcross'];
$columnTo = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($columnID) + $cell_ss['MergeAcross']);
}
$rowTo = $rowID;
if (isset($cell_ss['MergeDown'])) {
$rowTo = $rowTo + $cell_ss['MergeDown'];
}
$cellRange .= ':' . $columnTo . $rowTo;
$spreadsheet->getActiveSheet()->mergeCells($cellRange);
}
$hasCalculatedValue = false;
$cellDataFormula = '';
if (isset($cell_ss['Formula'])) {
$cellDataFormula = $cell_ss['Formula'];
$hasCalculatedValue = true;
}
if (isset($cell->Data)) {
$cellData = $cell->Data;
$cellValue = (string) $cellData;
$type = DataType::TYPE_NULL;
$cellData_ss = $cellData->attributes($namespaces['ss']);
if (isset($cellData_ss['Type'])) {
$cellDataType = $cellData_ss['Type'];
switch ($cellDataType) {
/*
const TYPE_STRING = 's';
const TYPE_FORMULA = 'f';
const TYPE_NUMERIC = 'n';
const TYPE_BOOL = 'b';
const TYPE_NULL = 'null';
const TYPE_INLINE = 'inlineStr';
const TYPE_ERROR = 'e';
*/
case 'String':
$type = DataType::TYPE_STRING;
break;
case 'Number':
$type = DataType::TYPE_NUMERIC;
$cellValue = (float) $cellValue;
if (floor($cellValue) == $cellValue) {
$cellValue = (int) $cellValue;
}
break;
case 'Boolean':
$type = DataType::TYPE_BOOL;
$cellValue = ($cellValue != 0);
break;
case 'DateTime':
$type = DataType::TYPE_NUMERIC;
$cellValue = Date::PHPToExcel(strtotime($cellValue . ' UTC'));
break;
case 'Error':
$type = DataType::TYPE_ERROR;
$hasCalculatedValue = false;
break;
}
}
if ($hasCalculatedValue) {
$type = DataType::TYPE_FORMULA;
$columnNumber = Coordinate::columnIndexFromString($columnID);
$cellDataFormula = AddressHelper::convertFormulaToA1($cellDataFormula, $rowID, $columnNumber);
}
$spreadsheet->getActiveSheet()->getCell($columnID . $rowID)->setValueExplicit((($hasCalculatedValue) ? $cellDataFormula : $cellValue), $type);
if ($hasCalculatedValue) {
$spreadsheet->getActiveSheet()->getCell($columnID . $rowID)->setCalculatedValue($cellValue);
}
$rowHasData = true;
}
if (isset($cell->Comment)) {
$commentAttributes = $cell->Comment->attributes($namespaces['ss']);
$author = 'unknown';
if (isset($commentAttributes->Author)) {
$author = (string) $commentAttributes->Author;
}
$node = $cell->Comment->Data->asXML();
$annotation = strip_tags($node);
$spreadsheet->getActiveSheet()->getComment($columnID . $rowID)->setAuthor($author)->setText($this->parseRichText($annotation));
}
if (isset($cell_ss['StyleID'])) {
$style = (string) $cell_ss['StyleID'];
if ((isset($this->styles[$style])) && (!empty($this->styles[$style]))) {
//if (!$spreadsheet->getActiveSheet()->cellExists($columnID . $rowID)) {
// $spreadsheet->getActiveSheet()->getCell($columnID . $rowID)->setValue(null);
//}
$spreadsheet->getActiveSheet()->getStyle($cellRange)->applyFromArray($this->styles[$style]);
}
}
++$columnID;
while ($additionalMergedCells > 0) {
++$columnID;
--$additionalMergedCells;
}
}
if ($rowHasData) {
if (isset($row_ss['Height'])) {
$rowHeight = $row_ss['Height'];
$spreadsheet->getActiveSheet()->getRowDimension($rowID)->setRowHeight($rowHeight);
}
}
++$rowID;
}
if (isset($namespaces['x'])) {
$xmlX = $worksheet->children($namespaces['x']);
if (isset($xmlX->WorksheetOptions)) {
(new PageSettings($xmlX, $namespaces))->loadPageSettings($spreadsheet);
}
}
}
++$worksheetID;
}
// Globally scoped defined names
$activeWorksheet = $spreadsheet->setActiveSheetIndex(0);
if (isset($xml->Names[0])) {
foreach ($xml->Names[0] as $definedName) {
$definedName_ss = $definedName->attributes($namespaces['ss']);
$name = (string) $definedName_ss['Name'];
$definedValue = (string) $definedName_ss['RefersTo'];
$convertedValue = AddressHelper::convertFormulaToA1($definedValue);
if ($convertedValue[0] === '=') {
$convertedValue = substr($convertedValue, 1);
}
$spreadsheet->addDefinedName(DefinedName::createInstance($name, $activeWorksheet, $convertedValue));
}
}
// Return
return $spreadsheet;
}
protected function parseRichText($is)
{
$value = new RichText();
$value->createText($is);
return $value;
}
private function parseStyles(SimpleXMLElement $xml, array $namespaces): void
{
if (!isset($xml->Styles)) {
return;
}
foreach ($xml->Styles[0] as $style) {
$style_ss = $style->attributes($namespaces['ss']);
$styleID = (string) $style_ss['ID'];
$this->styles[$styleID] = (isset($this->styles['Default'])) ? $this->styles['Default'] : [];
foreach ($style as $styleType => $styleData) {
$styleAttributes = $styleData->attributes($namespaces['ss']);
switch ($styleType) {
case 'Alignment':
$this->parseStyleAlignment($styleID, $styleAttributes);
break;
case 'Borders':
$this->parseStyleBorders($styleID, $styleData, $namespaces);
break;
case 'Font':
$this->parseStyleFont($styleID, $styleAttributes);
break;
case 'Interior':
$this->parseStyleInterior($styleID, $styleAttributes);
break;
case 'NumberFormat':
$this->parseStyleNumberFormat($styleID, $styleAttributes);
break;
}
}
}
}
/**
* @param string $styleID
*/
private function parseStyleAlignment($styleID, SimpleXMLElement $styleAttributes): void
{
$verticalAlignmentStyles = [
Alignment::VERTICAL_BOTTOM,
Alignment::VERTICAL_TOP,
Alignment::VERTICAL_CENTER,
Alignment::VERTICAL_JUSTIFY,
];
$horizontalAlignmentStyles = [
Alignment::HORIZONTAL_GENERAL,
Alignment::HORIZONTAL_LEFT,
Alignment::HORIZONTAL_RIGHT,
Alignment::HORIZONTAL_CENTER,
Alignment::HORIZONTAL_CENTER_CONTINUOUS,
Alignment::HORIZONTAL_JUSTIFY,
];
foreach ($styleAttributes as $styleAttributeKey => $styleAttributeValue) {
$styleAttributeValue = (string) $styleAttributeValue;
switch ($styleAttributeKey) {
case 'Vertical':
if (self::identifyFixedStyleValue($verticalAlignmentStyles, $styleAttributeValue)) {
$this->styles[$styleID]['alignment']['vertical'] = $styleAttributeValue;
}
break;
case 'Horizontal':
if (self::identifyFixedStyleValue($horizontalAlignmentStyles, $styleAttributeValue)) {
$this->styles[$styleID]['alignment']['horizontal'] = $styleAttributeValue;
}
break;
case 'WrapText':
$this->styles[$styleID]['alignment']['wrapText'] = true;
break;
case 'Rotate':
$this->styles[$styleID]['alignment']['textRotation'] = $styleAttributeValue;
break;
}
}
}
private static $borderPositions = ['top', 'left', 'bottom', 'right'];
/**
* @param $styleID
*/
private function parseStyleBorders($styleID, SimpleXMLElement $styleData, array $namespaces): void
{
$diagonalDirection = '';
$borderPosition = '';
foreach ($styleData->Border as $borderStyle) {
$borderAttributes = $borderStyle->attributes($namespaces['ss']);
$thisBorder = [];
$style = (string) $borderAttributes->Weight;
$style .= strtolower((string) $borderAttributes->LineStyle);
$thisBorder['borderStyle'] = self::$mappings['borderStyle'][$style] ?? Border::BORDER_NONE;
foreach ($borderAttributes as $borderStyleKey => $borderStyleValue) {
switch ($borderStyleKey) {
case 'Position':
$borderStyleValue = strtolower((string) $borderStyleValue);
if (in_array($borderStyleValue, self::$borderPositions)) {
$borderPosition = $borderStyleValue;
} elseif ($borderStyleValue == 'diagonalleft') {
$diagonalDirection = $diagonalDirection ? Borders::DIAGONAL_BOTH : Borders::DIAGONAL_DOWN;
} elseif ($borderStyleValue == 'diagonalright') {
$diagonalDirection = $diagonalDirection ? Borders::DIAGONAL_BOTH : Borders::DIAGONAL_UP;
}
break;
case 'Color':
$borderColour = substr($borderStyleValue, 1);
$thisBorder['color']['rgb'] = $borderColour;
break;
}
}
if ($borderPosition) {
$this->styles[$styleID]['borders'][$borderPosition] = $thisBorder;
} elseif ($diagonalDirection) {
$this->styles[$styleID]['borders']['diagonalDirection'] = $diagonalDirection;
$this->styles[$styleID]['borders']['diagonal'] = $thisBorder;
}
}
}
private static $underlineStyles = [
Font::UNDERLINE_NONE,
Font::UNDERLINE_DOUBLE,
Font::UNDERLINE_DOUBLEACCOUNTING,
Font::UNDERLINE_SINGLE,
Font::UNDERLINE_SINGLEACCOUNTING,
];
private function parseStyleFontUnderline(string $styleID, string $styleAttributeValue): void
{
if (self::identifyFixedStyleValue(self::$underlineStyles, $styleAttributeValue)) {
$this->styles[$styleID]['font']['underline'] = $styleAttributeValue;
}
}
private function parseStyleFontVerticalAlign(string $styleID, string $styleAttributeValue): void
{
if ($styleAttributeValue == 'Superscript') {
$this->styles[$styleID]['font']['superscript'] = true;
}
if ($styleAttributeValue == 'Subscript') {
$this->styles[$styleID]['font']['subscript'] = true;
}
}
/**
* @param $styleID
*/
private function parseStyleFont(string $styleID, SimpleXMLElement $styleAttributes): void
{
foreach ($styleAttributes as $styleAttributeKey => $styleAttributeValue) {
$styleAttributeValue = (string) $styleAttributeValue;
switch ($styleAttributeKey) {
case 'FontName':
$this->styles[$styleID]['font']['name'] = $styleAttributeValue;
break;
case 'Size':
$this->styles[$styleID]['font']['size'] = $styleAttributeValue;
break;
case 'Color':
$this->styles[$styleID]['font']['color']['rgb'] = substr($styleAttributeValue, 1);
break;
case 'Bold':
$this->styles[$styleID]['font']['bold'] = true;
break;
case 'Italic':
$this->styles[$styleID]['font']['italic'] = true;
break;
case 'Underline':
$this->parseStyleFontUnderline($styleID, $styleAttributeValue);
break;
case 'VerticalAlign':
$this->parseStyleFontVerticalAlign($styleID, $styleAttributeValue);
break;
}
}
}
/**
* @param $styleID
*/
private function parseStyleInterior($styleID, SimpleXMLElement $styleAttributes): void
{
foreach ($styleAttributes as $styleAttributeKey => $styleAttributeValue) {
switch ($styleAttributeKey) {
case 'Color':
$this->styles[$styleID]['fill']['endColor']['rgb'] = substr($styleAttributeValue, 1);
$this->styles[$styleID]['fill']['startColor']['rgb'] = substr($styleAttributeValue, 1);
break;
case 'PatternColor':
$this->styles[$styleID]['fill']['startColor']['rgb'] = substr($styleAttributeValue, 1);
break;
case 'Pattern':
$lcStyleAttributeValue = strtolower((string) $styleAttributeValue);
$this->styles[$styleID]['fill']['fillType'] = self::$mappings['fillType'][$lcStyleAttributeValue] ?? Fill::FILL_NONE;
break;
}
}
}
/**
* @param $styleID
*/
private function parseStyleNumberFormat($styleID, SimpleXMLElement $styleAttributes): void
{
$fromFormats = ['\-', '\ '];
$toFormats = ['-', ' '];
foreach ($styleAttributes as $styleAttributeKey => $styleAttributeValue) {
$styleAttributeValue = str_replace($fromFormats, $toFormats, $styleAttributeValue);
switch ($styleAttributeValue) {
case 'Short Date':
$styleAttributeValue = 'dd/mm/yyyy';
break;
}
if ($styleAttributeValue > '') {
$this->styles[$styleID]['numberFormat']['formatCode'] = $styleAttributeValue;
}
}
}
}

View File

@@ -0,0 +1,130 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Reader\Xml;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup;
use SimpleXMLElement;
use stdClass;
class PageSettings
{
/**
* @var stdClass
*/
private $printSettings;
public function __construct(SimpleXMLElement $xmlX, array $namespaces)
{
$printSettings = $this->pageSetup($xmlX, $namespaces, $this->getPrintDefaults());
$this->printSettings = $this->printSetup($xmlX, $printSettings);
}
public function loadPageSettings(Spreadsheet $spreadsheet): void
{
$spreadsheet->getActiveSheet()->getPageSetup()
->setPaperSize($this->printSettings->paperSize)
->setOrientation($this->printSettings->orientation)
->setScale($this->printSettings->scale)
->setVerticalCentered($this->printSettings->verticalCentered)
->setHorizontalCentered($this->printSettings->horizontalCentered)
->setPageOrder($this->printSettings->printOrder);
$spreadsheet->getActiveSheet()->getPageMargins()
->setTop($this->printSettings->topMargin)
->setHeader($this->printSettings->headerMargin)
->setLeft($this->printSettings->leftMargin)
->setRight($this->printSettings->rightMargin)
->setBottom($this->printSettings->bottomMargin)
->setFooter($this->printSettings->footerMargin);
}
private function getPrintDefaults(): stdClass
{
return (object) [
'paperSize' => 9,
'orientation' => PageSetup::ORIENTATION_DEFAULT,
'scale' => 100,
'horizontalCentered' => false,
'verticalCentered' => false,
'printOrder' => PageSetup::PAGEORDER_DOWN_THEN_OVER,
'topMargin' => 0.75,
'headerMargin' => 0.3,
'leftMargin' => 0.7,
'rightMargin' => 0.7,
'bottomMargin' => 0.75,
'footerMargin' => 0.3,
];
}
private function pageSetup(SimpleXMLElement $xmlX, array $namespaces, stdClass $printDefaults): stdClass
{
if (isset($xmlX->WorksheetOptions->PageSetup)) {
foreach ($xmlX->WorksheetOptions->PageSetup as $pageSetupData) {
foreach ($pageSetupData as $pageSetupKey => $pageSetupValue) {
$pageSetupAttributes = $pageSetupValue->attributes($namespaces['x']);
switch ($pageSetupKey) {
case 'Layout':
$this->setLayout($printDefaults, $pageSetupAttributes);
break;
case 'Header':
$printDefaults->headerMargin = (float) $pageSetupAttributes->Margin ?: 1.0;
break;
case 'Footer':
$printDefaults->footerMargin = (float) $pageSetupAttributes->Margin ?: 1.0;
break;
case 'PageMargins':
$this->setMargins($printDefaults, $pageSetupAttributes);
break;
}
}
}
}
return $printDefaults;
}
private function printSetup(SimpleXMLElement $xmlX, stdClass $printDefaults): stdClass
{
if (isset($xmlX->WorksheetOptions->Print)) {
foreach ($xmlX->WorksheetOptions->Print as $printData) {
foreach ($printData as $printKey => $printValue) {
switch ($printKey) {
case 'LeftToRight':
$printDefaults->printOrder = PageSetup::PAGEORDER_OVER_THEN_DOWN;
break;
case 'PaperSizeIndex':
$printDefaults->paperSize = (int) $printValue ?: 9;
break;
case 'Scale':
$printDefaults->scale = (int) $printValue ?: 100;
break;
}
}
}
}
return $printDefaults;
}
private function setLayout(stdClass $printDefaults, SimpleXMLElement $pageSetupAttributes): void
{
$printDefaults->orientation = (string) strtolower($pageSetupAttributes->Orientation) ?: PageSetup::ORIENTATION_PORTRAIT;
$printDefaults->horizontalCentered = (bool) $pageSetupAttributes->CenterHorizontal ?: false;
$printDefaults->verticalCentered = (bool) $pageSetupAttributes->CenterVertical ?: false;
}
private function setMargins(stdClass $printDefaults, SimpleXMLElement $pageSetupAttributes): void
{
$printDefaults->leftMargin = (float) $pageSetupAttributes->Left ?: 1.0;
$printDefaults->rightMargin = (float) $pageSetupAttributes->Right ?: 1.0;
$printDefaults->topMargin = (float) $pageSetupAttributes->Top ?: 1.0;
$printDefaults->bottomMargin = (float) $pageSetupAttributes->Bottom ?: 1.0;
}
}