repo
stringlengths
7
63
file_url
stringlengths
81
284
file_path
stringlengths
5
200
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:02:33
2026-01-05 05:24:06
truncated
bool
2 classes
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Document/Properties.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Document/Properties.php
<?php namespace PhpOffice\PhpSpreadsheet\Document; use DateTime; use PhpOffice\PhpSpreadsheet\Shared\IntOrFloat; class Properties { /** constants */ public const PROPERTY_TYPE_BOOLEAN = 'b'; public const PROPERTY_TYPE_INTEGER = 'i'; public const PROPERTY_TYPE_FLOAT = 'f'; public const PROPERTY_TYPE_DATE = 'd'; public const PROPERTY_TYPE_STRING = 's'; public const PROPERTY_TYPE_UNKNOWN = 'u'; private const VALID_PROPERTY_TYPE_LIST = [ self::PROPERTY_TYPE_BOOLEAN, self::PROPERTY_TYPE_INTEGER, self::PROPERTY_TYPE_FLOAT, self::PROPERTY_TYPE_DATE, self::PROPERTY_TYPE_STRING, ]; /** * Creator. * * @var string */ private $creator = 'Unknown Creator'; /** * LastModifiedBy. * * @var string */ private $lastModifiedBy; /** * Created. * * @var float|int */ private $created; /** * Modified. * * @var float|int */ private $modified; /** * Title. * * @var string */ private $title = 'Untitled Spreadsheet'; /** * Description. * * @var string */ private $description = ''; /** * Subject. * * @var string */ private $subject = ''; /** * Keywords. * * @var string */ private $keywords = ''; /** * Category. * * @var string */ private $category = ''; /** * Manager. * * @var string */ private $manager = ''; /** * Company. * * @var string */ private $company = ''; /** * Custom Properties. * * @var array{value: mixed, type: string}[] */ private $customProperties = []; /** * Create a new Document Properties instance. */ public function __construct() { // Initialise values $this->lastModifiedBy = $this->creator; $this->created = self::intOrFloatTimestamp(null); $this->modified = self::intOrFloatTimestamp(null); } /** * Get Creator. */ public function getCreator(): string { return $this->creator; } /** * Set Creator. * * @return $this */ public function setCreator(string $creator): self { $this->creator = $creator; return $this; } /** * Get Last Modified By. */ public function getLastModifiedBy(): string { return $this->lastModifiedBy; } /** * Set Last Modified By. * * @return $this */ public function setLastModifiedBy(string $modifiedBy): self { $this->lastModifiedBy = $modifiedBy; return $this; } /** * @param null|float|int|string $timestamp * * @return float|int */ private static function intOrFloatTimestamp($timestamp) { if ($timestamp === null) { $timestamp = (float) (new DateTime())->format('U'); } elseif (is_string($timestamp)) { if (is_numeric($timestamp)) { $timestamp = (float) $timestamp; } else { $timestamp = preg_replace('/[.][0-9]*$/', '', $timestamp) ?? ''; $timestamp = preg_replace('/^(\\d{4})- (\\d)/', '$1-0$2', $timestamp) ?? ''; $timestamp = preg_replace('/^(\\d{4}-\\d{2})- (\\d)/', '$1-0$2', $timestamp) ?? ''; $timestamp = (float) (new DateTime($timestamp))->format('U'); } } return IntOrFloat::evaluate($timestamp); } /** * Get Created. * * @return float|int */ public function getCreated() { return $this->created; } /** * Set Created. * * @param null|float|int|string $timestamp * * @return $this */ public function setCreated($timestamp): self { $this->created = self::intOrFloatTimestamp($timestamp); return $this; } /** * Get Modified. * * @return float|int */ public function getModified() { return $this->modified; } /** * Set Modified. * * @param null|float|int|string $timestamp * * @return $this */ public function setModified($timestamp): self { $this->modified = self::intOrFloatTimestamp($timestamp); return $this; } /** * Get Title. */ public function getTitle(): string { return $this->title; } /** * Set Title. * * @return $this */ public function setTitle(string $title): self { $this->title = $title; return $this; } /** * Get Description. */ public function getDescription(): string { return $this->description; } /** * Set Description. * * @return $this */ public function setDescription(string $description): self { $this->description = $description; return $this; } /** * Get Subject. */ public function getSubject(): string { return $this->subject; } /** * Set Subject. * * @return $this */ public function setSubject(string $subject): self { $this->subject = $subject; return $this; } /** * Get Keywords. */ public function getKeywords(): string { return $this->keywords; } /** * Set Keywords. * * @return $this */ public function setKeywords(string $keywords): self { $this->keywords = $keywords; return $this; } /** * Get Category. */ public function getCategory(): string { return $this->category; } /** * Set Category. * * @return $this */ public function setCategory(string $category): self { $this->category = $category; return $this; } /** * Get Company. */ public function getCompany(): string { return $this->company; } /** * Set Company. * * @return $this */ public function setCompany(string $company): self { $this->company = $company; return $this; } /** * Get Manager. */ public function getManager(): string { return $this->manager; } /** * Set Manager. * * @return $this */ public function setManager(string $manager): self { $this->manager = $manager; return $this; } /** * Get a List of Custom Property Names. * * @return string[] */ public function getCustomProperties(): array { return array_keys($this->customProperties); } /** * Check if a Custom Property is defined. */ public function isCustomPropertySet(string $propertyName): bool { return array_key_exists($propertyName, $this->customProperties); } /** * Get a Custom Property Value. * * @return mixed */ public function getCustomPropertyValue(string $propertyName) { if (isset($this->customProperties[$propertyName])) { return $this->customProperties[$propertyName]['value']; } return null; } /** * Get a Custom Property Type. * * @return null|string */ public function getCustomPropertyType(string $propertyName) { return $this->customProperties[$propertyName]['type'] ?? null; } /** * @param mixed $propertyValue */ private function identifyPropertyType($propertyValue): string { if (is_float($propertyValue)) { return self::PROPERTY_TYPE_FLOAT; } if (is_int($propertyValue)) { return self::PROPERTY_TYPE_INTEGER; } if (is_bool($propertyValue)) { return self::PROPERTY_TYPE_BOOLEAN; } return self::PROPERTY_TYPE_STRING; } /** * Set a Custom Property. * * @param mixed $propertyValue * @param string $propertyType * 'i' : Integer * 'f' : Floating Point * 's' : String * 'd' : Date/Time * 'b' : Boolean * * @return $this */ public function setCustomProperty(string $propertyName, $propertyValue = '', $propertyType = null): self { if (($propertyType === null) || (!in_array($propertyType, self::VALID_PROPERTY_TYPE_LIST))) { $propertyType = $this->identifyPropertyType($propertyValue); } if (!is_object($propertyValue)) { $this->customProperties[$propertyName] = [ 'value' => self::convertProperty($propertyValue, $propertyType), 'type' => $propertyType, ]; } return $this; } private const PROPERTY_TYPE_ARRAY = [ 'i' => self::PROPERTY_TYPE_INTEGER, // Integer 'i1' => self::PROPERTY_TYPE_INTEGER, // 1-Byte Signed Integer 'i2' => self::PROPERTY_TYPE_INTEGER, // 2-Byte Signed Integer 'i4' => self::PROPERTY_TYPE_INTEGER, // 4-Byte Signed Integer 'i8' => self::PROPERTY_TYPE_INTEGER, // 8-Byte Signed Integer 'int' => self::PROPERTY_TYPE_INTEGER, // Integer 'ui1' => self::PROPERTY_TYPE_INTEGER, // 1-Byte Unsigned Integer 'ui2' => self::PROPERTY_TYPE_INTEGER, // 2-Byte Unsigned Integer 'ui4' => self::PROPERTY_TYPE_INTEGER, // 4-Byte Unsigned Integer 'ui8' => self::PROPERTY_TYPE_INTEGER, // 8-Byte Unsigned Integer 'uint' => self::PROPERTY_TYPE_INTEGER, // Unsigned Integer 'f' => self::PROPERTY_TYPE_FLOAT, // Real Number 'r4' => self::PROPERTY_TYPE_FLOAT, // 4-Byte Real Number 'r8' => self::PROPERTY_TYPE_FLOAT, // 8-Byte Real Number 'decimal' => self::PROPERTY_TYPE_FLOAT, // Decimal 's' => self::PROPERTY_TYPE_STRING, // String 'empty' => self::PROPERTY_TYPE_STRING, // Empty 'null' => self::PROPERTY_TYPE_STRING, // Null 'lpstr' => self::PROPERTY_TYPE_STRING, // LPSTR 'lpwstr' => self::PROPERTY_TYPE_STRING, // LPWSTR 'bstr' => self::PROPERTY_TYPE_STRING, // Basic String 'd' => self::PROPERTY_TYPE_DATE, // Date and Time 'date' => self::PROPERTY_TYPE_DATE, // Date and Time 'filetime' => self::PROPERTY_TYPE_DATE, // File Time 'b' => self::PROPERTY_TYPE_BOOLEAN, // Boolean 'bool' => self::PROPERTY_TYPE_BOOLEAN, // Boolean ]; private const SPECIAL_TYPES = [ 'empty' => '', 'null' => null, ]; /** * Convert property to form desired by Excel. * * @param mixed $propertyValue * * @return mixed */ public static function convertProperty($propertyValue, string $propertyType) { return self::SPECIAL_TYPES[$propertyType] ?? self::convertProperty2($propertyValue, $propertyType); } /** * Convert property to form desired by Excel. * * @param mixed $propertyValue * * @return mixed */ private static function convertProperty2($propertyValue, string $type) { $propertyType = self::convertPropertyType($type); switch ($propertyType) { case self::PROPERTY_TYPE_INTEGER: $intValue = (int) $propertyValue; return ($type[0] === 'u') ? abs($intValue) : $intValue; case self::PROPERTY_TYPE_FLOAT: return (float) $propertyValue; case self::PROPERTY_TYPE_DATE: return self::intOrFloatTimestamp($propertyValue); case self::PROPERTY_TYPE_BOOLEAN: return is_bool($propertyValue) ? $propertyValue : ($propertyValue === 'true'); default: // includes string return $propertyValue; } } public static function convertPropertyType(string $propertyType): string { return self::PROPERTY_TYPE_ARRAY[$propertyType] ?? self::PROPERTY_TYPE_UNKNOWN; } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Collection/Memory.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Collection/Memory.php
<?php namespace PhpOffice\PhpSpreadsheet\Collection; use Psr\SimpleCache\CacheInterface; /** * This is the default implementation for in-memory cell collection. * * Alternatives implementation should leverage off-memory, non-volatile storage * to reduce overall memory usage. */ class Memory implements CacheInterface { private $cache = []; public function clear() { $this->cache = []; return true; } public function delete($key) { unset($this->cache[$key]); return true; } public function deleteMultiple($keys) { foreach ($keys as $key) { $this->delete($key); } return true; } public function get($key, $default = null) { if ($this->has($key)) { return $this->cache[$key]; } return $default; } public function getMultiple($keys, $default = null) { $results = []; foreach ($keys as $key) { $results[$key] = $this->get($key, $default); } return $results; } public function has($key) { return array_key_exists($key, $this->cache); } public function set($key, $value, $ttl = null) { $this->cache[$key] = $value; return true; } public function setMultiple($values, $ttl = null) { foreach ($values as $key => $value) { $this->set($key, $value); } return true; } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Collection/Cells.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Collection/Cells.php
<?php namespace PhpOffice\PhpSpreadsheet\Collection; use Generator; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; use Psr\SimpleCache\CacheInterface; class Cells { /** * @var CacheInterface */ private $cache; /** * Parent worksheet. * * @var null|Worksheet */ private $parent; /** * The currently active Cell. * * @var null|Cell */ private $currentCell; /** * Coordinate of the currently active Cell. * * @var null|string */ private $currentCoordinate; /** * Flag indicating whether the currently active Cell requires saving. * * @var bool */ private $currentCellIsDirty = false; /** * An index of existing cells. Booleans indexed by their coordinate. * * @var bool[] */ private $index = []; /** * Prefix used to uniquely identify cache data for this worksheet. * * @var string */ private $cachePrefix; /** * Initialise this new cell collection. * * @param Worksheet $parent The worksheet for this cell collection */ public function __construct(Worksheet $parent, CacheInterface $cache) { // Set our parent worksheet. // This is maintained here to facilitate re-attaching it to Cell objects when // they are woken from a serialized state $this->parent = $parent; $this->cache = $cache; $this->cachePrefix = $this->getUniqueID(); } /** * Return the parent worksheet for this cell collection. * * @return null|Worksheet */ public function getParent() { return $this->parent; } /** * Whether the collection holds a cell for the given coordinate. * * @param string $cellCoordinate Coordinate of the cell to check * * @return bool */ public function has($cellCoordinate) { if ($cellCoordinate === $this->currentCoordinate) { return true; } // Check if the requested entry exists in the index return isset($this->index[$cellCoordinate]); } /** * Add or update a cell in the collection. * * @param Cell $cell Cell to update * * @return Cell */ public function update(Cell $cell) { return $this->add($cell->getCoordinate(), $cell); } /** * Delete a cell in cache identified by coordinate. * * @param string $cellCoordinate Coordinate of the cell to delete */ public function delete($cellCoordinate): void { if ($cellCoordinate === $this->currentCoordinate && $this->currentCell !== null) { $this->currentCell->detach(); $this->currentCoordinate = null; $this->currentCell = null; $this->currentCellIsDirty = false; } unset($this->index[$cellCoordinate]); // Delete the entry from cache $this->cache->delete($this->cachePrefix . $cellCoordinate); } /** * Get a list of all cell coordinates currently held in the collection. * * @return string[] */ public function getCoordinates() { return array_keys($this->index); } /** * Get a sorted list of all cell coordinates currently held in the collection by row and column. * * @return string[] */ public function getSortedCoordinates() { $sortKeys = []; foreach ($this->getCoordinates() as $coord) { $column = ''; $row = 0; sscanf($coord, '%[A-Z]%d', $column, $row); $sortKeys[sprintf('%09d%3s', $row, $column)] = $coord; } ksort($sortKeys); return array_values($sortKeys); } /** * Get highest worksheet column and highest row that have cell records. * * @return array Highest column name and highest row number */ public function getHighestRowAndColumn() { // Lookup highest column and highest row $col = ['A' => '1A']; $row = [1]; foreach ($this->getCoordinates() as $coord) { $c = ''; $r = 0; sscanf($coord, '%[A-Z]%d', $c, $r); $row[$r] = $r; $col[$c] = strlen($c) . $c; } // Determine highest column and row $highestRow = max($row); $highestColumn = substr((string) @max($col), 1); return [ 'row' => $highestRow, 'column' => $highestColumn, ]; } /** * Return the cell coordinate of the currently active cell object. * * @return null|string */ public function getCurrentCoordinate() { return $this->currentCoordinate; } /** * Return the column coordinate of the currently active cell object. * * @return string */ public function getCurrentColumn() { $column = ''; $row = 0; sscanf($this->currentCoordinate ?? '', '%[A-Z]%d', $column, $row); return $column; } /** * Return the row coordinate of the currently active cell object. * * @return int */ public function getCurrentRow() { $column = ''; $row = 0; sscanf($this->currentCoordinate ?? '', '%[A-Z]%d', $column, $row); return (int) $row; } /** * Get highest worksheet column. * * @param null|int|string $row Return the highest column for the specified row, * or the highest column of any row if no row number is passed * * @return string Highest column name */ public function getHighestColumn($row = null) { if ($row === null) { $colRow = $this->getHighestRowAndColumn(); return $colRow['column']; } $columnList = [1]; foreach ($this->getCoordinates() as $coord) { $c = ''; $r = 0; sscanf($coord, '%[A-Z]%d', $c, $r); if ($r != $row) { continue; } $columnList[] = Coordinate::columnIndexFromString($c); } return Coordinate::stringFromColumnIndex((int) @max($columnList)); } /** * Get highest worksheet row. * * @param null|string $column Return the highest row for the specified column, * or the highest row of any column if no column letter is passed * * @return int Highest row number */ public function getHighestRow($column = null) { if ($column === null) { $colRow = $this->getHighestRowAndColumn(); return $colRow['row']; } $rowList = [0]; foreach ($this->getCoordinates() as $coord) { $c = ''; $r = 0; sscanf($coord, '%[A-Z]%d', $c, $r); if ($c != $column) { continue; } $rowList[] = $r; } return max($rowList); } /** * Generate a unique ID for cache referencing. * * @return string Unique Reference */ private function getUniqueID() { return uniqid('phpspreadsheet.', true) . '.'; } /** * Clone the cell collection. * * @return self */ public function cloneCellCollection(Worksheet $worksheet) { $this->storeCurrentCell(); $newCollection = clone $this; $newCollection->parent = $worksheet; if (is_object($newCollection->currentCell)) { $newCollection->currentCell->attach($this); } // Get old values $oldKeys = $newCollection->getAllCacheKeys(); $oldValues = $newCollection->cache->getMultiple($oldKeys); $newValues = []; $oldCachePrefix = $newCollection->cachePrefix; // Change prefix $newCollection->cachePrefix = $newCollection->getUniqueID(); foreach ($oldValues as $oldKey => $value) { /** @var string $newKey */ $newKey = str_replace($oldCachePrefix, $newCollection->cachePrefix, $oldKey); $newValues[$newKey] = clone $value; } // Store new values $stored = $newCollection->cache->setMultiple($newValues); $this->destructIfNeeded($stored, $newCollection, 'Failed to copy cells in cache'); return $newCollection; } /** * Remove a row, deleting all cells in that row. * * @param string $row Row number to remove */ public function removeRow($row): void { foreach ($this->getCoordinates() as $coord) { $c = ''; $r = 0; sscanf($coord, '%[A-Z]%d', $c, $r); if ($r == $row) { $this->delete($coord); } } } /** * Remove a column, deleting all cells in that column. * * @param string $column Column ID to remove */ public function removeColumn($column): void { foreach ($this->getCoordinates() as $coord) { $c = ''; $r = 0; sscanf($coord, '%[A-Z]%d', $c, $r); if ($c == $column) { $this->delete($coord); } } } /** * Store cell data in cache for the current cell object if it's "dirty", * and the 'nullify' the current cell object. */ private function storeCurrentCell(): void { if ($this->currentCellIsDirty && isset($this->currentCoordinate, $this->currentCell)) { $this->currentCell->detach(); $stored = $this->cache->set($this->cachePrefix . $this->currentCoordinate, $this->currentCell); $this->destructIfNeeded($stored, $this, "Failed to store cell {$this->currentCoordinate} in cache"); $this->currentCellIsDirty = false; } $this->currentCoordinate = null; $this->currentCell = null; } private function destructIfNeeded(bool $stored, self $cells, string $message): void { if (!$stored) { $cells->__destruct(); throw new PhpSpreadsheetException($message); } } /** * Add or update a cell identified by its coordinate into the collection. * * @param string $cellCoordinate Coordinate of the cell to update * @param Cell $cell Cell to update * * @return Cell */ public function add($cellCoordinate, Cell $cell) { if ($cellCoordinate !== $this->currentCoordinate) { $this->storeCurrentCell(); } $this->index[$cellCoordinate] = true; $this->currentCoordinate = $cellCoordinate; $this->currentCell = $cell; $this->currentCellIsDirty = true; return $cell; } /** * Get cell at a specific coordinate. * * @param string $cellCoordinate Coordinate of the cell * * @return null|Cell Cell that was found, or null if not found */ public function get($cellCoordinate) { if ($cellCoordinate === $this->currentCoordinate) { return $this->currentCell; } $this->storeCurrentCell(); // Return null if requested entry doesn't exist in collection if (!$this->has($cellCoordinate)) { return null; } // Check if the entry that has been requested actually exists $cell = $this->cache->get($this->cachePrefix . $cellCoordinate); if ($cell === null) { throw new PhpSpreadsheetException("Cell entry {$cellCoordinate} no longer exists in cache. This probably means that the cache was cleared by someone else."); } // Set current entry to the requested entry $this->currentCoordinate = $cellCoordinate; $this->currentCell = $cell; // Re-attach this as the cell's parent $this->currentCell->attach($this); // Return requested entry return $this->currentCell; } /** * Clear the cell collection and disconnect from our parent. */ public function unsetWorksheetCells(): void { if ($this->currentCell !== null) { $this->currentCell->detach(); $this->currentCell = null; $this->currentCoordinate = null; } // Flush the cache $this->__destruct(); $this->index = []; // detach ourself from the worksheet, so that it can then delete this object successfully $this->parent = null; } /** * Destroy this cell collection. */ public function __destruct() { $this->cache->deleteMultiple($this->getAllCacheKeys()); } /** * Returns all known cache keys. * * @return Generator|string[] */ private function getAllCacheKeys() { foreach ($this->getCoordinates() as $coordinate) { yield $this->cachePrefix . $coordinate; } } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Collection/CellsFactory.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Collection/CellsFactory.php
<?php namespace PhpOffice\PhpSpreadsheet\Collection; use PhpOffice\PhpSpreadsheet\Settings; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; abstract class CellsFactory { /** * Initialise the cache storage. * * @param Worksheet $worksheet Enable cell caching for this worksheet * * @return Cells * */ public static function getInstance(Worksheet $worksheet) { return new Cells($worksheet, Settings::getCache()); } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/BaseReader.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/BaseReader.php
<?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 null|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($readCellValuesOnly) { $this->readDataOnly = (bool) $readCellValuesOnly; return $this; } public function getReadEmptyCells() { return $this->readEmptyCells; } public function setReadEmptyCells($readEmptyCells) { $this->readEmptyCells = (bool) $readEmptyCells; return $this; } public function getIncludeCharts() { return $this->includeCharts; } public function setIncludeCharts($includeCharts) { $this->includeCharts = (bool) $includeCharts; return $this; } public function getLoadSheetsOnly() { return $this->loadSheetsOnly; } public function setLoadSheetsOnly($sheetList) { if ($sheetList === null) { return $this->setLoadAllSheets(); } $this->loadSheetsOnly = is_array($sheetList) ? $sheetList : [$sheetList]; return $this; } public function setLoadAllSheets() { $this->loadSheetsOnly = null; return $this; } public function getReadFilter() { return $this->readFilter; } public function setReadFilter(IReadFilter $readFilter) { $this->readFilter = $readFilter; return $this; } public function getSecurityScanner() { return $this->securityScanner; } protected function processFlags(int $flags): void { if (((bool) ($flags & self::LOAD_WITH_CHARTS)) === true) { $this->setIncludeCharts(true); } } /** * Open file for reading. * * @param string $filename */ protected function openFile($filename): void { if ($filename) { File::assertFile($filename); // Open file $fileHandle = fopen($filename, 'rb'); } else { $fileHandle = false; } if ($fileHandle !== false) { $this->fileHandle = $fileHandle; } else { throw new ReaderException('Could not open file ' . $filename . ' for reading.'); } } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Gnumeric.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Gnumeric.php
<?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\Gnumeric\Properties; use PhpOffice\PhpSpreadsheet\Reader\Gnumeric\Styles; use PhpOffice\PhpSpreadsheet\Reader\Security\XmlScanner; use PhpOffice\PhpSpreadsheet\ReferenceHelper; use PhpOffice\PhpSpreadsheet\RichText\RichText; use PhpOffice\PhpSpreadsheet\Settings; use PhpOffice\PhpSpreadsheet\Shared\File; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; use SimpleXMLElement; use XMLReader; class Gnumeric extends BaseReader { const NAMESPACE_GNM = 'http://www.gnumeric.org/v10.dtd'; // gmr in old sheets const NAMESPACE_XSI = 'http://www.w3.org/2001/XMLSchema-instance'; const NAMESPACE_OFFICE = 'urn:oasis:names:tc:opendocument:xmlns:office:1.0'; const NAMESPACE_XLINK = 'http://www.w3.org/1999/xlink'; const NAMESPACE_DC = 'http://purl.org/dc/elements/1.1/'; const NAMESPACE_META = 'urn:oasis:names:tc:opendocument:xmlns:meta:1.0'; const NAMESPACE_OOO = 'http://openoffice.org/2004/office'; /** * Shared Expressions. * * @var array */ private $expressions = []; /** * Spreadsheet shared across all functions. * * @var Spreadsheet */ private $spreadsheet; /** @var ReferenceHelper */ private $referenceHelper; /** @var array */ public static $mappings = [ '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 ], ]; /** * 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? */ public function canRead(string $filename): bool { // Check if gzlib functions are available if (File::testFileNoThrow($filename) && function_exists('gzread')) { // Read signature data (first 3 bytes) $fh = fopen($filename, 'rb'); if ($fh !== false) { $data = fread($fh, 2); fclose($fh); } } return isset($data) && $data === chr(0x1F) . chr(0x8B); } private static function matchXml(XMLReader $xml, string $expectedLocalName): bool { return $xml->namespaceURI === self::NAMESPACE_GNM && $xml->localName === $expectedLocalName && $xml->nodeType === XMLReader::ELEMENT; } /** * Reads names of the worksheets from a file, without parsing the whole file to a Spreadsheet object. * * @param string $filename * * @return array */ public function listWorksheetNames($filename) { File::assertFile($filename); $xml = new XMLReader(); $xml->xml($this->securityScanner->scanFile('compress.zlib://' . realpath($filename)), null, Settings::getLibXmlLoaderOptions()); $xml->setParserProperty(2, true); $worksheetNames = []; while ($xml->read()) { if (self::matchXml($xml, 'SheetName')) { $xml->read(); // Move onto the value node $worksheetNames[] = (string) $xml->value; } elseif (self::matchXml($xml, '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 $filename * * @return array */ public function listWorksheetInfo($filename) { File::assertFile($filename); $xml = new XMLReader(); $xml->xml($this->securityScanner->scanFile('compress.zlib://' . realpath($filename)), null, Settings::getLibXmlLoaderOptions()); $xml->setParserProperty(2, true); $worksheetInfo = []; while ($xml->read()) { if (self::matchXml($xml, 'Sheet')) { $tmpInfo = [ 'worksheetName' => '', 'lastColumnLetter' => 'A', 'lastColumnIndex' => 0, 'totalRows' => 0, 'totalColumns' => 0, ]; while ($xml->read()) { if (self::matchXml($xml, 'Name')) { $xml->read(); // Move onto the value node $tmpInfo['worksheetName'] = (string) $xml->value; } elseif (self::matchXml($xml, 'MaxCol')) { $xml->read(); // Move onto the value node $tmpInfo['lastColumnIndex'] = (int) $xml->value; $tmpInfo['totalColumns'] = (int) $xml->value + 1; } elseif (self::matchXml($xml, '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; } public static function gnumericMappings(): array { return array_merge(self::$mappings, Styles::$mappings); } private function processComments(SimpleXMLElement $sheet): void { if ((!$this->readDataOnly) && (isset($sheet->Objects))) { foreach ($sheet->Objects->children(self::NAMESPACE_GNM) as $key => $comment) { $commentAttributes = $comment->attributes(); // Only comment objects are handled at the moment if ($commentAttributes && $commentAttributes->Text) { $this->spreadsheet->getActiveSheet()->getComment((string) $commentAttributes->ObjectBound) ->setAuthor((string) $commentAttributes->Author) ->setText($this->parseRichText((string) $commentAttributes->Text)); } } } } /** * @param mixed $value */ private static function testSimpleXml($value): SimpleXMLElement { return ($value instanceof SimpleXMLElement) ? $value : new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><root></root>'); } /** * Loads Spreadsheet from file. * * @return Spreadsheet */ public function load(string $filename, int $flags = 0) { $this->processFlags($flags); // Create new Spreadsheet $spreadsheet = new Spreadsheet(); $spreadsheet->removeSheetByIndex(0); // Load into this instance return $this->loadIntoExisting($filename, $spreadsheet); } /** * Loads from file into Spreadsheet instance. */ public function loadIntoExisting(string $filename, Spreadsheet $spreadsheet): Spreadsheet { $this->spreadsheet = $spreadsheet; File::assertFile($filename); $gFileData = $this->gzfileGetContents($filename); $xml2 = simplexml_load_string($this->securityScanner->scan($gFileData), 'SimpleXMLElement', Settings::getLibXmlLoaderOptions()); $xml = self::testSimpleXml($xml2); $gnmXML = $xml->children(self::NAMESPACE_GNM); (new Properties($this->spreadsheet))->readProperties($xml, $gnmXML); $worksheetID = 0; foreach ($gnmXML->Sheets->Sheet as $sheetOrNull) { $sheet = self::testSimpleXml($sheetOrNull); $worksheetName = (string) $sheet->Name; if (is_array($this->loadSheetsOnly) && !in_array($worksheetName, $this->loadSheetsOnly, true)) { 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)) ->printInformation($sheet) ->sheetMargins($sheet); } foreach ($sheet->Cells->Cell as $cellOrNull) { $cell = self::testSimpleXml($cellOrNull); $cellAttributes = self::testSimpleXml($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); } if ($sheet->Styles !== null) { (new Styles($this->spreadsheet, $this->readDataOnly))->read($sheet, $maxRow, $maxCol); } $this->processComments($sheet); $this->processColumnWidths($sheet, $maxCol); $this->processRowHeights($sheet, $maxRow); $this->processMergedCells($sheet); $this->processAutofilter($sheet); ++$worksheetID; } $this->processDefinedNames($gnmXML); // Return return $this->spreadsheet; } private function processMergedCells(?SimpleXMLElement $sheet): void { // Handle Merged Cells in this worksheet if ($sheet !== null && isset($sheet->MergedRegions)) { foreach ($sheet->MergedRegions->Merge as $mergeCells) { if (strpos((string) $mergeCells, ':') !== false) { $this->spreadsheet->getActiveSheet()->mergeCells($mergeCells); } } } } private function processAutofilter(?SimpleXMLElement $sheet): void { if ($sheet !== null && isset($sheet->Filters)) { foreach ($sheet->Filters->Filter as $autofilter) { if ($autofilter !== null) { $attributes = $autofilter->attributes(); if (isset($attributes['Area'])) { $this->spreadsheet->getActiveSheet()->setAutoFilter((string) $attributes['Area']); } } } } } private function setColumnWidth(int $whichColumn, float $defaultWidth): void { $columnDimension = $this->spreadsheet->getActiveSheet()->getColumnDimension(Coordinate::stringFromColumnIndex($whichColumn + 1)); if ($columnDimension !== null) { $columnDimension->setWidth($defaultWidth); } } private function setColumnInvisible(int $whichColumn): void { $columnDimension = $this->spreadsheet->getActiveSheet()->getColumnDimension(Coordinate::stringFromColumnIndex($whichColumn + 1)); if ($columnDimension !== null) { $columnDimension->setVisible(false); } } private function processColumnLoop(int $whichColumn, int $maxCol, ?SimpleXMLElement $columnOverride, float $defaultWidth): int { $columnOverride = self::testSimpleXml($columnOverride); $columnAttributes = self::testSimpleXml($columnOverride->attributes()); $column = $columnAttributes['No']; $columnWidth = ((float) $columnAttributes['Unit']) / 5.4; $hidden = (isset($columnAttributes['Hidden'])) && ((string) $columnAttributes['Hidden'] == '1'); $columnCount = (int) ($columnAttributes['Count'] ?? 1); while ($whichColumn < $column) { $this->setColumnWidth($whichColumn, $defaultWidth); ++$whichColumn; } while (($whichColumn < ($column + $columnCount)) && ($whichColumn <= $maxCol)) { $this->setColumnWidth($whichColumn, $columnWidth); if ($hidden) { $this->setColumnInvisible($whichColumn); } ++$whichColumn; } return $whichColumn; } private function processColumnWidths(?SimpleXMLElement $sheet, int $maxCol): void { if ((!$this->readDataOnly) && $sheet !== null && (isset($sheet->Cols))) { // Column Widths $defaultWidth = 0; $columnAttributes = $sheet->Cols->attributes(); if ($columnAttributes !== null) { $defaultWidth = $columnAttributes['DefaultSizePts'] / 5.4; } $whichColumn = 0; foreach ($sheet->Cols->ColInfo as $columnOverride) { $whichColumn = $this->processColumnLoop($whichColumn, $maxCol, $columnOverride, $defaultWidth); } while ($whichColumn <= $maxCol) { $this->setColumnWidth($whichColumn, $defaultWidth); ++$whichColumn; } } } private function setRowHeight(int $whichRow, float $defaultHeight): void { $rowDimension = $this->spreadsheet->getActiveSheet()->getRowDimension($whichRow); if ($rowDimension !== null) { $rowDimension->setRowHeight($defaultHeight); } } private function setRowInvisible(int $whichRow): void { $rowDimension = $this->spreadsheet->getActiveSheet()->getRowDimension($whichRow); if ($rowDimension !== null) { $rowDimension->setVisible(false); } } private function processRowLoop(int $whichRow, int $maxRow, ?SimpleXMLElement $rowOverride, float $defaultHeight): int { $rowOverride = self::testSimpleXml($rowOverride); $rowAttributes = self::testSimpleXml($rowOverride->attributes()); $row = $rowAttributes['No']; $rowHeight = (float) $rowAttributes['Unit']; $hidden = (isset($rowAttributes['Hidden'])) && ((string) $rowAttributes['Hidden'] == '1'); $rowCount = (int) ($rowAttributes['Count'] ?? 1); while ($whichRow < $row) { ++$whichRow; $this->setRowHeight($whichRow, $defaultHeight); } while (($whichRow < ($row + $rowCount)) && ($whichRow < $maxRow)) { ++$whichRow; $this->setRowHeight($whichRow, $rowHeight); if ($hidden) { $this->setRowInvisible($whichRow); } } return $whichRow; } private function processRowHeights(?SimpleXMLElement $sheet, int $maxRow): void { if ((!$this->readDataOnly) && $sheet !== null && (isset($sheet->Rows))) { // Row Heights $defaultHeight = 0; $rowAttributes = $sheet->Rows->attributes(); if ($rowAttributes !== null) { $defaultHeight = (float) $rowAttributes['DefaultSizePts']; } $whichRow = 0; foreach ($sheet->Rows->RowInfo as $rowOverride) { $whichRow = $this->processRowLoop($whichRow, $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 ($whichRow < $maxRow) { // ++$whichRow; // $this->spreadsheet->getActiveSheet()->getRowDimension($whichRow)->setRowHeight($defaultHeight); //} } } private function processDefinedNames(?SimpleXMLElement $gnmXML): void { // Loop through definedNames (global named ranges) if ($gnmXML !== null && 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 parseRichText(string $is): RichText { $value = new RichText(); $value->createText($is); return $value; } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Exception.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Exception.php
<?php namespace PhpOffice\PhpSpreadsheet\Reader; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; class Exception extends PhpSpreadsheetException { }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Csv.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Csv.php
<?php namespace PhpOffice\PhpSpreadsheet\Reader; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Reader\Csv\Delimiter; use PhpOffice\PhpSpreadsheet\Reader\Exception as ReaderException; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; use PhpOffice\PhpSpreadsheet\Spreadsheet; class Csv extends BaseReader { const DEFAULT_FALLBACK_ENCODING = 'CP1252'; const GUESS_ENCODING = 'guess'; 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'; /** * Fallback encoding if guess strikes out. * * @var string */ private $fallbackEncoding = self::DEFAULT_FALLBACK_ENCODING; /** * 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 = '\\'; /** * Callback for setting defaults in construction. * * @var ?callable */ private static $constructorCallback; /** * Create a new CSV Reader instance. */ public function __construct() { parent::__construct(); $callback = self::$constructorCallback; if ($callback !== null) { $callback($this); } } /** * Set a callback to change the defaults. * * The callback must accept the Csv Reader object as the first parameter, * and it should return void. */ public static function setConstructorCallback(?callable $callback): void { self::$constructorCallback = $callback; } public static function getConstructorCallback(): ?callable { return self::$constructorCallback; } public function setInputEncoding(string $encoding): self { $this->inputEncoding = $encoding; return $this; } public function getInputEncoding(): string { return $this->inputEncoding; } public function setFallbackEncoding(string $fallbackEncoding): self { $this->fallbackEncoding = $fallbackEncoding; return $this; } public function getFallbackEncoding(): string { return $this->fallbackEncoding; } /** * 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; } $inferenceEngine = new Delimiter($this->fileHandle, $this->escapeCharacter, $this->enclosure); // If number of lines is 0, nothing to infer : fall back to the default if ($inferenceEngine->linesCounted() === 0) { $this->delimiter = $inferenceEngine->getDefaultDelimiter(); $this->skipBOM(); return; } $this->delimiter = $inferenceEngine->infer(); // If no delimiter could be detected, fall back to the default if ($this->delimiter === null) { $this->delimiter = $inferenceEngine->getDefaultDelimiter(); } $this->skipBOM(); } /** * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns). */ public function listWorksheetInfo(string $filename): array { // Open file $this->openFileOrMemory($filename); $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 $rowData = fgetcsv($fileHandle, 0, $this->delimiter ?? '', $this->enclosure, $this->escapeCharacter); while (is_array($rowData)) { ++$worksheetInfo[0]['totalRows']; $worksheetInfo[0]['lastColumnIndex'] = max($worksheetInfo[0]['lastColumnIndex'], count($rowData) - 1); $rowData = fgetcsv($fileHandle, 0, $this->delimiter ?? '', $this->enclosure, $this->escapeCharacter); } $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. * * @return Spreadsheet */ public function load(string $filename, int $flags = 0) { $this->processFlags($flags); // Create new Spreadsheet $spreadsheet = new Spreadsheet(); // Load into this instance return $this->loadIntoExisting($filename, $spreadsheet); } private function openFileOrMemory(string $filename): void { // Open file $fhandle = $this->canRead($filename); if (!$fhandle) { throw new Exception($filename . ' is an Invalid Spreadsheet file.'); } if ($this->inputEncoding === self::GUESS_ENCODING) { $this->inputEncoding = self::guessEncoding($filename, $this->fallbackEncoding); } $this->openFile($filename); if ($this->inputEncoding !== 'UTF-8') { fclose($this->fileHandle); $entireFile = file_get_contents($filename); $this->fileHandle = fopen('php://memory', 'r+b'); if ($this->fileHandle !== false && $entireFile !== false) { $data = StringHelper::convertEncoding($entireFile, 'UTF-8', $this->inputEncoding); fwrite($this->fileHandle, $data); $this->skipBOM(); } } } private static function setAutoDetect(?string $value): ?string { $retVal = null; if ($value !== null) { $retVal2 = @ini_set('auto_detect_line_endings', $value); if (is_string($retVal2)) { $retVal = $retVal2; } } return $retVal; } /** * Loads PhpSpreadsheet from file into PhpSpreadsheet instance. */ public function loadIntoExisting(string $filename, Spreadsheet $spreadsheet): Spreadsheet { // Deprecated in Php8.1 $iniset = self::setAutoDetect('1'); // Open file $this->openFileOrMemory($filename); $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 $rowData = fgetcsv($fileHandle, 0, $this->delimiter ?? '', $this->enclosure, $this->escapeCharacter); $valueBinder = Cell::getValueBinder(); $preserveBooleanString = method_exists($valueBinder, 'getBooleanConversion') && $valueBinder->getBooleanConversion(); while (is_array($rowData)) { $noOutputYet = true; $columnLetter = 'A'; foreach ($rowData as $rowDatum) { $this->convertBoolean($rowDatum, $preserveBooleanString); 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; } $rowData = fgetcsv($fileHandle, 0, $this->delimiter ?? '', $this->enclosure, $this->escapeCharacter); ++$currentRow; } // Close file fclose($fileHandle); self::setAutoDetect($iniset); // Return return $spreadsheet; } /** * Convert string true/false to boolean, and null to null-string. * * @param mixed $rowDatum */ private function convertBoolean(&$rowDatum, bool $preserveBooleanString): void { if (is_string($rowDatum) && !$preserveBooleanString) { if (strcasecmp('true', $rowDatum) === 0) { $rowDatum = true; } elseif (strcasecmp('false', $rowDatum) === 0) { $rowDatum = false; } } elseif ($rowDatum === null) { $rowDatum = ''; } } public function getDelimiter(): ?string { return $this->delimiter; } public function setDelimiter(?string $delimiter): self { $this->delimiter = $delimiter; return $this; } public function getEnclosure(): string { return $this->enclosure; } public function setEnclosure(string $enclosure): self { if ($enclosure == '') { $enclosure = '"'; } $this->enclosure = $enclosure; return $this; } public function getSheetIndex(): int { return $this->sheetIndex; } public function setSheetIndex(int $indexValue): self { $this->sheetIndex = $indexValue; return $this; } public function setContiguous(bool $contiguous): self { $this->contiguous = $contiguous; return $this; } public function getContiguous(): bool { return $this->contiguous; } public function setEscapeCharacter(string $escapeCharacter): self { $this->escapeCharacter = $escapeCharacter; return $this; } public function getEscapeCharacter(): string { return $this->escapeCharacter; } /** * Can the current IReader read the file? */ public function canRead(string $filename): bool { // Check if file exists try { $this->openFile($filename); } catch (ReaderException $e) { return false; } fclose($this->fileHandle); // Trust file extension if any $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION)); if (in_array($extension, ['csv', 'tsv'])) { return true; } // Attempt to guess mimetype $type = mime_content_type($filename); $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 = self::DEFAULT_FALLBACK_ENCODING): string { $encoding = self::guessEncodingBom($filename); if ($encoding === '') { $encoding = self::guessEncodingNoBom($filename); } return ($encoding === '') ? $dflt : $encoding; } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/DefaultReadFilter.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/DefaultReadFilter.php
<?php namespace PhpOffice\PhpSpreadsheet\Reader; class DefaultReadFilter implements IReadFilter { /** * Should this cell be read? * * @param string $columnAddress 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($columnAddress, $row, $worksheetName = '') { return true; } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls.php
<?php namespace PhpOffice\PhpSpreadsheet\Reader; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Cell\DataType; use PhpOffice\PhpSpreadsheet\Cell\DataValidation; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; use PhpOffice\PhpSpreadsheet\NamedRange; use PhpOffice\PhpSpreadsheet\Reader\Xls\Style\CellFont; use PhpOffice\PhpSpreadsheet\RichText\RichText; use PhpOffice\PhpSpreadsheet\Shared\CodePage; use PhpOffice\PhpSpreadsheet\Shared\Date; use PhpOffice\PhpSpreadsheet\Shared\Escher; use PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer\BSE; use PhpOffice\PhpSpreadsheet\Shared\File; use PhpOffice\PhpSpreadsheet\Shared\OLE; use PhpOffice\PhpSpreadsheet\Shared\OLERead; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; use PhpOffice\PhpSpreadsheet\Shared\Xls as SharedXls; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Style\Alignment; use PhpOffice\PhpSpreadsheet\Style\Borders; use PhpOffice\PhpSpreadsheet\Style\Font; use PhpOffice\PhpSpreadsheet\Style\NumberFormat; use PhpOffice\PhpSpreadsheet\Style\Protection; use PhpOffice\PhpSpreadsheet\Style\Style; use PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing; use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup; use PhpOffice\PhpSpreadsheet\Worksheet\SheetView; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; // Original file header of ParseXL (used as the base for this class): // -------------------------------------------------------------------------------- // Adapted from Excel_Spreadsheet_Reader developed by users bizon153, // trex005, and mmp11 (SourceForge.net) // https://sourceforge.net/projects/phpexcelreader/ // Primary changes made by canyoncasa (dvc) for ParseXL 1.00 ... // Modelled moreso after Perl Excel Parse/Write modules // Added Parse_Excel_Spreadsheet object // Reads a whole worksheet or tab as row,column array or as // associated hash of indexed rows and named column fields // Added variables for worksheet (tab) indexes and names // Added an object call for loading individual woorksheets // Changed default indexing defaults to 0 based arrays // Fixed date/time and percent formats // Includes patches found at SourceForge... // unicode patch by nobody // unpack("d") machine depedency patch by matchy // boundsheet utf16 patch by bjaenichen // Renamed functions for shorter names // General code cleanup and rigor, including <80 column width // Included a testcase Excel file and PHP example calls // Code works for PHP 5.x // Primary changes made by canyoncasa (dvc) for ParseXL 1.10 ... // http://sourceforge.net/tracker/index.php?func=detail&aid=1466964&group_id=99160&atid=623334 // Decoding of formula conditions, results, and tokens. // Support for user-defined named cells added as an array "namedcells" // Patch code for user-defined named cells supports single cells only. // NOTE: this patch only works for BIFF8 as BIFF5-7 use a different // external sheet reference structure class Xls extends BaseReader { // ParseXL definitions const XLS_BIFF8 = 0x0600; const XLS_BIFF7 = 0x0500; const XLS_WORKBOOKGLOBALS = 0x0005; const XLS_WORKSHEET = 0x0010; // record identifiers const XLS_TYPE_FORMULA = 0x0006; const XLS_TYPE_EOF = 0x000a; const XLS_TYPE_PROTECT = 0x0012; const XLS_TYPE_OBJECTPROTECT = 0x0063; const XLS_TYPE_SCENPROTECT = 0x00dd; const XLS_TYPE_PASSWORD = 0x0013; const XLS_TYPE_HEADER = 0x0014; const XLS_TYPE_FOOTER = 0x0015; const XLS_TYPE_EXTERNSHEET = 0x0017; const XLS_TYPE_DEFINEDNAME = 0x0018; const XLS_TYPE_VERTICALPAGEBREAKS = 0x001a; const XLS_TYPE_HORIZONTALPAGEBREAKS = 0x001b; const XLS_TYPE_NOTE = 0x001c; const XLS_TYPE_SELECTION = 0x001d; const XLS_TYPE_DATEMODE = 0x0022; const XLS_TYPE_EXTERNNAME = 0x0023; const XLS_TYPE_LEFTMARGIN = 0x0026; const XLS_TYPE_RIGHTMARGIN = 0x0027; const XLS_TYPE_TOPMARGIN = 0x0028; const XLS_TYPE_BOTTOMMARGIN = 0x0029; const XLS_TYPE_PRINTGRIDLINES = 0x002b; const XLS_TYPE_FILEPASS = 0x002f; const XLS_TYPE_FONT = 0x0031; const XLS_TYPE_CONTINUE = 0x003c; const XLS_TYPE_PANE = 0x0041; const XLS_TYPE_CODEPAGE = 0x0042; const XLS_TYPE_DEFCOLWIDTH = 0x0055; const XLS_TYPE_OBJ = 0x005d; const XLS_TYPE_COLINFO = 0x007d; const XLS_TYPE_IMDATA = 0x007f; const XLS_TYPE_SHEETPR = 0x0081; const XLS_TYPE_HCENTER = 0x0083; const XLS_TYPE_VCENTER = 0x0084; const XLS_TYPE_SHEET = 0x0085; const XLS_TYPE_PALETTE = 0x0092; const XLS_TYPE_SCL = 0x00a0; const XLS_TYPE_PAGESETUP = 0x00a1; const XLS_TYPE_MULRK = 0x00bd; const XLS_TYPE_MULBLANK = 0x00be; const XLS_TYPE_DBCELL = 0x00d7; const XLS_TYPE_XF = 0x00e0; const XLS_TYPE_MERGEDCELLS = 0x00e5; const XLS_TYPE_MSODRAWINGGROUP = 0x00eb; const XLS_TYPE_MSODRAWING = 0x00ec; const XLS_TYPE_SST = 0x00fc; const XLS_TYPE_LABELSST = 0x00fd; const XLS_TYPE_EXTSST = 0x00ff; const XLS_TYPE_EXTERNALBOOK = 0x01ae; const XLS_TYPE_DATAVALIDATIONS = 0x01b2; const XLS_TYPE_TXO = 0x01b6; const XLS_TYPE_HYPERLINK = 0x01b8; const XLS_TYPE_DATAVALIDATION = 0x01be; const XLS_TYPE_DIMENSION = 0x0200; const XLS_TYPE_BLANK = 0x0201; const XLS_TYPE_NUMBER = 0x0203; const XLS_TYPE_LABEL = 0x0204; const XLS_TYPE_BOOLERR = 0x0205; const XLS_TYPE_STRING = 0x0207; const XLS_TYPE_ROW = 0x0208; const XLS_TYPE_INDEX = 0x020b; const XLS_TYPE_ARRAY = 0x0221; const XLS_TYPE_DEFAULTROWHEIGHT = 0x0225; const XLS_TYPE_WINDOW2 = 0x023e; const XLS_TYPE_RK = 0x027e; const XLS_TYPE_STYLE = 0x0293; const XLS_TYPE_FORMAT = 0x041e; const XLS_TYPE_SHAREDFMLA = 0x04bc; const XLS_TYPE_BOF = 0x0809; const XLS_TYPE_SHEETPROTECTION = 0x0867; const XLS_TYPE_RANGEPROTECTION = 0x0868; const XLS_TYPE_SHEETLAYOUT = 0x0862; const XLS_TYPE_XFEXT = 0x087d; const XLS_TYPE_PAGELAYOUTVIEW = 0x088b; const XLS_TYPE_UNKNOWN = 0xffff; // Encryption type const MS_BIFF_CRYPTO_NONE = 0; const MS_BIFF_CRYPTO_XOR = 1; const MS_BIFF_CRYPTO_RC4 = 2; // Size of stream blocks when using RC4 encryption const REKEY_BLOCK = 0x400; /** * Summary Information stream data. * * @var string */ private $summaryInformation; /** * Extended Summary Information stream data. * * @var string */ private $documentSummaryInformation; /** * Workbook stream data. (Includes workbook globals substream as well as sheet substreams). * * @var string */ private $data; /** * Size in bytes of $this->data. * * @var int */ private $dataSize; /** * Current position in stream. * * @var int */ private $pos; /** * Workbook to be returned by the reader. * * @var Spreadsheet */ private $spreadsheet; /** * Worksheet that is currently being built by the reader. * * @var Worksheet */ private $phpSheet; /** * BIFF version. * * @var int */ private $version; /** * Codepage set in the Excel file being read. Only important for BIFF5 (Excel 5.0 - Excel 95) * For BIFF8 (Excel 97 - Excel 2003) this will always have the value 'UTF-16LE'. * * @var string */ private $codepage; /** * Shared formats. * * @var array */ private $formats; /** * Shared fonts. * * @var Font[] */ private $objFonts; /** * Color palette. * * @var array */ private $palette; /** * Worksheets. * * @var array */ private $sheets; /** * External books. * * @var array */ private $externalBooks; /** * REF structures. Only applies to BIFF8. * * @var array */ private $ref; /** * External names. * * @var array */ private $externalNames; /** * Defined names. * * @var array */ private $definedname; /** * Shared strings. Only applies to BIFF8. * * @var array */ private $sst; /** * Panes are frozen? (in sheet currently being read). See WINDOW2 record. * * @var bool */ private $frozen; /** * Fit printout to number of pages? (in sheet currently being read). See SHEETPR record. * * @var bool */ private $isFitToPages; /** * Objects. One OBJ record contributes with one entry. * * @var array */ private $objs; /** * Text Objects. One TXO record corresponds with one entry. * * @var array */ private $textObjects; /** * Cell Annotations (BIFF8). * * @var array */ private $cellNotes; /** * The combined MSODRAWINGGROUP data. * * @var string */ private $drawingGroupData; /** * The combined MSODRAWING data (per sheet). * * @var string */ private $drawingData; /** * Keep track of XF index. * * @var int */ private $xfIndex; /** * Mapping of XF index (that is a cell XF) to final index in cellXf collection. * * @var array */ private $mapCellXfIndex; /** * Mapping of XF index (that is a style XF) to final index in cellStyleXf collection. * * @var array */ private $mapCellStyleXfIndex; /** * The shared formulas in a sheet. One SHAREDFMLA record contributes with one value. * * @var array */ private $sharedFormulas; /** * The shared formula parts in a sheet. One FORMULA record contributes with one value if it * refers to a shared formula. * * @var array */ private $sharedFormulaParts; /** * The type of encryption in use. * * @var int */ private $encryption = 0; /** * The position in the stream after which contents are encrypted. * * @var int */ private $encryptionStartPos = 0; /** * The current RC4 decryption object. * * @var Xls\RC4 */ private $rc4Key; /** * The position in the stream that the RC4 decryption object was left at. * * @var int */ private $rc4Pos = 0; /** * The current MD5 context state. * * @var string */ private $md5Ctxt; /** * @var int */ private $textObjRef; /** * @var string */ private $baseCell; /** * Create a new Xls Reader instance. */ public function __construct() { parent::__construct(); } /** * Can the current IReader read the file? */ public function canRead(string $filename): bool { if (!File::testFileNoThrow($filename)) { return false; } try { // Use ParseXL for the hard work. $ole = new OLERead(); // get excel data $ole->read($filename); return true; } catch (PhpSpreadsheetException $e) { return false; } } public function setCodepage(string $codepage): void { if (!CodePage::validate($codepage)) { throw new PhpSpreadsheetException('Unknown codepage: ' . $codepage); } $this->codepage = $codepage; } /** * Reads names of the worksheets from a file, without parsing the whole file to a PhpSpreadsheet object. * * @param string $filename * * @return array */ public function listWorksheetNames($filename) { File::assertFile($filename); $worksheetNames = []; // Read the OLE file $this->loadOLE($filename); // total byte size of Excel data (workbook global substream + sheet substreams) $this->dataSize = strlen($this->data); $this->pos = 0; $this->sheets = []; // Parse Workbook Global Substream while ($this->pos < $this->dataSize) { $code = self::getUInt2d($this->data, $this->pos); switch ($code) { case self::XLS_TYPE_BOF: $this->readBof(); break; case self::XLS_TYPE_SHEET: $this->readSheet(); break; case self::XLS_TYPE_EOF: $this->readDefault(); break 2; default: $this->readDefault(); break; } } foreach ($this->sheets as $sheet) { if ($sheet['sheetType'] != 0x00) { // 0x00: Worksheet, 0x02: Chart, 0x06: Visual Basic module continue; } $worksheetNames[] = $sheet['name']; } return $worksheetNames; } /** * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns). * * @param string $filename * * @return array */ public function listWorksheetInfo($filename) { File::assertFile($filename); $worksheetInfo = []; // Read the OLE file $this->loadOLE($filename); // total byte size of Excel data (workbook global substream + sheet substreams) $this->dataSize = strlen($this->data); // initialize $this->pos = 0; $this->sheets = []; // Parse Workbook Global Substream while ($this->pos < $this->dataSize) { $code = self::getUInt2d($this->data, $this->pos); switch ($code) { case self::XLS_TYPE_BOF: $this->readBof(); break; case self::XLS_TYPE_SHEET: $this->readSheet(); break; case self::XLS_TYPE_EOF: $this->readDefault(); break 2; default: $this->readDefault(); break; } } // Parse the individual sheets foreach ($this->sheets as $sheet) { if ($sheet['sheetType'] != 0x00) { // 0x00: Worksheet // 0x02: Chart // 0x06: Visual Basic module continue; } $tmpInfo = []; $tmpInfo['worksheetName'] = $sheet['name']; $tmpInfo['lastColumnLetter'] = 'A'; $tmpInfo['lastColumnIndex'] = 0; $tmpInfo['totalRows'] = 0; $tmpInfo['totalColumns'] = 0; $this->pos = $sheet['offset']; while ($this->pos <= $this->dataSize - 4) { $code = self::getUInt2d($this->data, $this->pos); switch ($code) { case self::XLS_TYPE_RK: case self::XLS_TYPE_LABELSST: case self::XLS_TYPE_NUMBER: case self::XLS_TYPE_FORMULA: case self::XLS_TYPE_BOOLERR: case self::XLS_TYPE_LABEL: $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; $rowIndex = self::getUInt2d($recordData, 0) + 1; $columnIndex = self::getUInt2d($recordData, 2); $tmpInfo['totalRows'] = max($tmpInfo['totalRows'], $rowIndex); $tmpInfo['lastColumnIndex'] = max($tmpInfo['lastColumnIndex'], $columnIndex); break; case self::XLS_TYPE_BOF: $this->readBof(); break; case self::XLS_TYPE_EOF: $this->readDefault(); break 2; default: $this->readDefault(); break; } } $tmpInfo['lastColumnLetter'] = Coordinate::stringFromColumnIndex($tmpInfo['lastColumnIndex'] + 1); $tmpInfo['totalColumns'] = $tmpInfo['lastColumnIndex'] + 1; $worksheetInfo[] = $tmpInfo; } return $worksheetInfo; } /** * Loads PhpSpreadsheet from file. * * @return Spreadsheet */ public function load(string $filename, int $flags = 0) { $this->processFlags($flags); // Read the OLE file $this->loadOLE($filename); // Initialisations $this->spreadsheet = new Spreadsheet(); $this->spreadsheet->removeSheetByIndex(0); // remove 1st sheet if (!$this->readDataOnly) { $this->spreadsheet->removeCellStyleXfByIndex(0); // remove the default style $this->spreadsheet->removeCellXfByIndex(0); // remove the default style } // Read the summary information stream (containing meta data) $this->readSummaryInformation(); // Read the Additional document summary information stream (containing application-specific meta data) $this->readDocumentSummaryInformation(); // total byte size of Excel data (workbook global substream + sheet substreams) $this->dataSize = strlen($this->data); // initialize $this->pos = 0; $this->codepage = $this->codepage ?: CodePage::DEFAULT_CODE_PAGE; $this->formats = []; $this->objFonts = []; $this->palette = []; $this->sheets = []; $this->externalBooks = []; $this->ref = []; $this->definedname = []; $this->sst = []; $this->drawingGroupData = ''; $this->xfIndex = 0; $this->mapCellXfIndex = []; $this->mapCellStyleXfIndex = []; // Parse Workbook Global Substream while ($this->pos < $this->dataSize) { $code = self::getUInt2d($this->data, $this->pos); switch ($code) { case self::XLS_TYPE_BOF: $this->readBof(); break; case self::XLS_TYPE_FILEPASS: $this->readFilepass(); break; case self::XLS_TYPE_CODEPAGE: $this->readCodepage(); break; case self::XLS_TYPE_DATEMODE: $this->readDateMode(); break; case self::XLS_TYPE_FONT: $this->readFont(); break; case self::XLS_TYPE_FORMAT: $this->readFormat(); break; case self::XLS_TYPE_XF: $this->readXf(); break; case self::XLS_TYPE_XFEXT: $this->readXfExt(); break; case self::XLS_TYPE_STYLE: $this->readStyle(); break; case self::XLS_TYPE_PALETTE: $this->readPalette(); break; case self::XLS_TYPE_SHEET: $this->readSheet(); break; case self::XLS_TYPE_EXTERNALBOOK: $this->readExternalBook(); break; case self::XLS_TYPE_EXTERNNAME: $this->readExternName(); break; case self::XLS_TYPE_EXTERNSHEET: $this->readExternSheet(); break; case self::XLS_TYPE_DEFINEDNAME: $this->readDefinedName(); break; case self::XLS_TYPE_MSODRAWINGGROUP: $this->readMsoDrawingGroup(); break; case self::XLS_TYPE_SST: $this->readSst(); break; case self::XLS_TYPE_EOF: $this->readDefault(); break 2; default: $this->readDefault(); break; } } // Resolve indexed colors for font, fill, and border colors // Cannot be resolved already in XF record, because PALETTE record comes afterwards if (!$this->readDataOnly) { foreach ($this->objFonts as $objFont) { if (isset($objFont->colorIndex)) { $color = Xls\Color::map($objFont->colorIndex, $this->palette, $this->version); $objFont->getColor()->setRGB($color['rgb']); } } foreach ($this->spreadsheet->getCellXfCollection() as $objStyle) { // fill start and end color $fill = $objStyle->getFill(); if (isset($fill->startcolorIndex)) { $startColor = Xls\Color::map($fill->startcolorIndex, $this->palette, $this->version); $fill->getStartColor()->setRGB($startColor['rgb']); } if (isset($fill->endcolorIndex)) { $endColor = Xls\Color::map($fill->endcolorIndex, $this->palette, $this->version); $fill->getEndColor()->setRGB($endColor['rgb']); } // border colors $top = $objStyle->getBorders()->getTop(); $right = $objStyle->getBorders()->getRight(); $bottom = $objStyle->getBorders()->getBottom(); $left = $objStyle->getBorders()->getLeft(); $diagonal = $objStyle->getBorders()->getDiagonal(); if (isset($top->colorIndex)) { $borderTopColor = Xls\Color::map($top->colorIndex, $this->palette, $this->version); $top->getColor()->setRGB($borderTopColor['rgb']); } if (isset($right->colorIndex)) { $borderRightColor = Xls\Color::map($right->colorIndex, $this->palette, $this->version); $right->getColor()->setRGB($borderRightColor['rgb']); } if (isset($bottom->colorIndex)) { $borderBottomColor = Xls\Color::map($bottom->colorIndex, $this->palette, $this->version); $bottom->getColor()->setRGB($borderBottomColor['rgb']); } if (isset($left->colorIndex)) { $borderLeftColor = Xls\Color::map($left->colorIndex, $this->palette, $this->version); $left->getColor()->setRGB($borderLeftColor['rgb']); } if (isset($diagonal->colorIndex)) { $borderDiagonalColor = Xls\Color::map($diagonal->colorIndex, $this->palette, $this->version); $diagonal->getColor()->setRGB($borderDiagonalColor['rgb']); } } } // treat MSODRAWINGGROUP records, workbook-level Escher $escherWorkbook = null; if (!$this->readDataOnly && $this->drawingGroupData) { $escher = new Escher(); $reader = new Xls\Escher($escher); $escherWorkbook = $reader->load($this->drawingGroupData); } // Parse the individual sheets foreach ($this->sheets as $sheet) { if ($sheet['sheetType'] != 0x00) { // 0x00: Worksheet, 0x02: Chart, 0x06: Visual Basic module continue; } // check if sheet should be skipped if (isset($this->loadSheetsOnly) && !in_array($sheet['name'], $this->loadSheetsOnly)) { continue; } // add sheet to PhpSpreadsheet object $this->phpSheet = $this->spreadsheet->createSheet(); // 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->phpSheet->setTitle($sheet['name'], false, false); $this->phpSheet->setSheetState($sheet['sheetState']); $this->pos = $sheet['offset']; // Initialize isFitToPages. May change after reading SHEETPR record. $this->isFitToPages = false; // Initialize drawingData $this->drawingData = ''; // Initialize objs $this->objs = []; // Initialize shared formula parts $this->sharedFormulaParts = []; // Initialize shared formulas $this->sharedFormulas = []; // Initialize text objs $this->textObjects = []; // Initialize cell annotations $this->cellNotes = []; $this->textObjRef = -1; while ($this->pos <= $this->dataSize - 4) { $code = self::getUInt2d($this->data, $this->pos); switch ($code) { case self::XLS_TYPE_BOF: $this->readBof(); break; case self::XLS_TYPE_PRINTGRIDLINES: $this->readPrintGridlines(); break; case self::XLS_TYPE_DEFAULTROWHEIGHT: $this->readDefaultRowHeight(); break; case self::XLS_TYPE_SHEETPR: $this->readSheetPr(); break; case self::XLS_TYPE_HORIZONTALPAGEBREAKS: $this->readHorizontalPageBreaks(); break; case self::XLS_TYPE_VERTICALPAGEBREAKS: $this->readVerticalPageBreaks(); break; case self::XLS_TYPE_HEADER: $this->readHeader(); break; case self::XLS_TYPE_FOOTER: $this->readFooter(); break; case self::XLS_TYPE_HCENTER: $this->readHcenter(); break; case self::XLS_TYPE_VCENTER: $this->readVcenter(); break; case self::XLS_TYPE_LEFTMARGIN: $this->readLeftMargin(); break; case self::XLS_TYPE_RIGHTMARGIN: $this->readRightMargin(); break; case self::XLS_TYPE_TOPMARGIN: $this->readTopMargin(); break; case self::XLS_TYPE_BOTTOMMARGIN: $this->readBottomMargin(); break; case self::XLS_TYPE_PAGESETUP: $this->readPageSetup(); break; case self::XLS_TYPE_PROTECT: $this->readProtect(); break; case self::XLS_TYPE_SCENPROTECT: $this->readScenProtect(); break; case self::XLS_TYPE_OBJECTPROTECT: $this->readObjectProtect(); break; case self::XLS_TYPE_PASSWORD: $this->readPassword(); break; case self::XLS_TYPE_DEFCOLWIDTH: $this->readDefColWidth(); break; case self::XLS_TYPE_COLINFO: $this->readColInfo(); break; case self::XLS_TYPE_DIMENSION: $this->readDefault(); break; case self::XLS_TYPE_ROW: $this->readRow(); break; case self::XLS_TYPE_DBCELL: $this->readDefault(); break; case self::XLS_TYPE_RK: $this->readRk(); break; case self::XLS_TYPE_LABELSST: $this->readLabelSst(); break; case self::XLS_TYPE_MULRK: $this->readMulRk(); break; case self::XLS_TYPE_NUMBER: $this->readNumber(); break; case self::XLS_TYPE_FORMULA: $this->readFormula(); break; case self::XLS_TYPE_SHAREDFMLA: $this->readSharedFmla(); break; case self::XLS_TYPE_BOOLERR: $this->readBoolErr(); break; case self::XLS_TYPE_MULBLANK: $this->readMulBlank(); break; case self::XLS_TYPE_LABEL: $this->readLabel(); break; case self::XLS_TYPE_BLANK: $this->readBlank(); break; case self::XLS_TYPE_MSODRAWING: $this->readMsoDrawing(); break; case self::XLS_TYPE_OBJ: $this->readObj(); break; case self::XLS_TYPE_WINDOW2: $this->readWindow2(); break; case self::XLS_TYPE_PAGELAYOUTVIEW: $this->readPageLayoutView(); break; case self::XLS_TYPE_SCL: $this->readScl(); break; case self::XLS_TYPE_PANE: $this->readPane(); break; case self::XLS_TYPE_SELECTION: $this->readSelection(); break; case self::XLS_TYPE_MERGEDCELLS: $this->readMergedCells(); break; case self::XLS_TYPE_HYPERLINK: $this->readHyperLink(); break; case self::XLS_TYPE_DATAVALIDATIONS: $this->readDataValidations(); break; case self::XLS_TYPE_DATAVALIDATION: $this->readDataValidation(); break; case self::XLS_TYPE_SHEETLAYOUT: $this->readSheetLayout(); break; case self::XLS_TYPE_SHEETPROTECTION: $this->readSheetProtection(); break; case self::XLS_TYPE_RANGEPROTECTION: $this->readRangeProtection(); break; case self::XLS_TYPE_NOTE: $this->readNote(); break; case self::XLS_TYPE_TXO: $this->readTextObject(); break; case self::XLS_TYPE_CONTINUE: $this->readContinue(); break; case self::XLS_TYPE_EOF: $this->readDefault(); break 2; default: $this->readDefault(); break; } } // treat MSODRAWING records, sheet-level Escher if (!$this->readDataOnly && $this->drawingData) { $escherWorksheet = new Escher(); $reader = new Xls\Escher($escherWorksheet); $escherWorksheet = $reader->load($this->drawingData);
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
true
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml.php
<?php namespace PhpOffice\PhpSpreadsheet\Reader; use DateTime; use DateTimeZone; use PhpOffice\PhpSpreadsheet\Cell\AddressHelper; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Cell\DataType; use PhpOffice\PhpSpreadsheet\DefinedName; use PhpOffice\PhpSpreadsheet\Reader\Security\XmlScanner; use PhpOffice\PhpSpreadsheet\Reader\Xml\PageSettings; use PhpOffice\PhpSpreadsheet\Reader\Xml\Properties; use PhpOffice\PhpSpreadsheet\Reader\Xml\Style; 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 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 = ''; public static function xmlMappings(): array { return array_merge( Style\Fill::FILL_MAPPINGS, Style\Border::BORDER_MAPPINGS ); } /** * Can the current IReader read the file? */ public function canRead(string $filename): bool { // 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"', 'xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet', ]; // Open file $data = file_get_contents($filename); // 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 $filename * * @return false|SimpleXMLElement */ public function trySimpleXMLLoadString($filename) { try { $xml = simplexml_load_string( $this->securityScanner->scan($this->fileContents ?: file_get_contents($filename)), 'SimpleXMLElement', Settings::getLibXmlLoaderOptions() ); } catch (\Exception $e) { throw new Exception('Cannot load invalid XML file: ' . $filename, 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 $filename * * @return array */ public function listWorksheetNames($filename) { File::assertFile($filename); if (!$this->canRead($filename)) { throw new Exception($filename . ' is an Invalid Spreadsheet file.'); } $worksheetNames = []; $xml = $this->trySimpleXMLLoadString($filename); if ($xml === false) { throw new Exception("Problem reading {$filename}"); } $namespaces = $xml->getNamespaces(true); $xml_ss = $xml->children($namespaces['ss']); foreach ($xml_ss->Worksheet as $worksheet) { $worksheet_ss = self::getAttributes($worksheet, $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 $filename * * @return array */ public function listWorksheetInfo($filename) { File::assertFile($filename); if (!$this->canRead($filename)) { throw new Exception($filename . ' is an Invalid Spreadsheet file.'); } $worksheetInfo = []; $xml = $this->trySimpleXMLLoadString($filename); if ($xml === false) { throw new Exception("Problem reading {$filename}"); } $namespaces = $xml->getNamespaces(true); $worksheetID = 1; $xml_ss = $xml->children($namespaces['ss']); foreach ($xml_ss->Worksheet as $worksheet) { $worksheet_ss = self::getAttributes($worksheet, $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. * * @return Spreadsheet */ public function load(string $filename, int $flags = 0) { $this->processFlags($flags); // Create new Spreadsheet $spreadsheet = new Spreadsheet(); $spreadsheet->removeSheetByIndex(0); // Load into this instance return $this->loadIntoExisting($filename, $spreadsheet); } /** * Loads from file into Spreadsheet instance. * * @param string $filename * * @return Spreadsheet */ public function loadIntoExisting($filename, Spreadsheet $spreadsheet) { File::assertFile($filename); if (!$this->canRead($filename)) { throw new Exception($filename . ' is an Invalid Spreadsheet file.'); } $xml = $this->trySimpleXMLLoadString($filename); if ($xml === false) { throw new Exception("Problem reading {$filename}"); } $namespaces = $xml->getNamespaces(true); (new Properties($spreadsheet))->readProperties($xml, $namespaces); $this->styles = (new Style())->parseStyles($xml, $namespaces); $worksheetID = 0; $xml_ss = $xml->children($namespaces['ss']); /** @var null|SimpleXMLElement $worksheetx */ foreach ($xml_ss->Worksheet as $worksheetx) { $worksheet = $worksheetx ?? new SimpleXMLElement('<xml></xml>'); $worksheet_ss = self::getAttributes($worksheet, $namespaces['ss']); if ( isset($this->loadSheetsOnly, $worksheet_ss['Name']) && (!in_array($worksheet_ss['Name'], $this->loadSheetsOnly)) ) { continue; } // Create new Worksheet $spreadsheet->createSheet(); $spreadsheet->setActiveSheetIndex($worksheetID); $worksheetName = ''; 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 = self::getAttributes($definedName, $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 = self::getAttributes($columnData, $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 = self::getAttributes($rowData, $namespaces['ss']); if (isset($row_ss['Index'])) { $rowID = (int) $row_ss['Index']; } $columnID = 'A'; foreach ($rowData->Cell as $cell) { $cell_ss = self::getAttributes($cell, $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((int) (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 = self::getAttributes($cellData, $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; $dateTime = new DateTime($cellValue, new DateTimeZone('UTC')); $cellValue = Date::PHPToExcel($dateTime); 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)) { $this->parseCellComment($cell->Comment, $namespaces, $spreadsheet, $columnID, $rowID); } 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((float) $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 = self::getAttributes($definedName, $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 parseCellComment( SimpleXMLElement $comment, array $namespaces, Spreadsheet $spreadsheet, string $columnID, int $rowID ): void { $commentAttributes = $comment->attributes($namespaces['ss']); $author = 'unknown'; if (isset($commentAttributes->Author)) { $author = (string) $commentAttributes->Author; } $node = $comment->Data->asXML(); $annotation = strip_tags((string) $node); $spreadsheet->getActiveSheet()->getComment($columnID . $rowID) ->setAuthor($author) ->setText($this->parseRichText($annotation)); } protected function parseRichText(string $annotation): RichText { $value = new RichText(); $value->createText($annotation); return $value; } private static function getAttributes(?SimpleXMLElement $simple, string $node): SimpleXMLElement { return ($simple === null) ? new SimpleXMLElement('<xml></xml>') : ($simple->attributes($node) ?? new SimpleXMLElement('<xml></xml>')); } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/IReader.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/IReader.php
<?php namespace PhpOffice\PhpSpreadsheet\Reader; interface IReader { public const LOAD_WITH_CHARTS = 1; /** * IReader constructor. */ public function __construct(); /** * Can the current IReader read the file? */ public function canRead(string $filename): bool; /** * 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 $readDataOnly * * @return IReader */ public function setReadDataOnly($readDataOnly); /** * 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 $readEmptyCells * * @return IReader */ public function setReadEmptyCells($readEmptyCells); /** * 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 $includeCharts * * @return IReader */ public function setIncludeCharts($includeCharts); /** * 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 $readFilter); /** * Loads PhpSpreadsheet from file. * * @return \PhpOffice\PhpSpreadsheet\Spreadsheet */ public function load(string $filename, int $flags = 0); }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Html.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Html.php
<?php namespace PhpOffice\PhpSpreadsheet\Reader; use DOMDocument; use DOMElement; use DOMNode; use DOMText; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Helper\Dimension as CssDimension; use PhpOffice\PhpSpreadsheet\Reader\Security\XmlScanner; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Style\Border; use PhpOffice\PhpSpreadsheet\Style\Color; use PhpOffice\PhpSpreadsheet\Style\Fill; use PhpOffice\PhpSpreadsheet\Style\Font; use PhpOffice\PhpSpreadsheet\Style\Style; use PhpOffice\PhpSpreadsheet\Worksheet\Drawing; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; use Throwable; /** PhpSpreadsheet root directory */ class Html extends BaseReader { /** * Sample size to read to determine if it's HTML or not. */ const TEST_SAMPLE_SIZE = 2048; /** * Input encoding. * * @var string */ protected $inputEncoding = 'ANSI'; /** * Sheet index to read. * * @var int */ protected $sheetIndex = 0; /** * Formats. * * @var array */ protected $formats = [ 'h1' => [ 'font' => [ 'bold' => true, 'size' => 24, ], ], // Bold, 24pt 'h2' => [ 'font' => [ 'bold' => true, 'size' => 18, ], ], // Bold, 18pt 'h3' => [ 'font' => [ 'bold' => true, 'size' => 13.5, ], ], // Bold, 13.5pt 'h4' => [ 'font' => [ 'bold' => true, 'size' => 12, ], ], // Bold, 12pt 'h5' => [ 'font' => [ 'bold' => true, 'size' => 10, ], ], // Bold, 10pt 'h6' => [ 'font' => [ 'bold' => true, 'size' => 7.5, ], ], // Bold, 7.5pt 'a' => [ 'font' => [ 'underline' => true, 'color' => [ 'argb' => Color::COLOR_BLUE, ], ], ], // Blue underlined 'hr' => [ 'borders' => [ 'bottom' => [ 'borderStyle' => Border::BORDER_THIN, 'color' => [ Color::COLOR_BLACK, ], ], ], ], // Bottom border 'strong' => [ 'font' => [ 'bold' => true, ], ], // Bold 'b' => [ 'font' => [ 'bold' => true, ], ], // Bold 'i' => [ 'font' => [ 'italic' => true, ], ], // Italic 'em' => [ 'font' => [ 'italic' => true, ], ], // Italic ]; /** @var array */ protected $rowspan = []; /** * Create a new HTML Reader instance. */ public function __construct() { parent::__construct(); $this->securityScanner = XmlScanner::getInstance($this); } /** * Validate that the current file is an HTML file. */ public function canRead(string $filename): bool { // Check if file exists try { $this->openFile($filename); } catch (Exception $e) { return false; } $beginning = $this->readBeginning(); $startWithTag = self::startsWithTag($beginning); $containsTags = self::containsTags($beginning); $endsWithTag = self::endsWithTag($this->readEnding()); fclose($this->fileHandle); return $startWithTag && $containsTags && $endsWithTag; } private function readBeginning(): string { fseek($this->fileHandle, 0); return (string) fread($this->fileHandle, self::TEST_SAMPLE_SIZE); } private function readEnding(): string { $meta = stream_get_meta_data($this->fileHandle); $filename = $meta['uri']; $size = (int) filesize($filename); if ($size === 0) { return ''; } $blockSize = self::TEST_SAMPLE_SIZE; if ($size < $blockSize) { $blockSize = $size; } fseek($this->fileHandle, $size - $blockSize); return (string) fread($this->fileHandle, $blockSize); } private static function startsWithTag(string $data): bool { return '<' === substr(trim($data), 0, 1); } private static function endsWithTag(string $data): bool { return '>' === substr(trim($data), -1, 1); } private static function containsTags(string $data): bool { return strlen($data) !== strlen(strip_tags($data)); } /** * Loads Spreadsheet from file. * * @return Spreadsheet */ public function load(string $filename, int $flags = 0) { $this->processFlags($flags); // Create new Spreadsheet $spreadsheet = new Spreadsheet(); // Load into this instance return $this->loadIntoExisting($filename, $spreadsheet); } /** * Set input encoding. * * @param string $inputEncoding Input encoding, eg: 'ANSI' * * @return $this * * @codeCoverageIgnore * * @deprecated no use is made of this property */ public function setInputEncoding($inputEncoding) { $this->inputEncoding = $inputEncoding; return $this; } /** * Get input encoding. * * @return string * * @codeCoverageIgnore * * @deprecated no use is made of this property */ public function getInputEncoding() { return $this->inputEncoding; } // Data Array used for testing only, should write to Spreadsheet object on completion of tests /** @var array */ protected $dataArray = []; /** @var int */ protected $tableLevel = 0; /** @var array */ protected $nestedColumn = ['A']; protected function setTableStartColumn(string $column): string { if ($this->tableLevel == 0) { $column = 'A'; } ++$this->tableLevel; $this->nestedColumn[$this->tableLevel] = $column; return $this->nestedColumn[$this->tableLevel]; } protected function getTableStartColumn(): string { return $this->nestedColumn[$this->tableLevel]; } protected function releaseTableStartColumn(): string { --$this->tableLevel; return array_pop($this->nestedColumn); } /** * Flush cell. * * @param string $column * @param int|string $row * @param mixed $cellContent */ protected function flushCell(Worksheet $sheet, $column, $row, &$cellContent): void { if (is_string($cellContent)) { // Simple String content if (trim($cellContent) > '') { // Only actually write it if there's content in the string // Write to worksheet to be done here... // ... we return the cell so we can mess about with styles more easily $sheet->setCellValue($column . $row, $cellContent); $this->dataArray[$row][$column] = $cellContent; } } else { // We have a Rich Text run // TODO $this->dataArray[$row][$column] = 'RICH TEXT: ' . $cellContent; } $cellContent = (string) ''; } private function processDomElementBody(Worksheet $sheet, int &$row, string &$column, string &$cellContent, DOMElement $child): void { $attributeArray = []; foreach (($child->attributes ?? []) as $attribute) { $attributeArray[$attribute->name] = $attribute->value; } if ($child->nodeName === 'body') { $row = 1; $column = 'A'; $cellContent = ''; $this->tableLevel = 0; $this->processDomElement($child, $sheet, $row, $column, $cellContent); } else { $this->processDomElementTitle($sheet, $row, $column, $cellContent, $child, $attributeArray); } } private function processDomElementTitle(Worksheet $sheet, int &$row, string &$column, string &$cellContent, DOMElement $child, array &$attributeArray): void { if ($child->nodeName === 'title') { $this->processDomElement($child, $sheet, $row, $column, $cellContent); $sheet->setTitle($cellContent, true, true); $cellContent = ''; } else { $this->processDomElementSpanEtc($sheet, $row, $column, $cellContent, $child, $attributeArray); } } private const SPAN_ETC = ['span', 'div', 'font', 'i', 'em', 'strong', 'b']; private function processDomElementSpanEtc(Worksheet $sheet, int &$row, string &$column, string &$cellContent, DOMElement $child, array &$attributeArray): void { if (in_array((string) $child->nodeName, self::SPAN_ETC, true)) { if (isset($attributeArray['class']) && $attributeArray['class'] === 'comment') { $sheet->getComment($column . $row) ->getText() ->createTextRun($child->textContent); } else { $this->processDomElement($child, $sheet, $row, $column, $cellContent); } if (isset($this->formats[$child->nodeName])) { $sheet->getStyle($column . $row)->applyFromArray($this->formats[$child->nodeName]); } } else { $this->processDomElementHr($sheet, $row, $column, $cellContent, $child, $attributeArray); } } private function processDomElementHr(Worksheet $sheet, int &$row, string &$column, string &$cellContent, DOMElement $child, array &$attributeArray): void { if ($child->nodeName === 'hr') { $this->flushCell($sheet, $column, $row, $cellContent); ++$row; if (isset($this->formats[$child->nodeName])) { $sheet->getStyle($column . $row)->applyFromArray($this->formats[$child->nodeName]); } ++$row; } // fall through to br $this->processDomElementBr($sheet, $row, $column, $cellContent, $child, $attributeArray); } private function processDomElementBr(Worksheet $sheet, int &$row, string &$column, string &$cellContent, DOMElement $child, array &$attributeArray): void { if ($child->nodeName === 'br' || $child->nodeName === 'hr') { if ($this->tableLevel > 0) { // If we're inside a table, replace with a \n and set the cell to wrap $cellContent .= "\n"; $sheet->getStyle($column . $row)->getAlignment()->setWrapText(true); } else { // Otherwise flush our existing content and move the row cursor on $this->flushCell($sheet, $column, $row, $cellContent); ++$row; } } else { $this->processDomElementA($sheet, $row, $column, $cellContent, $child, $attributeArray); } } private function processDomElementA(Worksheet $sheet, int &$row, string &$column, string &$cellContent, DOMElement $child, array &$attributeArray): void { if ($child->nodeName === 'a') { foreach ($attributeArray as $attributeName => $attributeValue) { switch ($attributeName) { case 'href': $sheet->getCell($column . $row)->getHyperlink()->setUrl($attributeValue); if (isset($this->formats[$child->nodeName])) { $sheet->getStyle($column . $row)->applyFromArray($this->formats[$child->nodeName]); } break; case 'class': if ($attributeValue === 'comment-indicator') { break; // Ignore - it's just a red square. } } } // no idea why this should be needed //$cellContent .= ' '; $this->processDomElement($child, $sheet, $row, $column, $cellContent); } else { $this->processDomElementH1Etc($sheet, $row, $column, $cellContent, $child, $attributeArray); } } private const H1_ETC = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'ol', 'ul', 'p']; private function processDomElementH1Etc(Worksheet $sheet, int &$row, string &$column, string &$cellContent, DOMElement $child, array &$attributeArray): void { if (in_array((string) $child->nodeName, self::H1_ETC, true)) { if ($this->tableLevel > 0) { // If we're inside a table, replace with a \n $cellContent .= $cellContent ? "\n" : ''; $sheet->getStyle($column . $row)->getAlignment()->setWrapText(true); $this->processDomElement($child, $sheet, $row, $column, $cellContent); } else { if ($cellContent > '') { $this->flushCell($sheet, $column, $row, $cellContent); ++$row; } $this->processDomElement($child, $sheet, $row, $column, $cellContent); $this->flushCell($sheet, $column, $row, $cellContent); if (isset($this->formats[$child->nodeName])) { $sheet->getStyle($column . $row)->applyFromArray($this->formats[$child->nodeName]); } ++$row; $column = 'A'; } } else { $this->processDomElementLi($sheet, $row, $column, $cellContent, $child, $attributeArray); } } private function processDomElementLi(Worksheet $sheet, int &$row, string &$column, string &$cellContent, DOMElement $child, array &$attributeArray): void { if ($child->nodeName === 'li') { if ($this->tableLevel > 0) { // If we're inside a table, replace with a \n $cellContent .= $cellContent ? "\n" : ''; $this->processDomElement($child, $sheet, $row, $column, $cellContent); } else { if ($cellContent > '') { $this->flushCell($sheet, $column, $row, $cellContent); } ++$row; $this->processDomElement($child, $sheet, $row, $column, $cellContent); $this->flushCell($sheet, $column, $row, $cellContent); $column = 'A'; } } else { $this->processDomElementImg($sheet, $row, $column, $cellContent, $child, $attributeArray); } } private function processDomElementImg(Worksheet $sheet, int &$row, string &$column, string &$cellContent, DOMElement $child, array &$attributeArray): void { if ($child->nodeName === 'img') { $this->insertImage($sheet, $column, $row, $attributeArray); } else { $this->processDomElementTable($sheet, $row, $column, $cellContent, $child, $attributeArray); } } private function processDomElementTable(Worksheet $sheet, int &$row, string &$column, string &$cellContent, DOMElement $child, array &$attributeArray): void { if ($child->nodeName === 'table') { $this->flushCell($sheet, $column, $row, $cellContent); $column = $this->setTableStartColumn($column); if ($this->tableLevel > 1 && $row > 1) { --$row; } $this->processDomElement($child, $sheet, $row, $column, $cellContent); $column = $this->releaseTableStartColumn(); if ($this->tableLevel > 1) { ++$column; } else { ++$row; } } else { $this->processDomElementTr($sheet, $row, $column, $cellContent, $child, $attributeArray); } } private function processDomElementTr(Worksheet $sheet, int &$row, string &$column, string &$cellContent, DOMElement $child, array &$attributeArray): void { if ($child->nodeName === 'tr') { $column = $this->getTableStartColumn(); $cellContent = ''; $this->processDomElement($child, $sheet, $row, $column, $cellContent); if (isset($attributeArray['height'])) { $sheet->getRowDimension($row)->setRowHeight($attributeArray['height']); } ++$row; } else { $this->processDomElementThTdOther($sheet, $row, $column, $cellContent, $child, $attributeArray); } } private function processDomElementThTdOther(Worksheet $sheet, int &$row, string &$column, string &$cellContent, DOMElement $child, array &$attributeArray): void { if ($child->nodeName !== 'td' && $child->nodeName !== 'th') { $this->processDomElement($child, $sheet, $row, $column, $cellContent); } else { $this->processDomElementThTd($sheet, $row, $column, $cellContent, $child, $attributeArray); } } private function processDomElementBgcolor(Worksheet $sheet, int $row, string $column, array $attributeArray): void { if (isset($attributeArray['bgcolor'])) { $sheet->getStyle("$column$row")->applyFromArray( [ 'fill' => [ 'fillType' => Fill::FILL_SOLID, 'color' => ['rgb' => $this->getStyleColor($attributeArray['bgcolor'])], ], ] ); } } private function processDomElementWidth(Worksheet $sheet, string $column, array $attributeArray): void { if (isset($attributeArray['width'])) { $sheet->getColumnDimension($column)->setWidth((new CssDimension($attributeArray['width']))->width()); } } private function processDomElementHeight(Worksheet $sheet, int $row, array $attributeArray): void { if (isset($attributeArray['height'])) { $sheet->getRowDimension($row)->setRowHeight((new CssDimension($attributeArray['height']))->height()); } } private function processDomElementAlign(Worksheet $sheet, int $row, string $column, array $attributeArray): void { if (isset($attributeArray['align'])) { $sheet->getStyle($column . $row)->getAlignment()->setHorizontal($attributeArray['align']); } } private function processDomElementVAlign(Worksheet $sheet, int $row, string $column, array $attributeArray): void { if (isset($attributeArray['valign'])) { $sheet->getStyle($column . $row)->getAlignment()->setVertical($attributeArray['valign']); } } private function processDomElementDataFormat(Worksheet $sheet, int $row, string $column, array $attributeArray): void { if (isset($attributeArray['data-format'])) { $sheet->getStyle($column . $row)->getNumberFormat()->setFormatCode($attributeArray['data-format']); } } private function processDomElementThTd(Worksheet $sheet, int &$row, string &$column, string &$cellContent, DOMElement $child, array &$attributeArray): void { while (isset($this->rowspan[$column . $row])) { ++$column; } $this->processDomElement($child, $sheet, $row, $column, $cellContent); // apply inline style $this->applyInlineStyle($sheet, $row, $column, $attributeArray); $this->flushCell($sheet, $column, $row, $cellContent); $this->processDomElementBgcolor($sheet, $row, $column, $attributeArray); $this->processDomElementWidth($sheet, $column, $attributeArray); $this->processDomElementHeight($sheet, $row, $attributeArray); $this->processDomElementAlign($sheet, $row, $column, $attributeArray); $this->processDomElementVAlign($sheet, $row, $column, $attributeArray); $this->processDomElementDataFormat($sheet, $row, $column, $attributeArray); if (isset($attributeArray['rowspan'], $attributeArray['colspan'])) { //create merging rowspan and colspan $columnTo = $column; for ($i = 0; $i < (int) $attributeArray['colspan'] - 1; ++$i) { ++$columnTo; } $range = $column . $row . ':' . $columnTo . ($row + (int) $attributeArray['rowspan'] - 1); foreach (Coordinate::extractAllCellReferencesInRange($range) as $value) { $this->rowspan[$value] = true; } $sheet->mergeCells($range); $column = $columnTo; } elseif (isset($attributeArray['rowspan'])) { //create merging rowspan $range = $column . $row . ':' . $column . ($row + (int) $attributeArray['rowspan'] - 1); foreach (Coordinate::extractAllCellReferencesInRange($range) as $value) { $this->rowspan[$value] = true; } $sheet->mergeCells($range); } elseif (isset($attributeArray['colspan'])) { //create merging colspan $columnTo = $column; for ($i = 0; $i < (int) $attributeArray['colspan'] - 1; ++$i) { ++$columnTo; } $sheet->mergeCells($column . $row . ':' . $columnTo . $row); $column = $columnTo; } ++$column; } protected function processDomElement(DOMNode $element, Worksheet $sheet, int &$row, string &$column, string &$cellContent): void { foreach ($element->childNodes as $child) { if ($child instanceof DOMText) { $domText = preg_replace('/\s+/u', ' ', trim($child->nodeValue)); if (is_string($cellContent)) { // simply append the text if the cell content is a plain text string $cellContent .= $domText; } // but if we have a rich text run instead, we need to append it correctly // TODO } elseif ($child instanceof DOMElement) { $this->processDomElementBody($sheet, $row, $column, $cellContent, $child); } } } /** * Make sure mb_convert_encoding returns string. * * @param mixed $result */ private static function ensureString($result): string { return is_string($result) ? $result : ''; } /** * Loads PhpSpreadsheet from file into PhpSpreadsheet instance. * * @param string $filename * * @return Spreadsheet */ public function loadIntoExisting($filename, Spreadsheet $spreadsheet) { // Validate if (!$this->canRead($filename)) { throw new Exception($filename . ' is an Invalid HTML file.'); } // Create a new DOM object $dom = new DOMDocument(); // Reload the HTML file into the DOM object try { $convert = mb_convert_encoding($this->securityScanner->scanFile($filename), 'HTML-ENTITIES', 'UTF-8'); $loaded = $dom->loadHTML(self::ensureString($convert)); } catch (Throwable $e) { $loaded = false; } if ($loaded === false) { throw new Exception('Failed to load ' . $filename . ' as a DOM Document', 0, $e ?? null); } return $this->loadDocument($dom, $spreadsheet); } /** * Spreadsheet from content. * * @param string $content */ public function loadFromString($content, ?Spreadsheet $spreadsheet = null): Spreadsheet { // Create a new DOM object $dom = new DOMDocument(); // Reload the HTML file into the DOM object try { $convert = mb_convert_encoding($this->securityScanner->scan($content), 'HTML-ENTITIES', 'UTF-8'); $loaded = $dom->loadHTML(self::ensureString($convert)); } catch (Throwable $e) { $loaded = false; } if ($loaded === false) { throw new Exception('Failed to load content as a DOM Document', 0, $e ?? null); } return $this->loadDocument($dom, $spreadsheet ?? new Spreadsheet()); } /** * Loads PhpSpreadsheet from DOMDocument into PhpSpreadsheet instance. */ private function loadDocument(DOMDocument $document, Spreadsheet $spreadsheet): Spreadsheet { while ($spreadsheet->getSheetCount() <= $this->sheetIndex) { $spreadsheet->createSheet(); } $spreadsheet->setActiveSheetIndex($this->sheetIndex); // Discard white space $document->preserveWhiteSpace = false; $row = 0; $column = 'A'; $content = ''; $this->rowspan = []; $this->processDomElement($document, $spreadsheet->getActiveSheet(), $row, $column, $content); // Return return $spreadsheet; } /** * Get sheet index. * * @return int */ public function getSheetIndex() { return $this->sheetIndex; } /** * Set sheet index. * * @param int $sheetIndex Sheet index * * @return $this */ public function setSheetIndex($sheetIndex) { $this->sheetIndex = $sheetIndex; return $this; } /** * Apply inline css inline style. * * NOTES : * Currently only intended for td & th element, * and only takes 'background-color' and 'color'; property with HEX color * * TODO : * - Implement to other propertie, such as border * * @param int $row * @param string $column * @param array $attributeArray */ private function applyInlineStyle(Worksheet &$sheet, $row, $column, $attributeArray): void { if (!isset($attributeArray['style'])) { return; } if (isset($attributeArray['rowspan'], $attributeArray['colspan'])) { $columnTo = $column; for ($i = 0; $i < (int) $attributeArray['colspan'] - 1; ++$i) { ++$columnTo; } $range = $column . $row . ':' . $columnTo . ($row + (int) $attributeArray['rowspan'] - 1); $cellStyle = $sheet->getStyle($range); } elseif (isset($attributeArray['rowspan'])) { $range = $column . $row . ':' . $column . ($row + (int) $attributeArray['rowspan'] - 1); $cellStyle = $sheet->getStyle($range); } elseif (isset($attributeArray['colspan'])) { $columnTo = $column; for ($i = 0; $i < (int) $attributeArray['colspan'] - 1; ++$i) { ++$columnTo; } $range = $column . $row . ':' . $columnTo . $row; $cellStyle = $sheet->getStyle($range); } else { $cellStyle = $sheet->getStyle($column . $row); } // add color styles (background & text) from dom element,currently support : td & th, using ONLY inline css style with RGB color $styles = explode(';', $attributeArray['style']); foreach ($styles as $st) { $value = explode(':', $st); $styleName = isset($value[0]) ? trim($value[0]) : null; $styleValue = isset($value[1]) ? trim($value[1]) : null; $styleValueString = (string) $styleValue; if (!$styleName) { continue; } switch ($styleName) { case 'background': case 'background-color': $styleColor = $this->getStyleColor($styleValueString); if (!$styleColor) { continue 2; } $cellStyle->applyFromArray(['fill' => ['fillType' => Fill::FILL_SOLID, 'color' => ['rgb' => $styleColor]]]); break; case 'color': $styleColor = $this->getStyleColor($styleValueString); if (!$styleColor) { continue 2; } $cellStyle->applyFromArray(['font' => ['color' => ['rgb' => $styleColor]]]); break; case 'border': $this->setBorderStyle($cellStyle, $styleValueString, 'allBorders'); break; case 'border-top': $this->setBorderStyle($cellStyle, $styleValueString, 'top'); break; case 'border-bottom': $this->setBorderStyle($cellStyle, $styleValueString, 'bottom'); break; case 'border-left': $this->setBorderStyle($cellStyle, $styleValueString, 'left'); break; case 'border-right': $this->setBorderStyle($cellStyle, $styleValueString, 'right'); break; case 'font-size': $cellStyle->getFont()->setSize( (float) $styleValue ); break; case 'font-weight': if ($styleValue === 'bold' || $styleValue >= 500) { $cellStyle->getFont()->setBold(true); } break; case 'font-style': if ($styleValue === 'italic') { $cellStyle->getFont()->setItalic(true); } break; case 'font-family': $cellStyle->getFont()->setName(str_replace('\'', '', $styleValueString)); break; case 'text-decoration': switch ($styleValue) { case 'underline': $cellStyle->getFont()->setUnderline(Font::UNDERLINE_SINGLE); break; case 'line-through': $cellStyle->getFont()->setStrikethrough(true); break; } break; case 'text-align': $cellStyle->getAlignment()->setHorizontal($styleValueString); break; case 'vertical-align': $cellStyle->getAlignment()->setVertical($styleValueString); break; case 'width': $sheet->getColumnDimension($column)->setWidth( (new CssDimension($styleValue ?? ''))->width() ); break; case 'height': $sheet->getRowDimension($row)->setRowHeight( (new CssDimension($styleValue ?? ''))->height() ); break; case 'word-wrap': $cellStyle->getAlignment()->setWrapText( $styleValue === 'break-word' ); break; case 'text-indent': $cellStyle->getAlignment()->setIndent( (int) str_replace(['px'], '', $styleValueString) ); break; } } } /** * Check if has #, so we can get clean hex. * * @param mixed $value * * @return null|string */ public function getStyleColor($value) { $value = (string) $value; if (strpos($value ?? '', '#') === 0) { return substr($value, 1); } return \PhpOffice\PhpSpreadsheet\Helper\Html::colourNameLookup($value); } /** * @param string $column * @param int $row */ private function insertImage(Worksheet $sheet, $column, $row, array $attributes): void { if (!isset($attributes['src'])) { return; } $src = urldecode($attributes['src']); $width = isset($attributes['width']) ? (float) $attributes['width'] : null; $height = isset($attributes['height']) ? (float) $attributes['height'] : null; $name = $attributes['alt'] ?? null; $drawing = new Drawing(); $drawing->setPath($src); $drawing->setWorksheet($sheet); $drawing->setCoordinates($column . $row); $drawing->setOffsetX(0); $drawing->setOffsetY(10); $drawing->setResizeProportional(true); if ($name) {
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
true
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx.php
<?php namespace PhpOffice\PhpSpreadsheet\Reader; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Cell\DataType; use PhpOffice\PhpSpreadsheet\Cell\Hyperlink; use PhpOffice\PhpSpreadsheet\DefinedName; use PhpOffice\PhpSpreadsheet\Reader\Security\XmlScanner; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\AutoFilter; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Chart; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\ColumnAndRowAttributes; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\ConditionalStyles; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\DataValidations; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Hyperlinks; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Namespaces; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\PageSetup; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Properties as PropertyReader; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\SheetViewOptions; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\SheetViews; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Styles; use PhpOffice\PhpSpreadsheet\ReferenceHelper; use PhpOffice\PhpSpreadsheet\RichText\RichText; use PhpOffice\PhpSpreadsheet\Settings; use PhpOffice\PhpSpreadsheet\Shared\Date; use PhpOffice\PhpSpreadsheet\Shared\Drawing; use PhpOffice\PhpSpreadsheet\Shared\File; use PhpOffice\PhpSpreadsheet\Shared\Font; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Style\Color; use PhpOffice\PhpSpreadsheet\Style\NumberFormat; use PhpOffice\PhpSpreadsheet\Style\Style; use PhpOffice\PhpSpreadsheet\Worksheet\HeaderFooterDrawing; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; use SimpleXMLElement; use stdClass; use Throwable; use XMLReader; use ZipArchive; class Xlsx extends BaseReader { const INITIAL_FILE = '_rels/.rels'; /** * ReferenceHelper instance. * * @var ReferenceHelper */ private $referenceHelper; /** * Xlsx\Theme instance. * * @var Xlsx\Theme */ private static $theme; /** * @var ZipArchive */ private $zip; /** * Create a new Xlsx Reader instance. */ public function __construct() { parent::__construct(); $this->referenceHelper = ReferenceHelper::getInstance(); $this->securityScanner = XmlScanner::getInstance($this); } /** * Can the current IReader read the file? */ public function canRead(string $filename): bool { if (!File::testFileNoThrow($filename, self::INITIAL_FILE)) { return false; } $result = false; $this->zip = $zip = new ZipArchive(); if ($zip->open($filename) === true) { [$workbookBasename] = $this->getWorkbookBaseName(); $result = !empty($workbookBasename); $zip->close(); } return $result; } /** * @param mixed $value */ public static function testSimpleXml($value): SimpleXMLElement { return ($value instanceof SimpleXMLElement) ? $value : new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><root></root>'); } public static function getAttributes(?SimpleXMLElement $value, string $ns = ''): SimpleXMLElement { return self::testSimpleXml($value === null ? $value : $value->attributes($ns)); } // Phpstan thinks, correctly, that xpath can return false. // Scrutinizer thinks it can't. // Sigh. private static function xpathNoFalse(SimpleXmlElement $sxml, string $path): array { return self::falseToArray($sxml->xpath($path)); } /** * @param mixed $value */ public static function falseToArray($value): array { return is_array($value) ? $value : []; } private function loadZip(string $filename, string $ns = ''): SimpleXMLElement { $contents = $this->getFromZipArchive($this->zip, $filename); $rels = simplexml_load_string( $this->securityScanner->scan($contents), 'SimpleXMLElement', Settings::getLibXmlLoaderOptions(), $ns ); return self::testSimpleXml($rels); } // This function is just to identify cases where I'm not sure // why empty namespace is required. private function loadZipNonamespace(string $filename, string $ns): SimpleXMLElement { $contents = $this->getFromZipArchive($this->zip, $filename); $rels = simplexml_load_string( $this->securityScanner->scan($contents), 'SimpleXMLElement', Settings::getLibXmlLoaderOptions(), ($ns === '' ? $ns : '') ); return self::testSimpleXml($rels); } private const REL_TO_MAIN = [ Namespaces::PURL_OFFICE_DOCUMENT => Namespaces::PURL_MAIN, ]; private const REL_TO_DRAWING = [ Namespaces::PURL_RELATIONSHIPS => Namespaces::PURL_DRAWING, ]; /** * Reads names of the worksheets from a file, without parsing the whole file to a Spreadsheet object. * * @param string $filename * * @return array */ public function listWorksheetNames($filename) { File::assertFile($filename, self::INITIAL_FILE); $worksheetNames = []; $this->zip = $zip = new ZipArchive(); $zip->open($filename); // The files we're looking at here are small enough that simpleXML is more efficient than XMLReader $rels = $this->loadZip(self::INITIAL_FILE, Namespaces::RELATIONSHIPS); foreach ($rels->Relationship as $relx) { $rel = self::getAttributes($relx); $relType = (string) $rel['Type']; $mainNS = self::REL_TO_MAIN[$relType] ?? Namespaces::MAIN; if ($mainNS !== '') { $xmlWorkbook = $this->loadZip((string) $rel['Target'], $mainNS); if ($xmlWorkbook->sheets) { foreach ($xmlWorkbook->sheets->sheet as $eleSheet) { // Check if sheet should be skipped $worksheetNames[] = (string) self::getAttributes($eleSheet)['name']; } } } } $zip->close(); return $worksheetNames; } /** * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns). * * @param string $filename * * @return array */ public function listWorksheetInfo($filename) { File::assertFile($filename, self::INITIAL_FILE); $worksheetInfo = []; $this->zip = $zip = new ZipArchive(); $zip->open($filename); $rels = $this->loadZip(self::INITIAL_FILE, Namespaces::RELATIONSHIPS); foreach ($rels->Relationship as $relx) { $rel = self::getAttributes($relx); $relType = (string) $rel['Type']; $mainNS = self::REL_TO_MAIN[$relType] ?? Namespaces::MAIN; if ($mainNS !== '') { $relTarget = (string) $rel['Target']; $dir = dirname($relTarget); $namespace = dirname($relType); $relsWorkbook = $this->loadZip("$dir/_rels/" . basename($relTarget) . '.rels', ''); $worksheets = []; foreach ($relsWorkbook->Relationship as $elex) { $ele = self::getAttributes($elex); if ((string) $ele['Type'] === "$namespace/worksheet") { $worksheets[(string) $ele['Id']] = $ele['Target']; } } $xmlWorkbook = $this->loadZip($relTarget, $mainNS); if ($xmlWorkbook->sheets) { $dir = dirname($relTarget); /** @var SimpleXMLElement $eleSheet */ foreach ($xmlWorkbook->sheets->sheet as $eleSheet) { $tmpInfo = [ 'worksheetName' => (string) self::getAttributes($eleSheet)['name'], 'lastColumnLetter' => 'A', 'lastColumnIndex' => 0, 'totalRows' => 0, 'totalColumns' => 0, ]; $fileWorksheet = (string) $worksheets[(string) self::getArrayItem(self::getAttributes($eleSheet, $namespace), 'id')]; $fileWorksheetPath = strpos($fileWorksheet, '/') === 0 ? substr($fileWorksheet, 1) : "$dir/$fileWorksheet"; $xml = new XMLReader(); $xml->xml( $this->securityScanner->scanFile( 'zip://' . File::realpath($filename) . '#' . $fileWorksheetPath ), null, Settings::getLibXmlLoaderOptions() ); $xml->setParserProperty(2, true); $currCells = 0; while ($xml->read()) { if ($xml->localName == 'row' && $xml->nodeType == XMLReader::ELEMENT && $xml->namespaceURI === $mainNS) { $row = $xml->getAttribute('r'); $tmpInfo['totalRows'] = $row; $tmpInfo['totalColumns'] = max($tmpInfo['totalColumns'], $currCells); $currCells = 0; } elseif ($xml->localName == 'c' && $xml->nodeType == XMLReader::ELEMENT && $xml->namespaceURI === $mainNS) { $cell = $xml->getAttribute('r'); $currCells = $cell ? max($currCells, Coordinate::indexesFromString($cell)[0]) : ($currCells + 1); } } $tmpInfo['totalColumns'] = max($tmpInfo['totalColumns'], $currCells); $xml->close(); $tmpInfo['lastColumnIndex'] = $tmpInfo['totalColumns'] - 1; $tmpInfo['lastColumnLetter'] = Coordinate::stringFromColumnIndex($tmpInfo['lastColumnIndex'] + 1); $worksheetInfo[] = $tmpInfo; } } } } $zip->close(); return $worksheetInfo; } private static function castToBoolean($c) { $value = isset($c->v) ? (string) $c->v : null; if ($value == '0') { return false; } elseif ($value == '1') { return true; } return (bool) $c->v; } private static function castToError($c) { return isset($c->v) ? (string) $c->v : null; } private static function castToString($c) { return isset($c->v) ? (string) $c->v : null; } private function castToFormula($c, $r, &$cellDataType, &$value, &$calculatedValue, &$sharedFormulas, $castBaseType): void { $attr = $c->f->attributes(); $cellDataType = 'f'; $value = "={$c->f}"; $calculatedValue = self::$castBaseType($c); // Shared formula? if (isset($attr['t']) && strtolower((string) $attr['t']) == 'shared') { $instance = (string) $attr['si']; if (!isset($sharedFormulas[(string) $attr['si']])) { $sharedFormulas[$instance] = ['master' => $r, 'formula' => $value]; } else { $master = Coordinate::indexesFromString($sharedFormulas[$instance]['master']); $current = Coordinate::indexesFromString($r); $difference = [0, 0]; $difference[0] = $current[0] - $master[0]; $difference[1] = $current[1] - $master[1]; $value = $this->referenceHelper->updateFormulaReferences($sharedFormulas[$instance]['formula'], 'A1', $difference[0], $difference[1]); } } } /** * @param string $fileName */ private function fileExistsInArchive(ZipArchive $archive, $fileName = ''): bool { // Root-relative paths if (strpos($fileName, '//') !== false) { $fileName = substr($fileName, strpos($fileName, '//') + 1); } $fileName = File::realpath($fileName); // Sadly, some 3rd party xlsx generators don't use consistent case for filenaming // so we need to load case-insensitively from the zip file // Apache POI fixes $contents = $archive->locateName($fileName, ZipArchive::FL_NOCASE); if ($contents === false) { $contents = $archive->locateName(substr($fileName, 1), ZipArchive::FL_NOCASE); } return $contents !== false; } /** * @param string $fileName * * @return string */ private function getFromZipArchive(ZipArchive $archive, $fileName = '') { // Root-relative paths if (strpos($fileName, '//') !== false) { $fileName = substr($fileName, strpos($fileName, '//') + 1); } $fileName = File::realpath($fileName); // Sadly, some 3rd party xlsx generators don't use consistent case for filenaming // so we need to load case-insensitively from the zip file // Apache POI fixes $contents = $archive->getFromName($fileName, 0, ZipArchive::FL_NOCASE); if ($contents === false) { $contents = $archive->getFromName(substr($fileName, 1), 0, ZipArchive::FL_NOCASE); } return $contents; } /** * Loads Spreadsheet from file. */ public function load(string $filename, int $flags = 0): Spreadsheet { File::assertFile($filename, self::INITIAL_FILE); $this->processFlags($flags); // Initialisations $excel = new Spreadsheet(); $excel->removeSheetByIndex(0); $addingFirstCellStyleXf = true; $addingFirstCellXf = true; $unparsedLoadedData = []; $this->zip = $zip = new ZipArchive(); $zip->open($filename); // Read the theme first, because we need the colour scheme when reading the styles [$workbookBasename, $xmlNamespaceBase] = $this->getWorkbookBaseName(); $wbRels = $this->loadZip("xl/_rels/${workbookBasename}.rels", Namespaces::RELATIONSHIPS); foreach ($wbRels->Relationship as $relx) { $rel = self::getAttributes($relx); $relTarget = (string) $rel['Target']; switch ($rel['Type']) { case "$xmlNamespaceBase/theme": $themeOrderArray = ['lt1', 'dk1', 'lt2', 'dk2']; $themeOrderAdditional = count($themeOrderArray); $drawingNS = self::REL_TO_DRAWING[$xmlNamespaceBase] ?? Namespaces::DRAWINGML; $xmlTheme = $this->loadZip("xl/{$relTarget}", $drawingNS); $xmlThemeName = self::getAttributes($xmlTheme); $xmlTheme = $xmlTheme->children($drawingNS); $themeName = (string) $xmlThemeName['name']; $colourScheme = self::getAttributes($xmlTheme->themeElements->clrScheme); $colourSchemeName = (string) $colourScheme['name']; $colourScheme = $xmlTheme->themeElements->clrScheme->children($drawingNS); $themeColours = []; foreach ($colourScheme as $k => $xmlColour) { $themePos = array_search($k, $themeOrderArray); if ($themePos === false) { $themePos = $themeOrderAdditional++; } if (isset($xmlColour->sysClr)) { $xmlColourData = self::getAttributes($xmlColour->sysClr); $themeColours[$themePos] = (string) $xmlColourData['lastClr']; } elseif (isset($xmlColour->srgbClr)) { $xmlColourData = self::getAttributes($xmlColour->srgbClr); $themeColours[$themePos] = (string) $xmlColourData['val']; } } self::$theme = new Xlsx\Theme($themeName, $colourSchemeName, $themeColours); break; } } $rels = $this->loadZip(self::INITIAL_FILE, Namespaces::RELATIONSHIPS); $propertyReader = new PropertyReader($this->securityScanner, $excel->getProperties()); foreach ($rels->Relationship as $relx) { $rel = self::getAttributes($relx); $relTarget = (string) $rel['Target']; $relType = (string) $rel['Type']; $mainNS = self::REL_TO_MAIN[$relType] ?? Namespaces::MAIN; switch ($relType) { case Namespaces::CORE_PROPERTIES: $propertyReader->readCoreProperties($this->getFromZipArchive($zip, $relTarget)); break; case "$xmlNamespaceBase/extended-properties": $propertyReader->readExtendedProperties($this->getFromZipArchive($zip, $relTarget)); break; case "$xmlNamespaceBase/custom-properties": $propertyReader->readCustomProperties($this->getFromZipArchive($zip, $relTarget)); break; //Ribbon case Namespaces::EXTENSIBILITY: $customUI = $relTarget; if ($customUI) { $this->readRibbon($excel, $customUI, $zip); } break; case "$xmlNamespaceBase/officeDocument": $dir = dirname($relTarget); // Do not specify namespace in next stmt - do it in Xpath $relsWorkbook = $this->loadZip("$dir/_rels/" . basename($relTarget) . '.rels', ''); $relsWorkbook->registerXPathNamespace('rel', Namespaces::RELATIONSHIPS); $sharedStrings = []; $relType = "rel:Relationship[@Type='" //. Namespaces::SHARED_STRINGS . "$xmlNamespaceBase/sharedStrings" . "']"; $xpath = self::getArrayItem($relsWorkbook->xpath($relType)); if ($xpath) { $xmlStrings = $this->loadZip("$dir/$xpath[Target]", $mainNS); if (isset($xmlStrings->si)) { foreach ($xmlStrings->si as $val) { if (isset($val->t)) { $sharedStrings[] = StringHelper::controlCharacterOOXML2PHP((string) $val->t); } elseif (isset($val->r)) { $sharedStrings[] = $this->parseRichText($val); } } } } $worksheets = []; $macros = $customUI = null; foreach ($relsWorkbook->Relationship as $elex) { $ele = self::getAttributes($elex); switch ($ele['Type']) { case Namespaces::WORKSHEET: case Namespaces::PURL_WORKSHEET: $worksheets[(string) $ele['Id']] = $ele['Target']; break; // a vbaProject ? (: some macros) case Namespaces::VBA: $macros = $ele['Target']; break; } } if ($macros !== null) { $macrosCode = $this->getFromZipArchive($zip, 'xl/vbaProject.bin'); //vbaProject.bin always in 'xl' dir and always named vbaProject.bin if ($macrosCode !== false) { $excel->setMacrosCode($macrosCode); $excel->setHasMacros(true); //short-circuit : not reading vbaProject.bin.rel to get Signature =>allways vbaProjectSignature.bin in 'xl' dir $Certificate = $this->getFromZipArchive($zip, 'xl/vbaProjectSignature.bin'); if ($Certificate !== false) { $excel->setMacrosCertificate($Certificate); } } } $relType = "rel:Relationship[@Type='" . "$xmlNamespaceBase/styles" . "']"; $xpath = self::getArrayItem(self::xpathNoFalse($relsWorkbook, $relType)); if ($xpath === null) { $xmlStyles = self::testSimpleXml(null); } else { // I think Nonamespace is okay because I'm using xpath. $xmlStyles = $this->loadZipNonamespace("$dir/$xpath[Target]", $mainNS); } $xmlStyles->registerXPathNamespace('smm', Namespaces::MAIN); $fills = self::xpathNoFalse($xmlStyles, 'smm:fills/smm:fill'); $fonts = self::xpathNoFalse($xmlStyles, 'smm:fonts/smm:font'); $borders = self::xpathNoFalse($xmlStyles, 'smm:borders/smm:border'); $xfTags = self::xpathNoFalse($xmlStyles, 'smm:cellXfs/smm:xf'); $cellXfTags = self::xpathNoFalse($xmlStyles, 'smm:cellStyleXfs/smm:xf'); $styles = []; $cellStyles = []; $numFmts = null; if (/*$xmlStyles && */ $xmlStyles->numFmts[0]) { $numFmts = $xmlStyles->numFmts[0]; } if (isset($numFmts) && ($numFmts !== null)) { $numFmts->registerXPathNamespace('sml', $mainNS); } if (!$this->readDataOnly/* && $xmlStyles*/) { foreach ($xfTags as $xfTag) { $xf = self::getAttributes($xfTag); $numFmt = null; if ($xf['numFmtId']) { if (isset($numFmts)) { $tmpNumFmt = self::getArrayItem($numFmts->xpath("sml:numFmt[@numFmtId=$xf[numFmtId]]")); if (isset($tmpNumFmt['formatCode'])) { $numFmt = (string) $tmpNumFmt['formatCode']; } } // We shouldn't override any of the built-in MS Excel values (values below id 164) // But there's a lot of naughty homebrew xlsx writers that do use "reserved" id values that aren't actually used // So we make allowance for them rather than lose formatting masks if ( $numFmt === null && (int) $xf['numFmtId'] < 164 && NumberFormat::builtInFormatCode((int) $xf['numFmtId']) !== '' ) { $numFmt = NumberFormat::builtInFormatCode((int) $xf['numFmtId']); } } $quotePrefix = (bool) ($xf['quotePrefix'] ?? false); $style = (object) [ 'numFmt' => $numFmt ?? NumberFormat::FORMAT_GENERAL, 'font' => $fonts[(int) ($xf['fontId'])], 'fill' => $fills[(int) ($xf['fillId'])], 'border' => $borders[(int) ($xf['borderId'])], 'alignment' => $xfTag->alignment, 'protection' => $xfTag->protection, 'quotePrefix' => $quotePrefix, ]; $styles[] = $style; // add style to cellXf collection $objStyle = new Style(); self::readStyle($objStyle, $style); if ($addingFirstCellXf) { $excel->removeCellXfByIndex(0); // remove the default style $addingFirstCellXf = false; } $excel->addCellXf($objStyle); } foreach ($cellXfTags as $xfTag) { $xf = self::getAttributes($xfTag); $numFmt = NumberFormat::FORMAT_GENERAL; if ($numFmts && $xf['numFmtId']) { $tmpNumFmt = self::getArrayItem($numFmts->xpath("sml:numFmt[@numFmtId=$xf[numFmtId]]")); if (isset($tmpNumFmt['formatCode'])) { $numFmt = (string) $tmpNumFmt['formatCode']; } elseif ((int) $xf['numFmtId'] < 165) { $numFmt = NumberFormat::builtInFormatCode((int) $xf['numFmtId']); } } $quotePrefix = (bool) ($xf['quotePrefix'] ?? false); $cellStyle = (object) [ 'numFmt' => $numFmt, 'font' => $fonts[(int) ($xf['fontId'])], 'fill' => $fills[((int) $xf['fillId'])], 'border' => $borders[(int) ($xf['borderId'])], 'alignment' => $xfTag->alignment, 'protection' => $xfTag->protection, 'quotePrefix' => $quotePrefix, ]; $cellStyles[] = $cellStyle; // add style to cellStyleXf collection $objStyle = new Style(); self::readStyle($objStyle, $cellStyle); if ($addingFirstCellStyleXf) { $excel->removeCellStyleXfByIndex(0); // remove the default style $addingFirstCellStyleXf = false; } $excel->addCellStyleXf($objStyle); } } $styleReader = new Styles($xmlStyles); $styleReader->setStyleBaseData(self::$theme, $styles, $cellStyles); $dxfs = $styleReader->dxfs($this->readDataOnly); $styles = $styleReader->styles(); $xmlWorkbook = $this->loadZipNoNamespace($relTarget, $mainNS); $xmlWorkbookNS = $this->loadZip($relTarget, $mainNS); // Set base date if ($xmlWorkbookNS->workbookPr) { Date::setExcelCalendar(Date::CALENDAR_WINDOWS_1900); $attrs1904 = self::getAttributes($xmlWorkbookNS->workbookPr); if (isset($attrs1904['date1904'])) { if (self::boolean((string) $attrs1904['date1904'])) { Date::setExcelCalendar(Date::CALENDAR_MAC_1904); } } } // Set protection $this->readProtection($excel, $xmlWorkbook); $sheetId = 0; // keep track of new sheet id in final workbook $oldSheetId = -1; // keep track of old sheet id in final workbook $countSkippedSheets = 0; // keep track of number of skipped sheets $mapSheetId = []; // mapping of sheet ids from old to new $charts = $chartDetails = []; if ($xmlWorkbookNS->sheets) { /** @var SimpleXMLElement $eleSheet */ foreach ($xmlWorkbookNS->sheets->sheet as $eleSheet) { $eleSheetAttr = self::getAttributes($eleSheet); ++$oldSheetId; // Check if sheet should be skipped if (is_array($this->loadSheetsOnly) && !in_array((string) $eleSheetAttr['name'], $this->loadSheetsOnly)) { ++$countSkippedSheets; $mapSheetId[$oldSheetId] = null; continue; } // Map old sheet id in original workbook to new sheet id. // They will differ if loadSheetsOnly() is being used $mapSheetId[$oldSheetId] = $oldSheetId - $countSkippedSheets; // Load sheet $docSheet = $excel->createSheet(); // 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 $docSheet->setTitle((string) $eleSheetAttr['name'], false, false); $fileWorksheet = (string) $worksheets[(string) self::getArrayItem(self::getAttributes($eleSheet, $xmlNamespaceBase), 'id')]; $xmlSheet = $this->loadZipNoNamespace("$dir/$fileWorksheet", $mainNS); $xmlSheetNS = $this->loadZip("$dir/$fileWorksheet", $mainNS); $sharedFormulas = []; if (isset($eleSheetAttr['state']) && (string) $eleSheetAttr['state'] != '') { $docSheet->setSheetState((string) $eleSheetAttr['state']); } if ($xmlSheetNS) { $xmlSheetMain = $xmlSheetNS->children($mainNS); // Setting Conditional Styles adjusts selected cells, so we need to execute this // before reading the sheet view data to get the actual selected cells if (!$this->readDataOnly && $xmlSheet->conditionalFormatting) { (new ConditionalStyles($docSheet, $xmlSheet, $dxfs))->load(); } if (isset($xmlSheetMain->sheetViews, $xmlSheetMain->sheetViews->sheetView)) { $sheetViews = new SheetViews($xmlSheetMain->sheetViews->sheetView, $docSheet); $sheetViews->load(); } $sheetViewOptions = new SheetViewOptions($docSheet, $xmlSheet); $sheetViewOptions->load($this->getReadDataOnly()); (new ColumnAndRowAttributes($docSheet, $xmlSheet)) ->load($this->getReadFilter(), $this->getReadDataOnly()); } if ($xmlSheetNS && $xmlSheetNS->sheetData && $xmlSheetNS->sheetData->row) { $cIndex = 1; // Cell Start from 1 foreach ($xmlSheetNS->sheetData->row as $row) { $rowIndex = 1; foreach ($row->c as $c) { $cAttr = self::getAttributes($c); $r = (string) $cAttr['r']; if ($r == '') { $r = Coordinate::stringFromColumnIndex($rowIndex) . $cIndex; } $cellDataType = (string) $cAttr['t']; $value = null; $calculatedValue = null; // Read cell?
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
true
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/IReadFilter.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/IReadFilter.php
<?php namespace PhpOffice\PhpSpreadsheet\Reader; interface IReadFilter { /** * Should this cell be read? * * @param string $columnAddress 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($columnAddress, $row, $worksheetName = ''); }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Slk.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Slk.php
<?php namespace PhpOffice\PhpSpreadsheet\Reader; 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. */ public function canRead(string $filename): bool { try { $this->openFile($filename); } catch (ReaderException $e) { return false; } // Read sample data (first 2 KB will do) $data = (string) 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 $filename): void { if (!$this->canRead($filename)) { throw new ReaderException($filename . ' is an Invalid SYLK file.'); } $this->openFile($filename); } /** * Set input encoding. * * @deprecated no use is made of this property * * @param string $inputEncoding Input encoding, eg: 'ANSI' * * @return $this * * @codeCoverageIgnore */ public function setInputEncoding($inputEncoding) { $this->inputEncoding = $inputEncoding; 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 $filename * * @return array */ public function listWorksheetInfo($filename) { // Open file $this->canReadOrBust($filename); $fileHandle = $this->fileHandle; rewind($fileHandle); $worksheetInfo = []; $worksheetInfo[0]['worksheetName'] = basename($filename, '.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 = (int) 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. * * @return Spreadsheet */ public function load(string $filename, int $flags = 0) { $this->processFlags($flags); // Create new Spreadsheet $spreadsheet = new Spreadsheet(); // Load into this instance return $this->loadIntoExisting($filename, $spreadsheet); } private const COLOR_ARRAY = [ '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 const FONT_STYLE_MAPPINGS = [ '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 $key = !$key; if ($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 = (int) $row + (int) 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 = (int) $column + (int) 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; case 'A': $comment = substr($rowDatum, 1); $columnLetter = Coordinate::stringFromColumnIndex((int) $column); $spreadsheet->getActiveSheet() ->getComment("$columnLetter$row") ->getText() ->createText($comment); 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 const STYLE_SETTINGS_FONT = ['D' => 'bold', 'I' => 'italic']; private const STYLE_SETTINGS_BORDER = [ '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, self::STYLE_SETTINGS_FONT)) { $styleData['font'][self::STYLE_SETTINGS_FONT[$char]] = true; } elseif (array_key_exists($char, self::STYLE_SETTINGS_BORDER)) { $styleData['borders'][self::STYLE_SETTINGS_BORDER[$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((int) $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((float) $columnWidth); } else { $startCol = Coordinate::stringFromColumnIndex((int) $startCol); $endCol = Coordinate::stringFromColumnIndex((int) $endCol); $spreadsheet->getActiveSheet()->getColumnDimension($startCol)->setWidth((float) $columnWidth); do { $spreadsheet->getActiveSheet()->getColumnDimension(++$startCol)->setWidth((float) $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'] = self::COLOR_ARRAY[$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], self::FONT_STYLE_MAPPINGS)) { $formatArray['font'][self::FONT_STYLE_MAPPINGS[$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 $filename * * @return Spreadsheet */ public function loadIntoExisting($filename, Spreadsheet $spreadsheet) { // Open file $this->canReadOrBust($filename); $fileHandle = $this->fileHandle; rewind($fileHandle); // Create new Worksheets while ($spreadsheet->getSheetCount() <= $this->sheetIndex) { $spreadsheet->createSheet(); } $spreadsheet->setActiveSheetIndex($this->sheetIndex); $spreadsheet->getActiveSheet()->setTitle(substr(basename($filename, '.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 $sheetIndex Sheet index * * @return $this */ public function setSheetIndex($sheetIndex) { $this->sheetIndex = $sheetIndex; return $this; } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods.php
<?php namespace PhpOffice\PhpSpreadsheet\Reader; use DateTime; 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\Reader\Ods\AutoFilter; use PhpOffice\PhpSpreadsheet\Reader\Ods\DefinedNames; 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 Throwable; use XMLReader; use ZipArchive; class Ods extends BaseReader { const INITIAL_FILE = 'content.xml'; /** * Create a new Ods Reader instance. */ public function __construct() { parent::__construct(); $this->securityScanner = XmlScanner::getInstance($this); } /** * Can the current IReader read the file? */ public function canRead(string $filename): bool { $mimeType = 'UNKNOWN'; // Load file if (File::testFileNoThrow($filename, '')) { $zip = new ZipArchive(); if ($zip->open($filename) === 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 && $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 $filename * * @return string[] */ public function listWorksheetNames($filename) { File::assertFile($filename, self::INITIAL_FILE); $worksheetNames = []; $xml = new XMLReader(); $xml->xml( $this->securityScanner->scanFile('zip://' . realpath($filename) . '#' . self::INITIAL_FILE), 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 $filename * * @return array */ public function listWorksheetInfo($filename) { File::assertFile($filename, self::INITIAL_FILE); $worksheetInfo = []; $xml = new XMLReader(); $xml->xml( $this->securityScanner->scanFile('zip://' . realpath($filename) . '#' . self::INITIAL_FILE), 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. * * @return Spreadsheet */ public function load(string $filename, int $flags = 0) { $this->processFlags($flags); // Create new Spreadsheet $spreadsheet = new Spreadsheet(); // Load into this instance return $this->loadIntoExisting($filename, $spreadsheet); } /** * Loads PhpSpreadsheet from file into PhpSpreadsheet instance. * * @param string $filename * * @return Spreadsheet */ public function loadIntoExisting($filename, Spreadsheet $spreadsheet) { File::assertFile($filename, self::INITIAL_FILE); $zip = new ZipArchive(); $zip->open($filename); // 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(self::INITIAL_FILE)), Settings::getLibXmlLoaderOptions() ); $officeNs = $dom->lookupNamespaceUri('office'); $tableNs = $dom->lookupNamespaceUri('table'); $textNs = $dom->lookupNamespaceUri('text'); $xlinkNs = $dom->lookupNamespaceUri('xlink'); $pageSettings->readStyleCrossReferences($dom); $autoFilterReader = new AutoFilter($spreadsheet, $tableNs); $definedNameReader = new DefinedNames($spreadsheet, $tableNs); // 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 = (int) $childNode->getAttributeNS($tableNs, 'number-rows-repeated'); } else { $rowRepeats = 1; } $columnID = 'A'; /** @var DOMElement $cellData */ foreach ($childNode->childNodes as $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); [$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; } $autoFilterReader->read($workbookData); $definedNameReader->read($workbookData); } $spreadsheet->setActiveSheetIndex(0); if ($zip->locateName('settings.xml') !== false) { $this->processSettings($zip, $spreadsheet); } // Return return $spreadsheet; } private function processSettings(ZipArchive $zip, Spreadsheet $spreadsheet): void { $dom = new DOMDocument('1.01', 'UTF-8'); $dom->loadXML( $this->securityScanner->scan($zip->getFromName('settings.xml')), Settings::getLibXmlLoaderOptions() ); //$xlinkNs = $dom->lookupNamespaceUri('xlink'); $configNs = $dom->lookupNamespaceUri('config'); //$oooNs = $dom->lookupNamespaceUri('ooo'); $officeNs = $dom->lookupNamespaceUri('office'); $settings = $dom->getElementsByTagNameNS($officeNs, 'settings') ->item(0); $this->lookForActiveSheet($settings, $spreadsheet, $configNs); $this->lookForSelectedCells($settings, $spreadsheet, $configNs); } private function lookForActiveSheet(DOMElement $settings, Spreadsheet $spreadsheet, string $configNs): void { /** @var DOMElement $t */ foreach ($settings->getElementsByTagNameNS($configNs, 'config-item') as $t) { if ($t->getAttributeNs($configNs, 'name') === 'ActiveTable') { try { $spreadsheet->setActiveSheetIndexByName($t->nodeValue); } catch (Throwable $e) { // do nothing } break; } } } private function lookForSelectedCells(DOMElement $settings, Spreadsheet $spreadsheet, string $configNs): void { /** @var DOMElement $t */ foreach ($settings->getElementsByTagNameNS($configNs, 'config-item-map-named') as $t) { if ($t->getAttributeNs($configNs, 'name') === 'Tables') { foreach ($t->getElementsByTagNameNS($configNs, 'config-item-map-entry') as $ws) { $setRow = $setCol = ''; $wsname = $ws->getAttributeNs($configNs, 'name'); foreach ($ws->getElementsByTagNameNS($configNs, 'config-item') as $configItem) { $attrName = $configItem->getAttributeNs($configNs, 'name'); if ($attrName === 'CursorPositionX') { $setCol = $configItem->nodeValue; } if ($attrName === 'CursorPositionY') { $setRow = $configItem->nodeValue; } } $this->setSelected($spreadsheet, $wsname, $setCol, $setRow); } break; } } } private function setSelected(Spreadsheet $spreadsheet, string $wsname, string $setCol, string $setRow): void { if (is_numeric($setCol) && is_numeric($setRow)) { try { $spreadsheet->getSheetByName($wsname)->setSelectedCellByColumnAndRow($setCol + 1, $setRow + 1); } catch (Throwable $e) { // do nothing } } } /** * 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); }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
true
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/MD5.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/MD5.php
<?php namespace PhpOffice\PhpSpreadsheet\Reader\Xls; class MD5 { // Context /** * @var int */ private $a; /** * @var int */ private $b; /** * @var int */ private $c; /** * @var int */ 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(string $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(int $X, int $Y, int $Z) { return ($X & $Y) | ((~$X) & $Z); // X AND Y OR NOT X AND Z } private static function g(int $X, int $Y, int $Z) { return ($X & $Z) | ($Y & (~$Z)); // X AND Z OR Y AND NOT Z } private static function h(int $X, int $Y, int $Z) { return $X ^ $Y ^ $Z; // X XOR Y XOR Z } private static function i(int $X, int $Y, int $Z) { return $Y ^ ($X | (~$Z)); // Y XOR (X OR NOT Z) } private static function step($func, int &$A, int $B, int $C, int $D, int $M, int $s, int $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(int $decimal, int $bits) { $binary = str_pad(decbin($decimal), 32, '0', STR_PAD_LEFT); return bindec(substr($binary, $bits) . substr($binary, 0, $bits)); } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/Escher.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/Escher.php
<?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; } private const WHICH_ROUTINE = [ self::DGGCONTAINER => 'readDggContainer', self::DGG => 'readDgg', self::BSTORECONTAINER => 'readBstoreContainer', self::BSE => 'readBSE', self::BLIPJPEG => 'readBlipJPEG', self::BLIPPNG => 'readBlipPNG', self::OPT => 'readOPT', self::TERTIARYOPT => 'readTertiaryOPT', self::SPLITMENUCOLORS => 'readSplitMenuColors', self::DGCONTAINER => 'readDgContainer', self::DG => 'readDg', self::SPGRCONTAINER => 'readSpgrContainer', self::SPCONTAINER => 'readSpContainer', self::SPGR => 'readSpgr', self::SP => 'readSp', self::CLIENTTEXTBOX => 'readClientTextbox', self::CLIENTANCHOR => 'readClientAnchor', self::CLIENTDATA => 'readClientData', ]; /** * Load Escher stream data. May be a partial Escher stream. * * @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); $routine = self::WHICH_ROUTINE[$fbt] ?? 'readDefault'; if (method_exists($this, $routine)) { $this->$routine(); } } return $this->object; } /** * Read a generic record. */ private function readDefault(): void { // offset 0; size: 2; recVer and recInstance //$verInstance = Xls::getUInt2d($this->data, $this->pos); // offset: 2; size: 2: Record Type //$fbt = Xls::getUInt2d($this->data, $this->pos + 2); // bit: 0-3; mask: 0x000F; recVer //$recVer = (0x000F & $verInstance) >> 0; $length = Xls::getInt4d($this->data, $this->pos + 4); //$recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; } /** * Read DggContainer record (Drawing Group Container). */ private function readDggContainer(): void { $length = Xls::getInt4d($this->data, $this->pos + 4); $recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; // record is a container, read contents $dggContainer = new DggContainer(); $this->applyAttribute('setDggContainer', $dggContainer); $reader = new self($dggContainer); $reader->load($recordData); } /** * Read Dgg record (Drawing Group). */ private function readDgg(): void { $length = Xls::getInt4d($this->data, $this->pos + 4); //$recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; } /** * Read BstoreContainer record (Blip Store Container). */ private function readBstoreContainer(): void { $length = Xls::getInt4d($this->data, $this->pos + 4); $recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; // record is a container, read contents $bstoreContainer = new BstoreContainer(); $this->applyAttribute('setBstoreContainer', $bstoreContainer); $reader = new self($bstoreContainer); $reader->load($recordData); } /** * Read BSE record. */ private function readBSE(): void { // offset: 0; size: 2; recVer and recInstance // bit: 4-15; mask: 0xFFF0; recInstance $recInstance = (0xFFF0 & Xls::getUInt2d($this->data, $this->pos)) >> 4; $length = Xls::getInt4d($this->data, $this->pos + 4); $recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; // add BSE to BstoreContainer $BSE = new BSE(); $this->applyAttribute('addBSE', $BSE); $BSE->setBLIPType($recInstance); // offset: 0; size: 1; btWin32 (MSOBLIPTYPE) //$btWin32 = ord($recordData[0]); // offset: 1; size: 1; btWin32 (MSOBLIPTYPE) //$btMacOS = ord($recordData[1]); // offset: 2; size: 16; MD4 digest //$rgbUid = substr($recordData, 2, 16); // offset: 18; size: 2; tag //$tag = Xls::getUInt2d($recordData, 18); // offset: 20; size: 4; size of BLIP in bytes //$size = Xls::getInt4d($recordData, 20); // offset: 24; size: 4; number of references to this BLIP //$cRef = Xls::getInt4d($recordData, 24); // offset: 28; size: 4; MSOFO file offset //$foDelay = Xls::getInt4d($recordData, 28); // offset: 32; size: 1; unused1 //$unused1 = ord($recordData[32]); // offset: 33; size: 1; size of nameData in bytes (including null terminator) $cbName = ord($recordData[33]); // offset: 34; size: 1; unused2 //$unused2 = ord($recordData[34]); // offset: 35; size: 1; unused3 //$unused3 = ord($recordData[35]); // offset: 36; size: $cbName; nameData //$nameData = substr($recordData, 36, $cbName); // offset: 36 + $cbName, size: var; the BLIP data $blipData = substr($recordData, 36 + $cbName); // record is a container, read contents $reader = new self($BSE); $reader->load($blipData); } /** * Read BlipJPEG record. Holds raw JPEG image data. */ private function readBlipJPEG(): void { // offset: 0; size: 2; recVer and recInstance // bit: 4-15; mask: 0xFFF0; recInstance $recInstance = (0xFFF0 & Xls::getUInt2d($this->data, $this->pos)) >> 4; $length = Xls::getInt4d($this->data, $this->pos + 4); $recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; $pos = 0; // offset: 0; size: 16; rgbUid1 (MD4 digest of) //$rgbUid1 = substr($recordData, 0, 16); $pos += 16; // offset: 16; size: 16; rgbUid2 (MD4 digest), only if $recInstance = 0x46B or 0x6E3 if (in_array($recInstance, [0x046B, 0x06E3])) { //$rgbUid2 = substr($recordData, 16, 16); $pos += 16; } // offset: var; size: 1; tag //$tag = ord($recordData[$pos]); ++$pos; // offset: var; size: var; the raw image data $data = substr($recordData, $pos); $blip = new Blip(); $blip->setData($data); $this->applyAttribute('setBlip', $blip); } /** * Read BlipPNG record. Holds raw PNG image data. */ private function readBlipPNG(): void { // offset: 0; size: 2; recVer and recInstance // bit: 4-15; mask: 0xFFF0; recInstance $recInstance = (0xFFF0 & Xls::getUInt2d($this->data, $this->pos)) >> 4; $length = Xls::getInt4d($this->data, $this->pos + 4); $recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; $pos = 0; // offset: 0; size: 16; rgbUid1 (MD4 digest of) //$rgbUid1 = substr($recordData, 0, 16); $pos += 16; // offset: 16; size: 16; rgbUid2 (MD4 digest), only if $recInstance = 0x46B or 0x6E3 if ($recInstance == 0x06E1) { //$rgbUid2 = substr($recordData, 16, 16); $pos += 16; } // offset: var; size: 1; tag //$tag = ord($recordData[$pos]); ++$pos; // offset: var; size: var; the raw image data $data = substr($recordData, $pos); $blip = new Blip(); $blip->setData($data); $this->applyAttribute('setBlip', $blip); } /** * Read OPT record. This record may occur within DggContainer record or SpContainer. */ private function readOPT(): void { // offset: 0; size: 2; recVer and recInstance // bit: 4-15; mask: 0xFFF0; recInstance $recInstance = (0xFFF0 & Xls::getUInt2d($this->data, $this->pos)) >> 4; $length = Xls::getInt4d($this->data, $this->pos + 4); $recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; $this->readOfficeArtRGFOPTE($recordData, $recInstance); } /** * Read TertiaryOPT record. */ private function readTertiaryOPT(): void { // offset: 0; size: 2; recVer and recInstance // bit: 4-15; mask: 0xFFF0; recInstance //$recInstance = (0xFFF0 & Xls::getUInt2d($this->data, $this->pos)) >> 4; $length = Xls::getInt4d($this->data, $this->pos + 4); //$recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; } /** * Read SplitMenuColors record. */ private function readSplitMenuColors(): void { $length = Xls::getInt4d($this->data, $this->pos + 4); //$recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; } /** * Read DgContainer record (Drawing Container). */ private function readDgContainer(): void { $length = Xls::getInt4d($this->data, $this->pos + 4); $recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; // record is a container, read contents $dgContainer = new DgContainer(); $this->applyAttribute('setDgContainer', $dgContainer); $reader = new self($dgContainer); $reader->load($recordData); } /** * Read Dg record (Drawing). */ private function readDg(): void { $length = Xls::getInt4d($this->data, $this->pos + 4); //$recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; } /** * Read SpgrContainer record (Shape Group Container). */ private function readSpgrContainer(): void { // context is either context DgContainer or SpgrContainer $length = Xls::getInt4d($this->data, $this->pos + 4); $recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; // record is a container, read contents $spgrContainer = new SpgrContainer(); if ($this->object instanceof DgContainer) { // DgContainer $this->object->setSpgrContainer($spgrContainer); } elseif ($this->object instanceof SpgrContainer) { // SpgrContainer $this->object->addChild($spgrContainer); } $reader = new self($spgrContainer); $reader->load($recordData); } /** * Read SpContainer record (Shape Container). */ private function readSpContainer(): void { $length = Xls::getInt4d($this->data, $this->pos + 4); $recordData = substr($this->data, $this->pos + 8, $length); // add spContainer to spgrContainer $spContainer = new SpContainer(); $this->applyAttribute('addChild', $spContainer); // move stream pointer to next record $this->pos += 8 + $length; // record is a container, read contents $reader = new self($spContainer); $reader->load($recordData); } /** * Read Spgr record (Shape Group). */ private function readSpgr(): void { $length = Xls::getInt4d($this->data, $this->pos + 4); //$recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; } /** * Read Sp record (Shape). */ private function readSp(): void { // offset: 0; size: 2; recVer and recInstance // bit: 4-15; mask: 0xFFF0; recInstance //$recInstance = (0xFFF0 & Xls::getUInt2d($this->data, $this->pos)) >> 4; $length = Xls::getInt4d($this->data, $this->pos + 4); //$recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; } /** * Read ClientTextbox record. */ private function readClientTextbox(): void { // offset: 0; size: 2; recVer and recInstance // bit: 4-15; mask: 0xFFF0; recInstance //$recInstance = (0xFFF0 & Xls::getUInt2d($this->data, $this->pos)) >> 4; $length = Xls::getInt4d($this->data, $this->pos + 4); //$recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; } /** * Read ClientAnchor record. This record holds information about where the shape is anchored in worksheet. */ private function readClientAnchor(): void { $length = Xls::getInt4d($this->data, $this->pos + 4); $recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; // offset: 2; size: 2; upper-left corner column index (0-based) $c1 = Xls::getUInt2d($recordData, 2); // offset: 4; size: 2; upper-left corner horizontal offset in 1/1024 of column width $startOffsetX = Xls::getUInt2d($recordData, 4); // offset: 6; size: 2; upper-left corner row index (0-based) $r1 = Xls::getUInt2d($recordData, 6); // offset: 8; size: 2; upper-left corner vertical offset in 1/256 of row height $startOffsetY = Xls::getUInt2d($recordData, 8); // offset: 10; size: 2; bottom-right corner column index (0-based) $c2 = Xls::getUInt2d($recordData, 10); // offset: 12; size: 2; bottom-right corner horizontal offset in 1/1024 of column width $endOffsetX = Xls::getUInt2d($recordData, 12); // offset: 14; size: 2; bottom-right corner row index (0-based) $r2 = Xls::getUInt2d($recordData, 14); // offset: 16; size: 2; bottom-right corner vertical offset in 1/256 of row height $endOffsetY = Xls::getUInt2d($recordData, 16); $this->applyAttribute('setStartCoordinates', Coordinate::stringFromColumnIndex($c1 + 1) . ($r1 + 1)); $this->applyAttribute('setStartOffsetX', $startOffsetX); $this->applyAttribute('setStartOffsetY', $startOffsetY); $this->applyAttribute('setEndCoordinates', Coordinate::stringFromColumnIndex($c2 + 1) . ($r2 + 1)); $this->applyAttribute('setEndOffsetX', $endOffsetX); $this->applyAttribute('setEndOffsetY', $endOffsetY); } /** * @param mixed $value */ private function applyAttribute(string $name, $value): void { if (method_exists($this->object, $name)) { $this->object->$name($value); } } /** * Read ClientData record. */ private function readClientData(): void { $length = Xls::getInt4d($this->data, $this->pos + 4); //$recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; } /** * Read OfficeArtRGFOPTE table of property-value pairs. * * @param string $data Binary data * @param int $n Number of properties */ private function readOfficeArtRGFOPTE($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; } if (method_exists($this->object, 'setOPT')) { $this->object->setOPT($opidOpid, $value); } } } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/ErrorCode.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/ErrorCode.php
<?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; } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/Color.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/Color.php
<?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[$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); } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/RC4.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/RC4.php
<?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; } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/Style/FillPattern.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/Style/FillPattern.php
<?php namespace PhpOffice\PhpSpreadsheet\Reader\Xls\Style; use PhpOffice\PhpSpreadsheet\Style\Fill; class FillPattern { /** * @var array<int, string> */ protected static $fillPatternMap = [ 0x00 => Fill::FILL_NONE, 0x01 => Fill::FILL_SOLID, 0x02 => Fill::FILL_PATTERN_MEDIUMGRAY, 0x03 => Fill::FILL_PATTERN_DARKGRAY, 0x04 => Fill::FILL_PATTERN_LIGHTGRAY, 0x05 => Fill::FILL_PATTERN_DARKHORIZONTAL, 0x06 => Fill::FILL_PATTERN_DARKVERTICAL, 0x07 => Fill::FILL_PATTERN_DARKDOWN, 0x08 => Fill::FILL_PATTERN_DARKUP, 0x09 => Fill::FILL_PATTERN_DARKGRID, 0x0A => Fill::FILL_PATTERN_DARKTRELLIS, 0x0B => Fill::FILL_PATTERN_LIGHTHORIZONTAL, 0x0C => Fill::FILL_PATTERN_LIGHTVERTICAL, 0x0D => Fill::FILL_PATTERN_LIGHTDOWN, 0x0E => Fill::FILL_PATTERN_LIGHTUP, 0x0F => Fill::FILL_PATTERN_LIGHTGRID, 0x10 => Fill::FILL_PATTERN_LIGHTTRELLIS, 0x11 => Fill::FILL_PATTERN_GRAY125, 0x12 => Fill::FILL_PATTERN_GRAY0625, ]; /** * Get fill pattern from index * OpenOffice documentation: 2.5.12. * * @param int $index * * @return string */ public static function lookup($index) { if (isset(self::$fillPatternMap[$index])) { return self::$fillPatternMap[$index]; } return Fill::FILL_NONE; } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/Style/Border.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/Style/Border.php
<?php namespace PhpOffice\PhpSpreadsheet\Reader\Xls\Style; use PhpOffice\PhpSpreadsheet\Style\Border as StyleBorder; class Border { /** * @var array<int, string> */ protected static $borderStyleMap = [ 0x00 => StyleBorder::BORDER_NONE, 0x01 => StyleBorder::BORDER_THIN, 0x02 => StyleBorder::BORDER_MEDIUM, 0x03 => StyleBorder::BORDER_DASHED, 0x04 => StyleBorder::BORDER_DOTTED, 0x05 => StyleBorder::BORDER_THICK, 0x06 => StyleBorder::BORDER_DOUBLE, 0x07 => StyleBorder::BORDER_HAIR, 0x08 => StyleBorder::BORDER_MEDIUMDASHED, 0x09 => StyleBorder::BORDER_DASHDOT, 0x0A => StyleBorder::BORDER_MEDIUMDASHDOT, 0x0B => StyleBorder::BORDER_DASHDOTDOT, 0x0C => StyleBorder::BORDER_MEDIUMDASHDOTDOT, 0x0D => StyleBorder::BORDER_SLANTDASHDOT, ]; public static function lookup(int $index): string { if (isset(self::$borderStyleMap[$index])) { return self::$borderStyleMap[$index]; } return StyleBorder::BORDER_NONE; } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/Style/CellFont.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/Style/CellFont.php
<?php namespace PhpOffice\PhpSpreadsheet\Reader\Xls\Style; use PhpOffice\PhpSpreadsheet\Style\Font; class CellFont { public static function escapement(Font $font, int $escapement): void { switch ($escapement) { case 0x0001: $font->setSuperscript(true); break; case 0x0002: $font->setSubscript(true); break; } } /** * @var array<int, string> */ protected static $underlineMap = [ 0x01 => Font::UNDERLINE_SINGLE, 0x02 => Font::UNDERLINE_DOUBLE, 0x21 => Font::UNDERLINE_SINGLEACCOUNTING, 0x22 => Font::UNDERLINE_DOUBLEACCOUNTING, ]; public static function underline(Font $font, int $underline): void { if (array_key_exists($underline, self::$underlineMap)) { $font->setUnderline(self::$underlineMap[$underline]); } } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/Style/CellAlignment.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/Style/CellAlignment.php
<?php namespace PhpOffice\PhpSpreadsheet\Reader\Xls\Style; use PhpOffice\PhpSpreadsheet\Style\Alignment; class CellAlignment { /** * @var array<int, string> */ protected static $horizontalAlignmentMap = [ 0 => Alignment::HORIZONTAL_GENERAL, 1 => Alignment::HORIZONTAL_LEFT, 2 => Alignment::HORIZONTAL_CENTER, 3 => Alignment::HORIZONTAL_RIGHT, 4 => Alignment::HORIZONTAL_FILL, 5 => Alignment::HORIZONTAL_JUSTIFY, 6 => Alignment::HORIZONTAL_CENTER_CONTINUOUS, ]; /** * @var array<int, string> */ protected static $verticalAlignmentMap = [ 0 => Alignment::VERTICAL_TOP, 1 => Alignment::VERTICAL_CENTER, 2 => Alignment::VERTICAL_BOTTOM, 3 => Alignment::VERTICAL_JUSTIFY, ]; public static function horizontal(Alignment $alignment, int $horizontal): void { if (array_key_exists($horizontal, self::$horizontalAlignmentMap)) { $alignment->setHorizontal(self::$horizontalAlignmentMap[$horizontal]); } } public static function vertical(Alignment $alignment, int $vertical): void { if (array_key_exists($vertical, self::$verticalAlignmentMap)) { $alignment->setVertical(self::$verticalAlignmentMap[$vertical]); } } public static function wrap(Alignment $alignment, int $wrap): void { $alignment->setWrapText((bool) $wrap); } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/Color/BIFF8.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/Color/BIFF8.php
<?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']; } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/Color/BuiltIn.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/Color/BuiltIn.php
<?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']; } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/Color/BIFF5.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/Color/BIFF5.php
<?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']; } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/PageSettings.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/PageSettings.php
<?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']); if (!$pageSetupAttributes) { continue; } 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; } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Properties.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Properties.php
<?php namespace PhpOffice\PhpSpreadsheet\Reader\Xml; use PhpOffice\PhpSpreadsheet\Document\Properties as DocumentProperties; use PhpOffice\PhpSpreadsheet\Spreadsheet; use SimpleXMLElement; class Properties { /** * @var Spreadsheet */ protected $spreadsheet; public function __construct(Spreadsheet $spreadsheet) { $this->spreadsheet = $spreadsheet; } public function readProperties(SimpleXMLElement $xml, array $namespaces): void { $this->readStandardProperties($xml); $this->readCustomProperties($xml, $namespaces); } protected function readStandardProperties(SimpleXMLElement $xml): void { if (isset($xml->DocumentProperties[0])) { $docProps = $this->spreadsheet->getProperties(); foreach ($xml->DocumentProperties[0] as $propertyName => $propertyValue) { $propertyValue = (string) $propertyValue; $this->processStandardProperty($docProps, $propertyName, $propertyValue); } } } protected function readCustomProperties(SimpleXMLElement $xml, array $namespaces): void { if (isset($xml->CustomDocumentProperties)) { $docProps = $this->spreadsheet->getProperties(); foreach ($xml->CustomDocumentProperties[0] as $propertyName => $propertyValue) { $propertyAttributes = self::getAttributes($propertyValue, $namespaces['dt']); $propertyName = preg_replace_callback('/_x([0-9a-f]{4})_/i', [$this, 'hex2str'], $propertyName); $this->processCustomProperty($docProps, $propertyName, $propertyValue, $propertyAttributes); } } } protected function processStandardProperty( DocumentProperties $docProps, string $propertyName, string $stringValue ): void { switch ($propertyName) { case 'Title': $docProps->setTitle($stringValue); break; case 'Subject': $docProps->setSubject($stringValue); break; case 'Author': $docProps->setCreator($stringValue); break; case 'Created': $docProps->setCreated($stringValue); break; case 'LastAuthor': $docProps->setLastModifiedBy($stringValue); break; case 'LastSaved': $docProps->setModified($stringValue); 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; } } protected function processCustomProperty( DocumentProperties $docProps, string $propertyName, ?SimpleXMLElement $propertyValue, SimpleXMLElement $propertyAttributes ): void { $propertyType = DocumentProperties::PROPERTY_TYPE_UNKNOWN; switch ((string) $propertyAttributes) { case 'string': $propertyType = DocumentProperties::PROPERTY_TYPE_STRING; $propertyValue = trim((string) $propertyValue); break; case 'boolean': $propertyType = DocumentProperties::PROPERTY_TYPE_BOOLEAN; $propertyValue = (bool) $propertyValue; break; case 'integer': $propertyType = DocumentProperties::PROPERTY_TYPE_INTEGER; $propertyValue = (int) $propertyValue; break; case 'float': $propertyType = DocumentProperties::PROPERTY_TYPE_FLOAT; $propertyValue = (float) $propertyValue; break; case 'dateTime.tz': $propertyType = DocumentProperties::PROPERTY_TYPE_DATE; $propertyValue = trim((string) $propertyValue); break; } $docProps->setCustomProperty($propertyName, $propertyValue, $propertyType); } protected function hex2str(array $hex): string { return mb_chr((int) hexdec($hex[1]), 'UTF-8'); } private static function getAttributes(?SimpleXMLElement $simple, string $node): SimpleXMLElement { return ($simple === null) ? new SimpleXMLElement('<xml></xml>') : ($simple->attributes($node) ?? new SimpleXMLElement('<xml></xml>')); } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style.php
<?php namespace PhpOffice\PhpSpreadsheet\Reader\Xml; use SimpleXMLElement; class Style { /** * Formats. * * @var array */ protected $styles = []; public function parseStyles(SimpleXMLElement $xml, array $namespaces): array { if (!isset($xml->Styles)) { return []; } $alignmentStyleParser = new Style\Alignment(); $borderStyleParser = new Style\Border(); $fontStyleParser = new Style\Font(); $fillStyleParser = new Style\Fill(); $numberFormatStyleParser = new Style\NumberFormat(); foreach ($xml->Styles[0] as $style) { $style_ss = self::getAttributes($style, $namespaces['ss']); $styleID = (string) $style_ss['ID']; $this->styles[$styleID] = $this->styles['Default'] ?? []; $alignment = $border = $font = $fill = $numberFormat = []; foreach ($style as $styleType => $styleDatax) { $styleData = $styleDatax ?? new SimpleXMLElement('<xml></xml>'); $styleAttributes = $styleData->attributes($namespaces['ss']); switch ($styleType) { case 'Alignment': if ($styleAttributes) { $alignment = $alignmentStyleParser->parseStyle($styleAttributes); } break; case 'Borders': $border = $borderStyleParser->parseStyle($styleData, $namespaces); break; case 'Font': if ($styleAttributes) { $font = $fontStyleParser->parseStyle($styleAttributes); } break; case 'Interior': if ($styleAttributes) { $fill = $fillStyleParser->parseStyle($styleAttributes); } break; case 'NumberFormat': if ($styleAttributes) { $numberFormat = $numberFormatStyleParser->parseStyle($styleAttributes); } break; } } $this->styles[$styleID] = array_merge($alignment, $border, $font, $fill, $numberFormat); } return $this->styles; } protected static function getAttributes(?SimpleXMLElement $simple, string $node): SimpleXMLElement { return ($simple === null) ? new SimpleXMLElement('<xml></xml>') : ($simple->attributes($node) ?? new SimpleXMLElement('<xml></xml>')); } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style/Font.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style/Font.php
<?php namespace PhpOffice\PhpSpreadsheet\Reader\Xml\Style; use PhpOffice\PhpSpreadsheet\Style\Font as FontUnderline; use SimpleXMLElement; class Font extends StyleBase { protected const UNDERLINE_STYLES = [ FontUnderline::UNDERLINE_NONE, FontUnderline::UNDERLINE_DOUBLE, FontUnderline::UNDERLINE_DOUBLEACCOUNTING, FontUnderline::UNDERLINE_SINGLE, FontUnderline::UNDERLINE_SINGLEACCOUNTING, ]; protected function parseUnderline(array $style, string $styleAttributeValue): array { if (self::identifyFixedStyleValue(self::UNDERLINE_STYLES, $styleAttributeValue)) { $style['font']['underline'] = $styleAttributeValue; } return $style; } protected function parseVerticalAlign(array $style, string $styleAttributeValue): array { if ($styleAttributeValue == 'Superscript') { $style['font']['superscript'] = true; } if ($styleAttributeValue == 'Subscript') { $style['font']['subscript'] = true; } return $style; } public function parseStyle(SimpleXMLElement $styleAttributes): array { $style = []; foreach ($styleAttributes as $styleAttributeKey => $styleAttributeValue) { $styleAttributeValue = (string) $styleAttributeValue; switch ($styleAttributeKey) { case 'FontName': $style['font']['name'] = $styleAttributeValue; break; case 'Size': $style['font']['size'] = $styleAttributeValue; break; case 'Color': $style['font']['color']['rgb'] = substr($styleAttributeValue, 1); break; case 'Bold': $style['font']['bold'] = true; break; case 'Italic': $style['font']['italic'] = true; break; case 'Underline': $style = $this->parseUnderline($style, $styleAttributeValue); break; case 'VerticalAlign': $style = $this->parseVerticalAlign($style, $styleAttributeValue); break; } } return $style; } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style/StyleBase.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style/StyleBase.php
<?php namespace PhpOffice\PhpSpreadsheet\Reader\Xml\Style; use SimpleXMLElement; abstract class StyleBase { protected static function identifyFixedStyleValue(array $styleList, string &$styleAttributeValue): bool { $returnValue = false; $styleAttributeValue = strtolower($styleAttributeValue); foreach ($styleList as $style) { if ($styleAttributeValue == strtolower($style)) { $styleAttributeValue = $style; $returnValue = true; break; } } return $returnValue; } protected static function getAttributes(?SimpleXMLElement $simple, string $node): SimpleXMLElement { return ($simple === null) ? new SimpleXMLElement('<xml></xml>') : ($simple->attributes($node) ?? new SimpleXMLElement('<xml></xml>')); } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style/Fill.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style/Fill.php
<?php namespace PhpOffice\PhpSpreadsheet\Reader\Xml\Style; use PhpOffice\PhpSpreadsheet\Style\Fill as FillStyles; use SimpleXMLElement; class Fill extends StyleBase { /** * @var array */ public const FILL_MAPPINGS = [ 'fillType' => [ 'solid' => FillStyles::FILL_SOLID, 'gray75' => FillStyles::FILL_PATTERN_DARKGRAY, 'gray50' => FillStyles::FILL_PATTERN_MEDIUMGRAY, 'gray25' => FillStyles::FILL_PATTERN_LIGHTGRAY, 'gray125' => FillStyles::FILL_PATTERN_GRAY125, 'gray0625' => FillStyles::FILL_PATTERN_GRAY0625, 'horzstripe' => FillStyles::FILL_PATTERN_DARKHORIZONTAL, // horizontal stripe 'vertstripe' => FillStyles::FILL_PATTERN_DARKVERTICAL, // vertical stripe 'reversediagstripe' => FillStyles::FILL_PATTERN_DARKUP, // reverse diagonal stripe 'diagstripe' => FillStyles::FILL_PATTERN_DARKDOWN, // diagonal stripe 'diagcross' => FillStyles::FILL_PATTERN_DARKGRID, // diagoanl crosshatch 'thickdiagcross' => FillStyles::FILL_PATTERN_DARKTRELLIS, // thick diagonal crosshatch 'thinhorzstripe' => FillStyles::FILL_PATTERN_LIGHTHORIZONTAL, 'thinvertstripe' => FillStyles::FILL_PATTERN_LIGHTVERTICAL, 'thinreversediagstripe' => FillStyles::FILL_PATTERN_LIGHTUP, 'thindiagstripe' => FillStyles::FILL_PATTERN_LIGHTDOWN, 'thinhorzcross' => FillStyles::FILL_PATTERN_LIGHTGRID, // thin horizontal crosshatch 'thindiagcross' => FillStyles::FILL_PATTERN_LIGHTTRELLIS, // thin diagonal crosshatch ], ]; public function parseStyle(SimpleXMLElement $styleAttributes): array { $style = []; foreach ($styleAttributes as $styleAttributeKey => $styleAttributeValuex) { $styleAttributeValue = (string) $styleAttributeValuex; switch ($styleAttributeKey) { case 'Color': $style['fill']['endColor']['rgb'] = substr($styleAttributeValue, 1); $style['fill']['startColor']['rgb'] = substr($styleAttributeValue, 1); break; case 'PatternColor': $style['fill']['startColor']['rgb'] = substr($styleAttributeValue, 1); break; case 'Pattern': $lcStyleAttributeValue = strtolower((string) $styleAttributeValue); $style['fill']['fillType'] = self::FILL_MAPPINGS['fillType'][$lcStyleAttributeValue] ?? FillStyles::FILL_NONE; break; } } return $style; } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style/Border.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style/Border.php
<?php namespace PhpOffice\PhpSpreadsheet\Reader\Xml\Style; use PhpOffice\PhpSpreadsheet\Style\Border as BorderStyle; use PhpOffice\PhpSpreadsheet\Style\Borders; use SimpleXMLElement; class Border extends StyleBase { protected const BORDER_POSITIONS = [ 'top', 'left', 'bottom', 'right', ]; /** * @var array */ public const BORDER_MAPPINGS = [ 'borderStyle' => [ '1continuous' => BorderStyle::BORDER_THIN, '1dash' => BorderStyle::BORDER_DASHED, '1dashdot' => BorderStyle::BORDER_DASHDOT, '1dashdotdot' => BorderStyle::BORDER_DASHDOTDOT, '1dot' => BorderStyle::BORDER_DOTTED, '1double' => BorderStyle::BORDER_DOUBLE, '2continuous' => BorderStyle::BORDER_MEDIUM, '2dash' => BorderStyle::BORDER_MEDIUMDASHED, '2dashdot' => BorderStyle::BORDER_MEDIUMDASHDOT, '2dashdotdot' => BorderStyle::BORDER_MEDIUMDASHDOTDOT, '2dot' => BorderStyle::BORDER_DOTTED, '2double' => BorderStyle::BORDER_DOUBLE, '3continuous' => BorderStyle::BORDER_THICK, '3dash' => BorderStyle::BORDER_MEDIUMDASHED, '3dashdot' => BorderStyle::BORDER_MEDIUMDASHDOT, '3dashdotdot' => BorderStyle::BORDER_MEDIUMDASHDOTDOT, '3dot' => BorderStyle::BORDER_DOTTED, '3double' => BorderStyle::BORDER_DOUBLE, ], ]; public function parseStyle(SimpleXMLElement $styleData, array $namespaces): array { $style = []; $diagonalDirection = ''; $borderPosition = ''; foreach ($styleData->Border as $borderStyle) { $borderAttributes = self::getAttributes($borderStyle, $namespaces['ss']); $thisBorder = []; $styleType = (string) $borderAttributes->Weight; $styleType .= strtolower((string) $borderAttributes->LineStyle); $thisBorder['borderStyle'] = self::BORDER_MAPPINGS['borderStyle'][$styleType] ?? BorderStyle::BORDER_NONE; foreach ($borderAttributes as $borderStyleKey => $borderStyleValuex) { $borderStyleValue = (string) $borderStyleValuex; switch ($borderStyleKey) { case 'Position': [$borderPosition, $diagonalDirection] = $this->parsePosition($borderStyleValue, $diagonalDirection); break; case 'Color': $borderColour = substr($borderStyleValue, 1); $thisBorder['color']['rgb'] = $borderColour; break; } } if ($borderPosition) { $style['borders'][$borderPosition] = $thisBorder; } elseif ($diagonalDirection) { $style['borders']['diagonalDirection'] = $diagonalDirection; $style['borders']['diagonal'] = $thisBorder; } } return $style; } protected function parsePosition(string $borderStyleValue, string $diagonalDirection): array { $borderStyleValue = strtolower($borderStyleValue); if (in_array($borderStyleValue, self::BORDER_POSITIONS)) { $borderPosition = $borderStyleValue; } elseif ($borderStyleValue === 'diagonalleft') { $diagonalDirection = $diagonalDirection ? Borders::DIAGONAL_BOTH : Borders::DIAGONAL_DOWN; } elseif ($borderStyleValue === 'diagonalright') { $diagonalDirection = $diagonalDirection ? Borders::DIAGONAL_BOTH : Borders::DIAGONAL_UP; } return [$borderPosition ?? null, $diagonalDirection]; } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style/Alignment.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style/Alignment.php
<?php namespace PhpOffice\PhpSpreadsheet\Reader\Xml\Style; use PhpOffice\PhpSpreadsheet\Style\Alignment as AlignmentStyles; use SimpleXMLElement; class Alignment extends StyleBase { protected const VERTICAL_ALIGNMENT_STYLES = [ AlignmentStyles::VERTICAL_BOTTOM, AlignmentStyles::VERTICAL_TOP, AlignmentStyles::VERTICAL_CENTER, AlignmentStyles::VERTICAL_JUSTIFY, ]; protected const HORIZONTAL_ALIGNMENT_STYLES = [ AlignmentStyles::HORIZONTAL_GENERAL, AlignmentStyles::HORIZONTAL_LEFT, AlignmentStyles::HORIZONTAL_RIGHT, AlignmentStyles::HORIZONTAL_CENTER, AlignmentStyles::HORIZONTAL_CENTER_CONTINUOUS, AlignmentStyles::HORIZONTAL_JUSTIFY, ]; public function parseStyle(SimpleXMLElement $styleAttributes): array { $style = []; foreach ($styleAttributes as $styleAttributeKey => $styleAttributeValue) { $styleAttributeValue = (string) $styleAttributeValue; switch ($styleAttributeKey) { case 'Vertical': if (self::identifyFixedStyleValue(self::VERTICAL_ALIGNMENT_STYLES, $styleAttributeValue)) { $style['alignment']['vertical'] = $styleAttributeValue; } break; case 'Horizontal': if (self::identifyFixedStyleValue(self::HORIZONTAL_ALIGNMENT_STYLES, $styleAttributeValue)) { $style['alignment']['horizontal'] = $styleAttributeValue; } break; case 'WrapText': $style['alignment']['wrapText'] = true; break; case 'Rotate': $style['alignment']['textRotation'] = $styleAttributeValue; break; } } return $style; } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style/NumberFormat.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style/NumberFormat.php
<?php namespace PhpOffice\PhpSpreadsheet\Reader\Xml\Style; use SimpleXMLElement; class NumberFormat extends StyleBase { public function parseStyle(SimpleXMLElement $styleAttributes): array { $style = []; $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 > '') { $style['numberFormat']['formatCode'] = $styleAttributeValue; } } return $style; } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods/BaseReader.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods/BaseReader.php
<?php namespace PhpOffice\PhpSpreadsheet\Reader\Ods; use DOMElement; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Spreadsheet; abstract class BaseReader { /** * @var Spreadsheet */ protected $spreadsheet; /** * @var string */ protected $tableNs; public function __construct(Spreadsheet $spreadsheet, string $tableNs) { $this->spreadsheet = $spreadsheet; $this->tableNs = $tableNs; } abstract public function read(DOMElement $workbookData): void; protected 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 ?? ''; } protected function convertToExcelFormulaValue(string $openOfficeFormula): string { $temp = explode('"', $openOfficeFormula); $tKey = false; foreach ($temp as &$value) { // @var string $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 ?? ''); // Convert references to defined names/formulae $value = str_replace('$$', '', $value ?? ''); $value = Calculation::translateSeparator(';', ',', $value, $inBraces); } } // Then rebuild the formula string $excelFormula = implode('"', $temp); return $excelFormula; } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods/PageSettings.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods/PageSettings.php
<?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 = isset($headerProperties) ? $headerProperties->getAttributeNS($this->stylesFo, 'min-height') : null; $footer = $styleSet->getElementsByTagNameNS($this->stylesNs, 'footer-style')[0]; $footerProperties = $footer->getElementsByTagNameNS($this->stylesNs, 'header-footer-properties')[0]; $marginFooter = isset($footerProperties) ? $footerProperties->getAttributeNS($this->stylesFo, 'min-height') : null; $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); } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods/Properties.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods/Properties.php
<?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 = []; 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': $docProps->setModified($propertyValue); 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': $docProps->setCreated($propertyValue); 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); } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods/AutoFilter.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods/AutoFilter.php
<?php namespace PhpOffice\PhpSpreadsheet\Reader\Ods; use DOMElement; use DOMNode; class AutoFilter extends BaseReader { public function read(DOMElement $workbookData): void { $this->readAutoFilters($workbookData); } protected function readAutoFilters(DOMElement $workbookData): void { $databases = $workbookData->getElementsByTagNameNS($this->tableNs, 'database-ranges'); foreach ($databases as $autofilters) { foreach ($autofilters->childNodes as $autofilter) { $autofilterRange = $this->getAttributeValue($autofilter, 'target-range-address'); if ($autofilterRange !== null) { $baseAddress = $this->convertToExcelAddressValue($autofilterRange); $this->spreadsheet->getActiveSheet()->setAutoFilter($baseAddress); } } } } protected function getAttributeValue(?DOMNode $node, string $attributeName): ?string { if ($node !== null && $node->attributes !== null) { $attribute = $node->attributes->getNamedItemNS( $this->tableNs, $attributeName ); if ($attribute !== null) { return $attribute->nodeValue; } } return null; } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods/DefinedNames.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods/DefinedNames.php
<?php namespace PhpOffice\PhpSpreadsheet\Reader\Ods; use DOMElement; use PhpOffice\PhpSpreadsheet\DefinedName; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; class DefinedNames extends BaseReader { public function read(DOMElement $workbookData): void { $this->readDefinedRanges($workbookData); $this->readDefinedExpressions($workbookData); } /** * Read any Named Ranges that are defined in this spreadsheet. */ protected function readDefinedRanges(DOMElement $workbookData): void { $namedRanges = $workbookData->getElementsByTagNameNS($this->tableNs, 'named-range'); foreach ($namedRanges as $definedNameElement) { $definedName = $definedNameElement->getAttributeNS($this->tableNs, 'name'); $baseAddress = $definedNameElement->getAttributeNS($this->tableNs, 'base-cell-address'); $range = $definedNameElement->getAttributeNS($this->tableNs, 'cell-range-address'); $baseAddress = $this->convertToExcelAddressValue($baseAddress); $range = $this->convertToExcelAddressValue($range); $this->addDefinedName($baseAddress, $definedName, $range); } } /** * Read any Named Formulae that are defined in this spreadsheet. */ protected function readDefinedExpressions(DOMElement $workbookData): void { $namedExpressions = $workbookData->getElementsByTagNameNS($this->tableNs, 'named-expression'); foreach ($namedExpressions as $definedNameElement) { $definedName = $definedNameElement->getAttributeNS($this->tableNs, 'name'); $baseAddress = $definedNameElement->getAttributeNS($this->tableNs, 'base-cell-address'); $expression = $definedNameElement->getAttributeNS($this->tableNs, 'expression'); $baseAddress = $this->convertToExcelAddressValue($baseAddress); $expression = substr($expression, strpos($expression, ':=') + 1); $expression = $this->convertToExcelFormulaValue($expression); $this->addDefinedName($baseAddress, $definedName, $expression); } } /** * Assess scope and store the Defined Name. */ private function addDefinedName(string $baseAddress, string $definedName, string $value): void { [$sheetReference] = Worksheet::extractSheetTitle($baseAddress, true); $worksheet = $this->spreadsheet->getSheetByName($sheetReference); // 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((string) $definedName, $worksheet, $value)); } } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Csv/Delimiter.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Csv/Delimiter.php
<?php namespace PhpOffice\PhpSpreadsheet\Reader\Csv; class Delimiter { protected const POTENTIAL_DELIMETERS = [',', ';', "\t", '|', ':', ' ', '~']; /** @var resource */ protected $fileHandle; /** @var string */ protected $escapeCharacter; /** @var string */ protected $enclosure; /** @var array */ protected $counts = []; /** @var int */ protected $numberLines = 0; /** @var ?string */ protected $delimiter; /** * @param resource $fileHandle */ public function __construct($fileHandle, string $escapeCharacter, string $enclosure) { $this->fileHandle = $fileHandle; $this->escapeCharacter = $escapeCharacter; $this->enclosure = $enclosure; $this->countPotentialDelimiters(); } public function getDefaultDelimiter(): string { return self::POTENTIAL_DELIMETERS[0]; } public function linesCounted(): int { return $this->numberLines; } protected function countPotentialDelimiters(): void { $this->counts = array_fill_keys(self::POTENTIAL_DELIMETERS, []); $delimiterKeys = array_flip(self::POTENTIAL_DELIMETERS); // Count how many times each of the potential delimiters appears in each line $this->numberLines = 0; while (($line = $this->getNextLine()) !== false && (++$this->numberLines < 1000)) { $this->countDelimiterValues($line, $delimiterKeys); } } protected function countDelimiterValues(string $line, array $delimiterKeys): void { $splitString = str_split($line, 1); if (is_array($splitString)) { $distribution = array_count_values($splitString); $countLine = array_intersect_key($distribution, $delimiterKeys); foreach (self::POTENTIAL_DELIMETERS as $delimiter) { $this->counts[$delimiter][] = $countLine[$delimiter] ?? 0; } } } public function infer(): ?string { // Calculate the mean square deviations for each delimiter // (ignoring delimiters that haven't been found consistently) $meanSquareDeviations = []; $middleIdx = floor(($this->numberLines - 1) / 2); foreach (self::POTENTIAL_DELIMETERS as $delimiter) { $series = $this->counts[$delimiter]; sort($series); $median = ($this->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 (self::POTENTIAL_DELIMETERS as $delimiter) { if (!isset($meanSquareDeviations[$delimiter])) { continue; } if ($meanSquareDeviations[$delimiter] < $min) { $min = $meanSquareDeviations[$delimiter]; $this->delimiter = $delimiter; } } return $this->delimiter; } /** * Get the next full line from the file. * * @return false|string */ public 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 ?? false; } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Gnumeric/Styles.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Gnumeric/Styles.php
<?php namespace PhpOffice\PhpSpreadsheet\Reader\Gnumeric; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Shared\Date; 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; class Styles { /** * @var Spreadsheet */ private $spreadsheet; /** * @var bool */ protected $readDataOnly = false; /** @var array */ public 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, ], '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 function __construct(Spreadsheet $spreadsheet, bool $readDataOnly) { $this->spreadsheet = $spreadsheet; $this->readDataOnly = $readDataOnly; } public function read(SimpleXMLElement $sheet, int $maxRow, int $maxCol): void { if ($sheet->Styles->StyleRegion !== null) { $this->readStyles($sheet->Styles->StyleRegion, $maxRow, $maxCol); } } private function readStyles(SimpleXMLElement $styleRegion, int $maxRow, int $maxCol): void { foreach ($styleRegion as $style) { $styleAttributes = $style->attributes(); if ($styleAttributes !== null && ($styleAttributes['startRow'] <= $maxRow) && ($styleAttributes['startCol'] <= $maxCol)) { $cellRange = $this->readStyleRange($styleAttributes, $maxCol, $maxRow); $styleAttributes = $style->Style->attributes(); $styleArray = []; // We still set the number format mask for date/time values, even if readDataOnly is true // so that we can identify whether a float is a float or a date value $formatCode = $styleAttributes ? (string) $styleAttributes['Format'] : null; if ($formatCode && Date::isDateTimeFormatCode($formatCode)) { $styleArray['numberFormat']['formatCode'] = $formatCode; } if ($this->readDataOnly === false && $styleAttributes !== null) { // If readDataOnly is false, we set all formatting information $styleArray['numberFormat']['formatCode'] = $formatCode; $styleArray = $this->readStyle($styleArray, $styleAttributes, $style); } $this->spreadsheet->getActiveSheet()->getStyle($cellRange)->applyFromArray($styleArray); } } } 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 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(?SimpleXMLElement $borderAttributes): array { $styleArray = []; if ($borderAttributes !== null) { if (isset($borderAttributes['Color'])) { $styleArray['color']['rgb'] = self::parseGnumericColour($borderAttributes['Color']); } self::addStyle($styleArray, 'borderStyle', (string) $borderAttributes['Style']); } return $styleArray; } private static function parseGnumericColour(string $gnmColour): string { [$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((string) $styleAttributes['Fore']); $styleArray['font']['color']['rgb'] = $RGB; $RGB = self::parseGnumericColour((string) $styleAttributes['Back']); $shade = (string) $styleAttributes['Shade']; if (($RGB !== '000000') || ($shade !== '0')) { $RGB2 = self::parseGnumericColour((string) $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); } } private function readStyleRange(SimpleXMLElement $styleAttributes, int $maxCol, int $maxRow): string { $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; return $cellRange; } private function readStyle(array $styleArray, SimpleXMLElement $styleAttributes, SimpleXMLElement $style): array { self::addStyle2($styleArray, 'alignment', 'horizontal', (string) $styleAttributes['HAlign']); self::addStyle2($styleArray, 'alignment', 'vertical', (string) $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 = $style->Style->Font->attributes(); if ($fontAttributes !== null) { $styleArray['font']['name'] = (string) $style->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', (string) $fontAttributes['Underline']); switch ($fontAttributes['Script']) { case '1': $styleArray['font']['superscript'] = true; break; case '-1': $styleArray['font']['subscript'] = true; break; } } if (isset($style->Style->StyleBorder)) { $srssb = $style->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($style->Style->HyperLink)) { // TO DO $hyperlink = $style->Style->HyperLink->attributes(); } return $styleArray; } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Gnumeric/PageSetup.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Gnumeric/PageSetup.php
<?php namespace PhpOffice\PhpSpreadsheet\Reader\Gnumeric; use 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; public function __construct(Spreadsheet $spreadsheet) { $this->spreadsheet = $spreadsheet; } public function printInformation(SimpleXMLElement $sheet): self { if (isset($sheet->PrintInformation)) { $printInformation = $sheet->PrintInformation[0]; if (!$printInformation) { return $this; } $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(Gnumeric::NAMESPACE_GNM) 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; } } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Gnumeric/Properties.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Gnumeric/Properties.php
<?php namespace PhpOffice\PhpSpreadsheet\Reader\Gnumeric; use PhpOffice\PhpSpreadsheet\Reader\Gnumeric; use PhpOffice\PhpSpreadsheet\Spreadsheet; use SimpleXMLElement; class Properties { /** * @var Spreadsheet */ protected $spreadsheet; public function __construct(Spreadsheet $spreadsheet) { $this->spreadsheet = $spreadsheet; } 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 = $propertyValue; $docProps->setModified($creationDate); break; case 'description': $docProps->setDescription($propertyValue); break; } } } private function docPropertiesMeta(SimpleXMLElement $officePropertyMeta): void { $docProps = $this->spreadsheet->getProperties(); foreach ($officePropertyMeta as $propertyName => $propertyValue) { if ($propertyValue !== null) { $attributes = $propertyValue->attributes(Gnumeric::NAMESPACE_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 = $propertyValue; $docProps->setCreated($creationDate); break; case 'user-defined': if ($attributes) { [, $attrName] = explode(':', (string) $attributes['name']); $this->userDefinedProperties($attrName, $propertyValue); } break; } } } } private function userDefinedProperties(string $attrName, string $propertyValue): void { $docProps = $this->spreadsheet->getProperties(); switch ($attrName) { case 'publisher': $docProps->setCompany($propertyValue); break; case 'category': $docProps->setCategory($propertyValue); break; case 'manager': $docProps->setManager($propertyValue); break; } } public function readProperties(SimpleXMLElement $xml, SimpleXMLElement $gnmXML): void { $officeXML = $xml->children(Gnumeric::NAMESPACE_OFFICE); if (!empty($officeXML)) { $officeDocXML = $officeXML->{'document-meta'}; $officeDocMetaXML = $officeDocXML->meta; foreach ($officeDocMetaXML as $officePropertyData) { $officePropertyDC = $officePropertyData->children(Gnumeric::NAMESPACE_DC); $this->docPropertiesDC($officePropertyDC); $officePropertyMeta = $officePropertyData->children(Gnumeric::NAMESPACE_META); $this->docPropertiesMeta($officePropertyMeta); } } elseif (isset($gnmXML->Summary)) { $this->docPropertiesOld($gnmXML); } } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Styles.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Styles.php
<?php namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx; use 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; 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; } public static function readFontStyle(Font $fontStyle, SimpleXMLElement $fontStyleXml): void { if (isset($fontStyleXml->name, $fontStyleXml->name['val'])) { $fontStyle->setName((string) $fontStyleXml->name['val']); } if (isset($fontStyleXml->sz, $fontStyleXml->sz['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); } elseif ($verticalAlign === 'subscript') { $fontStyle->setSubscript(true); } } } private static function readNumberFormat(NumberFormat $numfmtStyle, SimpleXMLElement $numfmtStyleXml): void { if ($numfmtStyleXml->count() === 0) { return; } $numfmt = Xlsx::getAttributes($numfmtStyleXml); if ($numfmt->count() > 0 && isset($numfmt['formatCode'])) { $numfmtStyle->setFormatCode((string) $numfmt['formatCode']); } } public 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', Namespaces::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) { $defaultFillStyle = Fill::FILL_NONE; if ($fillStyleXml->patternFill->fgColor) { $fillStyle->getStartColor()->setARGB(self::readColor($fillStyleXml->patternFill->fgColor, true)); $defaultFillStyle = Fill::FILL_SOLID; } if ($fillStyleXml->patternFill->bgColor) { $fillStyle->getEndColor()->setARGB(self::readColor($fillStyleXml->patternFill->bgColor, true)); $defaultFillStyle = Fill::FILL_SOLID; } $patternType = (string) $fillStyleXml->patternFill['patternType'] != '' ? (string) $fillStyleXml->patternFill['patternType'] : $defaultFillStyle; $fillStyle->setFillType($patternType); } } public 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)); } } public static function readAlignmentStyle(Alignment $alignment, SimpleXMLElement $alignmentXml): void { $alignment->setHorizontal((string) $alignmentXml['horizontal']); $alignment->setVertical((string) $alignmentXml['vertical']); $textRotation = 0; if ((int) $alignmentXml['textRotation'] <= 90) { $textRotation = (int) $alignmentXml['textRotation']; } elseif ((int) $alignmentXml['textRotation'] > 90) { $textRotation = 90 - (int) $alignmentXml['textRotation']; } $alignment->setTextRotation((int) $textRotation); $alignment->setWrapText(self::boolean((string) $alignmentXml['wrapText'])); $alignment->setShrinkToFit(self::boolean((string) $alignmentXml['shrinkToFit'])); $alignment->setIndent( (int) ((string) $alignmentXml['indent']) > 0 ? (int) ((string) $alignmentXml['indent']) : 0 ); $alignment->setReadOrder( (int) ((string) $alignmentXml['readingOrder']) > 0 ? (int) ((string) $alignmentXml['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)) { self::readProtectionLocked($docStyle, $style); self::readProtectionHidden($docStyle, $style); } // top-level style settings if (isset($style->quotePrefix)) { $docStyle->setQuotePrefix(true); } } public static 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); } } } public static 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); } } } public 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 $cellStylex) { $cellStyle = Xlsx::getAttributes($cellStylex); 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; } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/BaseParserClass.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/BaseParserClass.php
<?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'); } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/DataValidations.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/DataValidations.php
<?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(filter_var($dataValidation['allowBlank'], FILTER_VALIDATE_BOOLEAN)); // showDropDown is inverted (works as hideDropDown if true) $docValidation->setShowDropDown(!filter_var($dataValidation['showDropDown'], FILTER_VALIDATE_BOOLEAN)); $docValidation->setShowInputMessage(filter_var($dataValidation['showInputMessage'], FILTER_VALIDATE_BOOLEAN)); $docValidation->setShowErrorMessage(filter_var($dataValidation['showErrorMessage'], FILTER_VALIDATE_BOOLEAN)); $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); $docValidation->setSqref($range); } } } } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Hyperlinks.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Hyperlinks.php
<?php namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Reader\Xlsx; 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->children(Namespaces::RELATIONSHIPS)->Relationship as $elementx) { $element = Xlsx::getAttributes($elementx); if ($element->Type == Namespaces::HYPERLINK) { $this->hyperlinks[(string) $element->Id] = (string) $element->Target; } } } public function setHyperlinks(SimpleXMLElement $worksheetXml): void { foreach ($worksheetXml->children(Namespaces::MAIN)->hyperlink as $hyperlink) { if ($hyperlink !== null) { $this->setHyperlink($hyperlink, $this->worksheet); } } } private function setHyperlink(SimpleXMLElement $hyperlink, Worksheet $worksheet): void { // Link url $linkRel = Xlsx::getAttributes($hyperlink, Namespaces::SCHEMA_OFFICE_DOCUMENT); $attributes = Xlsx::getAttributes($hyperlink); foreach (Coordinate::extractAllCellReferencesInRange($attributes->ref) as $cellReference) { $cell = $worksheet->getCell($cellReference); if (isset($linkRel['id'])) { $hyperlinkUrl = $this->hyperlinks[(string) $linkRel['id']] ?? null; if (isset($attributes['location'])) { $hyperlinkUrl .= '#' . (string) $attributes['location']; } $cell->getHyperlink()->setUrl($hyperlinkUrl); } elseif (isset($attributes['location'])) { $cell->getHyperlink()->setUrl('sheet://' . (string) $attributes['location']); } // Tooltip if (isset($attributes['tooltip'])) { $cell->getHyperlink()->setTooltip((string) $attributes['tooltip']); } } } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/PageSetup.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/PageSetup.php
<?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(Namespaces::SCHEMA_OFFICE_DOCUMENT); 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 ); } } } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Theme.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Theme.php
<?php namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx; class Theme { /** * Theme Name. * * @var string */ private $themeName; /** * Colour Scheme Name. * * @var string */ private $colourSchemeName; /** * Colour Map. * * @var string[] */ private $colourMap; /** * Create a new Theme. * * @param string $themeName * @param string $colourSchemeName * @param string[] $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 int $index * * @return null|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; } } } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Namespaces.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Namespaces.php
<?php namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx; class Namespaces { const SCHEMAS = 'http://schemas.openxmlformats.org'; const RELATIONSHIPS = 'http://schemas.openxmlformats.org/package/2006/relationships'; // This one used in Reader\Xlsx const CORE_PROPERTIES = 'http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties'; // This one used in Reader\Xlsx\Properties const CORE_PROPERTIES2 = 'http://schemas.openxmlformats.org/package/2006/metadata/core-properties'; const THEME = 'http://schemas.openxmlformats.org/package/2006/relationships/theme'; const COMPATIBILITY = 'http://schemas.openxmlformats.org/markup-compatibility/2006'; const MAIN = 'http://schemas.openxmlformats.org/spreadsheetml/2006/main'; const DRAWINGML = 'http://schemas.openxmlformats.org/drawingml/2006/main'; const CHART = 'http://schemas.openxmlformats.org/drawingml/2006/chart'; const SPREADSHEET_DRAWING = 'http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing'; const SCHEMA_OFFICE_DOCUMENT = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'; const COMMENTS = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments'; //const CUSTOM_PROPERTIES = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties'; //const EXTENDED_PROPERTIES = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties'; const HYPERLINK = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink'; const OFFICE_DOCUMENT = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument'; const SHARED_STRINGS = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings'; const STYLES = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles'; const IMAGE = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image'; const VML = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing'; const WORKSHEET = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet'; const SCHEMA_MICROSOFT = 'http://schemas.microsoft.com/office/2006/relationships'; const EXTENSIBILITY = 'http://schemas.microsoft.com/office/2006/relationships/ui/extensibility'; const VBA = 'http://schemas.microsoft.com/office/2006/relationships/vbaProject'; const DC_ELEMENTS = 'http://purl.org/dc/elements/1.1/'; const DC_TERMS = 'http://purl.org/dc/terms'; const URN_MSOFFICE = 'urn:schemas-microsoft-com:office:office'; const URN_VML = 'urn:schemas-microsoft-com:vml'; const SCHEMA_PURL = 'http://purl.oclc.org/ooxml'; const PURL_OFFICE_DOCUMENT = 'http://purl.oclc.org/ooxml/officeDocument/relationships/officeDocument'; const PURL_RELATIONSHIPS = 'http://purl.oclc.org/ooxml/officeDocument/relationships'; const PURL_MAIN = 'http://purl.oclc.org/ooxml/spreadsheetml/main'; const PURL_DRAWING = 'http://purl.oclc.org/ooxml/drawingml/main'; const PURL_WORKSHEET = 'http://purl.oclc.org/ooxml/officeDocument/relationships/worksheet'; }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Properties.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Properties.php
<?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 { /** @var XmlScanner */ private $securityScanner; /** @var DocumentProperties */ private $docProps; public function __construct(XmlScanner $securityScanner, DocumentProperties $docProps) { $this->securityScanner = $securityScanner; $this->docProps = $docProps; } /** * @param mixed $obj */ private static function nullOrSimple($obj): ?SimpleXMLElement { return ($obj instanceof SimpleXMLElement) ? $obj : null; } private function extractPropertyData(string $propertyData): ?SimpleXMLElement { // okay to omit namespace because everything will be processed by xpath $obj = simplexml_load_string( $this->securityScanner->scan($propertyData), 'SimpleXMLElement', Settings::getLibXmlLoaderOptions() ); return self::nullOrSimple($obj); } public function readCoreProperties(string $propertyData): void { $xmlCore = $this->extractPropertyData($propertyData); if (is_object($xmlCore)) { $xmlCore->registerXPathNamespace('dc', Namespaces::DC_ELEMENTS); $xmlCore->registerXPathNamespace('dcterms', Namespaces::DC_TERMS); $xmlCore->registerXPathNamespace('cp', Namespaces::CORE_PROPERTIES2); $this->docProps->setCreator((string) self::getArrayItem($xmlCore->xpath('dc:creator'))); $this->docProps->setLastModifiedBy((string) self::getArrayItem($xmlCore->xpath('cp:lastModifiedBy'))); $this->docProps->setCreated((string) self::getArrayItem($xmlCore->xpath('dcterms:created'))); //! respect xsi:type $this->docProps->setModified((string) 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(string $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(string $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); } } } } /** * @param array|false $array * @param mixed $key */ private static function getArrayItem($array, $key = 0): ?SimpleXMLElement { return is_array($array) ? ($array[$key] ?? null) : null; } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/AutoFilter.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/AutoFilter.php
<?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'])) && ((string) $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'])) && ((string) $filterRule['percent'] === '1')) ? Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT : Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_BY_VALUE ), (string) $filterRule['val'], ( ((isset($filterRule['top'])) && ((string) $filterRule['top'] === '1')) ? Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP : Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_BOTTOM ) )->setRuleType(Rule::AUTOFILTER_RULETYPE_TOPTENFILTER); } } } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Chart.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Chart.php
<?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') { $value = (string) $attributes[$name]; return $value === 'true' || $value === '1'; } 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; $plotArea = 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, $chartDetail->axPos)) { $axisLabel = self::chartTitle($chartDetail->title->children($namespacesChartMeta['c']), $namespacesChartMeta); $axPos = self::getAttribute($chartDetail->axPos, 'val', 'string'); switch ($axPos) { case 't': case 'b': $XaxisLabel = $axisLabel; break; case 'r': case 'l': $YaxisLabel = $axisLabel; break; } } 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; $seriesValues = new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, $seriesSource, null, null, null, $marker); if (isset($seriesDetail->strRef->strCache)) { $seriesData = self::chartDataSeriesValues($seriesDetail->strRef->strCache->children($namespacesChartMeta['c']), 's'); $seriesValues ->setFormatCode($seriesData['formatCode']) ->setDataValues($seriesData['dataValues']); } return $seriesValues; } elseif (isset($seriesDetail->numRef)) { $seriesSource = (string) $seriesDetail->numRef->f; $seriesValues = new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, $seriesSource, null, null, null, $marker); if (isset($seriesDetail->numRef->numCache)) { $seriesData = self::chartDataSeriesValues($seriesDetail->numRef->numCache->children($namespacesChartMeta['c'])); $seriesValues ->setFormatCode($seriesData['formatCode']) ->setDataValues($seriesData['dataValues']); } return $seriesValues; } elseif (isset($seriesDetail->multiLvlStrRef)) { $seriesSource = (string) $seriesDetail->multiLvlStrRef->f; $seriesValues = new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, $seriesSource, null, null, null, $marker); if (isset($seriesDetail->multiLvlStrRef->multiLvlStrCache)) { $seriesData = self::chartDataSeriesValuesMultiLevel($seriesDetail->multiLvlStrRef->multiLvlStrCache->children($namespacesChartMeta['c']), 's'); $seriesValues ->setFormatCode($seriesData['formatCode']) ->setDataValues($seriesData['dataValues']); } return $seriesValues; } elseif (isset($seriesDetail->multiLvlNumRef)) { $seriesSource = (string) $seriesDetail->multiLvlNumRef->f; $seriesValues = new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, $seriesSource, null, null, null, $marker); if (isset($seriesDetail->multiLvlNumRef->multiLvlNumCache)) { $seriesData = self::chartDataSeriesValuesMultiLevel($seriesDetail->multiLvlNumRef->multiLvlNumCache->children($namespacesChartMeta['c']), 's'); $seriesValues ->setFormatCode($seriesData['formatCode']) ->setDataValues($seriesData['dataValues']); } return $seriesValues; } 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 (is_int($fontSize)) { $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->showLegendKey)) { $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; } } } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/SheetViewOptions.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/SheetViewOptions.php
<?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); } } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/ColumnAndRowAttributes.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/ColumnAndRowAttributes.php
<?php namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Reader\DefaultReadFilter; 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']); } } public function load(?IReadFilter $readFilter = null, bool $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); } if ($readFilter !== null && get_class($readFilter) === DefaultReadFilter::class) { $readFilter = null; } // 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; } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/ConditionalStyles.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/ConditionalStyles.php
<?php namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx; use PhpOffice\PhpSpreadsheet\Style\Conditional; use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\ConditionalDataBar; use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\ConditionalFormattingRuleExtension; use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\ConditionalFormatValueObject; 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), $this->worksheetXml->extLst ); } private function readConditionalStyles($xmlSheet) { $conditionals = []; foreach ($xmlSheet->conditionalFormatting as $conditional) { foreach ($conditional->cfRule as $cfRule) { if (Conditional::isValidConditionType((string) $cfRule['type']) && isset($this->dxfs[(int) ($cfRule['dxfId'])])) { $conditionals[(string) $conditional['sqref']][(int) ($cfRule['priority'])] = $cfRule; } elseif ((string) $cfRule['type'] == Conditional::CONDITION_DATABAR) { $conditionals[(string) $conditional['sqref']][(int) ($cfRule['priority'])] = $cfRule; } } } return $conditionals; } private function setConditionalStyles(Worksheet $worksheet, array $conditionals, $xmlExtLst): void { foreach ($conditionals as $ref => $cfRules) { ksort($cfRules); $conditionalStyles = $this->readStyleRules($cfRules, $xmlExtLst); // 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, $extLst) { $conditionalFormattingRuleExtensions = ConditionalFormattingRuleExtension::parseExtLstXml($extLst); $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); } if (isset($cfRule->dataBar)) { $objConditional->setDataBar( $this->readDataBarOfConditionalRule($cfRule, $conditionalFormattingRuleExtensions) ); } else { $objConditional->setStyle(clone $this->dxfs[(int) ($cfRule['dxfId'])]); } $conditionalStyles[] = $objConditional; } return $conditionalStyles; } private function readDataBarOfConditionalRule($cfRule, $conditionalFormattingRuleExtensions): ConditionalDataBar { $dataBar = new ConditionalDataBar(); //dataBar attribute if (isset($cfRule->dataBar['showValue'])) { $dataBar->setShowValue((bool) $cfRule->dataBar['showValue']); } //dataBar children //conditionalFormatValueObjects $cfvoXml = $cfRule->dataBar->cfvo; $cfvoIndex = 0; foreach ((count($cfvoXml) > 1 ? $cfvoXml : [$cfvoXml]) as $cfvo) { if ($cfvoIndex === 0) { $dataBar->setMinimumConditionalFormatValueObject(new ConditionalFormatValueObject((string) $cfvo['type'], (string) $cfvo['val'])); } if ($cfvoIndex === 1) { $dataBar->setMaximumConditionalFormatValueObject(new ConditionalFormatValueObject((string) $cfvo['type'], (string) $cfvo['val'])); } ++$cfvoIndex; } //color if (isset($cfRule->dataBar->color)) { $dataBar->setColor((string) $cfRule->dataBar->color['rgb']); } //extLst $this->readDataBarExtLstOfConditionalRule($dataBar, $cfRule, $conditionalFormattingRuleExtensions); return $dataBar; } private function readDataBarExtLstOfConditionalRule(ConditionalDataBar $dataBar, $cfRule, $conditionalFormattingRuleExtensions): void { if (isset($cfRule->extLst)) { $ns = $cfRule->extLst->getNamespaces(true); foreach ((count($cfRule->extLst) > 0 ? $cfRule->extLst->ext : [$cfRule->extLst->ext]) as $ext) { $extId = (string) $ext->children($ns['x14'])->id; if (isset($conditionalFormattingRuleExtensions[$extId]) && (string) $ext['uri'] === '{B025F937-C7B1-47D3-B67F-A62EFF666E3E}') { $dataBar->setConditionalFormattingRuleExt($conditionalFormattingRuleExtensions[$extId]); } } } } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/SheetViews.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/SheetViews.php
<?php namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Reader\Xlsx; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; use SimpleXMLElement; class SheetViews extends BaseParserClass { /** @var SimpleXMLElement */ private $sheetViewXml; /** @var SimpleXMLElement */ private $sheetViewAttributes; /** @var Worksheet */ private $worksheet; public function __construct(SimpleXMLElement $sheetViewXml, Worksheet $workSheet) { $this->sheetViewXml = $sheetViewXml; $this->sheetViewAttributes = Xlsx::testSimpleXml($sheetViewXml->attributes()); $this->worksheet = $workSheet; } public function load(): void { $this->topLeft(); $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->attributes()->sqref)) { $this->selection(); } } private function zoomScale(): void { if (isset($this->sheetViewAttributes->zoomScale)) { $zoomScale = (int) ($this->sheetViewAttributes->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->sheetViewAttributes->zoomScaleNormal)) { $zoomScaleNormal = (int) ($this->sheetViewAttributes->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->sheetViewAttributes->view)) { $this->worksheet->getSheetView()->setView((string) $this->sheetViewAttributes->view); } } private function topLeft(): void { if (isset($this->sheetViewAttributes->topLeftCell)) { $this->worksheet->setTopLeftCell($this->sheetViewAttributes->topLeftCell); } } private function gridLines(): void { if (isset($this->sheetViewAttributes->showGridLines)) { $this->worksheet->setShowGridLines( self::boolean((string) $this->sheetViewAttributes->showGridLines) ); } } private function headers(): void { if (isset($this->sheetViewAttributes->showRowColHeaders)) { $this->worksheet->setShowRowColHeaders( self::boolean((string) $this->sheetViewAttributes->showRowColHeaders) ); } } private function direction(): void { if (isset($this->sheetViewAttributes->rightToLeft)) { $this->worksheet->setRightToLeft( self::boolean((string) $this->sheetViewAttributes->rightToLeft) ); } } private function showZeros(): void { if (isset($this->sheetViewAttributes->showZeros)) { $this->worksheet->getSheetView()->setShowZeros( self::boolean((string) $this->sheetViewAttributes->showZeros) ); } } private function pane(): void { $xSplit = 0; $ySplit = 0; $topLeftCell = null; $paneAttributes = $this->sheetViewXml->pane->attributes(); if (isset($paneAttributes->xSplit)) { $xSplit = (int) ($paneAttributes->xSplit); } if (isset($paneAttributes->ySplit)) { $ySplit = (int) ($paneAttributes->ySplit); } if (isset($paneAttributes->topLeftCell)) { $topLeftCell = (string) $paneAttributes->topLeftCell; } $this->worksheet->freezePane( Coordinate::stringFromColumnIndex($xSplit + 1) . ($ySplit + 1), $topLeftCell ); } private function selection(): void { $attributes = $this->sheetViewXml->selection->attributes(); if ($attributes !== null) { $sqref = (string) $attributes->sqref; $sqref = explode(' ', $sqref); $sqref = $sqref[0]; $this->worksheet->setSelectedCells($sqref); } } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Security/XmlScanner.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Security/XmlScanner.php
<?php namespace PhpOffice\PhpSpreadsheet\Reader\Security; use PhpOffice\PhpSpreadsheet\Reader; class XmlScanner { /** * String used to identify risky xml elements. * * @var string */ private $pattern; private $callback; private static $libxmlDisableEntityLoaderValue; /** * @var bool */ private static $shutdownRegistered = false; public function __construct($pattern = '<!DOCTYPE') { $this->pattern = $pattern; $this->disableEntityLoaderCheck(); // A fatal error will bypass the destructor, so we register a shutdown here if (!self::$shutdownRegistered) { self::$shutdownRegistered = true; 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 (\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)); } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/RowCellIterator.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/RowCellIterator.php
<?php namespace PhpOffice\PhpSpreadsheet\Worksheet; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; /** * @extends CellIterator<string> */ class RowCellIterator extends CellIterator { /** * Current iterator position. * * @var int */ private $currentColumnIndex; /** * Row index. * * @var int */ private $rowIndex = 1; /** * Start position. * * @var int */ private $startColumnIndex = 1; /** * End position. * * @var int */ private $endColumnIndex = 1; /** * Create a new column iterator. * * @param Worksheet $worksheet The worksheet to iterate over * @param int $rowIndex The row that we want to iterate * @param string $startColumn The column address at which to start iterating * @param string $endColumn Optionally, the column address at which to stop iterating */ public function __construct(Worksheet $worksheet, $rowIndex = 1, $startColumn = 'A', $endColumn = null) { // Set subject and row index $this->worksheet = $worksheet; $this->rowIndex = $rowIndex; $this->resetEnd($endColumn); $this->resetStart($startColumn); } /** * (Re)Set the start column and the current column pointer. * * @param string $startColumn The column address at which to start iterating * * @return $this */ public function resetStart(string $startColumn = 'A') { $this->startColumnIndex = Coordinate::columnIndexFromString($startColumn); $this->adjustForExistingOnlyRange(); $this->seek(Coordinate::stringFromColumnIndex($this->startColumnIndex)); return $this; } /** * (Re)Set the end column. * * @param string $endColumn The column address at which to stop iterating * * @return $this */ public function resetEnd($endColumn = null) { $endColumn = $endColumn ?: $this->worksheet->getHighestColumn(); $this->endColumnIndex = Coordinate::columnIndexFromString($endColumn); $this->adjustForExistingOnlyRange(); return $this; } /** * Set the column pointer to the selected column. * * @param string $column The column address to set the current pointer at * * @return $this */ public function seek(string $column = 'A') { $columnx = $column; $column = Coordinate::columnIndexFromString($column); if ($this->onlyExistingCells && !($this->worksheet->cellExistsByColumnAndRow($column, $this->rowIndex))) { throw new PhpSpreadsheetException('In "IterateOnlyExistingCells" mode and Cell does not exist'); } if (($column < $this->startColumnIndex) || ($column > $this->endColumnIndex)) { throw new PhpSpreadsheetException("Column $columnx is out of range ({$this->startColumnIndex} - {$this->endColumnIndex})"); } $this->currentColumnIndex = $column; return $this; } /** * Rewind the iterator to the starting column. */ public function rewind(): void { $this->currentColumnIndex = $this->startColumnIndex; } /** * Return the current cell in this worksheet row. */ public function current(): ?Cell { return $this->worksheet->getCellByColumnAndRow($this->currentColumnIndex, $this->rowIndex); } /** * Return the current iterator key. */ public function key(): string { return Coordinate::stringFromColumnIndex($this->currentColumnIndex); } /** * Set the iterator to its next value. */ public function next(): void { do { ++$this->currentColumnIndex; } while (($this->onlyExistingCells) && (!$this->worksheet->cellExistsByColumnAndRow($this->currentColumnIndex, $this->rowIndex)) && ($this->currentColumnIndex <= $this->endColumnIndex)); } /** * Set the iterator to its previous value. */ public function prev(): void { do { --$this->currentColumnIndex; } while (($this->onlyExistingCells) && (!$this->worksheet->cellExistsByColumnAndRow($this->currentColumnIndex, $this->rowIndex)) && ($this->currentColumnIndex >= $this->startColumnIndex)); } /** * Indicate if more columns exist in the worksheet range of columns that we're iterating. */ public function valid(): bool { return $this->currentColumnIndex <= $this->endColumnIndex && $this->currentColumnIndex >= $this->startColumnIndex; } /** * Return the current iterator position. */ public function getCurrentColumnIndex(): int { return $this->currentColumnIndex; } /** * Validate start/end values for "IterateOnlyExistingCells" mode, and adjust if necessary. */ protected function adjustForExistingOnlyRange(): void { if ($this->onlyExistingCells) { while ((!$this->worksheet->cellExistsByColumnAndRow($this->startColumnIndex, $this->rowIndex)) && ($this->startColumnIndex <= $this->endColumnIndex)) { ++$this->startColumnIndex; } while ((!$this->worksheet->cellExistsByColumnAndRow($this->endColumnIndex, $this->rowIndex)) && ($this->endColumnIndex >= $this->startColumnIndex)) { --$this->endColumnIndex; } } } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Drawing.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Drawing.php
<?php namespace PhpOffice\PhpSpreadsheet\Worksheet; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; class Drawing extends BaseDrawing { /** * Path. * * @var string */ private $path; /** * Whether or not we are dealing with a URL. * * @var bool */ private $isUrl; /** * Create a new Drawing. */ public function __construct() { // Initialise values $this->path = ''; $this->isUrl = false; // Initialize parent parent::__construct(); } /** * Get Filename. * * @return string */ public function getFilename() { return basename($this->path); } /** * Get indexed filename (using image index). */ public function getIndexedFilename(): string { $fileName = $this->getFilename(); $fileName = str_replace(' ', '_', $fileName); return str_replace('.' . $this->getExtension(), '', $fileName) . $this->getImageIndex() . '.' . $this->getExtension(); } /** * Get Extension. * * @return string */ public function getExtension() { $exploded = explode('.', basename($this->path)); return $exploded[count($exploded) - 1]; } /** * Get Path. * * @return string */ public function getPath() { return $this->path; } /** * Set Path. * * @param string $path File path * @param bool $verifyFile Verify file * * @return $this */ public function setPath($path, $verifyFile = true) { if ($verifyFile) { // Check if a URL has been passed. https://stackoverflow.com/a/2058596/1252979 if (filter_var($path, FILTER_VALIDATE_URL)) { $this->path = $path; // Implicit that it is a URL, rather store info than running check above on value in other places. $this->isUrl = true; $imageContents = file_get_contents($path); $filePath = tempnam(sys_get_temp_dir(), 'Drawing'); if ($filePath) { file_put_contents($filePath, $imageContents); if (file_exists($filePath)) { if ($this->width == 0 && $this->height == 0) { // Get width/height [$this->width, $this->height] = getimagesize($filePath); } unlink($filePath); } } } elseif (file_exists($path)) { $this->path = $path; if ($this->width == 0 && $this->height == 0) { // Get width/height [$this->width, $this->height] = getimagesize($path); } } else { throw new PhpSpreadsheetException("File $path not found!"); } } else { $this->path = $path; } return $this; } /** * Get isURL. */ public function getIsURL(): bool { return $this->isUrl; } /** * Set isURL. * * @return $this */ public function setIsURL(bool $isUrl): self { $this->isUrl = $isUrl; return $this; } /** * Get hash code. * * @return string Hash code */ public function getHashCode() { return md5( $this->path . parent::getHashCode() . __CLASS__ ); } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/ColumnCellIterator.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/ColumnCellIterator.php
<?php namespace PhpOffice\PhpSpreadsheet\Worksheet; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; /** * @extends CellIterator<int> */ class ColumnCellIterator extends CellIterator { /** * Current iterator position. * * @var int */ private $currentRow; /** * Column index. * * @var int */ private $columnIndex; /** * Start position. * * @var int */ private $startRow = 1; /** * End position. * * @var int */ private $endRow = 1; /** * Create a new row iterator. * * @param Worksheet $subject The worksheet to iterate over * @param string $columnIndex The column that we want to iterate * @param int $startRow The row number at which to start iterating * @param int $endRow Optionally, the row number at which to stop iterating */ public function __construct(Worksheet $subject, $columnIndex = 'A', $startRow = 1, $endRow = null) { // Set subject $this->worksheet = $subject; $this->columnIndex = Coordinate::columnIndexFromString($columnIndex); $this->resetEnd($endRow); $this->resetStart($startRow); } /** * (Re)Set the start row and the current row pointer. * * @param int $startRow The row number at which to start iterating * * @return $this */ public function resetStart(int $startRow = 1) { $this->startRow = $startRow; $this->adjustForExistingOnlyRange(); $this->seek($startRow); return $this; } /** * (Re)Set the end row. * * @param int $endRow The row number at which to stop iterating * * @return $this */ public function resetEnd($endRow = null) { $this->endRow = $endRow ?: $this->worksheet->getHighestRow(); $this->adjustForExistingOnlyRange(); return $this; } /** * Set the row pointer to the selected row. * * @param int $row The row number to set the current pointer at * * @return $this */ public function seek(int $row = 1) { if ($this->onlyExistingCells && !($this->worksheet->cellExistsByColumnAndRow($this->columnIndex, $row))) { throw new PhpSpreadsheetException('In "IterateOnlyExistingCells" mode and Cell does not exist'); } if (($row < $this->startRow) || ($row > $this->endRow)) { throw new PhpSpreadsheetException("Row $row is out of range ({$this->startRow} - {$this->endRow})"); } $this->currentRow = $row; return $this; } /** * Rewind the iterator to the starting row. */ public function rewind(): void { $this->currentRow = $this->startRow; } /** * Return the current cell in this worksheet column. */ public function current(): ?Cell { return $this->worksheet->getCellByColumnAndRow($this->columnIndex, $this->currentRow); } /** * Return the current iterator key. */ public function key(): int { return $this->currentRow; } /** * Set the iterator to its next value. */ public function next(): void { do { ++$this->currentRow; } while ( ($this->onlyExistingCells) && (!$this->worksheet->cellExistsByColumnAndRow($this->columnIndex, $this->currentRow)) && ($this->currentRow <= $this->endRow) ); } /** * Set the iterator to its previous value. */ public function prev(): void { do { --$this->currentRow; } while ( ($this->onlyExistingCells) && (!$this->worksheet->cellExistsByColumnAndRow($this->columnIndex, $this->currentRow)) && ($this->currentRow >= $this->startRow) ); } /** * Indicate if more rows exist in the worksheet range of rows that we're iterating. */ public function valid(): bool { return $this->currentRow <= $this->endRow && $this->currentRow >= $this->startRow; } /** * Validate start/end values for "IterateOnlyExistingCells" mode, and adjust if necessary. */ protected function adjustForExistingOnlyRange(): void { if ($this->onlyExistingCells) { while ( (!$this->worksheet->cellExistsByColumnAndRow($this->columnIndex, $this->startRow)) && ($this->startRow <= $this->endRow) ) { ++$this->startRow; } while ( (!$this->worksheet->cellExistsByColumnAndRow($this->columnIndex, $this->endRow)) && ($this->endRow >= $this->startRow) ) { --$this->endRow; } } } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Dimension.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Dimension.php
<?php namespace PhpOffice\PhpSpreadsheet\Worksheet; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; abstract class Dimension { /** * Visible? * * @var bool */ private $visible = true; /** * Outline level. * * @var int */ private $outlineLevel = 0; /** * Collapsed. * * @var bool */ private $collapsed = false; /** * Index to cellXf. Null value means row has no explicit cellXf format. * * @var null|int */ private $xfIndex; /** * Create a new Dimension. * * @param int $initialValue Numeric row index */ public function __construct($initialValue = null) { // set dimension as unformatted by default $this->xfIndex = $initialValue; } /** * Get Visible. */ public function getVisible(): bool { return $this->visible; } /** * Set Visible. * * @return $this */ public function setVisible(bool $visible) { $this->visible = $visible; return $this; } /** * Get Outline Level. */ public function getOutlineLevel(): int { return $this->outlineLevel; } /** * Set Outline Level. * Value must be between 0 and 7. * * @return $this */ public function setOutlineLevel(int $level) { if ($level < 0 || $level > 7) { throw new PhpSpreadsheetException('Outline level must range between 0 and 7.'); } $this->outlineLevel = $level; return $this; } /** * Get Collapsed. */ public function getCollapsed(): bool { return $this->collapsed; } /** * Set Collapsed. * * @return $this */ public function setCollapsed(bool $collapsed) { $this->collapsed = $collapsed; return $this; } /** * Get index to cellXf. * * @return int */ public function getXfIndex(): ?int { return $this->xfIndex; } /** * Set index to cellXf. * * @return $this */ public function setXfIndex(int $XfIndex) { $this->xfIndex = $XfIndex; return $this; } /** * 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)) { $this->$key = clone $value; } else { $this->$key = $value; } } } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/PageSetup.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/PageSetup.php
<?php namespace PhpOffice\PhpSpreadsheet\Worksheet; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; /** * <code> * Paper size taken from Office Open XML Part 4 - Markup Language Reference, page 1988:. * * 1 = Letter paper (8.5 in. by 11 in.) * 2 = Letter small paper (8.5 in. by 11 in.) * 3 = Tabloid paper (11 in. by 17 in.) * 4 = Ledger paper (17 in. by 11 in.) * 5 = Legal paper (8.5 in. by 14 in.) * 6 = Statement paper (5.5 in. by 8.5 in.) * 7 = Executive paper (7.25 in. by 10.5 in.) * 8 = A3 paper (297 mm by 420 mm) * 9 = A4 paper (210 mm by 297 mm) * 10 = A4 small paper (210 mm by 297 mm) * 11 = A5 paper (148 mm by 210 mm) * 12 = B4 paper (250 mm by 353 mm) * 13 = B5 paper (176 mm by 250 mm) * 14 = Folio paper (8.5 in. by 13 in.) * 15 = Quarto paper (215 mm by 275 mm) * 16 = Standard paper (10 in. by 14 in.) * 17 = Standard paper (11 in. by 17 in.) * 18 = Note paper (8.5 in. by 11 in.) * 19 = #9 envelope (3.875 in. by 8.875 in.) * 20 = #10 envelope (4.125 in. by 9.5 in.) * 21 = #11 envelope (4.5 in. by 10.375 in.) * 22 = #12 envelope (4.75 in. by 11 in.) * 23 = #14 envelope (5 in. by 11.5 in.) * 24 = C paper (17 in. by 22 in.) * 25 = D paper (22 in. by 34 in.) * 26 = E paper (34 in. by 44 in.) * 27 = DL envelope (110 mm by 220 mm) * 28 = C5 envelope (162 mm by 229 mm) * 29 = C3 envelope (324 mm by 458 mm) * 30 = C4 envelope (229 mm by 324 mm) * 31 = C6 envelope (114 mm by 162 mm) * 32 = C65 envelope (114 mm by 229 mm) * 33 = B4 envelope (250 mm by 353 mm) * 34 = B5 envelope (176 mm by 250 mm) * 35 = B6 envelope (176 mm by 125 mm) * 36 = Italy envelope (110 mm by 230 mm) * 37 = Monarch envelope (3.875 in. by 7.5 in.). * 38 = 6 3/4 envelope (3.625 in. by 6.5 in.) * 39 = US standard fanfold (14.875 in. by 11 in.) * 40 = German standard fanfold (8.5 in. by 12 in.) * 41 = German legal fanfold (8.5 in. by 13 in.) * 42 = ISO B4 (250 mm by 353 mm) * 43 = Japanese double postcard (200 mm by 148 mm) * 44 = Standard paper (9 in. by 11 in.) * 45 = Standard paper (10 in. by 11 in.) * 46 = Standard paper (15 in. by 11 in.) * 47 = Invite envelope (220 mm by 220 mm) * 50 = Letter extra paper (9.275 in. by 12 in.) * 51 = Legal extra paper (9.275 in. by 15 in.) * 52 = Tabloid extra paper (11.69 in. by 18 in.) * 53 = A4 extra paper (236 mm by 322 mm) * 54 = Letter transverse paper (8.275 in. by 11 in.) * 55 = A4 transverse paper (210 mm by 297 mm) * 56 = Letter extra transverse paper (9.275 in. by 12 in.) * 57 = SuperA/SuperA/A4 paper (227 mm by 356 mm) * 58 = SuperB/SuperB/A3 paper (305 mm by 487 mm) * 59 = Letter plus paper (8.5 in. by 12.69 in.) * 60 = A4 plus paper (210 mm by 330 mm) * 61 = A5 transverse paper (148 mm by 210 mm) * 62 = JIS B5 transverse paper (182 mm by 257 mm) * 63 = A3 extra paper (322 mm by 445 mm) * 64 = A5 extra paper (174 mm by 235 mm) * 65 = ISO B5 extra paper (201 mm by 276 mm) * 66 = A2 paper (420 mm by 594 mm) * 67 = A3 transverse paper (297 mm by 420 mm) * 68 = A3 extra transverse paper (322 mm by 445 mm) * </code> */ class PageSetup { // Paper size const PAPERSIZE_LETTER = 1; const PAPERSIZE_LETTER_SMALL = 2; const PAPERSIZE_TABLOID = 3; const PAPERSIZE_LEDGER = 4; const PAPERSIZE_LEGAL = 5; const PAPERSIZE_STATEMENT = 6; const PAPERSIZE_EXECUTIVE = 7; const PAPERSIZE_A3 = 8; const PAPERSIZE_A4 = 9; const PAPERSIZE_A4_SMALL = 10; const PAPERSIZE_A5 = 11; const PAPERSIZE_B4 = 12; const PAPERSIZE_B5 = 13; const PAPERSIZE_FOLIO = 14; const PAPERSIZE_QUARTO = 15; const PAPERSIZE_STANDARD_1 = 16; const PAPERSIZE_STANDARD_2 = 17; const PAPERSIZE_NOTE = 18; const PAPERSIZE_NO9_ENVELOPE = 19; const PAPERSIZE_NO10_ENVELOPE = 20; const PAPERSIZE_NO11_ENVELOPE = 21; const PAPERSIZE_NO12_ENVELOPE = 22; const PAPERSIZE_NO14_ENVELOPE = 23; const PAPERSIZE_C = 24; const PAPERSIZE_D = 25; const PAPERSIZE_E = 26; const PAPERSIZE_DL_ENVELOPE = 27; const PAPERSIZE_C5_ENVELOPE = 28; const PAPERSIZE_C3_ENVELOPE = 29; const PAPERSIZE_C4_ENVELOPE = 30; const PAPERSIZE_C6_ENVELOPE = 31; const PAPERSIZE_C65_ENVELOPE = 32; const PAPERSIZE_B4_ENVELOPE = 33; const PAPERSIZE_B5_ENVELOPE = 34; const PAPERSIZE_B6_ENVELOPE = 35; const PAPERSIZE_ITALY_ENVELOPE = 36; const PAPERSIZE_MONARCH_ENVELOPE = 37; const PAPERSIZE_6_3_4_ENVELOPE = 38; const PAPERSIZE_US_STANDARD_FANFOLD = 39; const PAPERSIZE_GERMAN_STANDARD_FANFOLD = 40; const PAPERSIZE_GERMAN_LEGAL_FANFOLD = 41; const PAPERSIZE_ISO_B4 = 42; const PAPERSIZE_JAPANESE_DOUBLE_POSTCARD = 43; const PAPERSIZE_STANDARD_PAPER_1 = 44; const PAPERSIZE_STANDARD_PAPER_2 = 45; const PAPERSIZE_STANDARD_PAPER_3 = 46; const PAPERSIZE_INVITE_ENVELOPE = 47; const PAPERSIZE_LETTER_EXTRA_PAPER = 48; const PAPERSIZE_LEGAL_EXTRA_PAPER = 49; const PAPERSIZE_TABLOID_EXTRA_PAPER = 50; const PAPERSIZE_A4_EXTRA_PAPER = 51; const PAPERSIZE_LETTER_TRANSVERSE_PAPER = 52; const PAPERSIZE_A4_TRANSVERSE_PAPER = 53; const PAPERSIZE_LETTER_EXTRA_TRANSVERSE_PAPER = 54; const PAPERSIZE_SUPERA_SUPERA_A4_PAPER = 55; const PAPERSIZE_SUPERB_SUPERB_A3_PAPER = 56; const PAPERSIZE_LETTER_PLUS_PAPER = 57; const PAPERSIZE_A4_PLUS_PAPER = 58; const PAPERSIZE_A5_TRANSVERSE_PAPER = 59; const PAPERSIZE_JIS_B5_TRANSVERSE_PAPER = 60; const PAPERSIZE_A3_EXTRA_PAPER = 61; const PAPERSIZE_A5_EXTRA_PAPER = 62; const PAPERSIZE_ISO_B5_EXTRA_PAPER = 63; const PAPERSIZE_A2_PAPER = 64; const PAPERSIZE_A3_TRANSVERSE_PAPER = 65; const PAPERSIZE_A3_EXTRA_TRANSVERSE_PAPER = 66; // Page orientation const ORIENTATION_DEFAULT = 'default'; const ORIENTATION_LANDSCAPE = 'landscape'; const ORIENTATION_PORTRAIT = 'portrait'; // Print Range Set Method const SETPRINTRANGE_OVERWRITE = 'O'; const SETPRINTRANGE_INSERT = 'I'; const PAGEORDER_OVER_THEN_DOWN = 'overThenDown'; const PAGEORDER_DOWN_THEN_OVER = 'downThenOver'; /** * Paper size. * * @var int */ private $paperSize = self::PAPERSIZE_LETTER; /** * Orientation. * * @var string */ private $orientation = self::ORIENTATION_DEFAULT; /** * Scale (Print Scale). * * Print scaling. Valid values range from 10 to 400 * This setting is overridden when fitToWidth and/or fitToHeight are in use * * @var null|int */ private $scale = 100; /** * Fit To Page * Whether scale or fitToWith / fitToHeight applies. * * @var bool */ private $fitToPage = false; /** * Fit To Height * Number of vertical pages to fit on. * * @var null|int */ private $fitToHeight = 1; /** * Fit To Width * Number of horizontal pages to fit on. * * @var null|int */ private $fitToWidth = 1; /** * Columns to repeat at left. * * @var array Containing start column and end column, empty array if option unset */ private $columnsToRepeatAtLeft = ['', '']; /** * Rows to repeat at top. * * @var array Containing start row number and end row number, empty array if option unset */ private $rowsToRepeatAtTop = [0, 0]; /** * Center page horizontally. * * @var bool */ private $horizontalCentered = false; /** * Center page vertically. * * @var bool */ private $verticalCentered = false; /** * Print area. * * @var null|string */ private $printArea; /** * First page number. * * @var int */ private $firstPageNumber; private $pageOrder = self::PAGEORDER_DOWN_THEN_OVER; /** * Create a new PageSetup. */ public function __construct() { } /** * Get Paper Size. * * @return int */ public function getPaperSize() { return $this->paperSize; } /** * Set Paper Size. * * @param int $paperSize see self::PAPERSIZE_* * * @return $this */ public function setPaperSize($paperSize) { $this->paperSize = $paperSize; return $this; } /** * Get Orientation. * * @return string */ public function getOrientation() { return $this->orientation; } /** * Set Orientation. * * @param string $orientation see self::ORIENTATION_* * * @return $this */ public function setOrientation($orientation) { $this->orientation = $orientation; return $this; } /** * Get Scale. * * @return null|int */ public function getScale() { return $this->scale; } /** * Set Scale. * Print scaling. Valid values range from 10 to 400 * This setting is overridden when fitToWidth and/or fitToHeight are in use. * * @param null|int $scale * @param bool $update Update fitToPage so scaling applies rather than fitToHeight / fitToWidth * * @return $this */ public function setScale($scale, $update = true) { // Microsoft Office Excel 2007 only allows setting a scale between 10 and 400 via the user interface, // but it is apparently still able to handle any scale >= 0, where 0 results in 100 if (($scale >= 0) || $scale === null) { $this->scale = $scale; if ($update) { $this->fitToPage = false; } } else { throw new PhpSpreadsheetException('Scale must not be negative'); } return $this; } /** * Get Fit To Page. * * @return bool */ public function getFitToPage() { return $this->fitToPage; } /** * Set Fit To Page. * * @param bool $fitToPage * * @return $this */ public function setFitToPage($fitToPage) { $this->fitToPage = $fitToPage; return $this; } /** * Get Fit To Height. * * @return null|int */ public function getFitToHeight() { return $this->fitToHeight; } /** * Set Fit To Height. * * @param null|int $fitToHeight * @param bool $update Update fitToPage so it applies rather than scaling * * @return $this */ public function setFitToHeight($fitToHeight, $update = true) { $this->fitToHeight = $fitToHeight; if ($update) { $this->fitToPage = true; } return $this; } /** * Get Fit To Width. * * @return null|int */ public function getFitToWidth() { return $this->fitToWidth; } /** * Set Fit To Width. * * @param null|int $value * @param bool $update Update fitToPage so it applies rather than scaling * * @return $this */ public function setFitToWidth($value, $update = true) { $this->fitToWidth = $value; if ($update) { $this->fitToPage = true; } return $this; } /** * Is Columns to repeat at left set? * * @return bool */ public function isColumnsToRepeatAtLeftSet() { if (is_array($this->columnsToRepeatAtLeft)) { if ($this->columnsToRepeatAtLeft[0] != '' && $this->columnsToRepeatAtLeft[1] != '') { return true; } } return false; } /** * Get Columns to repeat at left. * * @return array Containing start column and end column, empty array if option unset */ public function getColumnsToRepeatAtLeft() { return $this->columnsToRepeatAtLeft; } /** * Set Columns to repeat at left. * * @param array $columnsToRepeatAtLeft Containing start column and end column, empty array if option unset * * @return $this */ public function setColumnsToRepeatAtLeft(array $columnsToRepeatAtLeft) { $this->columnsToRepeatAtLeft = $columnsToRepeatAtLeft; return $this; } /** * Set Columns to repeat at left by start and end. * * @param string $start eg: 'A' * @param string $end eg: 'B' * * @return $this */ public function setColumnsToRepeatAtLeftByStartAndEnd($start, $end) { $this->columnsToRepeatAtLeft = [$start, $end]; return $this; } /** * Is Rows to repeat at top set? * * @return bool */ public function isRowsToRepeatAtTopSet() { if (is_array($this->rowsToRepeatAtTop)) { if ($this->rowsToRepeatAtTop[0] != 0 && $this->rowsToRepeatAtTop[1] != 0) { return true; } } return false; } /** * Get Rows to repeat at top. * * @return array Containing start column and end column, empty array if option unset */ public function getRowsToRepeatAtTop() { return $this->rowsToRepeatAtTop; } /** * Set Rows to repeat at top. * * @param array $rowsToRepeatAtTop Containing start column and end column, empty array if option unset * * @return $this */ public function setRowsToRepeatAtTop(array $rowsToRepeatAtTop) { $this->rowsToRepeatAtTop = $rowsToRepeatAtTop; return $this; } /** * Set Rows to repeat at top by start and end. * * @param int $start eg: 1 * @param int $end eg: 1 * * @return $this */ public function setRowsToRepeatAtTopByStartAndEnd($start, $end) { $this->rowsToRepeatAtTop = [$start, $end]; return $this; } /** * Get center page horizontally. * * @return bool */ public function getHorizontalCentered() { return $this->horizontalCentered; } /** * Set center page horizontally. * * @param bool $value * * @return $this */ public function setHorizontalCentered($value) { $this->horizontalCentered = $value; return $this; } /** * Get center page vertically. * * @return bool */ public function getVerticalCentered() { return $this->verticalCentered; } /** * Set center page vertically. * * @param bool $value * * @return $this */ public function setVerticalCentered($value) { $this->verticalCentered = $value; return $this; } /** * Get print area. * * @param int $index Identifier for a specific print area range if several ranges have been set * Default behaviour, or a index value of 0, will return all ranges as a comma-separated string * Otherwise, the specific range identified by the value of $index will be returned * Print areas are numbered from 1 * * @return string */ public function getPrintArea($index = 0) { if ($index == 0) { return $this->printArea; } $printAreas = explode(',', $this->printArea); if (isset($printAreas[$index - 1])) { return $printAreas[$index - 1]; } throw new PhpSpreadsheetException('Requested Print Area does not exist'); } /** * Is print area set? * * @param int $index Identifier for a specific print area range if several ranges have been set * Default behaviour, or an index value of 0, will identify whether any print range is set * Otherwise, existence of the range identified by the value of $index will be returned * Print areas are numbered from 1 * * @return bool */ public function isPrintAreaSet($index = 0) { if ($index == 0) { return $this->printArea !== null; } $printAreas = explode(',', $this->printArea); return isset($printAreas[$index - 1]); } /** * Clear a print area. * * @param int $index Identifier for a specific print area range if several ranges have been set * Default behaviour, or an index value of 0, will clear all print ranges that are set * Otherwise, the range identified by the value of $index will be removed from the series * Print areas are numbered from 1 * * @return $this */ public function clearPrintArea($index = 0) { if ($index == 0) { $this->printArea = null; } else { $printAreas = explode(',', $this->printArea); if (isset($printAreas[$index - 1])) { unset($printAreas[$index - 1]); $this->printArea = implode(',', $printAreas); } } return $this; } /** * Set print area. e.g. 'A1:D10' or 'A1:D10,G5:M20'. * * @param string $value * @param int $index Identifier for a specific print area range allowing several ranges to be set * When the method is "O"verwrite, then a positive integer index will overwrite that indexed * entry in the print areas list; a negative index value will identify which entry to * overwrite working bacward through the print area to the list, with the last entry as -1. * Specifying an index value of 0, will overwrite <b>all</b> existing print ranges. * When the method is "I"nsert, then a positive index will insert after that indexed entry in * the print areas list, while a negative index will insert before the indexed entry. * Specifying an index value of 0, will always append the new print range at the end of the * list. * Print areas are numbered from 1 * @param string $method Determines the method used when setting multiple print areas * Default behaviour, or the "O" method, overwrites existing print area * The "I" method, inserts the new print area before any specified index, or at the end of the list * * @return $this */ public function setPrintArea($value, $index = 0, $method = self::SETPRINTRANGE_OVERWRITE) { if (strpos($value, '!') !== false) { throw new PhpSpreadsheetException('Cell coordinate must not specify a worksheet.'); } elseif (strpos($value, ':') === false) { throw new PhpSpreadsheetException('Cell coordinate must be a range of cells.'); } elseif (strpos($value, '$') !== false) { throw new PhpSpreadsheetException('Cell coordinate must not be absolute.'); } $value = strtoupper($value); if (!$this->printArea) { $index = 0; } if ($method == self::SETPRINTRANGE_OVERWRITE) { if ($index == 0) { $this->printArea = $value; } else { $printAreas = explode(',', $this->printArea); if ($index < 0) { $index = count($printAreas) - abs($index) + 1; } if (($index <= 0) || ($index > count($printAreas))) { throw new PhpSpreadsheetException('Invalid index for setting print range.'); } $printAreas[$index - 1] = $value; $this->printArea = implode(',', $printAreas); } } elseif ($method == self::SETPRINTRANGE_INSERT) { if ($index == 0) { $this->printArea = $this->printArea ? ($this->printArea . ',' . $value) : $value; } else { $printAreas = explode(',', $this->printArea); if ($index < 0) { $index = abs($index) - 1; } if ($index > count($printAreas)) { throw new PhpSpreadsheetException('Invalid index for setting print range.'); } $printAreas = array_merge(array_slice($printAreas, 0, $index), [$value], array_slice($printAreas, $index)); $this->printArea = implode(',', $printAreas); } } else { throw new PhpSpreadsheetException('Invalid method for setting print range.'); } return $this; } /** * Add a new print area (e.g. 'A1:D10' or 'A1:D10,G5:M20') to the list of print areas. * * @param string $value * @param int $index Identifier for a specific print area range allowing several ranges to be set * A positive index will insert after that indexed entry in the print areas list, while a * negative index will insert before the indexed entry. * Specifying an index value of 0, will always append the new print range at the end of the * list. * Print areas are numbered from 1 * * @return $this */ public function addPrintArea($value, $index = -1) { return $this->setPrintArea($value, $index, self::SETPRINTRANGE_INSERT); } /** * Set print area. * * @param int $column1 Column 1 * @param int $row1 Row 1 * @param int $column2 Column 2 * @param int $row2 Row 2 * @param int $index Identifier for a specific print area range allowing several ranges to be set * When the method is "O"verwrite, then a positive integer index will overwrite that indexed * entry in the print areas list; a negative index value will identify which entry to * overwrite working backward through the print area to the list, with the last entry as -1. * Specifying an index value of 0, will overwrite <b>all</b> existing print ranges. * When the method is "I"nsert, then a positive index will insert after that indexed entry in * the print areas list, while a negative index will insert before the indexed entry. * Specifying an index value of 0, will always append the new print range at the end of the * list. * Print areas are numbered from 1 * @param string $method Determines the method used when setting multiple print areas * Default behaviour, or the "O" method, overwrites existing print area * The "I" method, inserts the new print area before any specified index, or at the end of the list * * @return $this */ public function setPrintAreaByColumnAndRow($column1, $row1, $column2, $row2, $index = 0, $method = self::SETPRINTRANGE_OVERWRITE) { return $this->setPrintArea( Coordinate::stringFromColumnIndex($column1) . $row1 . ':' . Coordinate::stringFromColumnIndex($column2) . $row2, $index, $method ); } /** * Add a new print area to the list of print areas. * * @param int $column1 Start Column for the print area * @param int $row1 Start Row for the print area * @param int $column2 End Column for the print area * @param int $row2 End Row for the print area * @param int $index Identifier for a specific print area range allowing several ranges to be set * A positive index will insert after that indexed entry in the print areas list, while a * negative index will insert before the indexed entry. * Specifying an index value of 0, will always append the new print range at the end of the * list. * Print areas are numbered from 1 * * @return $this */ public function addPrintAreaByColumnAndRow($column1, $row1, $column2, $row2, $index = -1) { return $this->setPrintArea( Coordinate::stringFromColumnIndex($column1) . $row1 . ':' . Coordinate::stringFromColumnIndex($column2) . $row2, $index, self::SETPRINTRANGE_INSERT ); } /** * Get first page number. * * @return int */ public function getFirstPageNumber() { return $this->firstPageNumber; } /** * Set first page number. * * @param int $value * * @return $this */ public function setFirstPageNumber($value) { $this->firstPageNumber = $value; return $this; } /** * Reset first page number. * * @return $this */ public function resetFirstPageNumber() { return $this->setFirstPageNumber(null); } public function getPageOrder(): string { return $this->pageOrder; } public function setPageOrder(?string $pageOrder): self { if ($pageOrder === null || $pageOrder === self::PAGEORDER_DOWN_THEN_OVER || $pageOrder === self::PAGEORDER_OVER_THEN_DOWN) { $this->pageOrder = $pageOrder ?? self::PAGEORDER_DOWN_THEN_OVER; } return $this; } /** * 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)) { $this->$key = clone $value; } else { $this->$key = $value; } } } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Row.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Row.php
<?php namespace PhpOffice\PhpSpreadsheet\Worksheet; class Row { /** * \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet. * * @var Worksheet */ private $worksheet; /** * Row index. * * @var int */ private $rowIndex = 0; /** * Create a new row. * * @param int $rowIndex */ public function __construct(?Worksheet $worksheet = null, $rowIndex = 1) { // Set parent and row index $this->worksheet = $worksheet; $this->rowIndex = $rowIndex; } /** * Destructor. */ public function __destruct() { // @phpstan-ignore-next-line $this->worksheet = null; } /** * Get row index. */ public function getRowIndex(): int { return $this->rowIndex; } /** * Get cell iterator. * * @param string $startColumn The column address at which to start iterating * @param string $endColumn Optionally, the column address at which to stop iterating * * @return RowCellIterator */ public function getCellIterator($startColumn = 'A', $endColumn = null) { return new RowCellIterator($this->worksheet, $this->rowIndex, $startColumn, $endColumn); } /** * Returns bound worksheet. */ public function getWorksheet(): Worksheet { return $this->worksheet; } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/ColumnIterator.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/ColumnIterator.php
<?php namespace PhpOffice\PhpSpreadsheet\Worksheet; use Iterator; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Exception; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; /** * @implements Iterator<string, Column> */ class ColumnIterator implements Iterator { /** * Worksheet to iterate. * * @var Worksheet */ private $worksheet; /** * Current iterator position. * * @var int */ private $currentColumnIndex = 1; /** * Start position. * * @var int */ private $startColumnIndex = 1; /** * End position. * * @var int */ private $endColumnIndex = 1; /** * Create a new column iterator. * * @param Worksheet $worksheet The worksheet to iterate over * @param string $startColumn The column address at which to start iterating * @param string $endColumn Optionally, the column address at which to stop iterating */ public function __construct(Worksheet $worksheet, $startColumn = 'A', $endColumn = null) { // Set subject $this->worksheet = $worksheet; $this->resetEnd($endColumn); $this->resetStart($startColumn); } /** * Destructor. */ public function __destruct() { // @phpstan-ignore-next-line $this->worksheet = null; } /** * (Re)Set the start column and the current column pointer. * * @param string $startColumn The column address at which to start iterating * * @return $this */ public function resetStart(string $startColumn = 'A') { $startColumnIndex = Coordinate::columnIndexFromString($startColumn); if ($startColumnIndex > Coordinate::columnIndexFromString($this->worksheet->getHighestColumn())) { throw new Exception( "Start column ({$startColumn}) is beyond highest column ({$this->worksheet->getHighestColumn()})" ); } $this->startColumnIndex = $startColumnIndex; if ($this->endColumnIndex < $this->startColumnIndex) { $this->endColumnIndex = $this->startColumnIndex; } $this->seek($startColumn); return $this; } /** * (Re)Set the end column. * * @param string $endColumn The column address at which to stop iterating * * @return $this */ public function resetEnd($endColumn = null) { $endColumn = $endColumn ?: $this->worksheet->getHighestColumn(); $this->endColumnIndex = Coordinate::columnIndexFromString($endColumn); return $this; } /** * Set the column pointer to the selected column. * * @param string $column The column address to set the current pointer at * * @return $this */ public function seek(string $column = 'A') { $column = Coordinate::columnIndexFromString($column); if (($column < $this->startColumnIndex) || ($column > $this->endColumnIndex)) { throw new PhpSpreadsheetException( "Column $column is out of range ({$this->startColumnIndex} - {$this->endColumnIndex})" ); } $this->currentColumnIndex = $column; return $this; } /** * Rewind the iterator to the starting column. */ public function rewind(): void { $this->currentColumnIndex = $this->startColumnIndex; } /** * Return the current column in this worksheet. */ public function current(): Column { return new Column($this->worksheet, Coordinate::stringFromColumnIndex($this->currentColumnIndex)); } /** * Return the current iterator key. */ public function key(): string { return Coordinate::stringFromColumnIndex($this->currentColumnIndex); } /** * Set the iterator to its next value. */ public function next(): void { ++$this->currentColumnIndex; } /** * Set the iterator to its previous value. */ public function prev(): void { --$this->currentColumnIndex; } /** * Indicate if more columns exist in the worksheet range of columns that we're iterating. */ public function valid(): bool { return $this->currentColumnIndex <= $this->endColumnIndex && $this->currentColumnIndex >= $this->startColumnIndex; } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/MemoryDrawing.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/MemoryDrawing.php
<?php namespace PhpOffice\PhpSpreadsheet\Worksheet; use GdImage; use PhpOffice\PhpSpreadsheet\Exception; class MemoryDrawing extends BaseDrawing { // Rendering functions const RENDERING_DEFAULT = 'imagepng'; const RENDERING_PNG = 'imagepng'; const RENDERING_GIF = 'imagegif'; const RENDERING_JPEG = 'imagejpeg'; // MIME types const MIMETYPE_DEFAULT = 'image/png'; const MIMETYPE_PNG = 'image/png'; const MIMETYPE_GIF = 'image/gif'; const MIMETYPE_JPEG = 'image/jpeg'; /** * Image resource. * * @var null|GdImage|resource */ private $imageResource; /** * Rendering function. * * @var string */ private $renderingFunction; /** * Mime type. * * @var string */ private $mimeType; /** * Unique name. * * @var string */ private $uniqueName; /** * Create a new MemoryDrawing. */ public function __construct() { // Initialise values $this->renderingFunction = self::RENDERING_DEFAULT; $this->mimeType = self::MIMETYPE_DEFAULT; $this->uniqueName = md5(mt_rand(0, 9999) . time() . mt_rand(0, 9999)); // Initialize parent parent::__construct(); } public function __destruct() { if ($this->imageResource) { imagedestroy($this->imageResource); $this->imageResource = null; } } public function __clone() { parent::__clone(); $this->cloneResource(); } private function cloneResource(): void { if (!$this->imageResource) { return; } $width = imagesx($this->imageResource); $height = imagesy($this->imageResource); if (imageistruecolor($this->imageResource)) { $clone = imagecreatetruecolor($width, $height); if (!$clone) { throw new Exception('Could not clone image resource'); } imagealphablending($clone, false); imagesavealpha($clone, true); } else { $clone = imagecreate($width, $height); if (!$clone) { throw new Exception('Could not clone image resource'); } // If the image has transparency... $transparent = imagecolortransparent($this->imageResource); if ($transparent >= 0) { $rgb = imagecolorsforindex($this->imageResource, $transparent); if ($rgb === false) { throw new Exception('Could not get image colors'); } imagesavealpha($clone, true); $color = imagecolorallocatealpha($clone, $rgb['red'], $rgb['green'], $rgb['blue'], $rgb['alpha']); if ($color === false) { throw new Exception('Could not get image alpha color'); } imagefill($clone, 0, 0, $color); } } //Create the Clone!! imagecopy($clone, $this->imageResource, 0, 0, 0, 0, $width, $height); $this->imageResource = $clone; } /** * Get image resource. * * @return null|GdImage|resource */ public function getImageResource() { return $this->imageResource; } /** * Set image resource. * * @param GdImage|resource $value * * @return $this */ public function setImageResource($value) { $this->imageResource = $value; if ($this->imageResource !== null) { // Get width/height $this->width = imagesx($this->imageResource); $this->height = imagesy($this->imageResource); } return $this; } /** * Get rendering function. * * @return string */ public function getRenderingFunction() { return $this->renderingFunction; } /** * Set rendering function. * * @param string $value see self::RENDERING_* * * @return $this */ public function setRenderingFunction($value) { $this->renderingFunction = $value; return $this; } /** * Get mime type. * * @return string */ public function getMimeType() { return $this->mimeType; } /** * Set mime type. * * @param string $value see self::MIMETYPE_* * * @return $this */ public function setMimeType($value) { $this->mimeType = $value; return $this; } /** * Get indexed filename (using image index). */ public function getIndexedFilename(): string { $extension = strtolower($this->getMimeType()); $extension = explode('/', $extension); $extension = $extension[1]; return $this->uniqueName . $this->getImageIndex() . '.' . $extension; } /** * Get hash code. * * @return string Hash code */ public function getHashCode() { return md5( $this->renderingFunction . $this->mimeType . $this->uniqueName . parent::getHashCode() . __CLASS__ ); } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/CellIterator.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/CellIterator.php
<?php namespace PhpOffice\PhpSpreadsheet\Worksheet; use Iterator; use PhpOffice\PhpSpreadsheet\Cell\Cell; /** * @template TKey * @implements Iterator<TKey, Cell> */ abstract class CellIterator implements Iterator { /** * Worksheet to iterate. * * @var Worksheet */ protected $worksheet; /** * Iterate only existing cells. * * @var bool */ protected $onlyExistingCells = false; /** * Destructor. */ public function __destruct() { // @phpstan-ignore-next-line $this->worksheet = null; } /** * Get loop only existing cells. */ public function getIterateOnlyExistingCells(): bool { return $this->onlyExistingCells; } /** * Validate start/end values for "IterateOnlyExistingCells" mode, and adjust if necessary. */ abstract protected function adjustForExistingOnlyRange(); /** * Set the iterator to loop only existing cells. */ public function setIterateOnlyExistingCells(bool $value): void { $this->onlyExistingCells = (bool) $value; $this->adjustForExistingOnlyRange(); } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Worksheet.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Worksheet.php
<?php namespace PhpOffice\PhpSpreadsheet\Worksheet; use ArrayObject; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Cell\DataType; use PhpOffice\PhpSpreadsheet\Cell\DataValidation; use PhpOffice\PhpSpreadsheet\Cell\Hyperlink; use PhpOffice\PhpSpreadsheet\Chart\Chart; use PhpOffice\PhpSpreadsheet\Collection\Cells; use PhpOffice\PhpSpreadsheet\Collection\CellsFactory; use PhpOffice\PhpSpreadsheet\Comment; use PhpOffice\PhpSpreadsheet\DefinedName; use PhpOffice\PhpSpreadsheet\Exception; use PhpOffice\PhpSpreadsheet\IComparable; use PhpOffice\PhpSpreadsheet\ReferenceHelper; use PhpOffice\PhpSpreadsheet\RichText\RichText; use PhpOffice\PhpSpreadsheet\Shared; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Style\Color; use PhpOffice\PhpSpreadsheet\Style\Conditional; use PhpOffice\PhpSpreadsheet\Style\NumberFormat; use PhpOffice\PhpSpreadsheet\Style\Style; class Worksheet implements IComparable { // Break types const BREAK_NONE = 0; const BREAK_ROW = 1; const BREAK_COLUMN = 2; // Sheet state const SHEETSTATE_VISIBLE = 'visible'; const SHEETSTATE_HIDDEN = 'hidden'; const SHEETSTATE_VERYHIDDEN = 'veryHidden'; /** * Maximum 31 characters allowed for sheet title. * * @var int */ const SHEET_TITLE_MAXIMUM_LENGTH = 31; /** * Invalid characters in sheet title. * * @var array */ private static $invalidCharacters = ['*', ':', '/', '\\', '?', '[', ']']; /** * Parent spreadsheet. * * @var Spreadsheet */ private $parent; /** * Collection of cells. * * @var Cells */ private $cellCollection; /** * Collection of row dimensions. * * @var RowDimension[] */ private $rowDimensions = []; /** * Default row dimension. * * @var RowDimension */ private $defaultRowDimension; /** * Collection of column dimensions. * * @var ColumnDimension[] */ private $columnDimensions = []; /** * Default column dimension. * * @var ColumnDimension */ private $defaultColumnDimension; /** * Collection of drawings. * * @var ArrayObject<int, BaseDrawing> */ private $drawingCollection; /** * Collection of Chart objects. * * @var ArrayObject<int, Chart> */ private $chartCollection; /** * Worksheet title. * * @var string */ private $title; /** * Sheet state. * * @var string */ private $sheetState; /** * Page setup. * * @var PageSetup */ private $pageSetup; /** * Page margins. * * @var PageMargins */ private $pageMargins; /** * Page header/footer. * * @var HeaderFooter */ private $headerFooter; /** * Sheet view. * * @var SheetView */ private $sheetView; /** * Protection. * * @var Protection */ private $protection; /** * Collection of styles. * * @var Style[] */ private $styles = []; /** * Conditional styles. Indexed by cell coordinate, e.g. 'A1'. * * @var array */ private $conditionalStylesCollection = []; /** * Is the current cell collection sorted already? * * @var bool */ private $cellCollectionIsSorted = false; /** * Collection of breaks. * * @var int[] */ private $breaks = []; /** * Collection of merged cell ranges. * * @var string[] */ private $mergeCells = []; /** * Collection of protected cell ranges. * * @var string[] */ private $protectedCells = []; /** * Autofilter Range and selection. * * @var AutoFilter */ private $autoFilter; /** * Freeze pane. * * @var null|string */ private $freezePane; /** * Default position of the right bottom pane. * * @var null|string */ private $topLeftCell; /** * Show gridlines? * * @var bool */ private $showGridlines = true; /** * Print gridlines? * * @var bool */ private $printGridlines = false; /** * Show row and column headers? * * @var bool */ private $showRowColHeaders = true; /** * Show summary below? (Row/Column outline). * * @var bool */ private $showSummaryBelow = true; /** * Show summary right? (Row/Column outline). * * @var bool */ private $showSummaryRight = true; /** * Collection of comments. * * @var Comment[] */ private $comments = []; /** * Active cell. (Only one!). * * @var string */ private $activeCell = 'A1'; /** * Selected cells. * * @var string */ private $selectedCells = 'A1'; /** * Cached highest column. * * @var int */ private $cachedHighestColumn = 1; /** * Cached highest row. * * @var int */ private $cachedHighestRow = 1; /** * Right-to-left? * * @var bool */ private $rightToLeft = false; /** * Hyperlinks. Indexed by cell coordinate, e.g. 'A1'. * * @var array */ private $hyperlinkCollection = []; /** * Data validation objects. Indexed by cell coordinate, e.g. 'A1'. * * @var array */ private $dataValidationCollection = []; /** * Tab color. * * @var null|Color */ private $tabColor; /** * Dirty flag. * * @var bool */ private $dirty = true; /** * Hash. * * @var string */ private $hash; /** * CodeName. * * @var string */ private $codeName; /** * Create a new worksheet. * * @param string $title */ public function __construct(?Spreadsheet $parent = null, $title = 'Worksheet') { // Set parent and title $this->parent = $parent; $this->setTitle($title, false); // setTitle can change $pTitle $this->setCodeName($this->getTitle()); $this->setSheetState(self::SHEETSTATE_VISIBLE); $this->cellCollection = CellsFactory::getInstance($this); // Set page setup $this->pageSetup = new PageSetup(); // Set page margins $this->pageMargins = new PageMargins(); // Set page header/footer $this->headerFooter = new HeaderFooter(); // Set sheet view $this->sheetView = new SheetView(); // Drawing collection $this->drawingCollection = new ArrayObject(); // Chart collection $this->chartCollection = new ArrayObject(); // Protection $this->protection = new Protection(); // Default row dimension $this->defaultRowDimension = new RowDimension(null); // Default column dimension $this->defaultColumnDimension = new ColumnDimension(null); $this->autoFilter = new AutoFilter(null, $this); } /** * Disconnect all cells from this Worksheet object, * typically so that the worksheet object can be unset. */ public function disconnectCells(): void { if ($this->cellCollection !== null) { $this->cellCollection->unsetWorksheetCells(); // @phpstan-ignore-next-line $this->cellCollection = null; } // detach ourself from the workbook, so that it can then delete this worksheet successfully // @phpstan-ignore-next-line $this->parent = null; } /** * Code to execute when this worksheet is unset(). */ public function __destruct() { Calculation::getInstance($this->parent)->clearCalculationCacheForWorksheet($this->title); $this->disconnectCells(); $this->rowDimensions = []; } /** * Return the cell collection. * * @return Cells */ public function getCellCollection() { return $this->cellCollection; } /** * Get array of invalid characters for sheet title. * * @return array */ public static function getInvalidCharacters() { return self::$invalidCharacters; } /** * Check sheet code name for valid Excel syntax. * * @param string $sheetCodeName The string to check * * @return string The valid string */ private static function checkSheetCodeName($sheetCodeName) { $charCount = Shared\StringHelper::countCharacters($sheetCodeName); if ($charCount == 0) { throw new Exception('Sheet code name cannot be empty.'); } // Some of the printable ASCII characters are invalid: * : / \ ? [ ] and first and last characters cannot be a "'" if ( (str_replace(self::$invalidCharacters, '', $sheetCodeName) !== $sheetCodeName) || (Shared\StringHelper::substring($sheetCodeName, -1, 1) == '\'') || (Shared\StringHelper::substring($sheetCodeName, 0, 1) == '\'') ) { throw new Exception('Invalid character found in sheet code name'); } // Enforce maximum characters allowed for sheet title if ($charCount > self::SHEET_TITLE_MAXIMUM_LENGTH) { throw new Exception('Maximum ' . self::SHEET_TITLE_MAXIMUM_LENGTH . ' characters allowed in sheet code name.'); } return $sheetCodeName; } /** * Check sheet title for valid Excel syntax. * * @param string $sheetTitle The string to check * * @return string The valid string */ private static function checkSheetTitle($sheetTitle) { // Some of the printable ASCII characters are invalid: * : / \ ? [ ] if (str_replace(self::$invalidCharacters, '', $sheetTitle) !== $sheetTitle) { throw new Exception('Invalid character found in sheet title'); } // Enforce maximum characters allowed for sheet title if (Shared\StringHelper::countCharacters($sheetTitle) > self::SHEET_TITLE_MAXIMUM_LENGTH) { throw new Exception('Maximum ' . self::SHEET_TITLE_MAXIMUM_LENGTH . ' characters allowed in sheet title.'); } return $sheetTitle; } /** * Get a sorted list of all cell coordinates currently held in the collection by row and column. * * @param bool $sorted Also sort the cell collection? * * @return string[] */ public function getCoordinates($sorted = true) { if ($this->cellCollection == null) { return []; } if ($sorted) { return $this->cellCollection->getSortedCoordinates(); } return $this->cellCollection->getCoordinates(); } /** * Get collection of row dimensions. * * @return RowDimension[] */ public function getRowDimensions() { return $this->rowDimensions; } /** * Get default row dimension. * * @return RowDimension */ public function getDefaultRowDimension() { return $this->defaultRowDimension; } /** * Get collection of column dimensions. * * @return ColumnDimension[] */ public function getColumnDimensions() { return $this->columnDimensions; } /** * Get default column dimension. * * @return ColumnDimension */ public function getDefaultColumnDimension() { return $this->defaultColumnDimension; } /** * Get collection of drawings. * * @return ArrayObject<int, BaseDrawing> */ public function getDrawingCollection() { return $this->drawingCollection; } /** * Get collection of charts. * * @return ArrayObject<int, Chart> */ public function getChartCollection() { return $this->chartCollection; } /** * Add chart. * * @param null|int $chartIndex Index where chart should go (0,1,..., or null for last) * * @return Chart */ public function addChart(Chart $chart, $chartIndex = null) { $chart->setWorksheet($this); if ($chartIndex === null) { $this->chartCollection[] = $chart; } else { // Insert the chart at the requested index array_splice($this->chartCollection, $chartIndex, 0, [$chart]); } return $chart; } /** * Return the count of charts on this worksheet. * * @return int The number of charts */ public function getChartCount() { return count($this->chartCollection); } /** * Get a chart by its index position. * * @param string $index Chart index position * * @return Chart|false */ public function getChartByIndex($index) { $chartCount = count($this->chartCollection); if ($chartCount == 0) { return false; } if ($index === null) { $index = --$chartCount; } if (!isset($this->chartCollection[$index])) { return false; } return $this->chartCollection[$index]; } /** * Return an array of the names of charts on this worksheet. * * @return string[] The names of charts */ public function getChartNames() { $chartNames = []; foreach ($this->chartCollection as $chart) { $chartNames[] = $chart->getName(); } return $chartNames; } /** * Get a chart by name. * * @param string $chartName Chart name * * @return Chart|false */ public function getChartByName($chartName) { $chartCount = count($this->chartCollection); if ($chartCount == 0) { return false; } foreach ($this->chartCollection as $index => $chart) { if ($chart->getName() == $chartName) { return $this->chartCollection[$index]; } } return false; } /** * Refresh column dimensions. * * @return $this */ public function refreshColumnDimensions() { $currentColumnDimensions = $this->getColumnDimensions(); $newColumnDimensions = []; foreach ($currentColumnDimensions as $objColumnDimension) { $newColumnDimensions[$objColumnDimension->getColumnIndex()] = $objColumnDimension; } $this->columnDimensions = $newColumnDimensions; return $this; } /** * Refresh row dimensions. * * @return $this */ public function refreshRowDimensions() { $currentRowDimensions = $this->getRowDimensions(); $newRowDimensions = []; foreach ($currentRowDimensions as $objRowDimension) { $newRowDimensions[$objRowDimension->getRowIndex()] = $objRowDimension; } $this->rowDimensions = $newRowDimensions; return $this; } /** * Calculate worksheet dimension. * * @return string String containing the dimension of this worksheet */ public function calculateWorksheetDimension() { // Return return 'A1:' . $this->getHighestColumn() . $this->getHighestRow(); } /** * Calculate worksheet data dimension. * * @return string String containing the dimension of this worksheet that actually contain data */ public function calculateWorksheetDataDimension() { // Return return 'A1:' . $this->getHighestDataColumn() . $this->getHighestDataRow(); } /** * Calculate widths for auto-size columns. * * @return $this */ public function calculateColumnWidths() { // initialize $autoSizes array $autoSizes = []; foreach ($this->getColumnDimensions() as $colDimension) { if ($colDimension->getAutoSize()) { $autoSizes[$colDimension->getColumnIndex()] = -1; } } // There is only something to do if there are some auto-size columns if (!empty($autoSizes)) { // build list of cells references that participate in a merge $isMergeCell = []; foreach ($this->getMergeCells() as $cells) { foreach (Coordinate::extractAllCellReferencesInRange($cells) as $cellReference) { $isMergeCell[$cellReference] = true; } } // loop through all cells in the worksheet foreach ($this->getCoordinates(false) as $coordinate) { $cell = $this->getCellOrNull($coordinate); if ($cell !== null && isset($autoSizes[$this->cellCollection->getCurrentColumn()])) { //Determine if cell is in merge range $isMerged = isset($isMergeCell[$this->cellCollection->getCurrentCoordinate()]); //By default merged cells should be ignored $isMergedButProceed = false; //The only exception is if it's a merge range value cell of a 'vertical' randge (1 column wide) if ($isMerged && $cell->isMergeRangeValueCell()) { $range = $cell->getMergeRange(); $rangeBoundaries = Coordinate::rangeDimension($range); if ($rangeBoundaries[0] == 1) { $isMergedButProceed = true; } } // Determine width if cell does not participate in a merge or does and is a value cell of 1-column wide range if (!$isMerged || $isMergedButProceed) { // Calculated value // To formatted string $cellValue = NumberFormat::toFormattedString( $cell->getCalculatedValue(), $this->getParent()->getCellXfByIndex($cell->getXfIndex())->getNumberFormat()->getFormatCode() ); if ($cellValue !== null && $cellValue !== '') { $autoSizes[$this->cellCollection->getCurrentColumn()] = max( (float) $autoSizes[$this->cellCollection->getCurrentColumn()], (float) Shared\Font::calculateColumnWidth( $this->getParent()->getCellXfByIndex($cell->getXfIndex())->getFont(), $cellValue, $this->getParent()->getCellXfByIndex($cell->getXfIndex())->getAlignment()->getTextRotation(), $this->getParent()->getDefaultStyle()->getFont() ) ); } } } } // adjust column widths foreach ($autoSizes as $columnIndex => $width) { if ($width == -1) { $width = $this->getDefaultColumnDimension()->getWidth(); } $this->getColumnDimension($columnIndex)->setWidth($width); } } return $this; } /** * Get parent. * * @return Spreadsheet */ public function getParent() { return $this->parent; } /** * Re-bind parent. * * @return $this */ public function rebindParent(Spreadsheet $parent) { if ($this->parent !== null) { $definedNames = $this->parent->getDefinedNames(); foreach ($definedNames as $definedName) { $parent->addDefinedName($definedName); } $this->parent->removeSheetByIndex( $this->parent->getIndex($this) ); } $this->parent = $parent; return $this; } /** * Get title. * * @return string */ public function getTitle() { return $this->title; } /** * Set title. * * @param string $title String containing the dimension of this worksheet * @param bool $updateFormulaCellReferences Flag indicating whether cell references in formulae should * be updated to reflect the new sheet name. * This should be left as the default true, unless you are * certain that no formula cells on any worksheet contain * references to this worksheet * @param bool $validate False to skip validation of new title. WARNING: This should only be set * at parse time (by Readers), where titles can be assumed to be valid. * * @return $this */ public function setTitle($title, $updateFormulaCellReferences = true, $validate = true) { // Is this a 'rename' or not? if ($this->getTitle() == $title) { return $this; } // Old title $oldTitle = $this->getTitle(); if ($validate) { // Syntax check self::checkSheetTitle($title); if ($this->parent) { // Is there already such sheet name? if ($this->parent->sheetNameExists($title)) { // Use name, but append with lowest possible integer if (Shared\StringHelper::countCharacters($title) > 29) { $title = Shared\StringHelper::substring($title, 0, 29); } $i = 1; while ($this->parent->sheetNameExists($title . ' ' . $i)) { ++$i; if ($i == 10) { if (Shared\StringHelper::countCharacters($title) > 28) { $title = Shared\StringHelper::substring($title, 0, 28); } } elseif ($i == 100) { if (Shared\StringHelper::countCharacters($title) > 27) { $title = Shared\StringHelper::substring($title, 0, 27); } } } $title .= " $i"; } } } // Set title $this->title = $title; $this->dirty = true; if ($this->parent && $this->parent->getCalculationEngine()) { // New title $newTitle = $this->getTitle(); $this->parent->getCalculationEngine() ->renameCalculationCacheForWorksheet($oldTitle, $newTitle); if ($updateFormulaCellReferences) { ReferenceHelper::getInstance()->updateNamedFormulas($this->parent, $oldTitle, $newTitle); } } return $this; } /** * Get sheet state. * * @return string Sheet state (visible, hidden, veryHidden) */ public function getSheetState() { return $this->sheetState; } /** * Set sheet state. * * @param string $value Sheet state (visible, hidden, veryHidden) * * @return $this */ public function setSheetState($value) { $this->sheetState = $value; return $this; } /** * Get page setup. * * @return PageSetup */ public function getPageSetup() { return $this->pageSetup; } /** * Set page setup. * * @return $this */ public function setPageSetup(PageSetup $pageSetup) { $this->pageSetup = $pageSetup; return $this; } /** * Get page margins. * * @return PageMargins */ public function getPageMargins() { return $this->pageMargins; } /** * Set page margins. * * @return $this */ public function setPageMargins(PageMargins $pageMargins) { $this->pageMargins = $pageMargins; return $this; } /** * Get page header/footer. * * @return HeaderFooter */ public function getHeaderFooter() { return $this->headerFooter; } /** * Set page header/footer. * * @return $this */ public function setHeaderFooter(HeaderFooter $headerFooter) { $this->headerFooter = $headerFooter; return $this; } /** * Get sheet view. * * @return SheetView */ public function getSheetView() { return $this->sheetView; } /** * Set sheet view. * * @return $this */ public function setSheetView(SheetView $sheetView) { $this->sheetView = $sheetView; return $this; } /** * Get Protection. * * @return Protection */ public function getProtection() { return $this->protection; } /** * Set Protection. * * @return $this */ public function setProtection(Protection $protection) { $this->protection = $protection; $this->dirty = true; return $this; } /** * Get highest worksheet column. * * @param null|int|string $row Return the data highest column for the specified row, * or the highest column of any row if no row number is passed * * @return string Highest column name */ public function getHighestColumn($row = null) { if (empty($row)) { return Coordinate::stringFromColumnIndex($this->cachedHighestColumn); } return $this->getHighestDataColumn($row); } /** * Get highest worksheet column that contains data. * * @param null|int|string $row Return the highest data column for the specified row, * or the highest data column of any row if no row number is passed * * @return string Highest column name that contains data */ public function getHighestDataColumn($row = null) { return $this->cellCollection->getHighestColumn($row); } /** * Get highest worksheet row. * * @param null|string $column Return the highest data row for the specified column, * or the highest row of any column if no column letter is passed * * @return int Highest row number */ public function getHighestRow($column = null) { if ($column == null) { return $this->cachedHighestRow; } return $this->getHighestDataRow($column); } /** * Get highest worksheet row that contains data. * * @param null|string $column Return the highest data row for the specified column, * or the highest data row of any column if no column letter is passed * * @return int Highest row number that contains data */ public function getHighestDataRow($column = null) { return $this->cellCollection->getHighestRow($column); } /** * Get highest worksheet column and highest row that have cell records. * * @return array Highest column name and highest row number */ public function getHighestRowAndColumn() { return $this->cellCollection->getHighestRowAndColumn(); } /** * Set a cell value. * * @param string $coordinate Coordinate of the cell, eg: 'A1' * @param mixed $value Value of the cell * * @return $this */ public function setCellValue($coordinate, $value) { $this->getCell($coordinate)->setValue($value); return $this; } /** * Set a cell value by using numeric cell coordinates. * * @param int $columnIndex Numeric column coordinate of the cell * @param int $row Numeric row coordinate of the cell * @param mixed $value Value of the cell * * @return $this */ public function setCellValueByColumnAndRow($columnIndex, $row, $value) { $this->getCellByColumnAndRow($columnIndex, $row)->setValue($value); return $this; } /** * Set a cell value. * * @param string $coordinate Coordinate of the cell, eg: 'A1' * @param mixed $value Value of the cell * @param string $dataType Explicit data type, see DataType::TYPE_* * * @return $this */ public function setCellValueExplicit($coordinate, $value, $dataType) { // Set value $this->getCell($coordinate)->setValueExplicit($value, $dataType); return $this; } /** * Set a cell value by using numeric cell coordinates. * * @param int $columnIndex Numeric column coordinate of the cell * @param int $row Numeric row coordinate of the cell * @param mixed $value Value of the cell * @param string $dataType Explicit data type, see DataType::TYPE_* * * @return $this */ public function setCellValueExplicitByColumnAndRow($columnIndex, $row, $value, $dataType) { $this->getCellByColumnAndRow($columnIndex, $row)->setValueExplicit($value, $dataType); return $this; } /** * Get cell at a specific coordinate. * * @param string $coordinate Coordinate of the cell, eg: 'A1' * * @return Cell Cell that was found or created */ public function getCell(string $coordinate): Cell { // Shortcut for increased performance for the vast majority of simple cases if ($this->cellCollection->has($coordinate)) { /** @var Cell $cell */ $cell = $this->cellCollection->get($coordinate); return $cell; } /** @var Worksheet $sheet */ [$sheet, $finalCoordinate] = $this->getWorksheetAndCoordinate($coordinate); $cell = $sheet->cellCollection->get($finalCoordinate); return $cell ?? $sheet->createNewCell($finalCoordinate); } /** * Get the correct Worksheet and coordinate from a coordinate that may * contains reference to another sheet or a named range. * * @return array{0: Worksheet, 1: string} */ private function getWorksheetAndCoordinate(string $coordinate): array { $sheet = null; $finalCoordinate = null; // Worksheet reference? if (strpos($coordinate, '!') !== false) { $worksheetReference = self::extractSheetTitle($coordinate, true); $sheet = $this->parent->getSheetByName($worksheetReference[0]); $finalCoordinate = strtoupper($worksheetReference[1]); if (!$sheet) { throw new Exception('Sheet not found for name: ' . $worksheetReference[0]); } } elseif ( !preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/i', $coordinate) && preg_match('/^' . Calculation::CALCULATION_REGEXP_DEFINEDNAME . '$/i', $coordinate) ) { // Named range? $namedRange = $this->validateNamedRange($coordinate, true); if ($namedRange !== null) { $sheet = $namedRange->getWorksheet(); if (!$sheet) { throw new Exception('Sheet not found for named range: ' . $namedRange->getName()); } $cellCoordinate = ltrim(substr($namedRange->getValue(), strrpos($namedRange->getValue(), '!')), '!'); $finalCoordinate = str_replace('$', '', $cellCoordinate); } } if (!$sheet || !$finalCoordinate) { $sheet = $this; $finalCoordinate = strtoupper($coordinate); } if (Coordinate::coordinateIsRange($finalCoordinate)) { throw new Exception('Cell coordinate string can not be a range of cells.'); } elseif (strpos($finalCoordinate, '$') !== false) { throw new Exception('Cell coordinate must not be absolute.'); } return [$sheet, $finalCoordinate]; } /** * Get an existing cell at a specific coordinate, or null. * * @param string $coordinate Coordinate of the cell, eg: 'A1' * * @return null|Cell Cell that was found or null */ private function getCellOrNull($coordinate): ?Cell {
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
true
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/PageMargins.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/PageMargins.php
<?php namespace PhpOffice\PhpSpreadsheet\Worksheet; class PageMargins { /** * Left. * * @var float */ private $left = 0.7; /** * Right. * * @var float */ private $right = 0.7; /** * Top. * * @var float */ private $top = 0.75; /** * Bottom. * * @var float */ private $bottom = 0.75; /** * Header. * * @var float */ private $header = 0.3; /** * Footer. * * @var float */ private $footer = 0.3; /** * Create a new PageMargins. */ public function __construct() { } /** * Get Left. * * @return float */ public function getLeft() { return $this->left; } /** * Set Left. * * @param float $left * * @return $this */ public function setLeft($left) { $this->left = $left; return $this; } /** * Get Right. * * @return float */ public function getRight() { return $this->right; } /** * Set Right. * * @param float $right * * @return $this */ public function setRight($right) { $this->right = $right; return $this; } /** * Get Top. * * @return float */ public function getTop() { return $this->top; } /** * Set Top. * * @param float $top * * @return $this */ public function setTop($top) { $this->top = $top; return $this; } /** * Get Bottom. * * @return float */ public function getBottom() { return $this->bottom; } /** * Set Bottom. * * @param float $bottom * * @return $this */ public function setBottom($bottom) { $this->bottom = $bottom; return $this; } /** * Get Header. * * @return float */ public function getHeader() { return $this->header; } /** * Set Header. * * @param float $header * * @return $this */ public function setHeader($header) { $this->header = $header; return $this; } /** * Get Footer. * * @return float */ public function getFooter() { return $this->footer; } /** * Set Footer. * * @param float $footer * * @return $this */ public function setFooter($footer) { $this->footer = $footer; return $this; } /** * 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)) { $this->$key = clone $value; } else { $this->$key = $value; } } } public static function fromCentimeters(float $value): float { return $value / 2.54; } public static function toCentimeters(float $value): float { return $value * 2.54; } public static function fromMillimeters(float $value): float { return $value / 25.4; } public static function toMillimeters(float $value): float { return $value * 25.4; } public static function fromPoints(float $value): float { return $value / 72; } public static function toPoints(float $value): float { return $value * 72; } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/BaseDrawing.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/BaseDrawing.php
<?php namespace PhpOffice\PhpSpreadsheet\Worksheet; use PhpOffice\PhpSpreadsheet\Cell\Hyperlink; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; use PhpOffice\PhpSpreadsheet\IComparable; class BaseDrawing implements IComparable { /** * Image counter. * * @var int */ private static $imageCounter = 0; /** * Image index. * * @var int */ private $imageIndex = 0; /** * Name. * * @var string */ protected $name; /** * Description. * * @var string */ protected $description; /** * Worksheet. * * @var null|Worksheet */ protected $worksheet; /** * Coordinates. * * @var string */ protected $coordinates; /** * Offset X. * * @var int */ protected $offsetX; /** * Offset Y. * * @var int */ protected $offsetY; /** * Width. * * @var int */ protected $width; /** * Height. * * @var int */ protected $height; /** * Proportional resize. * * @var bool */ protected $resizeProportional; /** * Rotation. * * @var int */ protected $rotation; /** * Shadow. * * @var Drawing\Shadow */ protected $shadow; /** * Image hyperlink. * * @var null|Hyperlink */ private $hyperlink; /** * Create a new BaseDrawing. */ public function __construct() { // Initialise values $this->name = ''; $this->description = ''; $this->worksheet = null; $this->coordinates = 'A1'; $this->offsetX = 0; $this->offsetY = 0; $this->width = 0; $this->height = 0; $this->resizeProportional = true; $this->rotation = 0; $this->shadow = new Drawing\Shadow(); // Set image index ++self::$imageCounter; $this->imageIndex = self::$imageCounter; } /** * Get image index. * * @return int */ public function getImageIndex() { return $this->imageIndex; } /** * Get Name. * * @return string */ public function getName() { return $this->name; } /** * Set Name. * * @param string $name * * @return $this */ public function setName($name) { $this->name = $name; return $this; } /** * Get Description. * * @return string */ public function getDescription() { return $this->description; } /** * Set Description. * * @param string $description * * @return $this */ public function setDescription($description) { $this->description = $description; return $this; } /** * Get Worksheet. * * @return null|Worksheet */ public function getWorksheet() { return $this->worksheet; } /** * Set Worksheet. * * @param bool $overrideOld If a Worksheet has already been assigned, overwrite it and remove image from old Worksheet? * * @return $this */ public function setWorksheet(?Worksheet $worksheet = null, $overrideOld = false) { if ($this->worksheet === null) { // Add drawing to \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $this->worksheet = $worksheet; $this->worksheet->getCell($this->coordinates); $this->worksheet->getDrawingCollection()->append($this); } else { if ($overrideOld) { // Remove drawing from old \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $iterator = $this->worksheet->getDrawingCollection()->getIterator(); while ($iterator->valid()) { if ($iterator->current()->getHashCode() === $this->getHashCode()) { $this->worksheet->getDrawingCollection()->offsetUnset($iterator->key()); $this->worksheet = null; break; } } // Set new \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $this->setWorksheet($worksheet); } else { throw new PhpSpreadsheetException('A Worksheet has already been assigned. Drawings can only exist on one \\PhpOffice\\PhpSpreadsheet\\Worksheet.'); } } return $this; } /** * Get Coordinates. * * @return string */ public function getCoordinates() { return $this->coordinates; } /** * Set Coordinates. * * @param string $coordinates eg: 'A1' * * @return $this */ public function setCoordinates($coordinates) { $this->coordinates = $coordinates; return $this; } /** * Get OffsetX. * * @return int */ public function getOffsetX() { return $this->offsetX; } /** * Set OffsetX. * * @param int $offsetX * * @return $this */ public function setOffsetX($offsetX) { $this->offsetX = $offsetX; return $this; } /** * Get OffsetY. * * @return int */ public function getOffsetY() { return $this->offsetY; } /** * Set OffsetY. * * @param int $offsetY * * @return $this */ public function setOffsetY($offsetY) { $this->offsetY = $offsetY; return $this; } /** * Get Width. * * @return int */ public function getWidth() { return $this->width; } /** * Set Width. * * @param int $width * * @return $this */ public function setWidth($width) { // Resize proportional? if ($this->resizeProportional && $width != 0) { $ratio = $this->height / ($this->width != 0 ? $this->width : 1); $this->height = (int) round($ratio * $width); } // Set width $this->width = $width; return $this; } /** * Get Height. * * @return int */ public function getHeight() { return $this->height; } /** * Set Height. * * @param int $height * * @return $this */ public function setHeight($height) { // Resize proportional? if ($this->resizeProportional && $height != 0) { $ratio = $this->width / ($this->height != 0 ? $this->height : 1); $this->width = (int) round($ratio * $height); } // Set height $this->height = $height; return $this; } /** * Set width and height with proportional resize. * * Example: * <code> * $objDrawing->setResizeProportional(true); * $objDrawing->setWidthAndHeight(160,120); * </code> * * @param int $width * @param int $height * * @return $this * * @author Vincent@luo MSN:kele_100@hotmail.com */ public function setWidthAndHeight($width, $height) { $xratio = $width / ($this->width != 0 ? $this->width : 1); $yratio = $height / ($this->height != 0 ? $this->height : 1); if ($this->resizeProportional && !($width == 0 || $height == 0)) { if (($xratio * $this->height) < $height) { $this->height = (int) ceil($xratio * $this->height); $this->width = $width; } else { $this->width = (int) ceil($yratio * $this->width); $this->height = $height; } } else { $this->width = $width; $this->height = $height; } return $this; } /** * Get ResizeProportional. * * @return bool */ public function getResizeProportional() { return $this->resizeProportional; } /** * Set ResizeProportional. * * @param bool $resizeProportional * * @return $this */ public function setResizeProportional($resizeProportional) { $this->resizeProportional = $resizeProportional; return $this; } /** * Get Rotation. * * @return int */ public function getRotation() { return $this->rotation; } /** * Set Rotation. * * @param int $rotation * * @return $this */ public function setRotation($rotation) { $this->rotation = $rotation; return $this; } /** * Get Shadow. * * @return Drawing\Shadow */ public function getShadow() { return $this->shadow; } /** * Set Shadow. * * @return $this */ public function setShadow(?Drawing\Shadow $shadow = null) { $this->shadow = $shadow; return $this; } /** * Get hash code. * * @return string Hash code */ public function getHashCode() { return md5( $this->name . $this->description . $this->worksheet->getHashCode() . $this->coordinates . $this->offsetX . $this->offsetY . $this->width . $this->height . $this->rotation . $this->shadow->getHashCode() . __CLASS__ ); } /** * 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 ($key == 'worksheet') { $this->worksheet = null; } elseif (is_object($value)) { $this->$key = clone $value; } else { $this->$key = $value; } } } public function setHyperlink(?Hyperlink $hyperlink = null): void { $this->hyperlink = $hyperlink; } /** * @return null|Hyperlink */ public function getHyperlink() { return $this->hyperlink; } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/RowIterator.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/RowIterator.php
<?php namespace PhpOffice\PhpSpreadsheet\Worksheet; use Iterator; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; /** * @implements Iterator<int, Row> */ class RowIterator implements Iterator { /** * Worksheet to iterate. * * @var Worksheet */ private $subject; /** * Current iterator position. * * @var int */ private $position = 1; /** * Start position. * * @var int */ private $startRow = 1; /** * End position. * * @var int */ private $endRow = 1; /** * Create a new row iterator. * * @param Worksheet $subject The worksheet to iterate over * @param int $startRow The row number at which to start iterating * @param int $endRow Optionally, the row number at which to stop iterating */ public function __construct(Worksheet $subject, $startRow = 1, $endRow = null) { // Set subject $this->subject = $subject; $this->resetEnd($endRow); $this->resetStart($startRow); } /** * (Re)Set the start row and the current row pointer. * * @param int $startRow The row number at which to start iterating * * @return $this */ public function resetStart(int $startRow = 1) { if ($startRow > $this->subject->getHighestRow()) { throw new PhpSpreadsheetException( "Start row ({$startRow}) is beyond highest row ({$this->subject->getHighestRow()})" ); } $this->startRow = $startRow; if ($this->endRow < $this->startRow) { $this->endRow = $this->startRow; } $this->seek($startRow); return $this; } /** * (Re)Set the end row. * * @param int $endRow The row number at which to stop iterating * * @return $this */ public function resetEnd($endRow = null) { $this->endRow = $endRow ?: $this->subject->getHighestRow(); return $this; } /** * Set the row pointer to the selected row. * * @param int $row The row number to set the current pointer at * * @return $this */ public function seek(int $row = 1) { if (($row < $this->startRow) || ($row > $this->endRow)) { throw new PhpSpreadsheetException("Row $row is out of range ({$this->startRow} - {$this->endRow})"); } $this->position = $row; return $this; } /** * Rewind the iterator to the starting row. */ public function rewind(): void { $this->position = $this->startRow; } /** * Return the current row in this worksheet. */ public function current(): Row { return new Row($this->subject, $this->position); } /** * Return the current iterator key. */ public function key(): int { return $this->position; } /** * Set the iterator to its next value. */ public function next(): void { ++$this->position; } /** * Set the iterator to its previous value. */ public function prev(): void { --$this->position; } /** * Indicate if more rows exist in the worksheet range of rows that we're iterating. */ public function valid(): bool { return $this->position <= $this->endRow && $this->position >= $this->startRow; } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Protection.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Protection.php
<?php namespace PhpOffice\PhpSpreadsheet\Worksheet; use PhpOffice\PhpSpreadsheet\Shared\PasswordHasher; class Protection { const ALGORITHM_MD2 = 'MD2'; const ALGORITHM_MD4 = 'MD4'; const ALGORITHM_MD5 = 'MD5'; const ALGORITHM_SHA_1 = 'SHA-1'; const ALGORITHM_SHA_256 = 'SHA-256'; const ALGORITHM_SHA_384 = 'SHA-384'; const ALGORITHM_SHA_512 = 'SHA-512'; const ALGORITHM_RIPEMD_128 = 'RIPEMD-128'; const ALGORITHM_RIPEMD_160 = 'RIPEMD-160'; const ALGORITHM_WHIRLPOOL = 'WHIRLPOOL'; /** * Sheet. * * @var bool */ private $sheet = false; /** * Objects. * * @var bool */ private $objects = false; /** * Scenarios. * * @var bool */ private $scenarios = false; /** * Format cells. * * @var bool */ private $formatCells = false; /** * Format columns. * * @var bool */ private $formatColumns = false; /** * Format rows. * * @var bool */ private $formatRows = false; /** * Insert columns. * * @var bool */ private $insertColumns = false; /** * Insert rows. * * @var bool */ private $insertRows = false; /** * Insert hyperlinks. * * @var bool */ private $insertHyperlinks = false; /** * Delete columns. * * @var bool */ private $deleteColumns = false; /** * Delete rows. * * @var bool */ private $deleteRows = false; /** * Select locked cells. * * @var bool */ private $selectLockedCells = false; /** * Sort. * * @var bool */ private $sort = false; /** * AutoFilter. * * @var bool */ private $autoFilter = false; /** * Pivot tables. * * @var bool */ private $pivotTables = false; /** * Select unlocked cells. * * @var bool */ private $selectUnlockedCells = false; /** * Hashed password. * * @var string */ private $password = ''; /** * Algorithm name. * * @var string */ private $algorithm = ''; /** * Salt value. * * @var string */ private $salt = ''; /** * Spin count. * * @var int */ private $spinCount = 10000; /** * Create a new Protection. */ public function __construct() { } /** * Is some sort of protection enabled? * * @return bool */ public function isProtectionEnabled() { return $this->sheet || $this->objects || $this->scenarios || $this->formatCells || $this->formatColumns || $this->formatRows || $this->insertColumns || $this->insertRows || $this->insertHyperlinks || $this->deleteColumns || $this->deleteRows || $this->selectLockedCells || $this->sort || $this->autoFilter || $this->pivotTables || $this->selectUnlockedCells; } /** * Get Sheet. * * @return bool */ public function getSheet() { return $this->sheet; } /** * Set Sheet. * * @param bool $sheet * * @return $this */ public function setSheet($sheet) { $this->sheet = $sheet; return $this; } /** * Get Objects. * * @return bool */ public function getObjects() { return $this->objects; } /** * Set Objects. * * @param bool $objects * * @return $this */ public function setObjects($objects) { $this->objects = $objects; return $this; } /** * Get Scenarios. * * @return bool */ public function getScenarios() { return $this->scenarios; } /** * Set Scenarios. * * @param bool $scenarios * * @return $this */ public function setScenarios($scenarios) { $this->scenarios = $scenarios; return $this; } /** * Get FormatCells. * * @return bool */ public function getFormatCells() { return $this->formatCells; } /** * Set FormatCells. * * @param bool $formatCells * * @return $this */ public function setFormatCells($formatCells) { $this->formatCells = $formatCells; return $this; } /** * Get FormatColumns. * * @return bool */ public function getFormatColumns() { return $this->formatColumns; } /** * Set FormatColumns. * * @param bool $formatColumns * * @return $this */ public function setFormatColumns($formatColumns) { $this->formatColumns = $formatColumns; return $this; } /** * Get FormatRows. * * @return bool */ public function getFormatRows() { return $this->formatRows; } /** * Set FormatRows. * * @param bool $formatRows * * @return $this */ public function setFormatRows($formatRows) { $this->formatRows = $formatRows; return $this; } /** * Get InsertColumns. * * @return bool */ public function getInsertColumns() { return $this->insertColumns; } /** * Set InsertColumns. * * @param bool $insertColumns * * @return $this */ public function setInsertColumns($insertColumns) { $this->insertColumns = $insertColumns; return $this; } /** * Get InsertRows. * * @return bool */ public function getInsertRows() { return $this->insertRows; } /** * Set InsertRows. * * @param bool $insertRows * * @return $this */ public function setInsertRows($insertRows) { $this->insertRows = $insertRows; return $this; } /** * Get InsertHyperlinks. * * @return bool */ public function getInsertHyperlinks() { return $this->insertHyperlinks; } /** * Set InsertHyperlinks. * * @param bool $insertHyperLinks * * @return $this */ public function setInsertHyperlinks($insertHyperLinks) { $this->insertHyperlinks = $insertHyperLinks; return $this; } /** * Get DeleteColumns. * * @return bool */ public function getDeleteColumns() { return $this->deleteColumns; } /** * Set DeleteColumns. * * @param bool $deleteColumns * * @return $this */ public function setDeleteColumns($deleteColumns) { $this->deleteColumns = $deleteColumns; return $this; } /** * Get DeleteRows. * * @return bool */ public function getDeleteRows() { return $this->deleteRows; } /** * Set DeleteRows. * * @param bool $deleteRows * * @return $this */ public function setDeleteRows($deleteRows) { $this->deleteRows = $deleteRows; return $this; } /** * Get SelectLockedCells. * * @return bool */ public function getSelectLockedCells() { return $this->selectLockedCells; } /** * Set SelectLockedCells. * * @param bool $selectLockedCells * * @return $this */ public function setSelectLockedCells($selectLockedCells) { $this->selectLockedCells = $selectLockedCells; return $this; } /** * Get Sort. * * @return bool */ public function getSort() { return $this->sort; } /** * Set Sort. * * @param bool $sort * * @return $this */ public function setSort($sort) { $this->sort = $sort; return $this; } /** * Get AutoFilter. * * @return bool */ public function getAutoFilter() { return $this->autoFilter; } /** * Set AutoFilter. * * @param bool $autoFilter * * @return $this */ public function setAutoFilter($autoFilter) { $this->autoFilter = $autoFilter; return $this; } /** * Get PivotTables. * * @return bool */ public function getPivotTables() { return $this->pivotTables; } /** * Set PivotTables. * * @param bool $pivotTables * * @return $this */ public function setPivotTables($pivotTables) { $this->pivotTables = $pivotTables; return $this; } /** * Get SelectUnlockedCells. * * @return bool */ public function getSelectUnlockedCells() { return $this->selectUnlockedCells; } /** * Set SelectUnlockedCells. * * @param bool $selectUnlockedCells * * @return $this */ public function setSelectUnlockedCells($selectUnlockedCells) { $this->selectUnlockedCells = $selectUnlockedCells; return $this; } /** * Get hashed password. * * @return string */ public function getPassword() { return $this->password; } /** * Set Password. * * @param string $password * @param bool $alreadyHashed If the password has already been hashed, set this to true * * @return $this */ public function setPassword($password, $alreadyHashed = false) { if (!$alreadyHashed) { $salt = $this->generateSalt(); $this->setSalt($salt); $password = PasswordHasher::hashPassword($password, $this->getAlgorithm(), $this->getSalt(), $this->getSpinCount()); } $this->password = $password; return $this; } /** * Create a pseudorandom string. */ private function generateSalt(): string { return base64_encode(random_bytes(16)); } /** * Get algorithm name. */ public function getAlgorithm(): string { return $this->algorithm; } /** * Set algorithm name. */ public function setAlgorithm(string $algorithm): void { $this->algorithm = $algorithm; } /** * Get salt value. */ public function getSalt(): string { return $this->salt; } /** * Set salt value. */ public function setSalt(string $salt): void { $this->salt = $salt; } /** * Get spin count. */ public function getSpinCount(): int { return $this->spinCount; } /** * Set spin count. */ public function setSpinCount(int $spinCount): void { $this->spinCount = $spinCount; } /** * Verify that the given non-hashed password can "unlock" the protection. */ public function verify(string $password): bool { if (!$this->isProtectionEnabled()) { return true; } $hash = PasswordHasher::hashPassword($password, $this->getAlgorithm(), $this->getSalt(), $this->getSpinCount()); return $this->getPassword() === $hash; } /** * 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)) { $this->$key = clone $value; } else { $this->$key = $value; } } } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/RowDimension.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/RowDimension.php
<?php namespace PhpOffice\PhpSpreadsheet\Worksheet; use PhpOffice\PhpSpreadsheet\Helper\Dimension as CssDimension; class RowDimension extends Dimension { /** * Row index. * * @var int */ private $rowIndex; /** * Row height (in pt). * * When this is set to a negative value, the row height should be ignored by IWriter * * @var float */ private $height = -1; /** * ZeroHeight for Row? * * @var bool */ private $zeroHeight = false; /** * Create a new RowDimension. * * @param int $index Numeric row index */ public function __construct($index = 0) { // Initialise values $this->rowIndex = $index; // set dimension as unformatted by default parent::__construct(null); } /** * Get Row Index. */ public function getRowIndex(): int { return $this->rowIndex; } /** * Set Row Index. * * @return $this */ public function setRowIndex(int $index) { $this->rowIndex = $index; return $this; } /** * Get Row Height. * By default, this will be in points; but this method accepts a unit of measure * argument, and will convert the value to the specified UoM. * * @return float */ public function getRowHeight(?string $unitOfMeasure = null) { return ($unitOfMeasure === null || $this->height < 0) ? $this->height : (new CssDimension($this->height . CssDimension::UOM_POINTS))->toUnit($unitOfMeasure); } /** * Set Row Height. * * @param float $height in points * By default, this will be the passed argument value; but this method accepts a unit of measure * argument, and will convert the passed argument value to points from the specified UoM * * @return $this */ public function setRowHeight($height, ?string $unitOfMeasure = null) { $this->height = ($unitOfMeasure === null || $height < 0) ? $height : (new CssDimension("{$height}{$unitOfMeasure}"))->height(); return $this; } /** * Get ZeroHeight. */ public function getZeroHeight(): bool { return $this->zeroHeight; } /** * Set ZeroHeight. * * @return $this */ public function setZeroHeight(bool $zeroHeight) { $this->zeroHeight = $zeroHeight; return $this; } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/ColumnDimension.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/ColumnDimension.php
<?php namespace PhpOffice\PhpSpreadsheet\Worksheet; use PhpOffice\PhpSpreadsheet\Helper\Dimension as CssDimension; class ColumnDimension extends Dimension { /** * Column index. * * @var string */ private $columnIndex; /** * Column width. * * When this is set to a negative value, the column width should be ignored by IWriter * * @var float */ private $width = -1; /** * Auto size? * * @var bool */ private $autoSize = false; /** * Create a new ColumnDimension. * * @param string $index Character column index */ public function __construct($index = 'A') { // Initialise values $this->columnIndex = $index; // set dimension as unformatted by default parent::__construct(0); } /** * Get column index as string eg: 'A'. */ public function getColumnIndex(): string { return $this->columnIndex; } /** * Set column index as string eg: 'A'. * * @return $this */ public function setColumnIndex(string $index) { $this->columnIndex = $index; return $this; } /** * Get Width. * * Each unit of column width is equal to the width of one character in the default font size. * By default, this will be the return value; but this method also accepts a unit of measure argument and will * return the value converted to the specified UoM using an approximation method. */ public function getWidth(?string $unitOfMeasure = null): float { return ($unitOfMeasure === null || $this->width < 0) ? $this->width : (new CssDimension((string) $this->width))->toUnit($unitOfMeasure); } /** * Set Width. * * Each unit of column width is equal to the width of one character in the default font size. * By default, this will be the unit of measure for the passed value; but this method accepts a unit of measure * argument, and will convert the value from the specified UoM using an approximation method. * * @return $this */ public function setWidth(float $width, ?string $unitOfMeasure = null) { $this->width = ($unitOfMeasure === null || $width < 0) ? $width : (new CssDimension("{$width}{$unitOfMeasure}"))->width(); return $this; } /** * Get Auto Size. */ public function getAutoSize(): bool { return $this->autoSize; } /** * Set Auto Size. * * @return $this */ public function setAutoSize(bool $autosizeEnabled) { $this->autoSize = $autosizeEnabled; return $this; } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/AutoFilter.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/AutoFilter.php
<?php namespace PhpOffice\PhpSpreadsheet\Worksheet; use DateTime; use DateTimeZone; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Internal\WildcardMatch; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; use PhpOffice\PhpSpreadsheet\Shared\Date; use PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule; class AutoFilter { /** * Autofilter Worksheet. * * @var null|Worksheet */ private $workSheet; /** * Autofilter Range. * * @var string */ private $range = ''; /** * Autofilter Column Ruleset. * * @var AutoFilter\Column[] */ private $columns = []; /** * Create a new AutoFilter. * * @param string $range Cell range (i.e. A1:E10) */ public function __construct($range = '', ?Worksheet $worksheet = null) { $this->range = $range; $this->workSheet = $worksheet; } /** * Get AutoFilter Parent Worksheet. * * @return null|Worksheet */ public function getParent() { return $this->workSheet; } /** * Set AutoFilter Parent Worksheet. * * @return $this */ public function setParent(?Worksheet $worksheet = null) { $this->workSheet = $worksheet; return $this; } /** * Get AutoFilter Range. * * @return string */ public function getRange() { return $this->range; } /** * Set AutoFilter Range. * * @param string $range Cell range (i.e. A1:E10) * * @return $this */ public function setRange($range) { // extract coordinate [$worksheet, $range] = Worksheet::extractSheetTitle($range, true); if (empty($range)) { // Discard all column rules $this->columns = []; $this->range = ''; return $this; } if (strpos($range, ':') === false) { throw new PhpSpreadsheetException('Autofilter must be set on a range of cells.'); } $this->range = $range; // Discard any column rules that are no longer valid within this range [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($this->range); foreach ($this->columns as $key => $value) { $colIndex = Coordinate::columnIndexFromString($key); if (($rangeStart[0] > $colIndex) || ($rangeEnd[0] < $colIndex)) { unset($this->columns[$key]); } } return $this; } /** * Get all AutoFilter Columns. * * @return AutoFilter\Column[] */ public function getColumns() { return $this->columns; } /** * Validate that the specified column is in the AutoFilter range. * * @param string $column Column name (e.g. A) * * @return int The column offset within the autofilter range */ public function testColumnInRange($column) { if (empty($this->range)) { throw new PhpSpreadsheetException('No autofilter range is defined.'); } $columnIndex = Coordinate::columnIndexFromString($column); [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($this->range); if (($rangeStart[0] > $columnIndex) || ($rangeEnd[0] < $columnIndex)) { throw new PhpSpreadsheetException('Column is outside of current autofilter range.'); } return $columnIndex - $rangeStart[0]; } /** * Get a specified AutoFilter Column Offset within the defined AutoFilter range. * * @param string $column Column name (e.g. A) * * @return int The offset of the specified column within the autofilter range */ public function getColumnOffset($column) { return $this->testColumnInRange($column); } /** * Get a specified AutoFilter Column. * * @param string $column Column name (e.g. A) * * @return AutoFilter\Column */ public function getColumn($column) { $this->testColumnInRange($column); if (!isset($this->columns[$column])) { $this->columns[$column] = new AutoFilter\Column($column, $this); } return $this->columns[$column]; } /** * Get a specified AutoFilter Column by it's offset. * * @param int $columnOffset Column offset within range (starting from 0) * * @return AutoFilter\Column */ public function getColumnByOffset($columnOffset) { [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($this->range); $pColumn = Coordinate::stringFromColumnIndex($rangeStart[0] + $columnOffset); return $this->getColumn($pColumn); } /** * Set AutoFilter. * * @param AutoFilter\Column|string $columnObjectOrString * A simple string containing a Column ID like 'A' is permitted * * @return $this */ public function setColumn($columnObjectOrString) { if ((is_string($columnObjectOrString)) && (!empty($columnObjectOrString))) { $column = $columnObjectOrString; } elseif (is_object($columnObjectOrString) && ($columnObjectOrString instanceof AutoFilter\Column)) { $column = $columnObjectOrString->getColumnIndex(); } else { throw new PhpSpreadsheetException('Column is not within the autofilter range.'); } $this->testColumnInRange($column); if (is_string($columnObjectOrString)) { $this->columns[$columnObjectOrString] = new AutoFilter\Column($columnObjectOrString, $this); } else { $columnObjectOrString->setParent($this); $this->columns[$column] = $columnObjectOrString; } ksort($this->columns); return $this; } /** * Clear a specified AutoFilter Column. * * @param string $column Column name (e.g. A) * * @return $this */ public function clearColumn($column) { $this->testColumnInRange($column); if (isset($this->columns[$column])) { unset($this->columns[$column]); } return $this; } /** * Shift an AutoFilter Column Rule to a different column. * * Note: This method bypasses validation of the destination column to ensure it is within this AutoFilter range. * Nor does it verify whether any column rule already exists at $toColumn, but will simply override any existing value. * Use with caution. * * @param string $fromColumn Column name (e.g. A) * @param string $toColumn Column name (e.g. B) * * @return $this */ public function shiftColumn($fromColumn, $toColumn) { $fromColumn = strtoupper($fromColumn); $toColumn = strtoupper($toColumn); if (($fromColumn !== null) && (isset($this->columns[$fromColumn])) && ($toColumn !== null)) { $this->columns[$fromColumn]->setParent(); $this->columns[$fromColumn]->setColumnIndex($toColumn); $this->columns[$toColumn] = $this->columns[$fromColumn]; $this->columns[$toColumn]->setParent($this); unset($this->columns[$fromColumn]); ksort($this->columns); } return $this; } /** * Test if cell value is in the defined set of values. * * @param mixed $cellValue * @param mixed[] $dataSet * * @return bool */ private static function filterTestInSimpleDataSet($cellValue, $dataSet) { $dataSetValues = $dataSet['filterValues']; $blanks = $dataSet['blanks']; if (($cellValue == '') || ($cellValue === null)) { return $blanks; } return in_array($cellValue, $dataSetValues); } /** * Test if cell value is in the defined set of Excel date values. * * @param mixed $cellValue * @param mixed[] $dataSet * * @return bool */ private static function filterTestInDateGroupSet($cellValue, $dataSet) { $dateSet = $dataSet['filterValues']; $blanks = $dataSet['blanks']; if (($cellValue == '') || ($cellValue === null)) { return $blanks; } $timeZone = new DateTimeZone('UTC'); if (is_numeric($cellValue)) { $dateTime = Date::excelToDateTimeObject((float) $cellValue, $timeZone); $cellValue = (float) $cellValue; if ($cellValue < 1) { // Just the time part $dtVal = $dateTime->format('His'); $dateSet = $dateSet['time']; } elseif ($cellValue == floor($cellValue)) { // Just the date part $dtVal = $dateTime->format('Ymd'); $dateSet = $dateSet['date']; } else { // date and time parts $dtVal = $dateTime->format('YmdHis'); $dateSet = $dateSet['dateTime']; } foreach ($dateSet as $dateValue) { // Use of substr to extract value at the appropriate group level if (substr($dtVal, 0, strlen($dateValue)) == $dateValue) { return true; } } } return false; } /** * Test if cell value is within a set of values defined by a ruleset. * * @param mixed $cellValue * @param mixed[] $ruleSet * * @return bool */ private static function filterTestInCustomDataSet($cellValue, $ruleSet) { /** @var array[] */ $dataSet = $ruleSet['filterRules']; $join = $ruleSet['join']; $customRuleForBlanks = $ruleSet['customRuleForBlanks'] ?? false; if (!$customRuleForBlanks) { // Blank cells are always ignored, so return a FALSE if (($cellValue == '') || ($cellValue === null)) { return false; } } $returnVal = ($join == AutoFilter\Column::AUTOFILTER_COLUMN_JOIN_AND); foreach ($dataSet as $rule) { /** @var string */ $ruleValue = $rule['value']; /** @var string */ $ruleOperator = $rule['operator']; /** @var string */ $cellValueString = $cellValue; $retVal = false; if (is_numeric($ruleValue)) { // Numeric values are tested using the appropriate operator $numericTest = is_numeric($cellValue); switch ($ruleOperator) { case Rule::AUTOFILTER_COLUMN_RULE_EQUAL: $retVal = $numericTest && ($cellValue == $ruleValue); break; case Rule::AUTOFILTER_COLUMN_RULE_NOTEQUAL: $retVal = !$numericTest || ($cellValue != $ruleValue); break; case Rule::AUTOFILTER_COLUMN_RULE_GREATERTHAN: $retVal = $numericTest && ($cellValue > $ruleValue); break; case Rule::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL: $retVal = $numericTest && ($cellValue >= $ruleValue); break; case Rule::AUTOFILTER_COLUMN_RULE_LESSTHAN: $retVal = $numericTest && ($cellValue < $ruleValue); break; case Rule::AUTOFILTER_COLUMN_RULE_LESSTHANOREQUAL: $retVal = $numericTest && ($cellValue <= $ruleValue); break; } } elseif ($ruleValue == '') { switch ($ruleOperator) { case Rule::AUTOFILTER_COLUMN_RULE_EQUAL: $retVal = (($cellValue == '') || ($cellValue === null)); break; case Rule::AUTOFILTER_COLUMN_RULE_NOTEQUAL: $retVal = (($cellValue != '') && ($cellValue !== null)); break; default: $retVal = true; break; } } else { // String values are always tested for equality, factoring in for wildcards (hence a regexp test) switch ($ruleOperator) { case Rule::AUTOFILTER_COLUMN_RULE_EQUAL: $retVal = (bool) preg_match('/^' . $ruleValue . '$/i', $cellValueString); break; case Rule::AUTOFILTER_COLUMN_RULE_NOTEQUAL: $retVal = !((bool) preg_match('/^' . $ruleValue . '$/i', $cellValueString)); break; case Rule::AUTOFILTER_COLUMN_RULE_GREATERTHAN: $retVal = strcasecmp($cellValueString, $ruleValue) > 0; break; case Rule::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL: $retVal = strcasecmp($cellValueString, $ruleValue) >= 0; break; case Rule::AUTOFILTER_COLUMN_RULE_LESSTHAN: $retVal = strcasecmp($cellValueString, $ruleValue) < 0; break; case Rule::AUTOFILTER_COLUMN_RULE_LESSTHANOREQUAL: $retVal = strcasecmp($cellValueString, $ruleValue) <= 0; break; } } // If there are multiple conditions, then we need to test both using the appropriate join operator switch ($join) { case AutoFilter\Column::AUTOFILTER_COLUMN_JOIN_OR: $returnVal = $returnVal || $retVal; // Break as soon as we have a TRUE match for OR joins, // to avoid unnecessary additional code execution if ($returnVal) { return $returnVal; } break; case AutoFilter\Column::AUTOFILTER_COLUMN_JOIN_AND: $returnVal = $returnVal && $retVal; break; } } return $returnVal; } /** * Test if cell date value is matches a set of values defined by a set of months. * * @param mixed $cellValue * @param mixed[] $monthSet * * @return bool */ private static function filterTestInPeriodDateSet($cellValue, $monthSet) { // Blank cells are always ignored, so return a FALSE if (($cellValue == '') || ($cellValue === null)) { return false; } if (is_numeric($cellValue)) { $dateObject = Date::excelToDateTimeObject((float) $cellValue, new DateTimeZone('UTC')); $dateValue = (int) $dateObject->format('m'); if (in_array($dateValue, $monthSet)) { return true; } } return false; } private static function makeDateObject(int $year, int $month, int $day, int $hour = 0, int $minute = 0, int $second = 0): DateTime { $baseDate = new DateTime(); $baseDate->setDate($year, $month, $day); $baseDate->setTime($hour, $minute, $second); return $baseDate; } private const DATE_FUNCTIONS = [ Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTMONTH => 'dynamicLastMonth', Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTQUARTER => 'dynamicLastQuarter', Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTWEEK => 'dynamicLastWeek', Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTYEAR => 'dynamicLastYear', Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTMONTH => 'dynamicNextMonth', Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTQUARTER => 'dynamicNextQuarter', Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTWEEK => 'dynamicNextWeek', Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTYEAR => 'dynamicNextYear', Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISMONTH => 'dynamicThisMonth', Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISQUARTER => 'dynamicThisQuarter', Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISWEEK => 'dynamicThisWeek', Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISYEAR => 'dynamicThisYear', Rule::AUTOFILTER_RULETYPE_DYNAMIC_TODAY => 'dynamicToday', Rule::AUTOFILTER_RULETYPE_DYNAMIC_TOMORROW => 'dynamicTomorrow', Rule::AUTOFILTER_RULETYPE_DYNAMIC_YEARTODATE => 'dynamicYearToDate', Rule::AUTOFILTER_RULETYPE_DYNAMIC_YESTERDAY => 'dynamicYesterday', ]; private static function dynamicLastMonth(): array { $maxval = new DateTime(); $year = (int) $maxval->format('Y'); $month = (int) $maxval->format('m'); $maxval->setDate($year, $month, 1); $maxval->setTime(0, 0, 0); $val = clone $maxval; $val->modify('-1 month'); return [$val, $maxval]; } private static function firstDayOfQuarter(): DateTime { $val = new DateTime(); $year = (int) $val->format('Y'); $month = (int) $val->format('m'); $month = 3 * intdiv($month - 1, 3) + 1; $val->setDate($year, $month, 1); $val->setTime(0, 0, 0); return $val; } private static function dynamicLastQuarter(): array { $maxval = self::firstDayOfQuarter(); $val = clone $maxval; $val->modify('-3 months'); return [$val, $maxval]; } private static function dynamicLastWeek(): array { $val = new DateTime(); $val->setTime(0, 0, 0); $dayOfWeek = (int) $val->format('w'); // Sunday is 0 $subtract = $dayOfWeek + 7; // revert to prior Sunday $val->modify("-$subtract days"); $maxval = clone $val; $maxval->modify('+7 days'); return [$val, $maxval]; } private static function dynamicLastYear(): array { $val = new DateTime(); $year = (int) $val->format('Y'); $val = self::makeDateObject($year - 1, 1, 1); $maxval = self::makeDateObject($year, 1, 1); return [$val, $maxval]; } private static function dynamicNextMonth(): array { $val = new DateTime(); $year = (int) $val->format('Y'); $month = (int) $val->format('m'); $val->setDate($year, $month, 1); $val->setTime(0, 0, 0); $val->modify('+1 month'); $maxval = clone $val; $maxval->modify('+1 month'); return [$val, $maxval]; } private static function dynamicNextQuarter(): array { $val = self::firstDayOfQuarter(); $val->modify('+3 months'); $maxval = clone $val; $maxval->modify('+3 months'); return [$val, $maxval]; } private static function dynamicNextWeek(): array { $val = new DateTime(); $val->setTime(0, 0, 0); $dayOfWeek = (int) $val->format('w'); // Sunday is 0 $add = 7 - $dayOfWeek; // move to next Sunday $val->modify("+$add days"); $maxval = clone $val; $maxval->modify('+7 days'); return [$val, $maxval]; } private static function dynamicNextYear(): array { $val = new DateTime(); $year = (int) $val->format('Y'); $val = self::makeDateObject($year + 1, 1, 1); $maxval = self::makeDateObject($year + 2, 1, 1); return [$val, $maxval]; } private static function dynamicThisMonth(): array { $baseDate = new DateTime(); $baseDate->setTime(0, 0, 0); $year = (int) $baseDate->format('Y'); $month = (int) $baseDate->format('m'); $val = self::makeDateObject($year, $month, 1); $maxval = clone $val; $maxval->modify('+1 month'); return [$val, $maxval]; } private static function dynamicThisQuarter(): array { $val = self::firstDayOfQuarter(); $maxval = clone $val; $maxval->modify('+3 months'); return [$val, $maxval]; } private static function dynamicThisWeek(): array { $val = new DateTime(); $val->setTime(0, 0, 0); $dayOfWeek = (int) $val->format('w'); // Sunday is 0 $subtract = $dayOfWeek; // revert to Sunday $val->modify("-$subtract days"); $maxval = clone $val; $maxval->modify('+7 days'); return [$val, $maxval]; } private static function dynamicThisYear(): array { $val = new DateTime(); $year = (int) $val->format('Y'); $val = self::makeDateObject($year, 1, 1); $maxval = self::makeDateObject($year + 1, 1, 1); return [$val, $maxval]; } private static function dynamicToday(): array { $val = new DateTime(); $val->setTime(0, 0, 0); $maxval = clone $val; $maxval->modify('+1 day'); return [$val, $maxval]; } private static function dynamicTomorrow(): array { $val = new DateTime(); $val->setTime(0, 0, 0); $val->modify('+1 day'); $maxval = clone $val; $maxval->modify('+1 day'); return [$val, $maxval]; } private static function dynamicYearToDate(): array { $maxval = new DateTime(); $maxval->setTime(0, 0, 0); $val = self::makeDateObject((int) $maxval->format('Y'), 1, 1); $maxval->modify('+1 day'); return [$val, $maxval]; } private static function dynamicYesterday(): array { $maxval = new DateTime(); $maxval->setTime(0, 0, 0); $val = clone $maxval; $val->modify('-1 day'); return [$val, $maxval]; } /** * Convert a dynamic rule daterange to a custom filter range expression for ease of calculation. * * @param string $dynamicRuleType * * @return mixed[] */ private function dynamicFilterDateRange($dynamicRuleType, AutoFilter\Column &$filterColumn) { $ruleValues = []; $callBack = [__CLASS__, self::DATE_FUNCTIONS[$dynamicRuleType]]; // What if not found? // Calculate start/end dates for the required date range based on current date // Val is lowest permitted value. // Maxval is greater than highest permitted value $val = $maxval = 0; if (is_callable($callBack)) { [$val, $maxval] = $callBack(); } $val = Date::dateTimeToExcel($val); $maxval = Date::dateTimeToExcel($maxval); // Set the filter column rule attributes ready for writing $filterColumn->setAttributes(['val' => $val, 'maxVal' => $maxval]); // Set the rules for identifying rows for hide/show $ruleValues[] = ['operator' => Rule::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL, 'value' => $val]; $ruleValues[] = ['operator' => Rule::AUTOFILTER_COLUMN_RULE_LESSTHAN, 'value' => $maxval]; return ['method' => 'filterTestInCustomDataSet', 'arguments' => ['filterRules' => $ruleValues, 'join' => AutoFilter\Column::AUTOFILTER_COLUMN_JOIN_AND]]; } /** * Apply the AutoFilter rules to the AutoFilter Range. * * @param string $columnID * @param int $startRow * @param int $endRow * @param ?string $ruleType * @param mixed $ruleValue * * @return mixed */ private function calculateTopTenValue($columnID, $startRow, $endRow, $ruleType, $ruleValue) { $range = $columnID . $startRow . ':' . $columnID . $endRow; $retVal = null; if ($this->workSheet !== null) { $dataValues = Functions::flattenArray($this->workSheet->rangeToArray($range, null, true, false)); $dataValues = array_filter($dataValues); if ($ruleType == Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP) { rsort($dataValues); } else { sort($dataValues); } $slice = array_slice($dataValues, 0, $ruleValue); $retVal = array_pop($slice); } return $retVal; } /** * Apply the AutoFilter rules to the AutoFilter Range. * * @return $this */ public function showHideRows() { if ($this->workSheet === null) { return $this; } [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($this->range); // The heading row should always be visible $this->workSheet->getRowDimension($rangeStart[1])->setVisible(true); $columnFilterTests = []; foreach ($this->columns as $columnID => $filterColumn) { $rules = $filterColumn->getRules(); switch ($filterColumn->getFilterType()) { case AutoFilter\Column::AUTOFILTER_FILTERTYPE_FILTER: $ruleType = null; $ruleValues = []; // Build a list of the filter value selections foreach ($rules as $rule) { $ruleType = $rule->getRuleType(); $ruleValues[] = $rule->getValue(); } // Test if we want to include blanks in our filter criteria $blanks = false; $ruleDataSet = array_filter($ruleValues); if (count($ruleValues) != count($ruleDataSet)) { $blanks = true; } if ($ruleType == Rule::AUTOFILTER_RULETYPE_FILTER) { // Filter on absolute values $columnFilterTests[$columnID] = [ 'method' => 'filterTestInSimpleDataSet', 'arguments' => ['filterValues' => $ruleDataSet, 'blanks' => $blanks], ]; } else { // Filter on date group values $arguments = [ 'date' => [], 'time' => [], 'dateTime' => [], ]; foreach ($ruleDataSet as $ruleValue) { if (!is_array($ruleValue)) { continue; } $date = $time = ''; if ( (isset($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_YEAR])) && ($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_YEAR] !== '') ) { $date .= sprintf('%04d', $ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_YEAR]); } if ( (isset($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_MONTH])) && ($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_MONTH] != '') ) { $date .= sprintf('%02d', $ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_MONTH]); } if ( (isset($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_DAY])) && ($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_DAY] !== '') ) { $date .= sprintf('%02d', $ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_DAY]); } if ( (isset($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_HOUR])) && ($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_HOUR] !== '') ) { $time .= sprintf('%02d', $ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_HOUR]); } if ( (isset($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_MINUTE])) && ($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_MINUTE] !== '') ) { $time .= sprintf('%02d', $ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_MINUTE]); } if ( (isset($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_SECOND])) && ($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_SECOND] !== '') ) { $time .= sprintf('%02d', $ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_SECOND]); } $dateTime = $date . $time; $arguments['date'][] = $date; $arguments['time'][] = $time; $arguments['dateTime'][] = $dateTime; } // Remove empty elements $arguments['date'] = array_filter($arguments['date']); $arguments['time'] = array_filter($arguments['time']); $arguments['dateTime'] = array_filter($arguments['dateTime']); $columnFilterTests[$columnID] = [ 'method' => 'filterTestInDateGroupSet', 'arguments' => ['filterValues' => $arguments, 'blanks' => $blanks], ]; } break; case AutoFilter\Column::AUTOFILTER_FILTERTYPE_CUSTOMFILTER: $customRuleForBlanks = true; $ruleValues = []; // Build a list of the filter value selections foreach ($rules as $rule) { $ruleValue = $rule->getValue(); if (!is_array($ruleValue) && !is_numeric($ruleValue)) { // Convert to a regexp allowing for regexp reserved characters, wildcards and escaped wildcards $ruleValue = WildcardMatch::wildcard($ruleValue); if (trim($ruleValue) == '') { $customRuleForBlanks = true; $ruleValue = trim($ruleValue); } } $ruleValues[] = ['operator' => $rule->getOperator(), 'value' => $ruleValue]; } $join = $filterColumn->getJoin(); $columnFilterTests[$columnID] = [ 'method' => 'filterTestInCustomDataSet', 'arguments' => ['filterRules' => $ruleValues, 'join' => $join, 'customRuleForBlanks' => $customRuleForBlanks], ]; break; case AutoFilter\Column::AUTOFILTER_FILTERTYPE_DYNAMICFILTER: $ruleValues = []; foreach ($rules as $rule) { // We should only ever have one Dynamic Filter Rule anyway $dynamicRuleType = $rule->getGrouping(); if ( ($dynamicRuleType == Rule::AUTOFILTER_RULETYPE_DYNAMIC_ABOVEAVERAGE) || ($dynamicRuleType == Rule::AUTOFILTER_RULETYPE_DYNAMIC_BELOWAVERAGE) ) { // Number (Average) based // Calculate the average $averageFormula = '=AVERAGE(' . $columnID . ($rangeStart[1] + 1) . ':' . $columnID . $rangeEnd[1] . ')'; $spreadsheet = ($this->workSheet === null) ? null : $this->workSheet->getParent(); $average = Calculation::getInstance($spreadsheet)->calculateFormula($averageFormula, null, $this->workSheet->getCell('A1')); // Set above/below rule based on greaterThan or LessTan $operator = ($dynamicRuleType === Rule::AUTOFILTER_RULETYPE_DYNAMIC_ABOVEAVERAGE) ? Rule::AUTOFILTER_COLUMN_RULE_GREATERTHAN : Rule::AUTOFILTER_COLUMN_RULE_LESSTHAN; $ruleValues[] = [ 'operator' => $operator, 'value' => $average,
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
true
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/SheetView.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/SheetView.php
<?php namespace PhpOffice\PhpSpreadsheet\Worksheet; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; class SheetView { // Sheet View types const SHEETVIEW_NORMAL = 'normal'; const SHEETVIEW_PAGE_LAYOUT = 'pageLayout'; const SHEETVIEW_PAGE_BREAK_PREVIEW = 'pageBreakPreview'; private static $sheetViewTypes = [ self::SHEETVIEW_NORMAL, self::SHEETVIEW_PAGE_LAYOUT, self::SHEETVIEW_PAGE_BREAK_PREVIEW, ]; /** * ZoomScale. * * Valid values range from 10 to 400. * * @var int */ private $zoomScale = 100; /** * ZoomScaleNormal. * * Valid values range from 10 to 400. * * @var int */ private $zoomScaleNormal = 100; /** * ShowZeros. * * If true, "null" values from a calculation will be shown as "0". This is the default Excel behaviour and can be changed * with the advanced worksheet option "Show a zero in cells that have zero value" * * @var bool */ private $showZeros = true; /** * View. * * Valid values range from 10 to 400. * * @var string */ private $sheetviewType = self::SHEETVIEW_NORMAL; /** * Create a new SheetView. */ public function __construct() { } /** * Get ZoomScale. * * @return int */ public function getZoomScale() { return $this->zoomScale; } /** * Set ZoomScale. * Valid values range from 10 to 400. * * @param int $zoomScale * * @return $this */ public function setZoomScale($zoomScale) { // Microsoft Office Excel 2007 only allows setting a scale between 10 and 400 via the user interface, // but it is apparently still able to handle any scale >= 1 if (($zoomScale >= 1) || $zoomScale === null) { $this->zoomScale = $zoomScale; } else { throw new PhpSpreadsheetException('Scale must be greater than or equal to 1.'); } return $this; } /** * Get ZoomScaleNormal. * * @return int */ public function getZoomScaleNormal() { return $this->zoomScaleNormal; } /** * Set ZoomScale. * Valid values range from 10 to 400. * * @param int $zoomScaleNormal * * @return $this */ public function setZoomScaleNormal($zoomScaleNormal) { if (($zoomScaleNormal >= 1) || $zoomScaleNormal === null) { $this->zoomScaleNormal = $zoomScaleNormal; } else { throw new PhpSpreadsheetException('Scale must be greater than or equal to 1.'); } return $this; } /** * Set ShowZeroes setting. * * @param bool $showZeros */ public function setShowZeros($showZeros): void { $this->showZeros = $showZeros; } /** * @return bool */ public function getShowZeros() { return $this->showZeros; } /** * Get View. * * @return string */ public function getView() { return $this->sheetviewType; } /** * Set View. * * Valid values are * 'normal' self::SHEETVIEW_NORMAL * 'pageLayout' self::SHEETVIEW_PAGE_LAYOUT * 'pageBreakPreview' self::SHEETVIEW_PAGE_BREAK_PREVIEW * * @param string $sheetViewType * * @return $this */ public function setView($sheetViewType) { // MS Excel 2007 allows setting the view to 'normal', 'pageLayout' or 'pageBreakPreview' via the user interface if ($sheetViewType === null) { $sheetViewType = self::SHEETVIEW_NORMAL; } if (in_array($sheetViewType, self::$sheetViewTypes)) { $this->sheetviewType = $sheetViewType; } else { throw new PhpSpreadsheetException('Invalid sheetview layout type.'); } return $this; } /** * 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)) { $this->$key = clone $value; } else { $this->$key = $value; } } } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Iterator.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Iterator.php
<?php namespace PhpOffice\PhpSpreadsheet\Worksheet; use PhpOffice\PhpSpreadsheet\Spreadsheet; /** * @implements \Iterator<int, Worksheet> */ class Iterator implements \Iterator { /** * Spreadsheet to iterate. * * @var Spreadsheet */ private $subject; /** * Current iterator position. * * @var int */ private $position = 0; /** * Create a new worksheet iterator. */ public function __construct(Spreadsheet $subject) { // Set subject $this->subject = $subject; } /** * Rewind iterator. */ public function rewind(): void { $this->position = 0; } /** * Current Worksheet. */ public function current(): Worksheet { return $this->subject->getSheet($this->position); } /** * Current key. */ public function key(): int { return $this->position; } /** * Next value. */ public function next(): void { ++$this->position; } /** * Are there more Worksheet instances available? */ public function valid(): bool { return $this->position < $this->subject->getSheetCount() && $this->position >= 0; } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/HeaderFooterDrawing.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/HeaderFooterDrawing.php
<?php namespace PhpOffice\PhpSpreadsheet\Worksheet; class HeaderFooterDrawing extends Drawing { /** * Get hash code. * * @return string Hash code */ public function getHashCode() { return md5( $this->getPath() . $this->name . $this->offsetX . $this->offsetY . $this->width . $this->height . __CLASS__ ); } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Column.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Column.php
<?php namespace PhpOffice\PhpSpreadsheet\Worksheet; class Column { /** * \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet. * * @var Worksheet */ private $parent; /** * Column index. * * @var string */ private $columnIndex; /** * Create a new column. * * @param string $columnIndex */ public function __construct(?Worksheet $parent = null, $columnIndex = 'A') { // Set parent and column index $this->parent = $parent; $this->columnIndex = $columnIndex; } /** * Destructor. */ public function __destruct() { // @phpstan-ignore-next-line $this->parent = null; } /** * Get column index as string eg: 'A'. */ public function getColumnIndex(): string { return $this->columnIndex; } /** * Get cell iterator. * * @param int $startRow The row number at which to start iterating * @param int $endRow Optionally, the row number at which to stop iterating * * @return ColumnCellIterator */ public function getCellIterator($startRow = 1, $endRow = null) { return new ColumnCellIterator($this->parent, $this->columnIndex, $startRow, $endRow); } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/HeaderFooter.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/HeaderFooter.php
<?php namespace PhpOffice\PhpSpreadsheet\Worksheet; /** * <code> * Header/Footer Formatting Syntax taken from Office Open XML Part 4 - Markup Language Reference, page 1970:. * * There are a number of formatting codes that can be written inline with the actual header / footer text, which * affect the formatting in the header or footer. * * Example: This example shows the text "Center Bold Header" on the first line (center section), and the date on * the second line (center section). * &CCenter &"-,Bold"Bold&"-,Regular"Header_x000A_&D * * General Rules: * There is no required order in which these codes must appear. * * The first occurrence of the following codes turns the formatting ON, the second occurrence turns it OFF again: * - strikethrough * - superscript * - subscript * Superscript and subscript cannot both be ON at same time. Whichever comes first wins and the other is ignored, * while the first is ON. * &L - code for "left section" (there are three header / footer locations, "left", "center", and "right"). When * two or more occurrences of this section marker exist, the contents from all markers are concatenated, in the * order of appearance, and placed into the left section. * &P - code for "current page #" * &N - code for "total pages" * &font size - code for "text font size", where font size is a font size in points. * &K - code for "text font color" * RGB Color is specified as RRGGBB * Theme Color is specifed as TTSNN where TT is the theme color Id, S is either "+" or "-" of the tint/shade * value, NN is the tint/shade value. * &S - code for "text strikethrough" on / off * &X - code for "text super script" on / off * &Y - code for "text subscript" on / off * &C - code for "center section". When two or more occurrences of this section marker exist, the contents * from all markers are concatenated, in the order of appearance, and placed into the center section. * * &D - code for "date" * &T - code for "time" * &G - code for "picture as background" * &U - code for "text single underline" * &E - code for "double underline" * &R - code for "right section". When two or more occurrences of this section marker exist, the contents * from all markers are concatenated, in the order of appearance, and placed into the right section. * &Z - code for "this workbook's file path" * &F - code for "this workbook's file name" * &A - code for "sheet tab name" * &+ - code for add to page #. * &- - code for subtract from page #. * &"font name,font type" - code for "text font name" and "text font type", where font name and font type * are strings specifying the name and type of the font, separated by a comma. When a hyphen appears in font * name, it means "none specified". Both of font name and font type can be localized values. * &"-,Bold" - code for "bold font style" * &B - also means "bold font style". * &"-,Regular" - code for "regular font style" * &"-,Italic" - code for "italic font style" * &I - also means "italic font style" * &"-,Bold Italic" code for "bold italic font style" * &O - code for "outline style" * &H - code for "shadow style" * </code> */ class HeaderFooter { // Header/footer image location const IMAGE_HEADER_LEFT = 'LH'; const IMAGE_HEADER_CENTER = 'CH'; const IMAGE_HEADER_RIGHT = 'RH'; const IMAGE_FOOTER_LEFT = 'LF'; const IMAGE_FOOTER_CENTER = 'CF'; const IMAGE_FOOTER_RIGHT = 'RF'; /** * OddHeader. * * @var string */ private $oddHeader = ''; /** * OddFooter. * * @var string */ private $oddFooter = ''; /** * EvenHeader. * * @var string */ private $evenHeader = ''; /** * EvenFooter. * * @var string */ private $evenFooter = ''; /** * FirstHeader. * * @var string */ private $firstHeader = ''; /** * FirstFooter. * * @var string */ private $firstFooter = ''; /** * Different header for Odd/Even, defaults to false. * * @var bool */ private $differentOddEven = false; /** * Different header for first page, defaults to false. * * @var bool */ private $differentFirst = false; /** * Scale with document, defaults to true. * * @var bool */ private $scaleWithDocument = true; /** * Align with margins, defaults to true. * * @var bool */ private $alignWithMargins = true; /** * Header/footer images. * * @var HeaderFooterDrawing[] */ private $headerFooterImages = []; /** * Create a new HeaderFooter. */ public function __construct() { } /** * Get OddHeader. * * @return string */ public function getOddHeader() { return $this->oddHeader; } /** * Set OddHeader. * * @param string $oddHeader * * @return $this */ public function setOddHeader($oddHeader) { $this->oddHeader = $oddHeader; return $this; } /** * Get OddFooter. * * @return string */ public function getOddFooter() { return $this->oddFooter; } /** * Set OddFooter. * * @param string $oddFooter * * @return $this */ public function setOddFooter($oddFooter) { $this->oddFooter = $oddFooter; return $this; } /** * Get EvenHeader. * * @return string */ public function getEvenHeader() { return $this->evenHeader; } /** * Set EvenHeader. * * @param string $eventHeader * * @return $this */ public function setEvenHeader($eventHeader) { $this->evenHeader = $eventHeader; return $this; } /** * Get EvenFooter. * * @return string */ public function getEvenFooter() { return $this->evenFooter; } /** * Set EvenFooter. * * @param string $evenFooter * * @return $this */ public function setEvenFooter($evenFooter) { $this->evenFooter = $evenFooter; return $this; } /** * Get FirstHeader. * * @return string */ public function getFirstHeader() { return $this->firstHeader; } /** * Set FirstHeader. * * @param string $firstHeader * * @return $this */ public function setFirstHeader($firstHeader) { $this->firstHeader = $firstHeader; return $this; } /** * Get FirstFooter. * * @return string */ public function getFirstFooter() { return $this->firstFooter; } /** * Set FirstFooter. * * @param string $firstFooter * * @return $this */ public function setFirstFooter($firstFooter) { $this->firstFooter = $firstFooter; return $this; } /** * Get DifferentOddEven. * * @return bool */ public function getDifferentOddEven() { return $this->differentOddEven; } /** * Set DifferentOddEven. * * @param bool $differentOddEvent * * @return $this */ public function setDifferentOddEven($differentOddEvent) { $this->differentOddEven = $differentOddEvent; return $this; } /** * Get DifferentFirst. * * @return bool */ public function getDifferentFirst() { return $this->differentFirst; } /** * Set DifferentFirst. * * @param bool $differentFirst * * @return $this */ public function setDifferentFirst($differentFirst) { $this->differentFirst = $differentFirst; return $this; } /** * Get ScaleWithDocument. * * @return bool */ public function getScaleWithDocument() { return $this->scaleWithDocument; } /** * Set ScaleWithDocument. * * @param bool $scaleWithDocument * * @return $this */ public function setScaleWithDocument($scaleWithDocument) { $this->scaleWithDocument = $scaleWithDocument; return $this; } /** * Get AlignWithMargins. * * @return bool */ public function getAlignWithMargins() { return $this->alignWithMargins; } /** * Set AlignWithMargins. * * @param bool $alignWithMargins * * @return $this */ public function setAlignWithMargins($alignWithMargins) { $this->alignWithMargins = $alignWithMargins; return $this; } /** * Add header/footer image. * * @param string $location * * @return $this */ public function addImage(HeaderFooterDrawing $image, $location = self::IMAGE_HEADER_LEFT) { $this->headerFooterImages[$location] = $image; return $this; } /** * Remove header/footer image. * * @param string $location * * @return $this */ public function removeImage($location = self::IMAGE_HEADER_LEFT) { if (isset($this->headerFooterImages[$location])) { unset($this->headerFooterImages[$location]); } return $this; } /** * Set header/footer images. * * @param HeaderFooterDrawing[] $images * * @return $this */ public function setImages(array $images) { $this->headerFooterImages = $images; return $this; } /** * Get header/footer images. * * @return HeaderFooterDrawing[] */ public function getImages() { // Sort array $images = []; if (isset($this->headerFooterImages[self::IMAGE_HEADER_LEFT])) { $images[self::IMAGE_HEADER_LEFT] = $this->headerFooterImages[self::IMAGE_HEADER_LEFT]; } if (isset($this->headerFooterImages[self::IMAGE_HEADER_CENTER])) { $images[self::IMAGE_HEADER_CENTER] = $this->headerFooterImages[self::IMAGE_HEADER_CENTER]; } if (isset($this->headerFooterImages[self::IMAGE_HEADER_RIGHT])) { $images[self::IMAGE_HEADER_RIGHT] = $this->headerFooterImages[self::IMAGE_HEADER_RIGHT]; } if (isset($this->headerFooterImages[self::IMAGE_FOOTER_LEFT])) { $images[self::IMAGE_FOOTER_LEFT] = $this->headerFooterImages[self::IMAGE_FOOTER_LEFT]; } if (isset($this->headerFooterImages[self::IMAGE_FOOTER_CENTER])) { $images[self::IMAGE_FOOTER_CENTER] = $this->headerFooterImages[self::IMAGE_FOOTER_CENTER]; } if (isset($this->headerFooterImages[self::IMAGE_FOOTER_RIGHT])) { $images[self::IMAGE_FOOTER_RIGHT] = $this->headerFooterImages[self::IMAGE_FOOTER_RIGHT]; } $this->headerFooterImages = $images; return $this->headerFooterImages; } /** * 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)) { $this->$key = clone $value; } else { $this->$key = $value; } } } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/AutoFilter/Column.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/AutoFilter/Column.php
<?php namespace PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; use PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter; class Column { const AUTOFILTER_FILTERTYPE_FILTER = 'filters'; const AUTOFILTER_FILTERTYPE_CUSTOMFILTER = 'customFilters'; // Supports no more than 2 rules, with an And/Or join criteria // if more than 1 rule is defined const AUTOFILTER_FILTERTYPE_DYNAMICFILTER = 'dynamicFilter'; // Even though the filter rule is constant, the filtered data can vary // e.g. filtered by date = TODAY const AUTOFILTER_FILTERTYPE_TOPTENFILTER = 'top10'; /** * Types of autofilter rules. * * @var string[] */ private static $filterTypes = [ // Currently we're not handling // colorFilter // extLst // iconFilter self::AUTOFILTER_FILTERTYPE_FILTER, self::AUTOFILTER_FILTERTYPE_CUSTOMFILTER, self::AUTOFILTER_FILTERTYPE_DYNAMICFILTER, self::AUTOFILTER_FILTERTYPE_TOPTENFILTER, ]; // Multiple Rule Connections const AUTOFILTER_COLUMN_JOIN_AND = 'and'; const AUTOFILTER_COLUMN_JOIN_OR = 'or'; /** * Join options for autofilter rules. * * @var string[] */ private static $ruleJoins = [ self::AUTOFILTER_COLUMN_JOIN_AND, self::AUTOFILTER_COLUMN_JOIN_OR, ]; /** * Autofilter. * * @var null|AutoFilter */ private $parent; /** * Autofilter Column Index. * * @var string */ private $columnIndex = ''; /** * Autofilter Column Filter Type. * * @var string */ private $filterType = self::AUTOFILTER_FILTERTYPE_FILTER; /** * Autofilter Multiple Rules And/Or. * * @var string */ private $join = self::AUTOFILTER_COLUMN_JOIN_OR; /** * Autofilter Column Rules. * * @var Column\Rule[] */ private $ruleset = []; /** * Autofilter Column Dynamic Attributes. * * @var mixed[] */ private $attributes = []; /** * Create a new Column. * * @param string $column Column (e.g. A) * @param AutoFilter $parent Autofilter for this column */ public function __construct($column, ?AutoFilter $parent = null) { $this->columnIndex = $column; $this->parent = $parent; } /** * Get AutoFilter column index as string eg: 'A'. * * @return string */ public function getColumnIndex() { return $this->columnIndex; } /** * Set AutoFilter column index as string eg: 'A'. * * @param string $column Column (e.g. A) * * @return $this */ public function setColumnIndex($column) { // Uppercase coordinate $column = strtoupper($column); if ($this->parent !== null) { $this->parent->testColumnInRange($column); } $this->columnIndex = $column; return $this; } /** * Get this Column's AutoFilter Parent. * * @return null|AutoFilter */ public function getParent() { return $this->parent; } /** * Set this Column's AutoFilter Parent. * * @return $this */ public function setParent(?AutoFilter $parent = null) { $this->parent = $parent; return $this; } /** * Get AutoFilter Type. * * @return string */ public function getFilterType() { return $this->filterType; } /** * Set AutoFilter Type. * * @param string $filterType * * @return $this */ public function setFilterType($filterType) { if (!in_array($filterType, self::$filterTypes)) { throw new PhpSpreadsheetException('Invalid filter type for column AutoFilter.'); } if ($filterType === self::AUTOFILTER_FILTERTYPE_CUSTOMFILTER && count($this->ruleset) > 2) { throw new PhpSpreadsheetException('No more than 2 rules are allowed in a Custom Filter'); } $this->filterType = $filterType; return $this; } /** * Get AutoFilter Multiple Rules And/Or Join. * * @return string */ public function getJoin() { return $this->join; } /** * Set AutoFilter Multiple Rules And/Or. * * @param string $join And/Or * * @return $this */ public function setJoin($join) { // Lowercase And/Or $join = strtolower($join); if (!in_array($join, self::$ruleJoins)) { throw new PhpSpreadsheetException('Invalid rule connection for column AutoFilter.'); } $this->join = $join; return $this; } /** * Set AutoFilter Attributes. * * @param mixed[] $attributes * * @return $this */ public function setAttributes($attributes) { $this->attributes = $attributes; return $this; } /** * Set An AutoFilter Attribute. * * @param string $name Attribute Name * @param string $value Attribute Value * * @return $this */ public function setAttribute($name, $value) { $this->attributes[$name] = $value; return $this; } /** * Get AutoFilter Column Attributes. * * @return int[]|string[] */ public function getAttributes() { return $this->attributes; } /** * Get specific AutoFilter Column Attribute. * * @param string $name Attribute Name * * @return null|int|string */ public function getAttribute($name) { if (isset($this->attributes[$name])) { return $this->attributes[$name]; } return null; } public function ruleCount(): int { return count($this->ruleset); } /** * Get all AutoFilter Column Rules. * * @return Column\Rule[] */ public function getRules() { return $this->ruleset; } /** * Get a specified AutoFilter Column Rule. * * @param int $index Rule index in the ruleset array * * @return Column\Rule */ public function getRule($index) { if (!isset($this->ruleset[$index])) { $this->ruleset[$index] = new Column\Rule($this); } return $this->ruleset[$index]; } /** * Create a new AutoFilter Column Rule in the ruleset. * * @return Column\Rule */ public function createRule() { if ($this->filterType === self::AUTOFILTER_FILTERTYPE_CUSTOMFILTER && count($this->ruleset) >= 2) { throw new PhpSpreadsheetException('No more than 2 rules are allowed in a Custom Filter'); } $this->ruleset[] = new Column\Rule($this); return end($this->ruleset); } /** * Add a new AutoFilter Column Rule to the ruleset. * * @return $this */ public function addRule(Column\Rule $rule) { $rule->setParent($this); $this->ruleset[] = $rule; return $this; } /** * Delete a specified AutoFilter Column Rule * If the number of rules is reduced to 1, then we reset And/Or logic to Or. * * @param int $index Rule index in the ruleset array * * @return $this */ public function deleteRule($index) { if (isset($this->ruleset[$index])) { unset($this->ruleset[$index]); // If we've just deleted down to a single rule, then reset And/Or joining to Or if (count($this->ruleset) <= 1) { $this->setJoin(self::AUTOFILTER_COLUMN_JOIN_OR); } } return $this; } /** * Delete all AutoFilter Column Rules. * * @return $this */ public function clearRules() { $this->ruleset = []; $this->setJoin(self::AUTOFILTER_COLUMN_JOIN_OR); return $this; } /** * 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 ($key === 'parent') { // Detach from autofilter parent $this->parent = null; } elseif ($key === 'ruleset') { // The columns array of \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet\AutoFilter objects $this->ruleset = []; foreach ($value as $k => $v) { $cloned = clone $v; $cloned->setParent($this); // attach the new cloned Rule to this new cloned Autofilter Cloned object $this->ruleset[$k] = $cloned; } } else { $this->$key = $value; } } } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/AutoFilter/Column/Rule.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/AutoFilter/Column/Rule.php
<?php namespace PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; use PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column; class Rule { const AUTOFILTER_RULETYPE_FILTER = 'filter'; const AUTOFILTER_RULETYPE_DATEGROUP = 'dateGroupItem'; const AUTOFILTER_RULETYPE_CUSTOMFILTER = 'customFilter'; const AUTOFILTER_RULETYPE_DYNAMICFILTER = 'dynamicFilter'; const AUTOFILTER_RULETYPE_TOPTENFILTER = 'top10Filter'; private const RULE_TYPES = [ // Currently we're not handling // colorFilter // extLst // iconFilter self::AUTOFILTER_RULETYPE_FILTER, self::AUTOFILTER_RULETYPE_DATEGROUP, self::AUTOFILTER_RULETYPE_CUSTOMFILTER, self::AUTOFILTER_RULETYPE_DYNAMICFILTER, self::AUTOFILTER_RULETYPE_TOPTENFILTER, ]; const AUTOFILTER_RULETYPE_DATEGROUP_YEAR = 'year'; const AUTOFILTER_RULETYPE_DATEGROUP_MONTH = 'month'; const AUTOFILTER_RULETYPE_DATEGROUP_DAY = 'day'; const AUTOFILTER_RULETYPE_DATEGROUP_HOUR = 'hour'; const AUTOFILTER_RULETYPE_DATEGROUP_MINUTE = 'minute'; const AUTOFILTER_RULETYPE_DATEGROUP_SECOND = 'second'; private const DATE_TIME_GROUPS = [ self::AUTOFILTER_RULETYPE_DATEGROUP_YEAR, self::AUTOFILTER_RULETYPE_DATEGROUP_MONTH, self::AUTOFILTER_RULETYPE_DATEGROUP_DAY, self::AUTOFILTER_RULETYPE_DATEGROUP_HOUR, self::AUTOFILTER_RULETYPE_DATEGROUP_MINUTE, self::AUTOFILTER_RULETYPE_DATEGROUP_SECOND, ]; const AUTOFILTER_RULETYPE_DYNAMIC_YESTERDAY = 'yesterday'; const AUTOFILTER_RULETYPE_DYNAMIC_TODAY = 'today'; const AUTOFILTER_RULETYPE_DYNAMIC_TOMORROW = 'tomorrow'; const AUTOFILTER_RULETYPE_DYNAMIC_YEARTODATE = 'yearToDate'; const AUTOFILTER_RULETYPE_DYNAMIC_THISYEAR = 'thisYear'; const AUTOFILTER_RULETYPE_DYNAMIC_THISQUARTER = 'thisQuarter'; const AUTOFILTER_RULETYPE_DYNAMIC_THISMONTH = 'thisMonth'; const AUTOFILTER_RULETYPE_DYNAMIC_THISWEEK = 'thisWeek'; const AUTOFILTER_RULETYPE_DYNAMIC_LASTYEAR = 'lastYear'; const AUTOFILTER_RULETYPE_DYNAMIC_LASTQUARTER = 'lastQuarter'; const AUTOFILTER_RULETYPE_DYNAMIC_LASTMONTH = 'lastMonth'; const AUTOFILTER_RULETYPE_DYNAMIC_LASTWEEK = 'lastWeek'; const AUTOFILTER_RULETYPE_DYNAMIC_NEXTYEAR = 'nextYear'; const AUTOFILTER_RULETYPE_DYNAMIC_NEXTQUARTER = 'nextQuarter'; const AUTOFILTER_RULETYPE_DYNAMIC_NEXTMONTH = 'nextMonth'; const AUTOFILTER_RULETYPE_DYNAMIC_NEXTWEEK = 'nextWeek'; const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_1 = 'M1'; const AUTOFILTER_RULETYPE_DYNAMIC_JANUARY = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_1; const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_2 = 'M2'; const AUTOFILTER_RULETYPE_DYNAMIC_FEBRUARY = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_2; const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_3 = 'M3'; const AUTOFILTER_RULETYPE_DYNAMIC_MARCH = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_3; const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_4 = 'M4'; const AUTOFILTER_RULETYPE_DYNAMIC_APRIL = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_4; const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_5 = 'M5'; const AUTOFILTER_RULETYPE_DYNAMIC_MAY = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_5; const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_6 = 'M6'; const AUTOFILTER_RULETYPE_DYNAMIC_JUNE = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_6; const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_7 = 'M7'; const AUTOFILTER_RULETYPE_DYNAMIC_JULY = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_7; const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_8 = 'M8'; const AUTOFILTER_RULETYPE_DYNAMIC_AUGUST = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_8; const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_9 = 'M9'; const AUTOFILTER_RULETYPE_DYNAMIC_SEPTEMBER = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_9; const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_10 = 'M10'; const AUTOFILTER_RULETYPE_DYNAMIC_OCTOBER = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_10; const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_11 = 'M11'; const AUTOFILTER_RULETYPE_DYNAMIC_NOVEMBER = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_11; const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_12 = 'M12'; const AUTOFILTER_RULETYPE_DYNAMIC_DECEMBER = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_12; const AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_1 = 'Q1'; const AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_2 = 'Q2'; const AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_3 = 'Q3'; const AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_4 = 'Q4'; const AUTOFILTER_RULETYPE_DYNAMIC_ABOVEAVERAGE = 'aboveAverage'; const AUTOFILTER_RULETYPE_DYNAMIC_BELOWAVERAGE = 'belowAverage'; private const DYNAMIC_TYPES = [ self::AUTOFILTER_RULETYPE_DYNAMIC_YESTERDAY, self::AUTOFILTER_RULETYPE_DYNAMIC_TODAY, self::AUTOFILTER_RULETYPE_DYNAMIC_TOMORROW, self::AUTOFILTER_RULETYPE_DYNAMIC_YEARTODATE, self::AUTOFILTER_RULETYPE_DYNAMIC_THISYEAR, self::AUTOFILTER_RULETYPE_DYNAMIC_THISQUARTER, self::AUTOFILTER_RULETYPE_DYNAMIC_THISMONTH, self::AUTOFILTER_RULETYPE_DYNAMIC_THISWEEK, self::AUTOFILTER_RULETYPE_DYNAMIC_LASTYEAR, self::AUTOFILTER_RULETYPE_DYNAMIC_LASTQUARTER, self::AUTOFILTER_RULETYPE_DYNAMIC_LASTMONTH, self::AUTOFILTER_RULETYPE_DYNAMIC_LASTWEEK, self::AUTOFILTER_RULETYPE_DYNAMIC_NEXTYEAR, self::AUTOFILTER_RULETYPE_DYNAMIC_NEXTQUARTER, self::AUTOFILTER_RULETYPE_DYNAMIC_NEXTMONTH, self::AUTOFILTER_RULETYPE_DYNAMIC_NEXTWEEK, self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_1, self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_2, self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_3, self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_4, self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_5, self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_6, self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_7, self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_8, self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_9, self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_10, self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_11, self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_12, self::AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_1, self::AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_2, self::AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_3, self::AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_4, self::AUTOFILTER_RULETYPE_DYNAMIC_ABOVEAVERAGE, self::AUTOFILTER_RULETYPE_DYNAMIC_BELOWAVERAGE, ]; // Filter rule operators for filter and customFilter types. const AUTOFILTER_COLUMN_RULE_EQUAL = 'equal'; const AUTOFILTER_COLUMN_RULE_NOTEQUAL = 'notEqual'; const AUTOFILTER_COLUMN_RULE_GREATERTHAN = 'greaterThan'; const AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL = 'greaterThanOrEqual'; const AUTOFILTER_COLUMN_RULE_LESSTHAN = 'lessThan'; const AUTOFILTER_COLUMN_RULE_LESSTHANOREQUAL = 'lessThanOrEqual'; private const OPERATORS = [ self::AUTOFILTER_COLUMN_RULE_EQUAL, self::AUTOFILTER_COLUMN_RULE_NOTEQUAL, self::AUTOFILTER_COLUMN_RULE_GREATERTHAN, self::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL, self::AUTOFILTER_COLUMN_RULE_LESSTHAN, self::AUTOFILTER_COLUMN_RULE_LESSTHANOREQUAL, ]; const AUTOFILTER_COLUMN_RULE_TOPTEN_BY_VALUE = 'byValue'; const AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT = 'byPercent'; private const TOP_TEN_VALUE = [ self::AUTOFILTER_COLUMN_RULE_TOPTEN_BY_VALUE, self::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT, ]; const AUTOFILTER_COLUMN_RULE_TOPTEN_TOP = 'top'; const AUTOFILTER_COLUMN_RULE_TOPTEN_BOTTOM = 'bottom'; private const TOP_TEN_TYPE = [ self::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP, self::AUTOFILTER_COLUMN_RULE_TOPTEN_BOTTOM, ]; // Unimplented Rule Operators (Numeric, Boolean etc) // const AUTOFILTER_COLUMN_RULE_BETWEEN = 'between'; // greaterThanOrEqual 1 && lessThanOrEqual 2 // Rule Operators (Numeric Special) which are translated to standard numeric operators with calculated values // Rule Operators (String) which are set as wild-carded values // const AUTOFILTER_COLUMN_RULE_BEGINSWITH = 'beginsWith'; // A* // const AUTOFILTER_COLUMN_RULE_ENDSWITH = 'endsWith'; // *Z // const AUTOFILTER_COLUMN_RULE_CONTAINS = 'contains'; // *B* // const AUTOFILTER_COLUMN_RULE_DOESNTCONTAIN = 'notEqual'; // notEqual *B* // Rule Operators (Date Special) which are translated to standard numeric operators with calculated values // const AUTOFILTER_COLUMN_RULE_BEFORE = 'lessThan'; // const AUTOFILTER_COLUMN_RULE_AFTER = 'greaterThan'; /** * Autofilter Column. * * @var ?Column */ private $parent; /** * Autofilter Rule Type. * * @var string */ private $ruleType = self::AUTOFILTER_RULETYPE_FILTER; /** * Autofilter Rule Value. * * @var int|int[]|string|string[] */ private $value = ''; /** * Autofilter Rule Operator. * * @var string */ private $operator = self::AUTOFILTER_COLUMN_RULE_EQUAL; /** * DateTimeGrouping Group Value. * * @var string */ private $grouping = ''; /** * Create a new Rule. */ public function __construct(?Column $parent = null) { $this->parent = $parent; } /** * Get AutoFilter Rule Type. * * @return string */ public function getRuleType() { return $this->ruleType; } /** * Set AutoFilter Rule Type. * * @param string $ruleType see self::AUTOFILTER_RULETYPE_* * * @return $this */ public function setRuleType($ruleType) { if (!in_array($ruleType, self::RULE_TYPES)) { throw new PhpSpreadsheetException('Invalid rule type for column AutoFilter Rule.'); } $this->ruleType = $ruleType; return $this; } /** * Get AutoFilter Rule Value. * * @return int|int[]|string|string[] */ public function getValue() { return $this->value; } /** * Set AutoFilter Rule Value. * * @param int|int[]|string|string[] $value * * @return $this */ public function setValue($value) { if (is_array($value)) { $grouping = -1; foreach ($value as $key => $v) { // Validate array entries if (!in_array($key, self::DATE_TIME_GROUPS)) { // Remove any invalid entries from the value array unset($value[$key]); } else { // Work out what the dateTime grouping will be $grouping = max($grouping, array_search($key, self::DATE_TIME_GROUPS)); } } if (count($value) == 0) { throw new PhpSpreadsheetException('Invalid rule value for column AutoFilter Rule.'); } // Set the dateTime grouping that we've anticipated $this->setGrouping(self::DATE_TIME_GROUPS[$grouping]); } $this->value = $value; return $this; } /** * Get AutoFilter Rule Operator. * * @return string */ public function getOperator() { return $this->operator; } /** * Set AutoFilter Rule Operator. * * @param string $operator see self::AUTOFILTER_COLUMN_RULE_* * * @return $this */ public function setOperator($operator) { if (empty($operator)) { $operator = self::AUTOFILTER_COLUMN_RULE_EQUAL; } if ( (!in_array($operator, self::OPERATORS)) && (!in_array($operator, self::TOP_TEN_VALUE)) ) { throw new PhpSpreadsheetException('Invalid operator for column AutoFilter Rule.'); } $this->operator = $operator; return $this; } /** * Get AutoFilter Rule Grouping. * * @return string */ public function getGrouping() { return $this->grouping; } /** * Set AutoFilter Rule Grouping. * * @param string $grouping * * @return $this */ public function setGrouping($grouping) { if ( ($grouping !== null) && (!in_array($grouping, self::DATE_TIME_GROUPS)) && (!in_array($grouping, self::DYNAMIC_TYPES)) && (!in_array($grouping, self::TOP_TEN_TYPE)) ) { throw new PhpSpreadsheetException('Invalid grouping for column AutoFilter Rule.'); } $this->grouping = $grouping; return $this; } /** * Set AutoFilter Rule. * * @param string $operator see self::AUTOFILTER_COLUMN_RULE_* * @param int|int[]|string|string[] $value * @param string $grouping * * @return $this */ public function setRule($operator, $value, $grouping = null) { $this->setOperator($operator); $this->setValue($value); // Only set grouping if it's been passed in as a user-supplied argument, // otherwise we're calculating it when we setValue() and don't want to overwrite that // If the user supplies an argumnet for grouping, then on their own head be it if ($grouping !== null) { $this->setGrouping($grouping); } return $this; } /** * Get this Rule's AutoFilter Column Parent. * * @return ?Column */ public function getParent() { return $this->parent; } /** * Set this Rule's AutoFilter Column Parent. * * @return $this */ public function setParent(?Column $parent = null) { $this->parent = $parent; return $this; } /** * 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)) { if ($key == 'parent') { // this is only object // Detach from autofilter column parent $this->$key = null; } } else { $this->$key = $value; } } } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Drawing/Shadow.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Drawing/Shadow.php
<?php namespace PhpOffice\PhpSpreadsheet\Worksheet\Drawing; use PhpOffice\PhpSpreadsheet\IComparable; use PhpOffice\PhpSpreadsheet\Style\Color; class Shadow implements IComparable { // Shadow alignment const SHADOW_BOTTOM = 'b'; const SHADOW_BOTTOM_LEFT = 'bl'; const SHADOW_BOTTOM_RIGHT = 'br'; const SHADOW_CENTER = 'ctr'; const SHADOW_LEFT = 'l'; const SHADOW_TOP = 't'; const SHADOW_TOP_LEFT = 'tl'; const SHADOW_TOP_RIGHT = 'tr'; /** * Visible. * * @var bool */ private $visible; /** * Blur radius. * * Defaults to 6 * * @var int */ private $blurRadius; /** * Shadow distance. * * Defaults to 2 * * @var int */ private $distance; /** * Shadow direction (in degrees). * * @var int */ private $direction; /** * Shadow alignment. * * @var string */ private $alignment; /** * Color. * * @var Color */ private $color; /** * Alpha. * * @var int */ private $alpha; /** * Create a new Shadow. */ public function __construct() { // Initialise values $this->visible = false; $this->blurRadius = 6; $this->distance = 2; $this->direction = 0; $this->alignment = self::SHADOW_BOTTOM_RIGHT; $this->color = new Color(Color::COLOR_BLACK); $this->alpha = 50; } /** * Get Visible. * * @return bool */ public function getVisible() { return $this->visible; } /** * Set Visible. * * @param bool $visible * * @return $this */ public function setVisible($visible) { $this->visible = $visible; return $this; } /** * Get Blur radius. * * @return int */ public function getBlurRadius() { return $this->blurRadius; } /** * Set Blur radius. * * @param int $blurRadius * * @return $this */ public function setBlurRadius($blurRadius) { $this->blurRadius = $blurRadius; return $this; } /** * Get Shadow distance. * * @return int */ public function getDistance() { return $this->distance; } /** * Set Shadow distance. * * @param int $distance * * @return $this */ public function setDistance($distance) { $this->distance = $distance; return $this; } /** * Get Shadow direction (in degrees). * * @return int */ public function getDirection() { return $this->direction; } /** * Set Shadow direction (in degrees). * * @param int $direction * * @return $this */ public function setDirection($direction) { $this->direction = $direction; return $this; } /** * Get Shadow alignment. * * @return string */ public function getAlignment() { return $this->alignment; } /** * Set Shadow alignment. * * @param string $alignment * * @return $this */ public function setAlignment($alignment) { $this->alignment = $alignment; return $this; } /** * Get Color. * * @return Color */ public function getColor() { return $this->color; } /** * Set Color. * * @return $this */ public function setColor(?Color $color = null) { $this->color = $color; return $this; } /** * Get Alpha. * * @return int */ public function getAlpha() { return $this->alpha; } /** * Set Alpha. * * @param int $alpha * * @return $this */ public function setAlpha($alpha) { $this->alpha = $alpha; return $this; } /** * Get hash code. * * @return string Hash code */ public function getHashCode() { return md5( ($this->visible ? 't' : 'f') . $this->blurRadius . $this->distance . $this->direction . $this->alignment . $this->color->getHashCode() . $this->alpha . __CLASS__ ); } /** * 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)) { $this->$key = clone $value; } else { $this->$key = $value; } } } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Helper/Dimension.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Helper/Dimension.php
<?php namespace PhpOffice\PhpSpreadsheet\Helper; use PhpOffice\PhpSpreadsheet\Exception; use PhpOffice\PhpSpreadsheet\Shared\Drawing; use PhpOffice\PhpSpreadsheet\Style\Font; class Dimension { public const UOM_CENTIMETERS = 'cm'; public const UOM_MILLIMETERS = 'mm'; public const UOM_INCHES = 'in'; public const UOM_PIXELS = 'px'; public const UOM_POINTS = 'pt'; public const UOM_PICA = 'pc'; /** * Based on 96 dpi. */ const ABSOLUTE_UNITS = [ self::UOM_CENTIMETERS => 96.0 / 2.54, self::UOM_MILLIMETERS => 96.0 / 25.4, self::UOM_INCHES => 96.0, self::UOM_PIXELS => 1.0, self::UOM_POINTS => 96.0 / 72, self::UOM_PICA => 96.0 * 12 / 72, ]; /** * Based on a standard column width of 8.54 units in MS Excel. */ const RELATIVE_UNITS = [ 'em' => 10.0 / 8.54, 'ex' => 10.0 / 8.54, 'ch' => 10.0 / 8.54, 'rem' => 10.0 / 8.54, 'vw' => 8.54, 'vh' => 8.54, 'vmin' => 8.54, 'vmax' => 8.54, '%' => 8.54 / 100, ]; /** * @var float|int If this is a width, then size is measured in pixels (if is set) * or in Excel's default column width units if $unit is null. * If this is a height, then size is measured in pixels () * or in points () if $unit is null. */ protected $size; /** * @var null|string */ protected $unit; public function __construct(string $dimension) { [$size, $unit] = sscanf($dimension, '%[1234567890.]%s'); $unit = strtolower(trim($unit)); // If a UoM is specified, then convert the size to pixels for internal storage if (isset(self::ABSOLUTE_UNITS[$unit])) { $size *= self::ABSOLUTE_UNITS[$unit]; $this->unit = self::UOM_PIXELS; } elseif (isset(self::RELATIVE_UNITS[$unit])) { $size *= self::RELATIVE_UNITS[$unit]; $size = round($size, 4); } $this->size = $size; } public function width(): float { return (float) ($this->unit === null) ? $this->size : round(Drawing::pixelsToCellDimension((int) $this->size, new Font(false)), 4); } public function height(): float { return (float) ($this->unit === null) ? $this->size : $this->toUnit(self::UOM_POINTS); } public function toUnit(string $unitOfMeasure): float { $unitOfMeasure = strtolower($unitOfMeasure); if (!array_key_exists($unitOfMeasure, self::ABSOLUTE_UNITS)) { throw new Exception("{$unitOfMeasure} is not a vaid unit of measure"); } $size = $this->size; if ($this->unit === null) { $size = Drawing::cellDimensionToPixels($size, new Font(false)); } return $size / self::ABSOLUTE_UNITS[$unitOfMeasure]; } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Helper/Size.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Helper/Size.php
<?php namespace PhpOffice\PhpSpreadsheet\Helper; class Size { const REGEXP_SIZE_VALIDATION = '/^(?P<size>\d*\.?\d+)(?P<unit>pt|px|em)?$/i'; /** * @var bool */ protected $valid; /** * @var string */ protected $size = ''; /** * @var string */ protected $unit = ''; public function __construct(string $size) { $this->valid = (bool) preg_match(self::REGEXP_SIZE_VALIDATION, $size, $matches); if ($this->valid) { $this->size = $matches['size']; $this->unit = $matches['unit'] ?? 'pt'; } } public function valid(): bool { return $this->valid; } public function size(): string { return $this->size; } public function unit(): string { return $this->unit; } public function __toString() { return $this->size . $this->unit; } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Helper/Sample.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Helper/Sample.php
<?php namespace PhpOffice\PhpSpreadsheet\Helper; use PhpOffice\PhpSpreadsheet\IOFactory; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Writer\IWriter; use RecursiveDirectoryIterator; use RecursiveIteratorIterator; use RecursiveRegexIterator; use ReflectionClass; use RegexIterator; use RuntimeException; /** * Helper class to be used in sample code. */ class Sample { /** * Returns whether we run on CLI or browser. * * @return bool */ public function isCli() { return PHP_SAPI === 'cli'; } /** * Return the filename currently being executed. * * @return string */ public function getScriptFilename() { return basename($_SERVER['SCRIPT_FILENAME'], '.php'); } /** * Whether we are executing the index page. * * @return bool */ public function isIndex() { return $this->getScriptFilename() === 'index'; } /** * Return the page title. * * @return string */ public function getPageTitle() { return $this->isIndex() ? 'PHPSpreadsheet' : $this->getScriptFilename(); } /** * Return the page heading. * * @return string */ public function getPageHeading() { return $this->isIndex() ? '' : '<h1>' . str_replace('_', ' ', $this->getScriptFilename()) . '</h1>'; } /** * Returns an array of all known samples. * * @return string[][] [$name => $path] */ public function getSamples() { // Populate samples $baseDir = realpath(__DIR__ . '/../../../samples'); $directory = new RecursiveDirectoryIterator($baseDir); $iterator = new RecursiveIteratorIterator($directory); $regex = new RegexIterator($iterator, '/^.+\.php$/', RecursiveRegexIterator::GET_MATCH); $files = []; foreach ($regex as $file) { $file = str_replace(str_replace('\\', '/', $baseDir) . '/', '', str_replace('\\', '/', $file[0])); $info = pathinfo($file); $category = str_replace('_', ' ', $info['dirname']); $name = str_replace('_', ' ', preg_replace('/(|\.php)/', '', $info['filename'])); if (!in_array($category, ['.', 'boostrap', 'templates'])) { if (!isset($files[$category])) { $files[$category] = []; } $files[$category][$name] = $file; } } // Sort everything ksort($files); foreach ($files as &$f) { asort($f); } return $files; } /** * Write documents. * * @param string $filename * @param string[] $writers */ public function write(Spreadsheet $spreadsheet, $filename, array $writers = ['Xlsx', 'Xls']): void { // Set active sheet index to the first sheet, so Excel opens this as the first sheet $spreadsheet->setActiveSheetIndex(0); // Write documents foreach ($writers as $writerType) { $path = $this->getFilename($filename, mb_strtolower($writerType)); $writer = IOFactory::createWriter($spreadsheet, $writerType); $callStartTime = microtime(true); $writer->save($path); $this->logWrite($writer, $path, $callStartTime); } $this->logEndingNotes(); } protected function isDirOrMkdir(string $folder): bool { return \is_dir($folder) || \mkdir($folder); } /** * Returns the temporary directory and make sure it exists. * * @return string */ private function getTemporaryFolder() { $tempFolder = sys_get_temp_dir() . '/phpspreadsheet'; if (!$this->isDirOrMkdir($tempFolder)) { throw new RuntimeException(sprintf('Directory "%s" was not created', $tempFolder)); } return $tempFolder; } /** * Returns the filename that should be used for sample output. * * @param string $filename * @param string $extension * * @return string */ public function getFilename($filename, $extension = 'xlsx') { $originalExtension = pathinfo($filename, PATHINFO_EXTENSION); return $this->getTemporaryFolder() . '/' . str_replace('.' . $originalExtension, '.' . $extension, basename($filename)); } /** * Return a random temporary file name. * * @param string $extension * * @return string */ public function getTemporaryFilename($extension = 'xlsx') { $temporaryFilename = tempnam($this->getTemporaryFolder(), 'phpspreadsheet-'); unlink($temporaryFilename); return $temporaryFilename . '.' . $extension; } public function log($message): void { $eol = $this->isCli() ? PHP_EOL : '<br />'; echo date('H:i:s ') . $message . $eol; } /** * Log ending notes. */ public function logEndingNotes(): void { // Do not show execution time for index $this->log('Peak memory usage: ' . (memory_get_peak_usage(true) / 1024 / 1024) . 'MB'); } /** * Log a line about the write operation. * * @param string $path * @param float $callStartTime */ public function logWrite(IWriter $writer, $path, $callStartTime): void { $callEndTime = microtime(true); $callTime = $callEndTime - $callStartTime; $reflection = new ReflectionClass($writer); $format = $reflection->getShortName(); $message = "Write {$format} format to <code>{$path}</code> in " . sprintf('%.4f', $callTime) . ' seconds'; $this->log($message); } /** * Log a line about the read operation. * * @param string $format * @param string $path * @param float $callStartTime */ public function logRead($format, $path, $callStartTime): void { $callEndTime = microtime(true); $callTime = $callEndTime - $callStartTime; $message = "Read {$format} format from <code>{$path}</code> in " . sprintf('%.4f', $callTime) . ' seconds'; $this->log($message); } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Helper/Html.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Helper/Html.php
<?php namespace PhpOffice\PhpSpreadsheet\Helper; use DOMDocument; use DOMElement; use DOMNode; use DOMText; use PhpOffice\PhpSpreadsheet\RichText\RichText; use PhpOffice\PhpSpreadsheet\Style\Color; use PhpOffice\PhpSpreadsheet\Style\Font; class Html { protected static $colourMap = [ 'aliceblue' => 'f0f8ff', 'antiquewhite' => 'faebd7', 'antiquewhite1' => 'ffefdb', 'antiquewhite2' => 'eedfcc', 'antiquewhite3' => 'cdc0b0', 'antiquewhite4' => '8b8378', 'aqua' => '00ffff', 'aquamarine1' => '7fffd4', 'aquamarine2' => '76eec6', 'aquamarine4' => '458b74', 'azure1' => 'f0ffff', 'azure2' => 'e0eeee', 'azure3' => 'c1cdcd', 'azure4' => '838b8b', 'beige' => 'f5f5dc', 'bisque1' => 'ffe4c4', 'bisque2' => 'eed5b7', 'bisque3' => 'cdb79e', 'bisque4' => '8b7d6b', 'black' => '000000', 'blanchedalmond' => 'ffebcd', 'blue' => '0000ff', 'blue1' => '0000ff', 'blue2' => '0000ee', 'blue4' => '00008b', 'blueviolet' => '8a2be2', 'brown' => 'a52a2a', 'brown1' => 'ff4040', 'brown2' => 'ee3b3b', 'brown3' => 'cd3333', 'brown4' => '8b2323', 'burlywood' => 'deb887', 'burlywood1' => 'ffd39b', 'burlywood2' => 'eec591', 'burlywood3' => 'cdaa7d', 'burlywood4' => '8b7355', 'cadetblue' => '5f9ea0', 'cadetblue1' => '98f5ff', 'cadetblue2' => '8ee5ee', 'cadetblue3' => '7ac5cd', 'cadetblue4' => '53868b', 'chartreuse1' => '7fff00', 'chartreuse2' => '76ee00', 'chartreuse3' => '66cd00', 'chartreuse4' => '458b00', 'chocolate' => 'd2691e', 'chocolate1' => 'ff7f24', 'chocolate2' => 'ee7621', 'chocolate3' => 'cd661d', 'coral' => 'ff7f50', 'coral1' => 'ff7256', 'coral2' => 'ee6a50', 'coral3' => 'cd5b45', 'coral4' => '8b3e2f', 'cornflowerblue' => '6495ed', 'cornsilk1' => 'fff8dc', 'cornsilk2' => 'eee8cd', 'cornsilk3' => 'cdc8b1', 'cornsilk4' => '8b8878', 'cyan1' => '00ffff', 'cyan2' => '00eeee', 'cyan3' => '00cdcd', 'cyan4' => '008b8b', 'darkgoldenrod' => 'b8860b', 'darkgoldenrod1' => 'ffb90f', 'darkgoldenrod2' => 'eead0e', 'darkgoldenrod3' => 'cd950c', 'darkgoldenrod4' => '8b6508', 'darkgreen' => '006400', 'darkkhaki' => 'bdb76b', 'darkolivegreen' => '556b2f', 'darkolivegreen1' => 'caff70', 'darkolivegreen2' => 'bcee68', 'darkolivegreen3' => 'a2cd5a', 'darkolivegreen4' => '6e8b3d', 'darkorange' => 'ff8c00', 'darkorange1' => 'ff7f00', 'darkorange2' => 'ee7600', 'darkorange3' => 'cd6600', 'darkorange4' => '8b4500', 'darkorchid' => '9932cc', 'darkorchid1' => 'bf3eff', 'darkorchid2' => 'b23aee', 'darkorchid3' => '9a32cd', 'darkorchid4' => '68228b', 'darksalmon' => 'e9967a', 'darkseagreen' => '8fbc8f', 'darkseagreen1' => 'c1ffc1', 'darkseagreen2' => 'b4eeb4', 'darkseagreen3' => '9bcd9b', 'darkseagreen4' => '698b69', 'darkslateblue' => '483d8b', 'darkslategray' => '2f4f4f', 'darkslategray1' => '97ffff', 'darkslategray2' => '8deeee', 'darkslategray3' => '79cdcd', 'darkslategray4' => '528b8b', 'darkturquoise' => '00ced1', 'darkviolet' => '9400d3', 'deeppink1' => 'ff1493', 'deeppink2' => 'ee1289', 'deeppink3' => 'cd1076', 'deeppink4' => '8b0a50', 'deepskyblue1' => '00bfff', 'deepskyblue2' => '00b2ee', 'deepskyblue3' => '009acd', 'deepskyblue4' => '00688b', 'dimgray' => '696969', 'dodgerblue1' => '1e90ff', 'dodgerblue2' => '1c86ee', 'dodgerblue3' => '1874cd', 'dodgerblue4' => '104e8b', 'firebrick' => 'b22222', 'firebrick1' => 'ff3030', 'firebrick2' => 'ee2c2c', 'firebrick3' => 'cd2626', 'firebrick4' => '8b1a1a', 'floralwhite' => 'fffaf0', 'forestgreen' => '228b22', 'fuchsia' => 'ff00ff', 'gainsboro' => 'dcdcdc', 'ghostwhite' => 'f8f8ff', 'gold1' => 'ffd700', 'gold2' => 'eec900', 'gold3' => 'cdad00', 'gold4' => '8b7500', 'goldenrod' => 'daa520', 'goldenrod1' => 'ffc125', 'goldenrod2' => 'eeb422', 'goldenrod3' => 'cd9b1d', 'goldenrod4' => '8b6914', 'gray' => 'bebebe', 'gray1' => '030303', 'gray10' => '1a1a1a', 'gray11' => '1c1c1c', 'gray12' => '1f1f1f', 'gray13' => '212121', 'gray14' => '242424', 'gray15' => '262626', 'gray16' => '292929', 'gray17' => '2b2b2b', 'gray18' => '2e2e2e', 'gray19' => '303030', 'gray2' => '050505', 'gray20' => '333333', 'gray21' => '363636', 'gray22' => '383838', 'gray23' => '3b3b3b', 'gray24' => '3d3d3d', 'gray25' => '404040', 'gray26' => '424242', 'gray27' => '454545', 'gray28' => '474747', 'gray29' => '4a4a4a', 'gray3' => '080808', 'gray30' => '4d4d4d', 'gray31' => '4f4f4f', 'gray32' => '525252', 'gray33' => '545454', 'gray34' => '575757', 'gray35' => '595959', 'gray36' => '5c5c5c', 'gray37' => '5e5e5e', 'gray38' => '616161', 'gray39' => '636363', 'gray4' => '0a0a0a', 'gray40' => '666666', 'gray41' => '696969', 'gray42' => '6b6b6b', 'gray43' => '6e6e6e', 'gray44' => '707070', 'gray45' => '737373', 'gray46' => '757575', 'gray47' => '787878', 'gray48' => '7a7a7a', 'gray49' => '7d7d7d', 'gray5' => '0d0d0d', 'gray50' => '7f7f7f', 'gray51' => '828282', 'gray52' => '858585', 'gray53' => '878787', 'gray54' => '8a8a8a', 'gray55' => '8c8c8c', 'gray56' => '8f8f8f', 'gray57' => '919191', 'gray58' => '949494', 'gray59' => '969696', 'gray6' => '0f0f0f', 'gray60' => '999999', 'gray61' => '9c9c9c', 'gray62' => '9e9e9e', 'gray63' => 'a1a1a1', 'gray64' => 'a3a3a3', 'gray65' => 'a6a6a6', 'gray66' => 'a8a8a8', 'gray67' => 'ababab', 'gray68' => 'adadad', 'gray69' => 'b0b0b0', 'gray7' => '121212', 'gray70' => 'b3b3b3', 'gray71' => 'b5b5b5', 'gray72' => 'b8b8b8', 'gray73' => 'bababa', 'gray74' => 'bdbdbd', 'gray75' => 'bfbfbf', 'gray76' => 'c2c2c2', 'gray77' => 'c4c4c4', 'gray78' => 'c7c7c7', 'gray79' => 'c9c9c9', 'gray8' => '141414', 'gray80' => 'cccccc', 'gray81' => 'cfcfcf', 'gray82' => 'd1d1d1', 'gray83' => 'd4d4d4', 'gray84' => 'd6d6d6', 'gray85' => 'd9d9d9', 'gray86' => 'dbdbdb', 'gray87' => 'dedede', 'gray88' => 'e0e0e0', 'gray89' => 'e3e3e3', 'gray9' => '171717', 'gray90' => 'e5e5e5', 'gray91' => 'e8e8e8', 'gray92' => 'ebebeb', 'gray93' => 'ededed', 'gray94' => 'f0f0f0', 'gray95' => 'f2f2f2', 'gray97' => 'f7f7f7', 'gray98' => 'fafafa', 'gray99' => 'fcfcfc', 'green' => '00ff00', 'green1' => '00ff00', 'green2' => '00ee00', 'green3' => '00cd00', 'green4' => '008b00', 'greenyellow' => 'adff2f', 'honeydew1' => 'f0fff0', 'honeydew2' => 'e0eee0', 'honeydew3' => 'c1cdc1', 'honeydew4' => '838b83', 'hotpink' => 'ff69b4', 'hotpink1' => 'ff6eb4', 'hotpink2' => 'ee6aa7', 'hotpink3' => 'cd6090', 'hotpink4' => '8b3a62', 'indianred' => 'cd5c5c', 'indianred1' => 'ff6a6a', 'indianred2' => 'ee6363', 'indianred3' => 'cd5555', 'indianred4' => '8b3a3a', 'ivory1' => 'fffff0', 'ivory2' => 'eeeee0', 'ivory3' => 'cdcdc1', 'ivory4' => '8b8b83', 'khaki' => 'f0e68c', 'khaki1' => 'fff68f', 'khaki2' => 'eee685', 'khaki3' => 'cdc673', 'khaki4' => '8b864e', 'lavender' => 'e6e6fa', 'lavenderblush1' => 'fff0f5', 'lavenderblush2' => 'eee0e5', 'lavenderblush3' => 'cdc1c5', 'lavenderblush4' => '8b8386', 'lawngreen' => '7cfc00', 'lemonchiffon1' => 'fffacd', 'lemonchiffon2' => 'eee9bf', 'lemonchiffon3' => 'cdc9a5', 'lemonchiffon4' => '8b8970', 'light' => 'eedd82', 'lightblue' => 'add8e6', 'lightblue1' => 'bfefff', 'lightblue2' => 'b2dfee', 'lightblue3' => '9ac0cd', 'lightblue4' => '68838b', 'lightcoral' => 'f08080', 'lightcyan1' => 'e0ffff', 'lightcyan2' => 'd1eeee', 'lightcyan3' => 'b4cdcd', 'lightcyan4' => '7a8b8b', 'lightgoldenrod1' => 'ffec8b', 'lightgoldenrod2' => 'eedc82', 'lightgoldenrod3' => 'cdbe70', 'lightgoldenrod4' => '8b814c', 'lightgoldenrodyellow' => 'fafad2', 'lightgray' => 'd3d3d3', 'lightpink' => 'ffb6c1', 'lightpink1' => 'ffaeb9', 'lightpink2' => 'eea2ad', 'lightpink3' => 'cd8c95', 'lightpink4' => '8b5f65', 'lightsalmon1' => 'ffa07a', 'lightsalmon2' => 'ee9572', 'lightsalmon3' => 'cd8162', 'lightsalmon4' => '8b5742', 'lightseagreen' => '20b2aa', 'lightskyblue' => '87cefa', 'lightskyblue1' => 'b0e2ff', 'lightskyblue2' => 'a4d3ee', 'lightskyblue3' => '8db6cd', 'lightskyblue4' => '607b8b', 'lightslateblue' => '8470ff', 'lightslategray' => '778899', 'lightsteelblue' => 'b0c4de', 'lightsteelblue1' => 'cae1ff', 'lightsteelblue2' => 'bcd2ee', 'lightsteelblue3' => 'a2b5cd', 'lightsteelblue4' => '6e7b8b', 'lightyellow1' => 'ffffe0', 'lightyellow2' => 'eeeed1', 'lightyellow3' => 'cdcdb4', 'lightyellow4' => '8b8b7a', 'lime' => '00ff00', 'limegreen' => '32cd32', 'linen' => 'faf0e6', 'magenta' => 'ff00ff', 'magenta2' => 'ee00ee', 'magenta3' => 'cd00cd', 'magenta4' => '8b008b', 'maroon' => 'b03060', 'maroon1' => 'ff34b3', 'maroon2' => 'ee30a7', 'maroon3' => 'cd2990', 'maroon4' => '8b1c62', 'medium' => '66cdaa', 'mediumaquamarine' => '66cdaa', 'mediumblue' => '0000cd', 'mediumorchid' => 'ba55d3', 'mediumorchid1' => 'e066ff', 'mediumorchid2' => 'd15fee', 'mediumorchid3' => 'b452cd', 'mediumorchid4' => '7a378b', 'mediumpurple' => '9370db', 'mediumpurple1' => 'ab82ff', 'mediumpurple2' => '9f79ee', 'mediumpurple3' => '8968cd', 'mediumpurple4' => '5d478b', 'mediumseagreen' => '3cb371', 'mediumslateblue' => '7b68ee', 'mediumspringgreen' => '00fa9a', 'mediumturquoise' => '48d1cc', 'mediumvioletred' => 'c71585', 'midnightblue' => '191970', 'mintcream' => 'f5fffa', 'mistyrose1' => 'ffe4e1', 'mistyrose2' => 'eed5d2', 'mistyrose3' => 'cdb7b5', 'mistyrose4' => '8b7d7b', 'moccasin' => 'ffe4b5', 'navajowhite1' => 'ffdead', 'navajowhite2' => 'eecfa1', 'navajowhite3' => 'cdb38b', 'navajowhite4' => '8b795e', 'navy' => '000080', 'navyblue' => '000080', 'oldlace' => 'fdf5e6', 'olive' => '808000', 'olivedrab' => '6b8e23', 'olivedrab1' => 'c0ff3e', 'olivedrab2' => 'b3ee3a', 'olivedrab4' => '698b22', 'orange' => 'ffa500', 'orange1' => 'ffa500', 'orange2' => 'ee9a00', 'orange3' => 'cd8500', 'orange4' => '8b5a00', 'orangered1' => 'ff4500', 'orangered2' => 'ee4000', 'orangered3' => 'cd3700', 'orangered4' => '8b2500', 'orchid' => 'da70d6', 'orchid1' => 'ff83fa', 'orchid2' => 'ee7ae9', 'orchid3' => 'cd69c9', 'orchid4' => '8b4789', 'pale' => 'db7093', 'palegoldenrod' => 'eee8aa', 'palegreen' => '98fb98', 'palegreen1' => '9aff9a', 'palegreen2' => '90ee90', 'palegreen3' => '7ccd7c', 'palegreen4' => '548b54', 'paleturquoise' => 'afeeee', 'paleturquoise1' => 'bbffff', 'paleturquoise2' => 'aeeeee', 'paleturquoise3' => '96cdcd', 'paleturquoise4' => '668b8b', 'palevioletred' => 'db7093', 'palevioletred1' => 'ff82ab', 'palevioletred2' => 'ee799f', 'palevioletred3' => 'cd6889', 'palevioletred4' => '8b475d', 'papayawhip' => 'ffefd5', 'peachpuff1' => 'ffdab9', 'peachpuff2' => 'eecbad', 'peachpuff3' => 'cdaf95', 'peachpuff4' => '8b7765', 'pink' => 'ffc0cb', 'pink1' => 'ffb5c5', 'pink2' => 'eea9b8', 'pink3' => 'cd919e', 'pink4' => '8b636c', 'plum' => 'dda0dd', 'plum1' => 'ffbbff', 'plum2' => 'eeaeee', 'plum3' => 'cd96cd', 'plum4' => '8b668b', 'powderblue' => 'b0e0e6', 'purple' => 'a020f0', 'rebeccapurple' => '663399', 'purple1' => '9b30ff', 'purple2' => '912cee', 'purple3' => '7d26cd', 'purple4' => '551a8b', 'red' => 'ff0000', 'red1' => 'ff0000', 'red2' => 'ee0000', 'red3' => 'cd0000', 'red4' => '8b0000', 'rosybrown' => 'bc8f8f', 'rosybrown1' => 'ffc1c1', 'rosybrown2' => 'eeb4b4', 'rosybrown3' => 'cd9b9b', 'rosybrown4' => '8b6969', 'royalblue' => '4169e1', 'royalblue1' => '4876ff', 'royalblue2' => '436eee', 'royalblue3' => '3a5fcd', 'royalblue4' => '27408b', 'saddlebrown' => '8b4513', 'salmon' => 'fa8072', 'salmon1' => 'ff8c69', 'salmon2' => 'ee8262', 'salmon3' => 'cd7054', 'salmon4' => '8b4c39', 'sandybrown' => 'f4a460', 'seagreen1' => '54ff9f', 'seagreen2' => '4eee94', 'seagreen3' => '43cd80', 'seagreen4' => '2e8b57', 'seashell1' => 'fff5ee', 'seashell2' => 'eee5de', 'seashell3' => 'cdc5bf', 'seashell4' => '8b8682', 'sienna' => 'a0522d', 'sienna1' => 'ff8247', 'sienna2' => 'ee7942', 'sienna3' => 'cd6839', 'sienna4' => '8b4726', 'silver' => 'c0c0c0', 'skyblue' => '87ceeb', 'skyblue1' => '87ceff', 'skyblue2' => '7ec0ee', 'skyblue3' => '6ca6cd', 'skyblue4' => '4a708b', 'slateblue' => '6a5acd', 'slateblue1' => '836fff', 'slateblue2' => '7a67ee', 'slateblue3' => '6959cd', 'slateblue4' => '473c8b', 'slategray' => '708090', 'slategray1' => 'c6e2ff', 'slategray2' => 'b9d3ee', 'slategray3' => '9fb6cd', 'slategray4' => '6c7b8b', 'snow1' => 'fffafa', 'snow2' => 'eee9e9', 'snow3' => 'cdc9c9', 'snow4' => '8b8989', 'springgreen1' => '00ff7f', 'springgreen2' => '00ee76', 'springgreen3' => '00cd66', 'springgreen4' => '008b45', 'steelblue' => '4682b4', 'steelblue1' => '63b8ff', 'steelblue2' => '5cacee', 'steelblue3' => '4f94cd', 'steelblue4' => '36648b', 'tan' => 'd2b48c', 'tan1' => 'ffa54f', 'tan2' => 'ee9a49', 'tan3' => 'cd853f', 'tan4' => '8b5a2b', 'teal' => '008080', 'thistle' => 'd8bfd8', 'thistle1' => 'ffe1ff', 'thistle2' => 'eed2ee', 'thistle3' => 'cdb5cd', 'thistle4' => '8b7b8b', 'tomato1' => 'ff6347', 'tomato2' => 'ee5c42', 'tomato3' => 'cd4f39', 'tomato4' => '8b3626', 'turquoise' => '40e0d0', 'turquoise1' => '00f5ff', 'turquoise2' => '00e5ee', 'turquoise3' => '00c5cd', 'turquoise4' => '00868b', 'violet' => 'ee82ee', 'violetred' => 'd02090', 'violetred1' => 'ff3e96', 'violetred2' => 'ee3a8c', 'violetred3' => 'cd3278', 'violetred4' => '8b2252', 'wheat' => 'f5deb3', 'wheat1' => 'ffe7ba', 'wheat2' => 'eed8ae', 'wheat3' => 'cdba96', 'wheat4' => '8b7e66', 'white' => 'ffffff', 'whitesmoke' => 'f5f5f5', 'yellow' => 'ffff00', 'yellow1' => 'ffff00', 'yellow2' => 'eeee00', 'yellow3' => 'cdcd00', 'yellow4' => '8b8b00', 'yellowgreen' => '9acd32', ]; protected $face; protected $size; protected $color; protected $bold = false; protected $italic = false; protected $underline = false; protected $superscript = false; protected $subscript = false; protected $strikethrough = false; protected $startTagCallbacks = [ 'font' => 'startFontTag', 'b' => 'startBoldTag', 'strong' => 'startBoldTag', 'i' => 'startItalicTag', 'em' => 'startItalicTag', 'u' => 'startUnderlineTag', 'ins' => 'startUnderlineTag', 'del' => 'startStrikethruTag', 'sup' => 'startSuperscriptTag', 'sub' => 'startSubscriptTag', ]; protected $endTagCallbacks = [ 'font' => 'endFontTag', 'b' => 'endBoldTag', 'strong' => 'endBoldTag', 'i' => 'endItalicTag', 'em' => 'endItalicTag', 'u' => 'endUnderlineTag', 'ins' => 'endUnderlineTag', 'del' => 'endStrikethruTag', 'sup' => 'endSuperscriptTag', 'sub' => 'endSubscriptTag', 'br' => 'breakTag', 'p' => 'breakTag', 'h1' => 'breakTag', 'h2' => 'breakTag', 'h3' => 'breakTag', 'h4' => 'breakTag', 'h5' => 'breakTag', 'h6' => 'breakTag', ]; protected $stack = []; protected $stringData = ''; /** * @var RichText */ protected $richTextObject; protected function initialise(): void { $this->face = $this->size = $this->color = null; $this->bold = $this->italic = $this->underline = $this->superscript = $this->subscript = $this->strikethrough = false; $this->stack = []; $this->stringData = ''; } /** * Parse HTML formatting and return the resulting RichText. * * @param string $html * * @return RichText */ public function toRichTextObject($html) { $this->initialise(); // Create a new DOM object $dom = new DOMDocument(); // Load the HTML file into the DOM object // Note the use of error suppression, because typically this will be an html fragment, so not fully valid markup $prefix = '<?xml encoding="UTF-8">'; @$dom->loadHTML($prefix . $html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD); // Discard excess white space $dom->preserveWhiteSpace = false; $this->richTextObject = new RichText(); $this->parseElements($dom); // Clean any further spurious whitespace $this->cleanWhitespace(); return $this->richTextObject; } protected function cleanWhitespace(): void { foreach ($this->richTextObject->getRichTextElements() as $key => $element) { $text = $element->getText(); // Trim any leading spaces on the first run if ($key == 0) { $text = ltrim($text); } // Trim any spaces immediately after a line break $text = preg_replace('/\n */mu', "\n", $text); $element->setText($text); } } protected function buildTextRun(): void { $text = $this->stringData; if (trim($text) === '') { return; } $richtextRun = $this->richTextObject->createTextRun($this->stringData); if ($this->face) { $richtextRun->getFont()->setName($this->face); } if ($this->size) { $richtextRun->getFont()->setSize($this->size); } if ($this->color) { $richtextRun->getFont()->setColor(new Color('ff' . $this->color)); } if ($this->bold) { $richtextRun->getFont()->setBold(true); } if ($this->italic) { $richtextRun->getFont()->setItalic(true); } if ($this->underline) { $richtextRun->getFont()->setUnderline(Font::UNDERLINE_SINGLE); } if ($this->superscript) { $richtextRun->getFont()->setSuperscript(true); } if ($this->subscript) { $richtextRun->getFont()->setSubscript(true); } if ($this->strikethrough) { $richtextRun->getFont()->setStrikethrough(true); } $this->stringData = ''; } protected function rgbToColour(string $rgbValue): string { preg_match_all('/\d+/', $rgbValue, $values); foreach ($values[0] as &$value) { $value = str_pad(dechex($value), 2, '0', STR_PAD_LEFT); } return implode('', $values[0]); } public static function colourNameLookup(string $colorName): string { return self::$colourMap[$colorName] ?? ''; } protected function startFontTag($tag): void { foreach ($tag->attributes as $attribute) { $attributeName = strtolower($attribute->name); $attributeValue = $attribute->value; if ($attributeName == 'color') { if (preg_match('/rgb\s*\(/', $attributeValue)) { $this->$attributeName = $this->rgbToColour($attributeValue); } elseif (strpos(trim($attributeValue), '#') === 0) { $this->$attributeName = ltrim($attributeValue, '#'); } else { $this->$attributeName = static::colourNameLookup($attributeValue); } } else { $this->$attributeName = $attributeValue; } } } protected function endFontTag(): void { $this->face = $this->size = $this->color = null; } protected function startBoldTag(): void { $this->bold = true; } protected function endBoldTag(): void { $this->bold = false; } protected function startItalicTag(): void { $this->italic = true; } protected function endItalicTag(): void { $this->italic = false; } protected function startUnderlineTag(): void { $this->underline = true; } protected function endUnderlineTag(): void { $this->underline = false; } protected function startSubscriptTag(): void { $this->subscript = true; } protected function endSubscriptTag(): void { $this->subscript = false; } protected function startSuperscriptTag(): void { $this->superscript = true; } protected function endSuperscriptTag(): void { $this->superscript = false; } protected function startStrikethruTag(): void { $this->strikethrough = true; } protected function endStrikethruTag(): void { $this->strikethrough = false; } protected function breakTag(): void { $this->stringData .= "\n"; } protected function parseTextNode(DOMText $textNode): void { $domText = preg_replace( '/\s+/u', ' ', str_replace(["\r", "\n"], ' ', $textNode->nodeValue) ); $this->stringData .= $domText; $this->buildTextRun(); } /** * @param string $callbackTag */ protected function handleCallback(DOMElement $element, $callbackTag, array $callbacks): void { if (isset($callbacks[$callbackTag])) { $elementHandler = $callbacks[$callbackTag]; if (method_exists($this, $elementHandler)) { call_user_func([$this, $elementHandler], $element); } } } protected function parseElementNode(DOMElement $element): void { $callbackTag = strtolower($element->nodeName); $this->stack[] = $callbackTag; $this->handleCallback($element, $callbackTag, $this->startTagCallbacks); $this->parseElements($element); array_pop($this->stack); $this->handleCallback($element, $callbackTag, $this->endTagCallbacks); } protected function parseElements(DOMNode $element): void { foreach ($element->childNodes as $child) { if ($child instanceof DOMText) { $this->parseTextNode($child); } elseif ($child instanceof DOMElement) { $this->parseElementNode($child); } } } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/Cell.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/Cell.php
<?php namespace PhpOffice\PhpSpreadsheet\Cell; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Collection\Cells; use PhpOffice\PhpSpreadsheet\Exception; use PhpOffice\PhpSpreadsheet\RichText\RichText; use PhpOffice\PhpSpreadsheet\Style\NumberFormat; use PhpOffice\PhpSpreadsheet\Style\Style; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; use Throwable; class Cell { /** * Value binder to use. * * @var IValueBinder */ private static $valueBinder; /** * Value of the cell. * * @var mixed */ private $value; /** * Calculated value of the cell (used for caching) * This returns the value last calculated by MS Excel or whichever spreadsheet program was used to * create the original spreadsheet file. * Note that this value is not guaranteed to reflect the actual calculated value because it is * possible that auto-calculation was disabled in the original spreadsheet, and underlying data * values used by the formula have changed since it was last calculated. * * @var mixed */ private $calculatedValue; /** * Type of the cell data. * * @var string */ private $dataType; /** * Collection of cells. * * @var Cells */ private $parent; /** * Index to cellXf. * * @var int */ private $xfIndex = 0; /** * Attributes of the formula. */ private $formulaAttributes; /** * Update the cell into the cell collection. * * @return $this */ public function updateInCollection(): self { $this->parent->update($this); return $this; } public function detach(): void { // @phpstan-ignore-next-line $this->parent = null; } public function attach(Cells $parent): void { $this->parent = $parent; } /** * Create a new Cell. * * @param mixed $value * @param string $dataType */ public function __construct($value, $dataType, Worksheet $worksheet) { // Initialise cell value $this->value = $value; // Set worksheet cache $this->parent = $worksheet->getCellCollection(); // Set datatype? if ($dataType !== null) { if ($dataType == DataType::TYPE_STRING2) { $dataType = DataType::TYPE_STRING; } $this->dataType = $dataType; } elseif (!self::getValueBinder()->bindValue($this, $value)) { throw new Exception('Value could not be bound to cell.'); } } /** * Get cell coordinate column. * * @return string */ public function getColumn() { return $this->parent->getCurrentColumn(); } /** * Get cell coordinate row. * * @return int */ public function getRow() { return $this->parent->getCurrentRow(); } /** * Get cell coordinate. * * @return string */ public function getCoordinate() { try { $coordinate = $this->parent->getCurrentCoordinate(); } catch (Throwable $e) { $coordinate = null; } if ($coordinate === null) { throw new Exception('Coordinate no longer exists'); } return $coordinate; } /** * Get cell value. * * @return mixed */ public function getValue() { return $this->value; } /** * Get cell value with formatting. * * @return string */ public function getFormattedValue() { return (string) NumberFormat::toFormattedString( $this->getCalculatedValue(), $this->getStyle() ->getNumberFormat()->getFormatCode() ); } /** * Set cell value. * * Sets the value for a cell, automatically determining the datatype using the value binder * * @param mixed $value Value * * @return $this */ public function setValue($value) { if (!self::getValueBinder()->bindValue($this, $value)) { throw new Exception('Value could not be bound to cell.'); } return $this; } /** * Set the value for a cell, with the explicit data type passed to the method (bypassing any use of the value binder). * * @param mixed $value Value * @param string $dataType Explicit data type, see DataType::TYPE_* * * @return Cell */ public function setValueExplicit($value, $dataType) { // set the value according to data type switch ($dataType) { case DataType::TYPE_NULL: $this->value = $value; break; case DataType::TYPE_STRING2: $dataType = DataType::TYPE_STRING; // no break case DataType::TYPE_STRING: // Synonym for string case DataType::TYPE_INLINE: // Rich text $this->value = DataType::checkString($value); break; case DataType::TYPE_NUMERIC: if (is_string($value) && !is_numeric($value)) { throw new Exception('Invalid numeric value for datatype Numeric'); } $this->value = 0 + $value; break; case DataType::TYPE_FORMULA: $this->value = (string) $value; break; case DataType::TYPE_BOOL: $this->value = (bool) $value; break; case DataType::TYPE_ERROR: $this->value = DataType::checkErrorCode($value); break; default: throw new Exception('Invalid datatype: ' . $dataType); break; } // set the datatype $this->dataType = $dataType; return $this->updateInCollection(); } /** * Get calculated cell value. * * @param bool $resetLog Whether the calculation engine logger should be reset or not * * @return mixed */ public function getCalculatedValue($resetLog = true) { if ($this->dataType == DataType::TYPE_FORMULA) { try { $index = $this->getWorksheet()->getParent()->getActiveSheetIndex(); $selected = $this->getWorksheet()->getSelectedCells(); $result = Calculation::getInstance( $this->getWorksheet()->getParent() )->calculateCellValue($this, $resetLog); $this->getWorksheet()->setSelectedCells($selected); $this->getWorksheet()->getParent()->setActiveSheetIndex($index); // We don't yet handle array returns if (is_array($result)) { while (is_array($result)) { $result = array_shift($result); } } } catch (Exception $ex) { if (($ex->getMessage() === 'Unable to access External Workbook') && ($this->calculatedValue !== null)) { return $this->calculatedValue; // Fallback for calculations referencing external files. } elseif (preg_match('/[Uu]ndefined (name|offset: 2|array key 2)/', $ex->getMessage()) === 1) { return \PhpOffice\PhpSpreadsheet\Calculation\Functions::NAME(); } throw new \PhpOffice\PhpSpreadsheet\Calculation\Exception( $this->getWorksheet()->getTitle() . '!' . $this->getCoordinate() . ' -> ' . $ex->getMessage() ); } if ($result === '#Not Yet Implemented') { return $this->calculatedValue; // Fallback if calculation engine does not support the formula. } return $result; } elseif ($this->value instanceof RichText) { return $this->value->getPlainText(); } return $this->value; } /** * Set old calculated value (cached). * * @param mixed $originalValue Value * * @return Cell */ public function setCalculatedValue($originalValue) { if ($originalValue !== null) { $this->calculatedValue = (is_numeric($originalValue)) ? (float) $originalValue : $originalValue; } return $this->updateInCollection(); } /** * Get old calculated value (cached) * This returns the value last calculated by MS Excel or whichever spreadsheet program was used to * create the original spreadsheet file. * Note that this value is not guaranteed to reflect the actual calculated value because it is * possible that auto-calculation was disabled in the original spreadsheet, and underlying data * values used by the formula have changed since it was last calculated. * * @return mixed */ public function getOldCalculatedValue() { return $this->calculatedValue; } /** * Get cell data type. * * @return string */ public function getDataType() { return $this->dataType; } /** * Set cell data type. * * @param string $dataType see DataType::TYPE_* * * @return Cell */ public function setDataType($dataType) { if ($dataType == DataType::TYPE_STRING2) { $dataType = DataType::TYPE_STRING; } $this->dataType = $dataType; return $this->updateInCollection(); } /** * Identify if the cell contains a formula. * * @return bool */ public function isFormula() { return $this->dataType == DataType::TYPE_FORMULA; } /** * Does this cell contain Data validation rules? * * @return bool */ public function hasDataValidation() { if (!isset($this->parent)) { throw new Exception('Cannot check for data validation when cell is not bound to a worksheet'); } return $this->getWorksheet()->dataValidationExists($this->getCoordinate()); } /** * Get Data validation rules. * * @return DataValidation */ public function getDataValidation() { if (!isset($this->parent)) { throw new Exception('Cannot get data validation for cell that is not bound to a worksheet'); } return $this->getWorksheet()->getDataValidation($this->getCoordinate()); } /** * Set Data validation rules. */ public function setDataValidation(?DataValidation $dataValidation = null): self { if (!isset($this->parent)) { throw new Exception('Cannot set data validation for cell that is not bound to a worksheet'); } $this->getWorksheet()->setDataValidation($this->getCoordinate(), $dataValidation); return $this->updateInCollection(); } /** * Does this cell contain valid value? * * @return bool */ public function hasValidValue() { $validator = new DataValidator(); return $validator->isValid($this); } /** * Does this cell contain a Hyperlink? * * @return bool */ public function hasHyperlink() { if (!isset($this->parent)) { throw new Exception('Cannot check for hyperlink when cell is not bound to a worksheet'); } return $this->getWorksheet()->hyperlinkExists($this->getCoordinate()); } /** * Get Hyperlink. * * @return Hyperlink */ public function getHyperlink() { if (!isset($this->parent)) { throw new Exception('Cannot get hyperlink for cell that is not bound to a worksheet'); } return $this->getWorksheet()->getHyperlink($this->getCoordinate()); } /** * Set Hyperlink. * * @return Cell */ public function setHyperlink(?Hyperlink $hyperlink = null) { if (!isset($this->parent)) { throw new Exception('Cannot set hyperlink for cell that is not bound to a worksheet'); } $this->getWorksheet()->setHyperlink($this->getCoordinate(), $hyperlink); return $this->updateInCollection(); } /** * Get cell collection. * * @return Cells */ public function getParent() { return $this->parent; } /** * Get parent worksheet. * * @return Worksheet */ public function getWorksheet() { try { $worksheet = $this->parent->getParent(); } catch (Throwable $e) { $worksheet = null; } if ($worksheet === null) { throw new Exception('Worksheet no longer exists'); } return $worksheet; } /** * Is this cell in a merge range. * * @return bool */ public function isInMergeRange() { return (bool) $this->getMergeRange(); } /** * Is this cell the master (top left cell) in a merge range (that holds the actual data value). * * @return bool */ public function isMergeRangeValueCell() { if ($mergeRange = $this->getMergeRange()) { $mergeRange = Coordinate::splitRange($mergeRange); [$startCell] = $mergeRange[0]; if ($this->getCoordinate() === $startCell) { return true; } } return false; } /** * If this cell is in a merge range, then return the range. * * @return false|string */ public function getMergeRange() { foreach ($this->getWorksheet()->getMergeCells() as $mergeRange) { if ($this->isInRange($mergeRange)) { return $mergeRange; } } return false; } /** * Get cell style. * * @return Style */ public function getStyle() { return $this->getWorksheet()->getStyle($this->getCoordinate()); } /** * Re-bind parent. * * @return Cell */ public function rebindParent(Worksheet $parent) { $this->parent = $parent->getCellCollection(); return $this->updateInCollection(); } /** * Is cell in a specific range? * * @param string $range Cell range (e.g. A1:A1) * * @return bool */ public function isInRange($range) { [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($range); // Translate properties $myColumn = Coordinate::columnIndexFromString($this->getColumn()); $myRow = $this->getRow(); // Verify if cell is in range return ($rangeStart[0] <= $myColumn) && ($rangeEnd[0] >= $myColumn) && ($rangeStart[1] <= $myRow) && ($rangeEnd[1] >= $myRow); } /** * Compare 2 cells. * * @param Cell $a Cell a * @param Cell $b Cell b * * @return int Result of comparison (always -1 or 1, never zero!) */ public static function compareCells(self $a, self $b) { if ($a->getRow() < $b->getRow()) { return -1; } elseif ($a->getRow() > $b->getRow()) { return 1; } elseif (Coordinate::columnIndexFromString($a->getColumn()) < Coordinate::columnIndexFromString($b->getColumn())) { return -1; } return 1; } /** * Get value binder to use. * * @return IValueBinder */ public static function getValueBinder() { if (self::$valueBinder === null) { self::$valueBinder = new DefaultValueBinder(); } return self::$valueBinder; } /** * Set value binder to use. */ public static function setValueBinder(IValueBinder $binder): void { self::$valueBinder = $binder; } /** * 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; } } } /** * Get index to cellXf. * * @return int */ public function getXfIndex() { return $this->xfIndex; } /** * Set index to cellXf. * * @param int $indexValue * * @return Cell */ public function setXfIndex($indexValue) { $this->xfIndex = $indexValue; return $this->updateInCollection(); } /** * Set the formula attributes. * * @param mixed $attributes * * @return $this */ public function setFormulaAttributes($attributes) { $this->formulaAttributes = $attributes; return $this; } /** * Get the formula attributes. */ public function getFormulaAttributes() { return $this->formulaAttributes; } /** * Convert to string. * * @return string */ public function __toString() { return (string) $this->getValue(); } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/StringValueBinder.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/StringValueBinder.php
<?php namespace PhpOffice\PhpSpreadsheet\Cell; use DateTimeInterface; use PhpOffice\PhpSpreadsheet\RichText\RichText; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; class StringValueBinder implements IValueBinder { /** * @var bool */ protected $convertNull = true; /** * @var bool */ protected $convertBoolean = true; /** * @var bool */ protected $convertNumeric = true; /** * @var bool */ protected $convertFormula = true; public function setNullConversion(bool $suppressConversion = false): self { $this->convertNull = $suppressConversion; return $this; } public function setBooleanConversion(bool $suppressConversion = false): self { $this->convertBoolean = $suppressConversion; return $this; } public function getBooleanConversion(): bool { return $this->convertBoolean; } public function setNumericConversion(bool $suppressConversion = false): self { $this->convertNumeric = $suppressConversion; return $this; } public function setFormulaConversion(bool $suppressConversion = false): self { $this->convertFormula = $suppressConversion; return $this; } public function setConversionForAllValueTypes(bool $suppressConversion = false): self { $this->convertNull = $suppressConversion; $this->convertBoolean = $suppressConversion; $this->convertNumeric = $suppressConversion; $this->convertFormula = $suppressConversion; return $this; } /** * Bind value to a cell. * * @param Cell $cell Cell to bind value to * @param mixed $value Value to bind in cell */ public function bindValue(Cell $cell, $value) { if (is_object($value)) { return $this->bindObjectValue($cell, $value); } // sanitize UTF-8 strings if (is_string($value)) { $value = StringHelper::sanitizeUTF8($value); } if ($value === null && $this->convertNull === false) { $cell->setValueExplicit($value, DataType::TYPE_NULL); } elseif (is_bool($value) && $this->convertBoolean === false) { $cell->setValueExplicit($value, DataType::TYPE_BOOL); } elseif ((is_int($value) || is_float($value)) && $this->convertNumeric === false) { $cell->setValueExplicit($value, DataType::TYPE_NUMERIC); } elseif (is_string($value) && strlen($value) > 1 && $value[0] === '=' && $this->convertFormula === false) { $cell->setValueExplicit($value, DataType::TYPE_FORMULA); } else { if (is_string($value) && strlen($value) > 1 && $value[0] === '=') { $cell->getStyle()->setQuotePrefix(true); } $cell->setValueExplicit((string) $value, DataType::TYPE_STRING); } return true; } protected function bindObjectValue(Cell $cell, object $value): bool { // Handle any objects that might be injected if ($value instanceof DateTimeInterface) { $value = $value->format('Y-m-d H:i:s'); } elseif ($value instanceof RichText) { $cell->setValueExplicit($value, DataType::TYPE_INLINE); return true; } $cell->setValueExplicit((string) $value, DataType::TYPE_STRING); return true; } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/DataValidation.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/DataValidation.php
<?php namespace PhpOffice\PhpSpreadsheet\Cell; class DataValidation { // Data validation types const TYPE_NONE = 'none'; const TYPE_CUSTOM = 'custom'; const TYPE_DATE = 'date'; const TYPE_DECIMAL = 'decimal'; const TYPE_LIST = 'list'; const TYPE_TEXTLENGTH = 'textLength'; const TYPE_TIME = 'time'; const TYPE_WHOLE = 'whole'; // Data validation error styles const STYLE_STOP = 'stop'; const STYLE_WARNING = 'warning'; const STYLE_INFORMATION = 'information'; // Data validation operators const OPERATOR_BETWEEN = 'between'; const OPERATOR_EQUAL = 'equal'; const OPERATOR_GREATERTHAN = 'greaterThan'; const OPERATOR_GREATERTHANOREQUAL = 'greaterThanOrEqual'; const OPERATOR_LESSTHAN = 'lessThan'; const OPERATOR_LESSTHANOREQUAL = 'lessThanOrEqual'; const OPERATOR_NOTBETWEEN = 'notBetween'; const OPERATOR_NOTEQUAL = 'notEqual'; /** * Formula 1. * * @var string */ private $formula1 = ''; /** * Formula 2. * * @var string */ private $formula2 = ''; /** * Type. * * @var string */ private $type = self::TYPE_NONE; /** * Error style. * * @var string */ private $errorStyle = self::STYLE_STOP; /** * Operator. * * @var string */ private $operator = self::OPERATOR_BETWEEN; /** * Allow Blank. * * @var bool */ private $allowBlank = false; /** * Show DropDown. * * @var bool */ private $showDropDown = false; /** * Show InputMessage. * * @var bool */ private $showInputMessage = false; /** * Show ErrorMessage. * * @var bool */ private $showErrorMessage = false; /** * Error title. * * @var string */ private $errorTitle = ''; /** * Error. * * @var string */ private $error = ''; /** * Prompt title. * * @var string */ private $promptTitle = ''; /** * Prompt. * * @var string */ private $prompt = ''; /** * Create a new DataValidation. */ public function __construct() { } /** * Get Formula 1. * * @return string */ public function getFormula1() { return $this->formula1; } /** * Set Formula 1. * * @param string $formula * * @return $this */ public function setFormula1($formula) { $this->formula1 = $formula; return $this; } /** * Get Formula 2. * * @return string */ public function getFormula2() { return $this->formula2; } /** * Set Formula 2. * * @param string $formula * * @return $this */ public function setFormula2($formula) { $this->formula2 = $formula; return $this; } /** * Get Type. * * @return string */ public function getType() { return $this->type; } /** * Set Type. * * @param string $type * * @return $this */ public function setType($type) { $this->type = $type; return $this; } /** * Get Error style. * * @return string */ public function getErrorStyle() { return $this->errorStyle; } /** * Set Error style. * * @param string $errorStyle see self::STYLE_* * * @return $this */ public function setErrorStyle($errorStyle) { $this->errorStyle = $errorStyle; return $this; } /** * Get Operator. * * @return string */ public function getOperator() { return $this->operator; } /** * Set Operator. * * @param string $operator * * @return $this */ public function setOperator($operator) { $this->operator = $operator; return $this; } /** * Get Allow Blank. * * @return bool */ public function getAllowBlank() { return $this->allowBlank; } /** * Set Allow Blank. * * @param bool $allowBlank * * @return $this */ public function setAllowBlank($allowBlank) { $this->allowBlank = $allowBlank; return $this; } /** * Get Show DropDown. * * @return bool */ public function getShowDropDown() { return $this->showDropDown; } /** * Set Show DropDown. * * @param bool $showDropDown * * @return $this */ public function setShowDropDown($showDropDown) { $this->showDropDown = $showDropDown; return $this; } /** * Get Show InputMessage. * * @return bool */ public function getShowInputMessage() { return $this->showInputMessage; } /** * Set Show InputMessage. * * @param bool $showInputMessage * * @return $this */ public function setShowInputMessage($showInputMessage) { $this->showInputMessage = $showInputMessage; return $this; } /** * Get Show ErrorMessage. * * @return bool */ public function getShowErrorMessage() { return $this->showErrorMessage; } /** * Set Show ErrorMessage. * * @param bool $showErrorMessage * * @return $this */ public function setShowErrorMessage($showErrorMessage) { $this->showErrorMessage = $showErrorMessage; return $this; } /** * Get Error title. * * @return string */ public function getErrorTitle() { return $this->errorTitle; } /** * Set Error title. * * @param string $errorTitle * * @return $this */ public function setErrorTitle($errorTitle) { $this->errorTitle = $errorTitle; return $this; } /** * Get Error. * * @return string */ public function getError() { return $this->error; } /** * Set Error. * * @param string $error * * @return $this */ public function setError($error) { $this->error = $error; return $this; } /** * Get Prompt title. * * @return string */ public function getPromptTitle() { return $this->promptTitle; } /** * Set Prompt title. * * @param string $promptTitle * * @return $this */ public function setPromptTitle($promptTitle) { $this->promptTitle = $promptTitle; return $this; } /** * Get Prompt. * * @return string */ public function getPrompt() { return $this->prompt; } /** * Set Prompt. * * @param string $prompt * * @return $this */ public function setPrompt($prompt) { $this->prompt = $prompt; return $this; } /** * Get hash code. * * @return string Hash code */ public function getHashCode() { return md5( $this->formula1 . $this->formula2 . $this->type . $this->errorStyle . $this->operator . ($this->allowBlank ? 't' : 'f') . ($this->showDropDown ? 't' : 'f') . ($this->showInputMessage ? 't' : 'f') . ($this->showErrorMessage ? 't' : 'f') . $this->errorTitle . $this->error . $this->promptTitle . $this->prompt . $this->sqref . __CLASS__ ); } /** * 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)) { $this->$key = clone $value; } else { $this->$key = $value; } } } /** @var ?string */ private $sqref; public function getSqref(): ?string { return $this->sqref; } public function setSqref(?string $str): self { $this->sqref = $str; return $this; } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/IValueBinder.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/IValueBinder.php
<?php namespace PhpOffice\PhpSpreadsheet\Cell; interface IValueBinder { /** * Bind value to a cell. * * @param Cell $cell Cell to bind value to * @param mixed $value Value to bind in cell * * @return bool */ public function bindValue(Cell $cell, $value); }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/DefaultValueBinder.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/DefaultValueBinder.php
<?php namespace PhpOffice\PhpSpreadsheet\Cell; use DateTimeInterface; use PhpOffice\PhpSpreadsheet\RichText\RichText; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; class DefaultValueBinder implements IValueBinder { /** * Bind value to a cell. * * @param Cell $cell Cell to bind value to * @param mixed $value Value to bind in cell * * @return bool */ public function bindValue(Cell $cell, $value) { // sanitize UTF-8 strings if (is_string($value)) { $value = StringHelper::sanitizeUTF8($value); } elseif (is_object($value)) { // Handle any objects that might be injected if ($value instanceof DateTimeInterface) { $value = $value->format('Y-m-d H:i:s'); } elseif (!($value instanceof RichText)) { // Attempt to cast any unexpected objects to string $value = (string) $value; } } // Set value explicit $cell->setValueExplicit($value, static::dataTypeForValue($value)); // Done! return true; } /** * DataType for value. * * @param mixed $value * * @return string */ public static function dataTypeForValue($value) { // Match the value against a few data types if ($value === null) { return DataType::TYPE_NULL; } elseif (is_float($value) || is_int($value)) { return DataType::TYPE_NUMERIC; } elseif (is_bool($value)) { return DataType::TYPE_BOOL; } elseif ($value === '') { return DataType::TYPE_STRING; } elseif ($value instanceof RichText) { return DataType::TYPE_INLINE; } elseif (is_string($value) && strlen($value) > 1 && $value[0] === '=') { return DataType::TYPE_FORMULA; } elseif (preg_match('/^[\+\-]?(\d+\\.?\d*|\d*\\.?\d+)([Ee][\-\+]?[0-2]?\d{1,3})?$/', $value)) { $tValue = ltrim($value, '+-'); if (is_string($value) && strlen($tValue) > 1 && $tValue[0] === '0' && $tValue[1] !== '.') { return DataType::TYPE_STRING; } elseif ((strpos($value, '.') === false) && ($value > PHP_INT_MAX)) { return DataType::TYPE_STRING; } elseif (!is_numeric($value)) { return DataType::TYPE_STRING; } return DataType::TYPE_NUMERIC; } elseif (is_string($value)) { $errorCodes = DataType::getErrorCodes(); if (isset($errorCodes[$value])) { return DataType::TYPE_ERROR; } } return DataType::TYPE_STRING; } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/Hyperlink.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/Hyperlink.php
<?php namespace PhpOffice\PhpSpreadsheet\Cell; class Hyperlink { /** * URL to link the cell to. * * @var string */ private $url; /** * Tooltip to display on the hyperlink. * * @var string */ private $tooltip; /** * Create a new Hyperlink. * * @param string $url Url to link the cell to * @param string $tooltip Tooltip to display on the hyperlink */ public function __construct($url = '', $tooltip = '') { // Initialise member variables $this->url = $url; $this->tooltip = $tooltip; } /** * Get URL. * * @return string */ public function getUrl() { return $this->url; } /** * Set URL. * * @param string $url * * @return $this */ public function setUrl($url) { $this->url = $url; return $this; } /** * Get tooltip. * * @return string */ public function getTooltip() { return $this->tooltip; } /** * Set tooltip. * * @param string $tooltip * * @return $this */ public function setTooltip($tooltip) { $this->tooltip = $tooltip; return $this; } /** * Is this hyperlink internal? (to another worksheet). * * @return bool */ public function isInternal() { return strpos($this->url, 'sheet://') !== false; } /** * @return string */ public function getTypeHyperlink() { return $this->isInternal() ? '' : 'External'; } /** * Get hash code. * * @return string Hash code */ public function getHashCode() { return md5( $this->url . $this->tooltip . __CLASS__ ); } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/AddressHelper.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/AddressHelper.php
<?php namespace PhpOffice\PhpSpreadsheet\Cell; use PhpOffice\PhpSpreadsheet\Exception; class AddressHelper { public const R1C1_COORDINATE_REGEX = '/(R((?:\[-?\d*\])|(?:\d*))?)(C((?:\[-?\d*\])|(?:\d*))?)/i'; /** * Converts an R1C1 format cell address to an A1 format cell address. */ public static function convertToA1( string $address, int $currentRowNumber = 1, int $currentColumnNumber = 1 ): string { $validityCheck = preg_match('/^(R(\[?-?\d*\]?))(C(\[?-?\d*\]?))$/i', $address, $cellReference); if ($validityCheck === 0) { throw new Exception('Invalid R1C1-format Cell Reference'); } $rowReference = $cellReference[2]; // Empty R reference is the current row if ($rowReference === '') { $rowReference = (string) $currentRowNumber; } // Bracketed R references are relative to the current row if ($rowReference[0] === '[') { $rowReference = $currentRowNumber + (int) trim($rowReference, '[]'); } $columnReference = $cellReference[4]; // Empty C reference is the current column if ($columnReference === '') { $columnReference = (string) $currentColumnNumber; } // Bracketed C references are relative to the current column if (is_string($columnReference) && $columnReference[0] === '[') { $columnReference = $currentColumnNumber + (int) trim($columnReference, '[]'); } if ($columnReference <= 0 || $rowReference <= 0) { throw new Exception('Invalid R1C1-format Cell Reference, Value out of range'); } $A1CellReference = Coordinate::stringFromColumnIndex($columnReference) . $rowReference; return $A1CellReference; } protected static function convertSpreadsheetMLFormula(string $formula): string { $formula = substr($formula, 3); $temp = explode('"', $formula); $key = false; foreach ($temp as &$value) { // Only replace in alternate array entries (i.e. non-quoted blocks) if ($key = !$key) { $value = str_replace(['[.', ':.', ']'], ['', ':', ''], $value); } } unset($value); return implode('"', $temp); } /** * Converts a formula that uses R1C1/SpreadsheetXML format cell address to an A1 format cell address. */ public static function convertFormulaToA1( string $formula, int $currentRowNumber = 1, int $currentColumnNumber = 1 ): string { if (substr($formula, 0, 3) == 'of:') { // We have an old-style SpreadsheetML Formula return self::convertSpreadsheetMLFormula($formula); } // Convert R1C1 style references to A1 style references (but only when not quoted) $temp = explode('"', $formula); $key = false; foreach ($temp as &$value) { // Only replace in alternate array entries (i.e. non-quoted blocks) if ($key = !$key) { preg_match_all(self::R1C1_COORDINATE_REGEX, $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) { $A1CellReference = self::convertToA1($cellReference[0][0], $currentRowNumber, $currentColumnNumber); $value = substr_replace($value, $A1CellReference, $cellReference[0][1], strlen($cellReference[0][0])); } } } unset($value); // Then rebuild the formula string return implode('"', $temp); } /** * Converts an A1 format cell address to an R1C1 format cell address. * If $currentRowNumber or $currentColumnNumber are provided, then the R1C1 address will be formatted as a relative address. */ public static function convertToR1C1( string $address, ?int $currentRowNumber = null, ?int $currentColumnNumber = null ): string { $validityCheck = preg_match(Coordinate::A1_COORDINATE_REGEX, $address, $cellReference); if ($validityCheck === 0) { throw new Exception('Invalid A1-format Cell Reference'); } $columnId = Coordinate::columnIndexFromString($cellReference['col_ref']); if ($cellReference['absolute_col'] === '$') { // Column must be absolute address $currentColumnNumber = null; } $rowId = (int) $cellReference['row_ref']; if ($cellReference['absolute_row'] === '$') { // Row must be absolute address $currentRowNumber = null; } if ($currentRowNumber !== null) { if ($rowId === $currentRowNumber) { $rowId = ''; } else { $rowId = '[' . ($rowId - $currentRowNumber) . ']'; } } if ($currentColumnNumber !== null) { if ($columnId === $currentColumnNumber) { $columnId = ''; } else { $columnId = '[' . ($columnId - $currentColumnNumber) . ']'; } } $R1C1Address = "R{$rowId}C{$columnId}"; return $R1C1Address; } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/Coordinate.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/Coordinate.php
<?php namespace PhpOffice\PhpSpreadsheet\Cell; use PhpOffice\PhpSpreadsheet\Exception; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; /** * Helper class to manipulate cell coordinates. * * Columns indexes and rows are always based on 1, **not** on 0. This match the behavior * that Excel users are used to, and also match the Excel functions `COLUMN()` and `ROW()`. */ abstract class Coordinate { public const A1_COORDINATE_REGEX = '/^(?<absolute_col>\$?)(?<col_ref>[A-Z]{1,3})(?<absolute_row>\$?)(?<row_ref>\d{1,7})$/i'; /** * Default range variable constant. * * @var string */ const DEFAULT_RANGE = 'A1:A1'; /** * Coordinate from string. * * @param string $cellAddress eg: 'A1' * * @return array{0: string, 1: string} Array containing column and row (indexes 0 and 1) */ public static function coordinateFromString($cellAddress) { if (preg_match(self::A1_COORDINATE_REGEX, $cellAddress, $matches)) { return [$matches['absolute_col'] . $matches['col_ref'], $matches['absolute_row'] . $matches['row_ref']]; } elseif (self::coordinateIsRange($cellAddress)) { throw new Exception('Cell coordinate string can not be a range of cells'); } elseif ($cellAddress == '') { throw new Exception('Cell coordinate can not be zero-length string'); } throw new Exception('Invalid cell coordinate ' . $cellAddress); } /** * Get indexes from a string coordinates. * * @param string $coordinates eg: 'A1', '$B$12' * * @return array{0: int, 1: int} Array containing column index and row index (indexes 0 and 1) */ public static function indexesFromString(string $coordinates): array { [$col, $row] = self::coordinateFromString($coordinates); return [ self::columnIndexFromString(ltrim($col, '$')), (int) ltrim($row, '$'), ]; } /** * Checks if a Cell Address represents a range of cells. * * @param string $cellAddress eg: 'A1' or 'A1:A2' or 'A1:A2,C1:C2' * * @return bool Whether the coordinate represents a range of cells */ public static function coordinateIsRange($cellAddress) { return (strpos($cellAddress, ':') !== false) || (strpos($cellAddress, ',') !== false); } /** * Make string row, column or cell coordinate absolute. * * @param string $cellAddress e.g. 'A' or '1' or 'A1' * Note that this value can be a row or column reference as well as a cell reference * * @return string Absolute coordinate e.g. '$A' or '$1' or '$A$1' */ public static function absoluteReference($cellAddress) { if (self::coordinateIsRange($cellAddress)) { throw new Exception('Cell coordinate string can not be a range of cells'); } // Split out any worksheet name from the reference [$worksheet, $cellAddress] = Worksheet::extractSheetTitle($cellAddress, true); if ($worksheet > '') { $worksheet .= '!'; } // Create absolute coordinate if (ctype_digit($cellAddress)) { return $worksheet . '$' . $cellAddress; } elseif (ctype_alpha($cellAddress)) { return $worksheet . '$' . strtoupper($cellAddress); } return $worksheet . self::absoluteCoordinate($cellAddress); } /** * Make string coordinate absolute. * * @param string $cellAddress e.g. 'A1' * * @return string Absolute coordinate e.g. '$A$1' */ public static function absoluteCoordinate($cellAddress) { if (self::coordinateIsRange($cellAddress)) { throw new Exception('Cell coordinate string can not be a range of cells'); } // Split out any worksheet name from the coordinate [$worksheet, $cellAddress] = Worksheet::extractSheetTitle($cellAddress, true); if ($worksheet > '') { $worksheet .= '!'; } // Create absolute coordinate [$column, $row] = self::coordinateFromString($cellAddress); $column = ltrim($column, '$'); $row = ltrim($row, '$'); return $worksheet . '$' . $column . '$' . $row; } /** * Split range into coordinate strings. * * @param string $range e.g. 'B4:D9' or 'B4:D9,H2:O11' or 'B4' * * @return array Array containing one or more arrays containing one or two coordinate strings * e.g. ['B4','D9'] or [['B4','D9'], ['H2','O11']] * or ['B4'] */ public static function splitRange($range) { // Ensure $pRange is a valid range if (empty($range)) { $range = self::DEFAULT_RANGE; } $exploded = explode(',', $range); $counter = count($exploded); for ($i = 0; $i < $counter; ++$i) { $exploded[$i] = explode(':', $exploded[$i]); } return $exploded; } /** * Build range from coordinate strings. * * @param array $range Array containing one or more arrays containing one or two coordinate strings * * @return string String representation of $pRange */ public static function buildRange(array $range) { // Verify range if (empty($range) || !is_array($range[0])) { throw new Exception('Range does not contain any information'); } // Build range $counter = count($range); for ($i = 0; $i < $counter; ++$i) { $range[$i] = implode(':', $range[$i]); } return implode(',', $range); } /** * Calculate range boundaries. * * @param string $range Cell range (e.g. A1:A1) * * @return array Range coordinates [Start Cell, End Cell] * where Start Cell and End Cell are arrays (Column Number, Row Number) */ public static function rangeBoundaries($range) { // Ensure $pRange is a valid range if (empty($range)) { $range = self::DEFAULT_RANGE; } // Uppercase coordinate $range = strtoupper($range); // Extract range if (strpos($range, ':') === false) { $rangeA = $rangeB = $range; } else { [$rangeA, $rangeB] = explode(':', $range); } // Calculate range outer borders $rangeStart = self::coordinateFromString($rangeA); $rangeEnd = self::coordinateFromString($rangeB); // Translate column into index $rangeStart[0] = self::columnIndexFromString($rangeStart[0]); $rangeEnd[0] = self::columnIndexFromString($rangeEnd[0]); return [$rangeStart, $rangeEnd]; } /** * Calculate range dimension. * * @param string $range Cell range (e.g. A1:A1) * * @return array Range dimension (width, height) */ public static function rangeDimension($range) { // Calculate range outer borders [$rangeStart, $rangeEnd] = self::rangeBoundaries($range); return [($rangeEnd[0] - $rangeStart[0] + 1), ($rangeEnd[1] - $rangeStart[1] + 1)]; } /** * Calculate range boundaries. * * @param string $range Cell range (e.g. A1:A1) * * @return array Range coordinates [Start Cell, End Cell] * where Start Cell and End Cell are arrays [Column ID, Row Number] */ public static function getRangeBoundaries($range) { // Ensure $pRange is a valid range if (empty($range)) { $range = self::DEFAULT_RANGE; } // Uppercase coordinate $range = strtoupper($range); // Extract range if (strpos($range, ':') === false) { $rangeA = $rangeB = $range; } else { [$rangeA, $rangeB] = explode(':', $range); } return [self::coordinateFromString($rangeA), self::coordinateFromString($rangeB)]; } /** * Column index from string. * * @param string $columnAddress eg 'A' * * @return int Column index (A = 1) */ public static function columnIndexFromString($columnAddress) { // Using a lookup cache adds a slight memory overhead, but boosts speed // caching using a static within the method is faster than a class static, // though it's additional memory overhead static $indexCache = []; if (isset($indexCache[$columnAddress])) { return $indexCache[$columnAddress]; } // It's surprising how costly the strtoupper() and ord() calls actually are, so we use a lookup array rather than use ord() // and make it case insensitive to get rid of the strtoupper() as well. Because it's a static, there's no significant // memory overhead either static $columnLookup = [ 'A' => 1, 'B' => 2, 'C' => 3, 'D' => 4, 'E' => 5, 'F' => 6, 'G' => 7, 'H' => 8, 'I' => 9, 'J' => 10, 'K' => 11, 'L' => 12, 'M' => 13, 'N' => 14, 'O' => 15, 'P' => 16, 'Q' => 17, 'R' => 18, 'S' => 19, 'T' => 20, 'U' => 21, 'V' => 22, 'W' => 23, 'X' => 24, 'Y' => 25, 'Z' => 26, 'a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6, 'g' => 7, 'h' => 8, 'i' => 9, 'j' => 10, 'k' => 11, 'l' => 12, 'm' => 13, 'n' => 14, 'o' => 15, 'p' => 16, 'q' => 17, 'r' => 18, 's' => 19, 't' => 20, 'u' => 21, 'v' => 22, 'w' => 23, 'x' => 24, 'y' => 25, 'z' => 26, ]; // We also use the language construct isset() rather than the more costly strlen() function to match the length of $columnAddress // for improved performance if (isset($columnAddress[0])) { if (!isset($columnAddress[1])) { $indexCache[$columnAddress] = $columnLookup[$columnAddress]; return $indexCache[$columnAddress]; } elseif (!isset($columnAddress[2])) { $indexCache[$columnAddress] = $columnLookup[$columnAddress[0]] * 26 + $columnLookup[$columnAddress[1]]; return $indexCache[$columnAddress]; } elseif (!isset($columnAddress[3])) { $indexCache[$columnAddress] = $columnLookup[$columnAddress[0]] * 676 + $columnLookup[$columnAddress[1]] * 26 + $columnLookup[$columnAddress[2]]; return $indexCache[$columnAddress]; } } throw new Exception('Column string index can not be ' . ((isset($columnAddress[0])) ? 'longer than 3 characters' : 'empty')); } /** * String from column index. * * @param int $columnIndex Column index (A = 1) * * @return string */ public static function stringFromColumnIndex($columnIndex) { static $indexCache = []; if (!isset($indexCache[$columnIndex])) { $indexValue = $columnIndex; $base26 = null; do { $characterValue = ($indexValue % 26) ?: 26; $indexValue = ($indexValue - $characterValue) / 26; $base26 = chr($characterValue + 64) . ($base26 ?: ''); } while ($indexValue > 0); $indexCache[$columnIndex] = $base26; } return $indexCache[$columnIndex]; } /** * Extract all cell references in range, which may be comprised of multiple cell ranges. * * @param string $cellRange Range: e.g. 'A1' or 'A1:C10' or 'A1:E10,A20:E25' or 'A1:E5 C3:G7' or 'A1:C1,A3:C3 B1:C3' * * @return array Array containing single cell references */ public static function extractAllCellReferencesInRange($cellRange): array { [$ranges, $operators] = self::getCellBlocksFromRangeString($cellRange); $cells = []; foreach ($ranges as $range) { $cells[] = self::getReferencesForCellBlock($range); } $cells = self::processRangeSetOperators($operators, $cells); if (empty($cells)) { return []; } $cellList = array_merge(...$cells); $cellList = self::sortCellReferenceArray($cellList); return $cellList; } private static function processRangeSetOperators(array $operators, array $cells): array { $operatorCount = count($operators); for ($offset = 0; $offset < $operatorCount; ++$offset) { $operator = $operators[$offset]; if ($operator !== ' ') { continue; } $cells[$offset] = array_intersect($cells[$offset], $cells[$offset + 1]); unset($operators[$offset], $cells[$offset + 1]); $operators = array_values($operators); $cells = array_values($cells); --$offset; --$operatorCount; } return $cells; } private static function sortCellReferenceArray(array $cellList): array { // Sort the result by column and row $sortKeys = []; foreach ($cellList as $coord) { [$column, $row] = sscanf($coord, '%[A-Z]%d'); $sortKeys[sprintf('%3s%09d', $column, $row)] = $coord; } ksort($sortKeys); return array_values($sortKeys); } /** * Get all cell references for an individual cell block. * * @param string $cellBlock A cell range e.g. A4:B5 * * @return array All individual cells in that range */ private static function getReferencesForCellBlock($cellBlock) { $returnValue = []; // Single cell? if (!self::coordinateIsRange($cellBlock)) { return (array) $cellBlock; } // Range... $ranges = self::splitRange($cellBlock); foreach ($ranges as $range) { // Single cell? if (!isset($range[1])) { $returnValue[] = $range[0]; continue; } // Range... [$rangeStart, $rangeEnd] = $range; [$startColumn, $startRow] = self::coordinateFromString($rangeStart); [$endColumn, $endRow] = self::coordinateFromString($rangeEnd); $startColumnIndex = self::columnIndexFromString($startColumn); $endColumnIndex = self::columnIndexFromString($endColumn); ++$endColumnIndex; // Current data $currentColumnIndex = $startColumnIndex; $currentRow = $startRow; self::validateRange($cellBlock, $startColumnIndex, $endColumnIndex, $currentRow, $endRow); // Loop cells while ($currentColumnIndex < $endColumnIndex) { while ($currentRow <= $endRow) { $returnValue[] = self::stringFromColumnIndex($currentColumnIndex) . $currentRow; ++$currentRow; } ++$currentColumnIndex; $currentRow = $startRow; } } return $returnValue; } /** * Convert an associative array of single cell coordinates to values to an associative array * of cell ranges to values. Only adjacent cell coordinates with the same * value will be merged. If the value is an object, it must implement the method getHashCode(). * * For example, this function converts: * * [ 'A1' => 'x', 'A2' => 'x', 'A3' => 'x', 'A4' => 'y' ] * * to: * * [ 'A1:A3' => 'x', 'A4' => 'y' ] * * @param array $coordinateCollection associative array mapping coordinates to values * * @return array associative array mapping coordinate ranges to valuea */ public static function mergeRangesInCollection(array $coordinateCollection) { $hashedValues = []; $mergedCoordCollection = []; foreach ($coordinateCollection as $coord => $value) { if (self::coordinateIsRange($coord)) { $mergedCoordCollection[$coord] = $value; continue; } [$column, $row] = self::coordinateFromString($coord); $row = (int) (ltrim($row, '$')); $hashCode = $column . '-' . (is_object($value) ? $value->getHashCode() : $value); if (!isset($hashedValues[$hashCode])) { $hashedValues[$hashCode] = (object) [ 'value' => $value, 'col' => $column, 'rows' => [$row], ]; } else { $hashedValues[$hashCode]->rows[] = $row; } } ksort($hashedValues); foreach ($hashedValues as $hashedValue) { sort($hashedValue->rows); $rowStart = null; $rowEnd = null; $ranges = []; foreach ($hashedValue->rows as $row) { if ($rowStart === null) { $rowStart = $row; $rowEnd = $row; } elseif ($rowEnd === $row - 1) { $rowEnd = $row; } else { if ($rowStart == $rowEnd) { $ranges[] = $hashedValue->col . $rowStart; } else { $ranges[] = $hashedValue->col . $rowStart . ':' . $hashedValue->col . $rowEnd; } $rowStart = $row; $rowEnd = $row; } } if ($rowStart !== null) { if ($rowStart == $rowEnd) { $ranges[] = $hashedValue->col . $rowStart; } else { $ranges[] = $hashedValue->col . $rowStart . ':' . $hashedValue->col . $rowEnd; } } foreach ($ranges as $range) { $mergedCoordCollection[$range] = $hashedValue->value; } } return $mergedCoordCollection; } /** * Get the individual cell blocks from a range string, removing any $ characters. * then splitting by operators and returning an array with ranges and operators. * * @param string $rangeString * * @return array[] */ private static function getCellBlocksFromRangeString($rangeString) { $rangeString = str_replace('$', '', strtoupper($rangeString)); // split range sets on intersection (space) or union (,) operators $tokens = preg_split('/([ ,])/', $rangeString, -1, PREG_SPLIT_DELIM_CAPTURE); // separate the range sets and the operators into arrays $split = array_chunk($tokens, 2); $ranges = array_column($split, 0); $operators = array_column($split, 1); return [$ranges, $operators]; } /** * Check that the given range is valid, i.e. that the start column and row are not greater than the end column and * row. * * @param string $cellBlock The original range, for displaying a meaningful error message * @param int $startColumnIndex * @param int $endColumnIndex * @param int $currentRow * @param int $endRow */ private static function validateRange($cellBlock, $startColumnIndex, $endColumnIndex, $currentRow, $endRow): void { if ($startColumnIndex >= $endColumnIndex || $currentRow > $endRow) { throw new Exception('Invalid range: "' . $cellBlock . '"'); } } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/AdvancedValueBinder.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/AdvancedValueBinder.php
<?php namespace PhpOffice\PhpSpreadsheet\Cell; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\RichText\RichText; use PhpOffice\PhpSpreadsheet\Shared\Date; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; use PhpOffice\PhpSpreadsheet\Style\NumberFormat; class AdvancedValueBinder extends DefaultValueBinder implements IValueBinder { /** * Bind value to a cell. * * @param Cell $cell Cell to bind value to * @param mixed $value Value to bind in cell * * @return bool */ public function bindValue(Cell $cell, $value = null) { if ($value === null) { return parent::bindValue($cell, $value); } elseif (is_string($value)) { // sanitize UTF-8 strings $value = StringHelper::sanitizeUTF8($value); } // Find out data type $dataType = parent::dataTypeForValue($value); // Style logic - strings if ($dataType === DataType::TYPE_STRING && !$value instanceof RichText) { // Test for booleans using locale-setting if ($value == Calculation::getTRUE()) { $cell->setValueExplicit(true, DataType::TYPE_BOOL); return true; } elseif ($value == Calculation::getFALSE()) { $cell->setValueExplicit(false, DataType::TYPE_BOOL); return true; } // Check for fractions if (preg_match('/^([+-]?)\s*(\d+)\s?\/\s*(\d+)$/', $value, $matches)) { return $this->setProperFraction($matches, $cell); } elseif (preg_match('/^([+-]?)(\d*) +(\d*)\s?\/\s*(\d*)$/', $value, $matches)) { return $this->setImproperFraction($matches, $cell); } // Check for percentage if (preg_match('/^\-?\d*\.?\d*\s?\%$/', $value)) { return $this->setPercentage($value, $cell); } // Check for currency $currencyCode = StringHelper::getCurrencyCode(); $decimalSeparator = StringHelper::getDecimalSeparator(); $thousandsSeparator = StringHelper::getThousandsSeparator(); if (preg_match('/^' . preg_quote($currencyCode, '/') . ' *(\d{1,3}(' . preg_quote($thousandsSeparator, '/') . '\d{3})*|(\d+))(' . preg_quote($decimalSeparator, '/') . '\d{2})?$/', $value)) { // Convert value to number $value = (float) trim(str_replace([$currencyCode, $thousandsSeparator, $decimalSeparator], ['', '', '.'], $value)); $cell->setValueExplicit($value, DataType::TYPE_NUMERIC); // Set style $cell->getWorksheet()->getStyle($cell->getCoordinate()) ->getNumberFormat()->setFormatCode( str_replace('$', $currencyCode, NumberFormat::FORMAT_CURRENCY_USD_SIMPLE) ); return true; } elseif (preg_match('/^\$ *(\d{1,3}(\,\d{3})*|(\d+))(\.\d{2})?$/', $value)) { // Convert value to number $value = (float) trim(str_replace(['$', ','], '', $value)); $cell->setValueExplicit($value, DataType::TYPE_NUMERIC); // Set style $cell->getWorksheet()->getStyle($cell->getCoordinate()) ->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_CURRENCY_USD_SIMPLE); return true; } // Check for time without seconds e.g. '9:45', '09:45' if (preg_match('/^(\d|[0-1]\d|2[0-3]):[0-5]\d$/', $value)) { return $this->setTimeHoursMinutes($value, $cell); } // Check for time with seconds '9:45:59', '09:45:59' if (preg_match('/^(\d|[0-1]\d|2[0-3]):[0-5]\d:[0-5]\d$/', $value)) { return $this->setTimeHoursMinutesSeconds($value, $cell); } // Check for datetime, e.g. '2008-12-31', '2008-12-31 15:59', '2008-12-31 15:59:10' if (($d = Date::stringToExcel($value)) !== false) { // Convert value to number $cell->setValueExplicit($d, DataType::TYPE_NUMERIC); // Determine style. Either there is a time part or not. Look for ':' if (strpos($value, ':') !== false) { $formatCode = 'yyyy-mm-dd h:mm'; } else { $formatCode = 'yyyy-mm-dd'; } $cell->getWorksheet()->getStyle($cell->getCoordinate()) ->getNumberFormat()->setFormatCode($formatCode); return true; } // Check for newline character "\n" if (strpos($value, "\n") !== false) { $cell->setValueExplicit($value, DataType::TYPE_STRING); // Set style $cell->getWorksheet()->getStyle($cell->getCoordinate()) ->getAlignment()->setWrapText(true); return true; } } // Not bound yet? Use parent... return parent::bindValue($cell, $value); } protected function setImproperFraction(array $matches, Cell $cell): bool { // Convert value to number $value = $matches[2] + ($matches[3] / $matches[4]); if ($matches[1] === '-') { $value = 0 - $value; } $cell->setValueExplicit((float) $value, DataType::TYPE_NUMERIC); // Build the number format mask based on the size of the matched values $dividend = str_repeat('?', strlen($matches[3])); $divisor = str_repeat('?', strlen($matches[4])); $fractionMask = "# {$dividend}/{$divisor}"; // Set style $cell->getWorksheet()->getStyle($cell->getCoordinate()) ->getNumberFormat()->setFormatCode($fractionMask); return true; } protected function setProperFraction(array $matches, Cell $cell): bool { // Convert value to number $value = $matches[2] / $matches[3]; if ($matches[1] === '-') { $value = 0 - $value; } $cell->setValueExplicit((float) $value, DataType::TYPE_NUMERIC); // Build the number format mask based on the size of the matched values $dividend = str_repeat('?', strlen($matches[2])); $divisor = str_repeat('?', strlen($matches[3])); $fractionMask = "{$dividend}/{$divisor}"; // Set style $cell->getWorksheet()->getStyle($cell->getCoordinate()) ->getNumberFormat()->setFormatCode($fractionMask); return true; } protected function setPercentage(string $value, Cell $cell): bool { // Convert value to number $value = ((float) str_replace('%', '', $value)) / 100; $cell->setValueExplicit($value, DataType::TYPE_NUMERIC); // Set style $cell->getWorksheet()->getStyle($cell->getCoordinate()) ->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_PERCENTAGE_00); return true; } protected function setTimeHoursMinutes(string $value, Cell $cell): bool { // Convert value to number [$hours, $minutes] = explode(':', $value); $days = ($hours / 24) + ($minutes / 1440); $cell->setValueExplicit($days, DataType::TYPE_NUMERIC); // Set style $cell->getWorksheet()->getStyle($cell->getCoordinate()) ->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_DATE_TIME3); return true; } protected function setTimeHoursMinutesSeconds(string $value, Cell $cell): bool { // Convert value to number [$hours, $minutes, $seconds] = explode(':', $value); $days = ($hours / 24) + ($minutes / 1440) + ($seconds / 86400); $cell->setValueExplicit($days, DataType::TYPE_NUMERIC); // Set style $cell->getWorksheet()->getStyle($cell->getCoordinate()) ->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_DATE_TIME4); return true; } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false