diff --git a/Distro/database/SQLite_Class.php b/Distro/database/SQLite_Class.php new file mode 100644 index 00000000..78265af0 --- /dev/null +++ b/Distro/database/SQLite_Class.php @@ -0,0 +1,139 @@ +DBFILE=$DBFILE; + $this->DBFLAGS=$flags; + $this->DBENCRYPT=$encryptionKey; + try{ + $this->DBLink = new SQLite3( $this->DBFILE, $this->DBFLAGS, $this->DBENCRYPT ); + $this->DBLink->busyTimeout(5000); + // WAL mode has better control over concurrency. + // Source: https://www.sqlite.org/wal.html + $this->DBLink->exec('PRAGMA journal_mode = wal;'); + $this->isConnected = true; + }catch( Exception $e ){ + echo $e->getMessage(); + }; + } + function CleanUpCache(){ + if ($DD=@opendir($this->CachePath)){ + while($FN=readdir($DD)){ + $CF=$this->CachePath.'/'.$FN; + if (is_file($CF)){ + if ( strstr($FN,'dbchache_') && (time()-filemtime($CF))>360){ + @unlink($CF); + }; + }; + }; + closedir($DD); + } else $this->isCached=false; + } + function ResetCache(){ + if ($DD=@opendir($this->CachePath)){ + while($FN=readdir($DD)){ + $CF=$this->CachePath.'/'.$FN; + if (is_file($CF)){ + if ( strstr($FN,'dbchache_')){ + @unlink($CF); + }; + }; + }; + closedir($DD); + } else $this->isCached=false; + } + function SetCacheDir($Path){ + $this->CachePath = $Path; + $this->isCached = is_dir($this->CachePath) && is_writable($this->CachePath); + if ($this->isCached) $this->CleanUpCache(); + } + function escape( $Str ){ + if( $this->isConnected ){ + return $this->DBLink->escapeString( $Str ); + }; + return ''; + } + function Query($QS,$ChacheIfAveable=true){ + if($this->isConnected){ + $QS = trim( $QS ); + if( $this->isCached && $ChacheIfAveable ){ + $QMD5=md5($QS); + $Prefetch=$this->CachePath.'/dbchache_'.$QMD5; + + if ( is_file($Prefetch)){ + + if ( (time()- filemtime($Prefetch))<360){ + $FData=file_get_contents($Prefetch); + $this->DebugLog .="[{$QS}] as (Cahed Data),\n"; + return unserialize($FData); + } else { + + $result = $this->DBLink->query( $QS ) or die (" Error during query [{$QS}]:");// . $this->DBLink->error ); + $RetVal=array(); + if( ( stripos( $QS, 'insert' ) === false ) && ( stripos( $QS, 'update' ) === false ) && $result !== false && is_a( $result, 'SQLite3Result' ) ){ + while( $array = $result->fetchArray( SQLITE3_ASSOC )) $RetVal[]=$array; + $result->finalize(); + }; + $FData=serialize($RetVal); + $FD=fopen($Prefetch,'w'); + fwrite($FD,$FData); + fclose($FD); + $this->DebugLog .="[{$QS}] as (".$this->DBLink->lastInsertRowID()."),\n"; + return $RetVal; + } + } else { + $result = $this->DBLink->query( $QS ) or die (" Error during query [{$QS}]:");// . $this->DBLink->error ); + $RetVal=array(); + if( ( stripos( $QS, 'insert' ) === false ) && ( stripos( $QS, 'update' ) === false ) && $result !== false && is_a( $result, 'SQLite3Result' ) ){ + while( $array = $result->fetchArray( SQLITE3_ASSOC )) $RetVal[]=$array; + $result->finalize(); + }; + $FData = serialize($RetVal); + $FD=fopen($Prefetch,'w'); + fwrite($FD,$FData); + fclose($FD); + $this->DebugLog .="[{$QS}] as (".$this->DBLink->lastInsertRowID()."),\n"; + return $RetVal; + } + } else { + $result = $this->DBLink->query( $QS ) or die (" Error during query [{$QS}]:");// . $this->DBLink->error ); + $RetVal=array(); + if( ( stripos( $QS, 'create' ) === false ) && ( stripos( $QS, 'insert' ) === false ) && ( stripos( $QS, 'update' ) === false ) && $result !== false && is_a( $result, 'SQLite3Result' ) ){ + while( $array = $result->fetchArray( SQLITE3_ASSOC )) $RetVal[]=$array; + $result->finalize(); + }; + $this->DebugLog .="[{$QS}] as (".$this->DBLink->lastInsertRowID()."),\n"; + return $RetVal; + }; + } else { + echo "No Connection to DB"; + }; + } + function getLastInsertID(){ + if($this->isConnected){ + return $this->DBLink->lastInsertRowID(); + }; + return -1; + } + function getDebugLog(){ + return $this->DebugLog; + } + function __destruct(){ + if( $this->isConnected ){ + $this->DBLink->close(); + unset( $this->DBLink ); + }; + } +} + + + + +?> \ No newline at end of file diff --git a/Distro/database/SimpleXLS.php b/Distro/database/SimpleXLS.php new file mode 100644 index 00000000..6ac70ead --- /dev/null +++ b/Distro/database/SimpleXLS.php @@ -0,0 +1,1327 @@ +'; + +if ( $xls = SimpleXLS::parse('excel5book.xls')) { + print_r( $xls->rows() ); // dump first sheet + print_r( $xls->rows(1)); /// dump second sheet +} else { + echo SimpleXLS::parseError(); +} + +echo ''; + */ + +/** + * A class for reading Microsoft Excel Spreadsheets. + * + * SimpleXLS version 2016-2020 packaged by Sergey Shuchkin from + * Spreadsheet_Excel_Reader class developed by Vadim Tkachenko + */ +class SimpleXLS +{ + public const BIFF8 = 0x600; + public const BIFF7 = 0x500; + public const WORKBOOKGLOBALS = 0x5; + public const WORKSHEET = 0x10; + + //const TYPE_BOF = 0x809; + public const TYPE_EOF = 0x0a; + public const TYPE_BOUNDSHEET = 0x85; + public const TYPE_DIMENSION = 0x200; + public const TYPE_ROW = 0x208; + public const TYPE_DBCELL = 0xd7; + public const TYPE_FILEPASS = 0x2f; + //const TYPE_NOTE = 0x1c; + //const TYPE_TXO = 0x1b6; + public const TYPE_RK = 0x7e; + public const TYPE_RK2 = 0x27e; + public const TYPE_MULRK = 0xbd; + public const TYPE_MULBLANK = 0xbe; + //const TYPE_INDEX = 0x20b; + public const TYPE_SST = 0xfc; + //const TYPE_EXTSST = 0xff; + //const TYPE_CONTINUE = 0x3c; + public const TYPE_LABEL = 0x204; + public const TYPE_LABELSST = 0xfd; + public const TYPE_NUMBER = 0x203; + public const TYPE_NAME = 0x18; + //const TYPE_ARRAY = 0x221; + //const TYPE_STRING = 0x207; + public const TYPE_FORMULA = 0x406; + public const TYPE_FORMULA2 = 0x6; + public const TYPE_FORMAT = 0x41e; + public const TYPE_XF = 0xe0; + public const TYPE_BOOLERR = 0x205; + //const TYPE_UNKNOWN = 0xffff; + public const TYPE_NINETEENFOUR = 0x22; + public const TYPE_MERGEDCELLS = 0xE5; + public const TYPE_WINDOW1 = 0x3D; + + //const DEF_NUM_FORMAT = "%.2f"; + public const DEF_NUM_FORMAT = '%s'; + + // OLE + public const NUM_BIG_BLOCK_DEPOT_BLOCKS_POS = 0x2c; + public const SMALL_BLOCK_DEPOT_BLOCK_POS = 0x3c; + public const ROOT_START_BLOCK_POS = 0x30; + public const BIG_BLOCK_SIZE = 0x200; + public const SMALL_BLOCK_SIZE = 0x40; + public const EXTENSION_BLOCK_POS = 0x44; + public const NUM_EXTENSION_BLOCK_POS = 0x48; + public const PROPERTY_STORAGE_BLOCK_SIZE = 0x80; + public const BIG_BLOCK_DEPOT_BLOCKS_POS = 0x4c; + public const SMALL_BLOCK_THRESHOLD = 0x1000; + // property storage offsets + public const SIZE_OF_NAME_POS = 0x40; + public const TYPE_POS = 0x42; + public const START_BLOCK_POS = 0x74; + public const SIZE_POS = 0x78; + /** + * Array of worksheets found + * + * @var array + * @access public + */ + public $boundsheets = array(); + public $activeSheet = 0; + + /** + * Array of format records found + * + * @var array + * @access public + */ + public $formatRecords = array(); + + /** + * + * @var array + * @access public + */ + public $sst = array(); + + /** + * Array of worksheets + * + * The data is stored in 'cells' and the meta-data is stored in an array + * called 'cellsInfo' + * + * Example: + * + * $sheets --> 'cells' --> row --> column --> Interpreted value + * --> 'cellsInfo' --> row --> column --> 'type' - Can be 'date', 'number', or 'unknown' + * --> 'raw' - The raw data that Excel stores for that data cell + * + * @var array + * @access public + */ + public $sheets = array(); + /** + * List of default date formats used by Excel + * + * @var array + * @access public + */ + public $dateFormats = array( + 0xe => 'd/m/Y', + 0xf => 'd-M-Y', + 0x10 => 'd-M', + 0x11 => 'M-Y', + 0x12 => 'h:i a', + 0x13 => 'h:i:s a', + 0x14 => 'H:i', + 0x15 => 'H:i:s', + 0x16 => 'd/m/Y H:i', + 0x2d => 'i:s', + 0x2e => 'H:i:s', + 0x2f => 'i:s.S' + ); +/** + * Default number formats used by Excel + * + * @var array + * @access public + */ + public $numberFormats = array( + 0x1 => '%1.0f', // "0" + 0x2 => '%1.2f', // "0.00", + 0x3 => '%1.0f', //"#,##0", + 0x4 => '%1.2f', //"#,##0.00", + 0x5 => '%1.0f', /*"$#,##0;($#,##0)",*/ + 0x6 => '$%1.0f', /*"$#,##0;($#,##0)",*/ + 0x7 => '$%1.2f', //"$#,##0.00;($#,##0.00)", + 0x8 => '$%1.2f', //"$#,##0.00;($#,##0.00)", + 0x9 => '%1.0f%%', // "0%" + 0xa => '%1.2f%%', // "0.00%" + 0xb => '%1.2f', // 0.00E00", + 0x25 => '%1.0f', // "#,##0;(#,##0)", + 0x26 => '%1.0f', //"#,##0;(#,##0)", + 0x27 => '%1.2f', //"#,##0.00;(#,##0.00)", + 0x28 => '%1.2f', //"#,##0.00;(#,##0.00)", + 0x29 => '%1.0f', //"#,##0;(#,##0)", + 0x2a => '$%1.0f', //"$#,##0;($#,##0)", + 0x2b => '%1.2f', //"#,##0.00;(#,##0.00)", + 0x2c => '$%1.2f', //"$#,##0.00;($#,##0.00)", + 0x30 => '%1.0f' + ); + protected $datetimeFormat = 'Y-m-d H:i:s'; + /** + * Default encoding + * + * @var string + * @access private + */ + protected $defaultEncoding = 'UTF-8'; + /** + * Default number format + * + * @var integer + * @access private + */ + protected $defaultFormat = self::DEF_NUM_FORMAT; + /** + * List of formats to use for each column + * + * @var array + * @access private + */ + protected $columnsFormat = array(); + + protected $nineteenFour; + protected $multiplier; + protected $sn; + protected $curFormat; + + // OLERead + protected $data; + protected $bigBlockChain; + protected $smallBlockChain; + protected $rootEntry; + protected $entry; + protected $props; + + // sergey.shuchkin@gmail.com + protected $wrkbook; // false - to use excel format + protected $error = false; + protected $debug; + + // {{{ Spreadsheet_Excel_Reader() + + /** + * Constructor + * + * @param string $filename XLS Filename or xls contents + * @param bool $isData If True then $filename is contents + * @param bool $debug Trigger PHP errors? + */ + public function __construct(string $filename, bool $isData = false, bool $debug = false) + { + $this->debug = $debug; + $this->_oleread($filename, $isData); + $this->_parse(); + } + public static function parseFile($filename, $debug = false) + { + return self::parse($filename, false, $debug); + } + + public static function parseData($data, $debug = false) + { + return self::parse($data, true, $debug); + } + public static function parse($filename, $isData = false, $debug = false) + { + $xls = new self($filename, $isData, $debug); + if ($xls->success()) { + return $xls; + } + self::parseError($xls->error()); + + return false; + } + public static function parseError($set = false) + { + static $error = false; + return $set ? $error = $set : $error; + } + public function error($set = false) + { + if ($set) { + $this->error = $set; + if ($this->debug) { + trigger_error($set); + } + } + + return $this->error; + } + public function success(): bool + { + return ! $this->error; + } + public function rows($worksheetIndex = 0, $limit = 0) + { + return iterator_to_array($this->readRows($worksheetIndex, $limit), false); + } + /** + * @param $sheetNum + * @param $limit + * @return \Generator + */ + public function readRows($sheetNum = 0, $limit = 0) + { + if ($this->sheets[ $sheetNum ]) { + $s = $this->sheets[ $sheetNum ]; + for ($i = 0; $i < $s['numRows']; $i ++) { + $r = array(); + for ($j = 0; $j < $s['numCols']; $j ++) { + $r[ $j ] = $s['cells'][$i][$j] ?? ''; + } + yield $r; + $limit--; + if ($limit === 0) { + break; + } + } + } + + return; + } + public function rowsEx($sheetNum = 0, $limit = 0): array + { + if ($this->sheets[ $sheetNum ]) { + $s = $this->sheets[ $sheetNum ]; + $result = array(); + for ($i = 0; $i < $s['numRows']; $i ++) { + $r = array(); + for ($j = 0; $j < $s['numCols']; $j ++) { + $v = $s['cellsInfo'][$i][$j] ?? array(); +// if ( $v['type'] === self::TYPE_RK || $v['type'] === self::TYPE_RK2 || + $v['value'] = $s['cells'][$i][$j] ?? ''; + $r[ $j ] = $v; + } + $result[] = $r; + $limit--; + if ($limit === 0) { + break; + } + } + + return $result; + } + + return []; + } + public function toHTML($worksheetIndex = 0): string + { + $s = ''; + foreach ($this->rows($worksheetIndex) as $r) { + $s .= ''; + foreach ($r as $c) { + $s .= '' . ( $c === '' ? ' ' : htmlspecialchars($c, ENT_QUOTES) ) . ''; + } + $s .= "\r\n"; + } + $s .= ''; + + return $s; + } + public function setDateTimeFormat($value): SimpleXLS + { + $this->datetimeFormat = is_string($value) ? $value : false; + return $this; + } + public function sheetNames(): array + { + $result = array(); + foreach ($this->boundsheets as $k => $v) { + $result[ $k ] = $v['name']; + } + return $result; + } + public function sheetName($index) + { + return isset($this->boundsheets[ $index ]) ? $this->boundsheets[ $index ]['name'] : null; + } + + // }}} + + protected function _oleread($sFileName, $isData = false): bool + { + if ($isData) { + $this->data = $sFileName; + } else { + // check if file exist and is readable (Darko Miljanovic) + if (! is_readable($sFileName)) { + $this->error('File not is readable ' . $sFileName); + return false; + } + + $this->data = file_get_contents($sFileName); + if (! $this->data) { + $this->error('File reading error ' . $sFileName); + return false; + } + } + //echo IDENTIFIER_OLE; + //echo 'start'; + if (strpos($this->data, pack('CCCCCCCC', 0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1)) !== 0) { + $this->error('File is not XLS'); + + return false; + } + + $numBigBlockDepotBlocks = $this->_getInt4d(self::NUM_BIG_BLOCK_DEPOT_BLOCKS_POS); + $sbdStartBlock = $this->_getInt4d(self::SMALL_BLOCK_DEPOT_BLOCK_POS); + $rootStartBlock = $this->_getInt4d(self::ROOT_START_BLOCK_POS); + $extensionBlock = $this->_getInt4d(self::EXTENSION_BLOCK_POS); + $numExtensionBlocks = $this->_getInt4d(self::NUM_EXTENSION_BLOCK_POS); + +/* + echo $this->numBigBlockDepotBlocks." "; + echo $this->sbdStartBlock." "; + echo $this->rootStartBlock." "; + echo $this->extensionBlock." "; + echo $this->numExtensionBlocks." "; + +*/ + //echo "sbdStartBlock = $this->sbdStartBlock\n"; + $bigBlockDepotBlocks = array(); + $pos = self::BIG_BLOCK_DEPOT_BLOCKS_POS; + // echo "pos = $pos"; + $bbdBlocks = $numBigBlockDepotBlocks; + + if ($numExtensionBlocks !== 0) { + $bbdBlocks = ( self::BIG_BLOCK_SIZE - self::BIG_BLOCK_DEPOT_BLOCKS_POS ) / 4; + } + + for ($i = 0; $i < $bbdBlocks; $i ++) { + $bigBlockDepotBlocks[ $i ] = $this->_getInt4d($pos); + $pos += 4; + } + + + for ($j = 0; $j < $numExtensionBlocks; $j ++) { + $pos = ( $extensionBlock + 1 ) * self::BIG_BLOCK_SIZE; + $blocksToRead = min($numBigBlockDepotBlocks - $bbdBlocks, self::BIG_BLOCK_SIZE / 4 - 1); + + for ($i = $bbdBlocks; $i < $bbdBlocks + $blocksToRead; $i ++) { + $bigBlockDepotBlocks[ $i ] = $this->_getInt4d($pos); + $pos += 4; + } + + $bbdBlocks += $blocksToRead; + if ($bbdBlocks < $numBigBlockDepotBlocks) { + $extensionBlock = $this->_getInt4d($pos); + } + } + + // var_dump($bigBlockDepotBlocks); + + // readBigBlockDepot + + $index = 0; + $this->bigBlockChain = array(); + + for ($i = 0; $i < $numBigBlockDepotBlocks; $i ++) { + $pos = ( $bigBlockDepotBlocks[ $i ] + 1 ) * self::BIG_BLOCK_SIZE; + //echo "pos = $pos"; + for ($j = 0; $j < self::BIG_BLOCK_SIZE / 4; $j ++) { + $this->bigBlockChain[ $index ] = $this->_getInt4d($pos); + $pos += 4; + $index ++; + } + } + + //var_dump($this->bigBlockChain); + //echo '=====2'; + // readSmallBlockDepot(); + + $index = 0; + $sbdBlock = $sbdStartBlock; + $this->smallBlockChain = array(); + + while ($sbdBlock !== - 2) { + $pos = ( $sbdBlock + 1 ) * self::BIG_BLOCK_SIZE; + + for ($j = 0; $j < self::BIG_BLOCK_SIZE / 4; $j ++) { + $this->smallBlockChain[ $index ] = $this->_getInt4d($pos); + $pos += 4; + $index ++; + } + + $sbdBlock = $this->bigBlockChain[ $sbdBlock ]; + } + + + // readData(rootStartBlock) + $block = $rootStartBlock; + + $this->entry = $this->_readData($block); + + /* + while ($block != -2) { + $pos = ($block + 1) * self::BIG_BLOCK_SIZE; + $this->entry = $this->entry.substr($this->_data, $pos, self::BIG_BLOCK_SIZE); + $block = $this->bigBlockChain[$block]; + } + */ + //echo '==='.$this->entry."==="; + $this->_readPropertySets(); + $this->data = $this->_readWorkBook(); + + return true; + } + + // {{{ setOutputEncoding() + protected function _getInt2d($pos): int + { + return ord($this->data[ $pos ]) | ord($this->data[ $pos + 1 ]) << 8; +// return ($value > 0x7FFFFFFF) ? $value - 0x100000000 : $value; + } + protected function _getInt4d($pos): int + { + $value = ord($this->data[ $pos ]) | ( ord($this->data[ $pos + 1 ]) << 8 ) | ( ord($this->data[ $pos + 2 ]) << 16 ) | ( ord($this->data[ $pos + 3 ]) << 24 ); + return ($value > 0x7FFFFFFF) ? $value - 0x100000000 : $value; + } + + // }}} + + // {{{ setRowColOffset() + + protected function _readData($bl): string + { + $block = $bl; + + $data = ''; + + while ($block !== - 2) { + $pos = ( $block + 1 ) * self::BIG_BLOCK_SIZE; + $data .= substr($this->data, $pos, self::BIG_BLOCK_SIZE); + //echo "pos = $pos data=$data\n"; + $block = $this->bigBlockChain[ $block ]; + } + + return $data; + } + + // }}} + // {{{ setDefaultFormat() + + protected function _readPropertySets(): void + { + $offset = 0; + //var_dump($this->entry); + while ($offset < strlen($this->entry)) { + $d = substr($this->entry, $offset, self::PROPERTY_STORAGE_BLOCK_SIZE); + + $nameSize = ord($d[ self::SIZE_OF_NAME_POS ]) | ( ord($d[ self::SIZE_OF_NAME_POS + 1 ]) << 8 ); + + $type = ord($d[ self::TYPE_POS ]); + //$maxBlock = $this->_strlen($d) / self::BIG_BLOCK_SIZE - 1; + + $startBlock = ord($d[ self::START_BLOCK_POS]) | ( ord($d[ self::START_BLOCK_POS + 1 ]) << 8 ) | ( ord($d[ self::START_BLOCK_POS + 2 ]) << 16 ) | ( ord($d[ self::START_BLOCK_POS + 3 ]) << 24 ); + $size = ord($d[ self::SIZE_POS]) | ( ord($d[ self::SIZE_POS + 1 ]) << 8 ) | ( ord($d[ self::SIZE_POS + 2 ]) << 16 ) | ( ord($d[ self::SIZE_POS + 3 ]) << 24 ); + + $name = ''; + for ($i = 0; $i < $nameSize; $i ++) { + $name .= $d[ $i ]; + } + + $name = str_replace("\x00", '', $name); + + $this->props[] = array( + 'name' => $name, + 'type' => $type, + 'startBlock' => $startBlock, + 'size' => $size + ); + + if (( $name === 'Workbook' ) || ( $name === 'Book' )) { + $this->wrkbook = count($this->props) - 1; + } + + if ($name === 'Root Entry') { + $this->rootEntry = count($this->props) - 1; + } + + //echo "name ==$name=\n"; + + + $offset += self::PROPERTY_STORAGE_BLOCK_SIZE; + } + } + + // }}} + // {{{ setColumnFormat() + + protected function _readWorkBook(): string + { + if ($this->props[ $this->wrkbook ]['size'] < self::SMALL_BLOCK_THRESHOLD) { +// getSmallBlockStream(PropertyStorage ps) + + $rootdata = $this->_readData($this->props[ $this->rootEntry ]['startBlock']); + + $streamData = ''; + $block = (int) $this->props[ $this->wrkbook ]['startBlock']; + //$count = 0; + while ($block !== - 2) { + $pos = $block * self::SMALL_BLOCK_SIZE; + $streamData .= substr($rootdata, $pos, self::SMALL_BLOCK_SIZE); + + $block = $this->smallBlockChain[ $block ]; + } + + return $streamData; + } + + $numBlocks = $this->props[ $this->wrkbook ]['size'] / self::BIG_BLOCK_SIZE; + if ($this->props[ $this->wrkbook ]['size'] % self::BIG_BLOCK_SIZE !== 0) { + $numBlocks ++; + } + + if ($numBlocks === 0) { + return ''; + } + + //echo "numBlocks = $numBlocks\n"; + //byte[] streamData = new byte[numBlocks * self::BIG_BLOCK_SIZE]; + //print_r($this->wrkbook); + $streamData = ''; + $block = $this->props[ $this->wrkbook ]['startBlock']; + + //echo "block = $block"; + while ($block !== - 2) { + $pos = ( $block + 1 ) * self::BIG_BLOCK_SIZE; + $streamData .= substr($this->data, $pos, self::BIG_BLOCK_SIZE); + $block = $this->bigBlockChain[ $block ]; + } + + //echo 'stream'.$streamData; + return $streamData; + } + + + // }}} + protected function parseSubstreamHeader($pos): array + { + $length = $this->_getInt2d($pos + 2); + + $version = $this->_getInt2d($pos + 4); + $substreamType = $this->_getInt2d($pos + 6); + return array( $length, $version, $substreamType ); + } + // {{{ _parse() + + /** + * Parse a workbook + * + * @access private + * @return bool + */ + protected function _parse() + { + $pos = 0; + +// $code = ord($this->data[$pos]) | ord($this->data[$pos+1])<<8; + [$length, $version, $substreamType] = $this->parseSubstreamHeader($pos); +// echo "Start parse code=".base_convert($code,10,16)." version=".base_convert($version,10,16)." substreamType=".base_convert($substreamType,10,16).""."\n"; + +// die(); + + if (( $version !== self::BIFF8 ) && + ( $version !== self::BIFF7 ) + ) { + return false; + } + + if ($substreamType !== self::WORKBOOKGLOBALS) { + return false; + } + + //print_r($rec); + $pos += $length + 4; + + $code = ord($this->data[ $pos ]) | ord($this->data[ $pos + 1 ]) << 8; + $length = ord($this->data[ $pos + 2 ]) | ord($this->data[ $pos + 3 ]) << 8; + + while ($code !== self::TYPE_EOF) { + switch ($code) { + case self::TYPE_SST: + //echo "Type_SST\n"; + $formattingRuns = 0; + $extendedRunLength = 0; + $spos = $pos + 4; + $limitpos = $spos + $length; + $uniqueStrings = $this->_getInt4d($spos + 4); + $spos += 8; + for ($i = 0; $i < $uniqueStrings; $i ++) { + // Read in the number of characters + if ($spos === $limitpos) { + $opcode = ord($this->data[ $spos ]) | ord($this->data[ $spos + 1 ]) << 8; + $conlength = ord($this->data[ $spos + 2 ]) | ord($this->data[ $spos + 3 ]) << 8; + if ($opcode !== 0x3c) { + return - 1; + } + $spos += 4; + $limitpos = $spos + $conlength; + } + $numChars = ord($this->data[ $spos ]) | ( ord($this->data[ $spos + 1 ]) << 8 ); + //echo "i = $i pos = $pos numChars = $numChars "; + $spos += 2; + $optionFlags = ord($this->data[ $spos ]); + $spos ++; + $asciiEncoding = ( ( $optionFlags & 0x01 ) === 0 ); + $extendedString = ( ( $optionFlags & 0x04 ) !== 0 ); + + // See if string contains formatting information + $richString = ( ( $optionFlags & 0x08 ) !== 0 ); + + if ($richString) { + // Read in the crun + $formattingRuns = $this->_getInt2d($spos); + $spos += 2; + } + + if ($extendedString) { + // Read in cchExtRst + $extendedRunLength = $this->_getInt4d($spos); + $spos += 4; + } + + $len = $asciiEncoding ? $numChars : $numChars * 2; + if ($spos + $len < $limitpos) { + $retstr = substr($this->data, $spos, $len); + $spos += $len; + } else { + // found countinue + $retstr = substr($this->data, $spos, $limitpos - $spos); + $bytesRead = $limitpos - $spos; + $charsLeft = $numChars - ( $asciiEncoding ? $bytesRead : ( $bytesRead / 2 ) ); + $spos = $limitpos; + + while ($charsLeft > 0) { + $opcode = $this->_getInt2d($spos); + $conlength = $this->_getInt2d($spos + 2); + if ($opcode !== 0x3c) { + return - 1; + } + $spos += 4; + $limitpos = $spos + $conlength; + $option = ord($this->data[ $spos ]); + $spos ++; + if ($asciiEncoding && ( $option === 0 )) { + $len = min($charsLeft, $limitpos - $spos); // min($charsLeft, $conlength); + $retstr .= substr($this->data, $spos, $len); + $charsLeft -= $len; + $asciiEncoding = true; + } elseif (! $asciiEncoding && ( $option !== 0 )) { + $len = min($charsLeft * 2, $limitpos - $spos); // min($charsLeft, $conlength); + $retstr .= substr($this->data, $spos, $len); + $charsLeft -= $len / 2; + $asciiEncoding = false; + } elseif (! $asciiEncoding && ( $option === 0 )) { + // Bummer - the string starts off as Unicode, but after the + // continuation it is in straightforward ASCII encoding + $len = min($charsLeft, $limitpos - $spos); // min($charsLeft, $conlength); + for ($j = 0; $j < $len; $j ++) { + $retstr .= $this->data[ $spos + $j ] . chr(0); + } + $charsLeft -= $len; + $asciiEncoding = false; + } else { + $newstr = ''; + for ($j = 0, $len_retstr = strlen($retstr); $j < $len_retstr; $j ++) { + $newstr = $retstr[ $j ] . chr(0); + } + $retstr = $newstr; + $len = min($charsLeft * 2, $limitpos - $spos); // min($charsLeft, $conlength); + $retstr .= substr($this->data, $spos, $len); + $charsLeft -= $len / 2; + $asciiEncoding = false; + //echo "Izavrat\n"; + } + $spos += $len; + } + } + $retstr = $asciiEncoding ? $this->_latin1toDef($retstr) : $this->_UTF16toDef($retstr); +// echo "Str $i = $retstr\n"; + if ($richString) { + $spos += 4 * $formattingRuns; + } + + // For extended strings, skip over the extended string data + if ($extendedString) { + $spos += $extendedRunLength; + } + //if ($retstr == 'Derby'){ + // echo "bb\n"; + //} + $this->sst[] = $retstr; + } + /*$continueRecords = array(); + while ($this->getNextCode() == Type_CONTINUE) { + $continueRecords[] = &$this->nextRecord(); + } + //echo " 1 Type_SST\n"; + $this->shareStrings = new SSTRecord($r, $continueRecords); + //print_r($this->shareStrings->strings); + */ + // echo 'SST read: '.($time_end-$time_start)."\n"; + break; + + case self::TYPE_FILEPASS: + return false; + case self::TYPE_NAME: + //echo "Type_NAME\n"; + break; + case self::TYPE_FORMAT: + $indexCode = $this->_getInt2d($pos + 4); + + if ($version === self::BIFF8) { + $numchars = $this->_getInt2d($pos + 6); + if (ord($this->data[ $pos + 8 ]) === 0) { // ascii + $formatString = substr($this->data, $pos + 9, $numchars); + $formatString = $this->_latin1toDef($formatString); + } else { + $formatString = substr($this->data, $pos + 9, $numchars * 2); + $formatString = $this->_UTF16toDef($formatString); + } + } else { + $numchars = ord($this->data[ $pos + 6 ]); + $formatString = substr($this->data, $pos + 7, $numchars * 2); + $formatString = $this->_latin1toDef($formatString); + } + + $this->formatRecords[ $indexCode ] = $formatString; +// echo "Type.FORMAT[$indexCode]=$formatString\n"; + break; + case self::TYPE_XF: + $formatstr = ''; + $indexCode = $this->_getInt2d($pos + 6); +// echo "\nType.XF code=".$indexCode." dateFormat=".$this->dateFormats[ $indexCode ]." numberFormats=".$this->numberFormats[ $indexCode ].PHP_EOL; + if (array_key_exists($indexCode, $this->dateFormats)) { + //echo "isdate ".$dateFormats[$indexCode]; + $this->formatRecords['xfrecords'][] = array( + 'type' => 'date', + 'format' => $this->dateFormats[ $indexCode ] + ); + } elseif (array_key_exists($indexCode, $this->numberFormats)) { + //echo "isnumber ".$this->numberFormats[$indexCode]; + $this->formatRecords['xfrecords'][] = array( + 'type' => 'number', + 'format' => $this->numberFormats[ $indexCode ] + ); + } else { + $isdate = false; + if ($indexCode > 0) { + if (isset($this->formatRecords[ $indexCode ])) { +// die( 'L:'.__LINE__ ); + $formatstr = $this->formatRecords[ $indexCode ]; + } + //echo '.other.'; +// echo "\nfl=".strlen( $formatstr)." fs=$formatstr=\n"; +// echo "\ncode=".$indexCode." fl=".strlen( $formatstr)." fs=$formatstr=\n"; + $fs = str_replace('\\', '', $formatstr); + if ($fs && preg_match('/^[hmsday\/\-:\., ]+$/i', $fs)) { // found day and time format + $isdate = true; + $formatstr = str_replace(array( 'yyyy',':mm','mm','dddd','dd', 'h','ss' ), array('Y',':i','m','l','d', 'H','s' ), $fs); + } + } + + if ($isdate) { + $this->formatRecords['xfrecords'][] = array( + 'type' => 'date', + 'format' => $formatstr, + 'code' => $indexCode + ); + } else { +// echo 'fs='.$formatstr.PHP_EOL; + $this->formatRecords['xfrecords'][] = array( + 'type' => 'other', + 'format' => '', + 'code' => $indexCode + ); + } + } +// echo count( $this->formatRecords['xfrecords'] ).' fs='.$formatstr.' ' . PHP_EOL; + //echo "\n"; + break; + case self::TYPE_NINETEENFOUR: + //echo "Type.NINETEENFOUR\n"; + $this->nineteenFour = ( ord($this->data[ $pos + 4 ]) === 1 ); + break; + case self::TYPE_BOUNDSHEET: + //echo "Type.BOUNDSHEET\n"; + $rec_offset = $this->_getInt4d($pos + 4); +// $rec_typeFlag = ord($this->_data[$pos + 8]); + $rec_length = ord($this->data[ $pos + 10 ]); + $hidden = false; + $rec_name = ''; + if ($version === self::BIFF8) { + //ord($this->data[$pos + 9]) + $hidden = ord($this->data[$pos + 8]) === 1; + $chartype = ord($this->data[ $pos + 11 ]); + if ($chartype === 0) { + $rec_name = substr($this->data, $pos + 12, $rec_length); + $rec_name = $this->_latin1toDef($rec_name); + } else { + $rec_name = substr($this->data, $pos + 12, $rec_length * 2); + $rec_name = $this->_UTF16toDef($rec_name); + } + } elseif ($version === self::BIFF7) { + $rec_name = substr($this->data, $pos + 11, $rec_length); + } + $this->boundsheets[] = array( + 'name' => $rec_name, + 'offset' => $rec_offset, + 'hidden' => $hidden, + 'active' => false + ); + + break; + + case self::TYPE_WINDOW1: + $this->activeSheet = $this->_getInt2d($pos + 14); + break; + } + + //echo "Code = ".base_convert($r['code'],10,16)."\n"; + $pos += $length + 4; + $code = $this->_getInt2d($pos); + $length = $this->_getInt2d($pos + 2); + + //$r = &$this->nextRecord(); + //echo "1 Code = ".base_convert($r['code'],10,16)."\n"; + } + + foreach ($this->boundsheets as $key => $val) { + $this->sn = $key; + $this->_parseSheet($val['offset']); + if ($key === $this->activeSheet) { + $this->boundsheets[ $key ]['active'] = true; + } + } + + return true; + } + protected function _latin1toDef($string) + { + $result = $string; + if ($this->defaultEncoding) { + $result = mb_convert_encoding($string, $this->defaultEncoding, 'ISO-8859-1'); + } + + return $result; + } + protected function _UTF16toDef($string) + { + $result = $string; + if ($this->defaultEncoding && $this->defaultEncoding !== 'UTF-16LE') { + $result = mb_convert_encoding($string, $this->defaultEncoding, 'UTF-16LE'); + } + + return $result; + } + + protected function _parseSheet($spos): bool + { + $cont = true; + // read BOF +// $code = ord($this->_data[$spos]) | ord($this->_data[$spos + 1]) << 8; + [$length, $version, $substreamType] = $this->parseSubstreamHeader($spos); + + if (( $version !== self::BIFF8 ) && ( $version !== self::BIFF7 )) { + return false; + } + + if ($substreamType !== self::WORKSHEET) { + return false; + } + //echo "Start parse code=".base_convert($code,10,16)." version=".base_convert($version,10,16)." substreamType=".base_convert($substreamType,10,16).""."\n"; + $spos += $length + 4; + //var_dump($this->formatRecords); + //echo "code $code $length"; + + $this->sheets[ $this->sn ]['maxrow'] = 0; + $this->sheets[ $this->sn ]['maxcol'] = 0; + $this->sheets[ $this->sn ]['numRows'] = 0; + $this->sheets[ $this->sn ]['numCols'] = 0; + + while ($cont) { + //echo "mem= ".memory_get_usage()."\n"; +// $r = &$this->file->nextRecord(); + $lowcode = ord($this->data[ $spos ]); + if ($lowcode === self::TYPE_EOF) { + break; + } + $t_code = $lowcode | ord($this->data[ $spos + 1 ]) << 8; + $length = ord($this->data[ $spos + 2 ]) | ord($this->data[ $spos + 3 ]) << 8; + $spos += 4; + + //echo "Code=".base_convert($code,10,16)." $code\n"; + $this->multiplier = 1; // need for format with % + switch ($t_code) { + case self::TYPE_DIMENSION: + //echo 'Type_DIMENSION '; + if (!isset($this->numRows)) { + if (( $length === 10 ) || ( $version === self::BIFF7 )) { + $this->sheets[ $this->sn ]['numRows'] = ord($this->data[ $spos + 2 ]) | ord($this->data[ $spos + 3 ]) << 8; + $this->sheets[ $this->sn ]['numCols'] = ord($this->data[ $spos + 6 ]) | ord($this->data[ $spos + 7 ]) << 8; + } else { + $this->sheets[ $this->sn ]['numRows'] = ord($this->data[ $spos + 4 ]) | ord($this->data[ $spos + 5 ]) << 8; + $this->sheets[ $this->sn ]['numCols'] = ord($this->data[ $spos + 10 ]) | ord($this->data[ $spos + 11 ]) << 8; + } + } + //echo 'numRows '.$this->numRows.' '.$this->numCols."\n"; + break; + case self::TYPE_MERGEDCELLS: + $cellRanges = ord($this->data[ $spos ]) | ord($this->data[ $spos + 1 ]) << 8; + for ($i = 0; $i < $cellRanges; $i ++) { + $fr = ord($this->data[ $spos + 8 * $i + 2 ]) | ord($this->data[ $spos + 8 * $i + 3 ]) << 8; + $lr = ord($this->data[ $spos + 8 * $i + 4 ]) | ord($this->data[ $spos + 8 * $i + 5 ]) << 8; + $fc = ord($this->data[ $spos + 8 * $i + 6 ]) | ord($this->data[ $spos + 8 * $i + 7 ]) << 8; + $lc = ord($this->data[ $spos + 8 * $i + 8 ]) | ord($this->data[ $spos + 8 * $i + 9 ]) << 8; + //$this->sheets[$this->sn]['mergedCells'][] = array($fr + 1, $fc + 1, $lr + 1, $lc + 1); + if ($lr - $fr > 0) { + $this->sheets[ $this->sn ]['cellsInfo'][ $fr + 1 ][ $fc + 1 ]['rowspan'] = $lr - $fr + 1; + } + if ($lc - $fc > 0) { + $this->sheets[ $this->sn ]['cellsInfo'][ $fr + 1 ][ $fc + 1 ]['colspan'] = $lc - $fc + 1; + } + } + //echo "Merged Cells $cellRanges $lr $fr $lc $fc\n"; + break; + case self::TYPE_RK: + case self::TYPE_RK2: + //echo 'self::TYPE_RK'."\n"; + $row = ord($this->data[ $spos ]) | ord($this->data[ $spos + 1 ]) << 8; + $column = ord($this->data[ $spos + 2 ]) | ord($this->data[ $spos + 3 ]) << 8; + $rknum = $this->_getInt4d($spos + 6); + $numValue = $this->_getIEEE754($rknum); + //echo $numValue." "; + $t_alias = 'n'; + if ($this->isDate($spos)) { + [$string, $raw] = $this->createDate((int) $numValue); + $t_alias = 'd'; + } else { + $raw = $numValue; + if (isset($this->columnsFormat[ $column + 1 ])) { + $this->curFormat = $this->columnsFormat[ $column + 1 ]; + } + $string = sprintf($this->curFormat, $numValue * $this->multiplier); + //$this->addcell(RKRecord($r)); + } + $this->addCell($row, $column, $string, $raw, $t_code, $t_alias); + //echo "Type_RK $row $column $string $raw {$this->curformat}\n"; + break; + case self::TYPE_LABELSST: + $row = ord($this->data[ $spos ]) | ord($this->data[ $spos + 1 ]) << 8; + $column = ord($this->data[ $spos + 2 ]) | ord($this->data[ $spos + 3 ]) << 8; +// $xfindex = ord($this->_data[$spos + 4]) | ord($this->_data[$spos + 5]) << 8; + $index = $this->_getInt4d($spos + 6); + //var_dump($this->sst); + $this->addCell($row, $column, $this->sst[ $index ], $index, $t_code, 's'); + //echo "LabelSST $row $column $string\n"; + break; + case self::TYPE_MULRK: + $row = ord($this->data[ $spos ]) | ord($this->data[ $spos + 1 ]) << 8; + $colFirst = ord($this->data[ $spos + 2 ]) | ord($this->data[ $spos + 3 ]) << 8; + $colLast = ord($this->data[ $spos + $length - 2 ]) | ord($this->data[ $spos + $length - 1 ]) << 8; + $columns = $colLast - $colFirst + 1; + $tmppos = $spos + 4; + $t_alias = 'n'; + for ($i = 0; $i < $columns; $i ++) { + $numValue = $this->_getIEEE754($this->_getInt4d($tmppos + 2)); + if ($this->isDate($tmppos - 4)) { + [$string, $raw] = $this->createDate((int) $numValue); + $t_alias = 'd'; + } else { + $raw = $numValue; + if (isset($this->columnsFormat[ $colFirst + $i + 1 ])) { + $this->curFormat = $this->columnsFormat[ $colFirst + $i + 1 ]; + } + $string = sprintf($this->curFormat, $numValue * $this->multiplier); + } + //$rec['rknumbers'][$i]['xfindex'] = ord($rec['data'][$pos]) | ord($rec['data'][$pos+1]) << 8; + $tmppos += 6; + $this->addCell($row, $colFirst + $i, $string, $raw, $t_code, $t_alias); + //echo "MULRK $row ".($colFirst + $i)." $string\n"; + } + //MulRKRecord($r); + // Get the individual cell records from the multiple record + //$num = ; + + break; + case self::TYPE_NUMBER: + $row = ord($this->data[ $spos ]) | ord($this->data[ $spos + 1 ]) << 8; + $column = ord($this->data[ $spos + 2 ]) | ord($this->data[ $spos + 3 ]) << 8; + $tmp = unpack('ddouble', substr($this->data, $spos + 6, 8)); // It machine machine dependent + $t_alias = 'n'; + if ($this->isDate($spos)) { + [$string, $raw] = $this->createDate((int) $tmp['double']); + $t_alias = 'd'; + // $this->addcell(DateRecord($r, 1)); + } else { + //$raw = $tmp['']; + if (isset($this->columnsFormat[ $column + 1 ])) { + $this->curFormat = $this->columnsFormat[ $column + 1 ]; + } + $raw = $this->createNumber($spos); + $string = sprintf($this->curFormat, $raw * $this->multiplier); + + // $this->addcell(NumberRecord($r)); + } + $this->addCell($row, $column, $string, $raw, $t_code, $t_alias); + //echo "Number $row $column $string\n"; + break; + case self::TYPE_FORMULA: + case self::TYPE_FORMULA2: + $row = ord($this->data[ $spos ]) | ord($this->data[ $spos + 1 ]) << 8; + $column = ord($this->data[ $spos + 2 ]) | ord($this->data[ $spos + 3 ]) << 8; + /* + $byte6 = ord($this->_data[$spos + 6]); + $byte12 = ord($this->_data[$spos + 12]); + $byte13 = ord($this->_data[$spos + 13]); + + if ( $byte6 === 0 && $byte12 === 255 && $byte13 === 255 ) { + //String formula. Result follows in a STRING record + //echo "FORMULA $row $column Formula with a string\n"; + } else if ($byte6 === 1 && $byte12 === 255 && $byte13 === 255 ) { + //Boolean formula. Result is in +2; 0=false,1=true + } else if ($byte6 === 2 && $byte12 === 255 && $byte13 === 255) { + //Error formula. Error code is in +2; + } else if ( $byte6 === 3 && $byte12 === 255 && $byte13 === 255) { + //Formula result is a null string. + */ + if (! ( ord($this->data[ $spos + 6 ]) < 4 && ord($this->data[ $spos + 12 ]) === 255 && ord($this->data[ $spos + 13 ]) === 255 )) { + // result is a number, so first 14 bytes are just like a _NUMBER record + $tmp = unpack('ddouble', substr($this->data, $spos + 6, 8)); // It machine machine dependent + if ($this->isDate($spos)) { + [$string, $raw] = $this->createDate((int) $tmp['double']); + // $this->addcell(DateRecord($r, 1)); + } else { + //$raw = $tmp['']; + if (isset($this->columnsFormat[ $column + 1 ])) { + $this->curFormat = $this->columnsFormat[ $column + 1 ]; + } + $raw = $this->createNumber($spos); + $string = sprintf($this->curFormat, $raw * $this->multiplier); + + // $this->addcell(NumberRecord($r)); + } + $this->addCell($row, $column, $string, $raw, $t_code, 'f'); + //echo "Number $row $column $string\n"; + } + break; + case self::TYPE_BOOLERR: + $row = $this->_getInt2d($spos); + $column = $this->_getInt2d($spos + 2); + $string = ord($this->data[ $spos + 6 ]); + $this->addCell($row, $column, $string, $string, $t_code, 'b'); + //echo 'Type_BOOLERR '."\n"; + break; + case self::TYPE_ROW: + case self::TYPE_DBCELL: + case self::TYPE_MULBLANK: + break; + case self::TYPE_LABEL: + $row = $this->_getInt2d($spos); + $column = $this->_getInt2d($spos + 2); + $string = substr($this->data, $spos + 8, ord($this->data[ $spos + 6 ]) | ord($this->data[ $spos + 7 ]) << 8); + $this->addCell($row, $column, $string, '', $t_code, 'inlineStr'); + + // $this->addcell(LabelRecord($r)); + break; + + case self::TYPE_EOF: + $cont = false; + break; + default: + //echo ' unknown :'.base_convert($r['code'],10,16)."\n"; + break; + } + $spos += $length; + } + + if ($this->sheets[ $this->sn ]['numRows'] === 0) { + $this->sheets[ $this->sn ]['numRows'] = $this->sheets[ $this->sn ]['maxrow']; + } + if ($this->sheets[ $this->sn ]['numCols'] === 0) { + $this->sheets[ $this->sn ]['numCols'] = $this->sheets[ $this->sn ]['maxcol']; + } + + return true; + } + + //}}} + //{{{ createDate() + + protected function _getIEEE754($rknum) + { + if (( $rknum & 0x02 ) !== 0) { + $value = $rknum >> 2; + } else { +//mmp +// first comment out the previously existing 7 lines of code here +// $tmp = unpack("d", pack("VV", 0, ($rknum & 0xfffffffc))); +// //$value = $tmp['']; +// if (array_key_exists(1, $tmp)) { +// $value = $tmp[1]; +// } else { +// $value = $tmp['']; +// } +// I got my info on IEEE754 encoding from +// http://research.microsoft.com/~hollasch/cgindex/coding/ieeefloat.html +// The RK format calls for using only the most significant 30 bits of the +// 64 bit floating point value. The other 34 bits are assumed to be 0 +// So, we use the upper 30 bits of $rknum as follows... + $sign = ( $rknum & 0x80000000 ) >> 31; + $exp = ( $rknum & 0x7ff00000 ) >> 20; + $mantissa = ( 0x100000 | ( $rknum & 0x000ffffc ) ); + $value = $mantissa / (2 ** (20 - ($exp - 1023))); + if ($sign) { + $value = - 1 * $value; + } +//end of changes by mmp + } + + if (( $rknum & 0x01 ) !== 0) { + $value /= 100; + } + + return $value; + } + + protected function isDate($spos): bool + { + //$xfindex = GetInt2d(, 4); + $xfindex = ord($this->data[ $spos + 4 ]) | ord($this->data[ $spos + 5 ]) << 8; +// echo 'check is date '.$xfindex.' '.$this->formatRecords['xfrecords'][$xfindex]['type']." ".$this->formatRecords['xfrecords'][ $xfindex ]['format']."\n"; + + + + if ($this->formatRecords['xfrecords'][ $xfindex ]['type'] === 'date') { + $this->curFormat = $this->formatRecords['xfrecords'][ $xfindex ]['format']; + + return true; + } + + if ($this->formatRecords['xfrecords'][ $xfindex ]['type'] === 'number') { + $this->curFormat = $this->formatRecords['xfrecords'][ $xfindex ]['format']; + if (strpos($this->curFormat, '%%') !== false) { + $this->multiplier = 100; + } + } else { + $this->curFormat = $this->defaultFormat; + } + + return false; + } + + /** + * Convert the raw Excel date into a human readable format + * + * Dates in Excel are stored as number of seconds from an epoch. On + * Windows, the epoch is 30/12/1899 and on Mac it's 01/01/1904 + * + * @param integer $timevalue The raw Excel value to convert + * + * @return array First element is the converted date, the second element is number a unix timestamp + */ + public function createDate(int $timevalue): array + { +// $offset = ($timeoffset===null)? date('Z') : $timeoffset * 3600; + if ($timevalue > 1) { + $timevalue -= ( $this->nineteenFour ? 24107 : 25569 ); + } + $ts = round($timevalue * 24 * 3600); + $string = $this->datetimeFormat ? gmdate($this->datetimeFormat, $ts) : gmdate($this->curFormat, $ts); + return array( $string, $ts ); + } + + protected function addCell($row, $col, $string, $raw = '', $type_code = 0, $type_alias = ''): void + { + //echo "ADD cel $row-$col $string\n"; + $this->sheets[ $this->sn ]['maxrow'] = max($this->sheets[ $this->sn ]['maxrow'], $row); + $this->sheets[ $this->sn ]['maxcol'] = max($this->sheets[ $this->sn ]['maxcol'], $col); + $this->sheets[ $this->sn ]['cells'][ $row ][ $col ] = $string; + if ($raw) { + $this->sheets[ $this->sn ]['cellsInfo'][ $row ][ $col ]['raw'] = $raw; + } + if ($type_code) { + $this->sheets[$this->sn]['cellsInfo'][$row][$col]['type'] = $type_code; + $this->sheets[$this->sn]['cellsInfo'][$row][$col]['t'] = $type_alias; + } + } + + protected function createNumber($spos) + { + $rknumhigh = $this->_getInt4d($spos + 10); + $rknumlow = $this->_getInt4d($spos + 6); + //for ($i=0; $i<8; $i++) { echo ord($this->_data[$i+$spos+6]) . " "; } echo ""; + $sign = ( $rknumhigh & 0x80000000 ) >> 31; + $exp = ( $rknumhigh & 0x7ff00000 ) >> 20; + $mantissa = ( 0x100000 | ( $rknumhigh & 0x000fffff ) ); + $mantissalow1 = ( $rknumlow & 0x80000000 ) >> 31; + $mantissalow2 = ( $rknumlow & 0x7fffffff ); + $value = $mantissa / (2 ** (20 - ($exp - 1023))); + if ($mantissalow1 !== 0) { + $value += 1 / (2 ** (21 - ($exp - 1023))); + } + $value += $mantissalow2 / (2 ** (52 - ($exp - 1023))); + //echo "Sign = $sign, Exp = $exp, mantissahighx = $mantissa, mantissalow1 = $mantissalow1, mantissalow2 = $mantissalow2\n"; + if ($sign) { + $value = - 1 * $value; + } + + return $value; + } + + /** + * Set the encoding method + * + * @param string $encoding Encoding to use + * + * @access public + */ + public function setOutputEncoding(string $encoding): SimpleXLS + { + $this->defaultEncoding = $encoding; + return $this; + } + + + /** + * Set the default number format, ex. "%.2f" + * + * @access public + * + * @param string $sFormat Default format + */ + public function setDefaultFormat(string $sFormat): SimpleXLS + { + $this->defaultFormat = $sFormat; + return $this; + } + + /** + * Force a column to use a certain format + * + * @access public + * + * @param integer $column Column number + * @param string $sFormat Format + */ + public function setColumnFormat(int $column, string $sFormat): SimpleXLS + { + $this->columnsFormat[ $column ] = $sFormat; + return $this; + } + +} diff --git a/Distro/database/SimpleXLSX.php b/Distro/database/SimpleXLSX.php new file mode 100644 index 00000000..787ed778 --- /dev/null +++ b/Distro/database/SimpleXLSX.php @@ -0,0 +1,1254 @@ +rows() as $r) { + * print_r( $r ); + * } + * } else { + * echo SimpleXLSX::parseError(); + * } + * + * Example 2: html table + * if ( $xlsx = SimpleXLSX::parse('book.xlsx') ) { + * echo $xlsx->toHTML(); + * } else { + * echo SimpleXLSX::parseError(); + * } + * + * Example 3: rowsEx + * $xlsx = SimpleXLSX::parse('book.xlsx'); + * foreach ( $xlsx->rowsEx() as $r ) { + * print_r( $r ); + * } + * + * Example 4: select worksheet + * $xlsx = SimpleXLSX::parse('book.xlsx'); + * foreach( $xlsx->rows(1) as $r ) { // second worksheet + * print_t( $r ); + * } + * + * Example 5: IDs and worksheet names + * $xlsx = SimpleXLSX::parse('book.xlsx'); + * print_r( $xlsx->sheetNames() ); // array( 0 => 'Sheet 1', 1 => 'Catalog' ); + * + * Example 6: get sheet name by index + * $xlsx = SimpleXLSX::parse('book.xlsx'); + * echo 'Sheet Name 2 = '.$xlsx->sheetName(1); + * + * Example 7: getCell (very slow) + * echo $xlsx->getCell(1,'D12'); // reads D12 cell from second sheet + * + * Example 8: read data + * if ( $xlsx = SimpleXLSX::parseData( file_get_contents('http://www.example.com/example.xlsx') ) ) { + * $dim = $xlsx->dimension(1); + * $num_cols = $dim[0]; + * $num_rows = $dim[1]; + * echo $xlsx->sheetName(1).':'.$num_cols.'x'.$num_rows; + * } else { + * echo SimpleXLSX::parseError(); + * } + * + * Example 9: old style + * $xlsx = new SimpleXLSX('book.xlsx'); + * if ( $xlsx->success() ) { + * print_r( $xlsx->rows() ); + * } else { + * echo 'xlsx error: '.$xlsx->error(); + * } + */ +class SimpleXLSX +{ + // Don't remove this string! Created by Sergey Shuchkin sergey.shuchkin@gmail.com + public static $CF = [ // Cell formats + 0 => 'General', + 1 => '0', + 2 => '0.00', + 3 => '#,##0', + 4 => '#,##0.00', + 9 => '0%', + 10 => '0.00%', + 11 => '0.00E+00', + 12 => '# ?/?', + 13 => '# ??/??', + 14 => 'mm-dd-yy', + 15 => 'd-mmm-yy', + 16 => 'd-mmm', + 17 => 'mmm-yy', + 18 => 'h:mm AM/PM', + 19 => 'h:mm:ss AM/PM', + 20 => 'h:mm', + 21 => 'h:mm:ss', + 22 => 'm/d/yy h:mm', + + 37 => '#,##0 ;(#,##0)', + 38 => '#,##0 ;[Red](#,##0)', + 39 => '#,##0.00;(#,##0.00)', + 40 => '#,##0.00;[Red](#,##0.00)', + + 44 => '_("$"* #,##0.00_);_("$"* \(#,##0.00\);_("$"* "-"??_);_(@_)', + 45 => 'mm:ss', + 46 => '[h]:mm:ss', + 47 => 'mmss.0', + 48 => '##0.0E+0', + 49 => '@', + + 27 => '[$-404]e/m/d', + 30 => 'm/d/yy', + 36 => '[$-404]e/m/d', + 50 => '[$-404]e/m/d', + 57 => '[$-404]e/m/d', + + 59 => 't0', + 60 => 't0.00', + 61 => 't#,##0', + 62 => 't#,##0.00', + 67 => 't0%', + 68 => 't0.00%', + 69 => 't# ?/?', + 70 => 't# ??/??', + ]; + public $nf = []; // number formats + public $cellFormats = []; // cellXfs + public $datetimeFormat = 'Y-m-d H:i:s'; + public $debug; + public $activeSheet = 0; + public $rowsExReader; + + /* @var SimpleXMLElement[] $sheets */ + protected $sheets; + protected $sheetFiles = []; + protected $sheetMetaData = []; + // scheme + public $styles; + protected $hyperlinks; + /* @var array[] $package */ + protected $package; + protected $sharedstrings; + protected $date1904 = 0; + + + /* + private $date_formats = array( + 0xe => "d/m/Y", + 0xf => "d-M-Y", + 0x10 => "d-M", + 0x11 => "M-Y", + 0x12 => "h:i a", + 0x13 => "h:i:s a", + 0x14 => "H:i", + 0x15 => "H:i:s", + 0x16 => "d/m/Y H:i", + 0x2d => "i:s", + 0x2e => "H:i:s", + 0x2f => "i:s.S" + ); + private $number_formats = array( + 0x1 => "%1.0f", // "0" + 0x2 => "%1.2f", // "0.00", + 0x3 => "%1.0f", //"#,##0", + 0x4 => "%1.2f", //"#,##0.00", + 0x5 => "%1.0f", //"$#,##0;($#,##0)", + 0x6 => '$%1.0f', //"$#,##0;($#,##0)", + 0x7 => '$%1.2f', //"$#,##0.00;($#,##0.00)", + 0x8 => '$%1.2f', //"$#,##0.00;($#,##0.00)", + 0x9 => '%1.0f%%', //"0%" + 0xa => '%1.2f%%', //"0.00%" + 0xb => '%1.2f', //"0.00E00", + 0x25 => '%1.0f', //"#,##0;(#,##0)", + 0x26 => '%1.0f', //"#,##0;(#,##0)", + 0x27 => '%1.2f', //"#,##0.00;(#,##0.00)", + 0x28 => '%1.2f', //"#,##0.00;(#,##0.00)", + 0x29 => '%1.0f', //"#,##0;(#,##0)", + 0x2a => '$%1.0f', //"$#,##0;($#,##0)", + 0x2b => '%1.2f', //"#,##0.00;(#,##0.00)", + 0x2c => '$%1.2f', //"$#,##0.00;($#,##0.00)", + 0x30 => '%1.0f'); //"##0.0E0"; + // }}} + */ + protected $errno = 0; + protected $error = false; + /** + * @var false|SimpleXMLElement + */ + public $theme; + + + public function __construct($filename = null, $is_data = null, $debug = null) + { + if ($debug !== null) { + $this->debug = $debug; + } + $this->package = [ + 'filename' => '', + 'mtime' => 0, + 'size' => 0, + 'comment' => '', + 'entries' => [] + ]; + if ($filename && $this->_unzip($filename, $is_data)) { + $this->_parse(); + } + } + + protected function _unzip($filename, $is_data = false) + { + + if ($is_data) { + $this->package['filename'] = 'default.xlsx'; + $this->package['mtime'] = time(); + $this->package['size'] = $this->_strlen($filename); + + $vZ = $filename; + } else { + if (!is_readable($filename)) { + $this->error(1, 'File not found ' . $filename); + + return false; + } + + // Package information + $this->package['filename'] = $filename; + $this->package['mtime'] = filemtime($filename); + $this->package['size'] = filesize($filename); + + // Read file + $vZ = file_get_contents($filename); + } + // Cut end of central directory + /* $aE = explode("\x50\x4b\x05\x06", $vZ); + + if (count($aE) == 1) { + $this->error('Unknown format'); + return false; + } + */ + // Explode to each part + $aE = explode("\x50\x4b\x03\x04", $vZ); + array_shift($aE); + + $aEL = count($aE); + if ($aEL === 0) { + $this->error(2, 'Unknown archive format'); + + return false; + } + // Search central directory end record + $last = $aE[$aEL - 1]; + $last = explode("\x50\x4b\x05\x06", $last); + if (count($last) !== 2) { + $this->error(2, 'Unknown archive format'); + + return false; + } + // Search central directory + $last = explode("\x50\x4b\x01\x02", $last[0]); + if (count($last) < 2) { + $this->error(2, 'Unknown archive format'); + + return false; + } + $aE[$aEL - 1] = $last[0]; + + // Loop through the entries + foreach ($aE as $vZ) { + $aI = []; + $aI['E'] = 0; + $aI['EM'] = ''; + // Retrieving local file header information +// $aP = unpack('v1VN/v1GPF/v1CM/v1FT/v1FD/V1CRC/V1CS/V1UCS/v1FNL', $vZ); + $aP = unpack('v1VN/v1GPF/v1CM/v1FT/v1FD/V1CRC/V1CS/V1UCS/v1FNL/v1EFL', $vZ); + + // Check if data is encrypted +// $bE = ($aP['GPF'] && 0x0001) ? TRUE : FALSE; +// $bE = false; + $nF = $aP['FNL']; + $mF = $aP['EFL']; + + // Special case : value block after the compressed data + if ($aP['GPF'] & 0x0008) { + $aP1 = unpack('V1CRC/V1CS/V1UCS', $this->_substr($vZ, -12)); + + $aP['CRC'] = $aP1['CRC']; + $aP['CS'] = $aP1['CS']; + $aP['UCS'] = $aP1['UCS']; + // 2013-08-10 + $vZ = $this->_substr($vZ, 0, -12); + if ($this->_substr($vZ, -4) === "\x50\x4b\x07\x08") { + $vZ = $this->_substr($vZ, 0, -4); + } + } + + // Getting stored filename + $aI['N'] = $this->_substr($vZ, 26, $nF); + $aI['N'] = str_replace('\\', '/', $aI['N']); + + if ($this->_substr($aI['N'], -1) === '/') { + // is a directory entry - will be skipped + continue; + } + + // Truncate full filename in path and filename + $aI['P'] = dirname($aI['N']); + $aI['P'] = ($aI['P'] === '.') ? '' : $aI['P']; + $aI['N'] = basename($aI['N']); + + $vZ = $this->_substr($vZ, 26 + $nF + $mF); + + if ($this->_strlen($vZ) !== (int)$aP['CS']) { // check only if availabled + $aI['E'] = 1; + $aI['EM'] = 'Compressed size is not equal with the value in header information.'; + } +// } elseif ( $bE ) { +// $aI['E'] = 5; +// $aI['EM'] = 'File is encrypted, which is not supported from this class.'; +/* } else { + switch ($aP['CM']) { + case 0: // Stored + // Here is nothing to do, the file ist flat. + break; + case 8: // Deflated + $vZ = gzinflate($vZ); + break; + case 12: // BZIP2 + if (extension_loaded('bz2')) { + $vZ = bzdecompress($vZ); + } else { + $aI['E'] = 7; + $aI['EM'] = 'PHP BZIP2 extension not available.'; + } + break; + default: + $aI['E'] = 6; + $aI['EM'] = "De-/Compression method {$aP['CM']} is not supported."; + } + if (!$aI['E']) { + if ($vZ === false) { + $aI['E'] = 2; + $aI['EM'] = 'Decompression of data failed.'; + } elseif ($this->_strlen($vZ) !== (int)$aP['UCS']) { + $aI['E'] = 3; + $aI['EM'] = 'Uncompressed size is not equal with the value in header information.'; + } elseif (crc32($vZ) !== $aP['CRC']) { + $aI['E'] = 4; + $aI['EM'] = 'CRC32 checksum is not equal with the value in header information.'; + } + } + } +*/ + + // DOS to UNIX timestamp + $aI['T'] = mktime( + ($aP['FT'] & 0xf800) >> 11, + ($aP['FT'] & 0x07e0) >> 5, + ($aP['FT'] & 0x001f) << 1, + ($aP['FD'] & 0x01e0) >> 5, + $aP['FD'] & 0x001f, + (($aP['FD'] & 0xfe00) >> 9) + 1980 + ); + + $this->package['entries'][] = [ + 'data' => $vZ, + 'ucs' => (int)$aP['UCS'], // ucompresses size + 'cm' => $aP['CM'], // compressed method + 'cs' => isset($aP['CS']) ? (int) $aP['CS'] : 0, // compresses size + 'crc' => $aP['CRC'], + 'error' => $aI['E'], + 'error_msg' => $aI['EM'], + 'name' => $aI['N'], + 'path' => $aI['P'], + 'time' => $aI['T'] + ]; + } // end for each entries + + return true; + } + + protected function _strlen($str) + { + return (ini_get('mbstring.func_overload') & 2) ? mb_strlen($str, '8bit') : strlen($str); + } + + public function error($num = null, $str = null) + { + if ($num) { + $this->errno = $num; + $this->error = $str; + if ($this->debug) { + trigger_error(__CLASS__ . ': ' . $this->error, E_USER_WARNING); + } + } + + return $this->error; + } + + protected function _substr($str, $start, $length = null) + { + return (ini_get('mbstring.func_overload') & 2) ? mb_substr($str, $start, ($length === null) ? mb_strlen($str, '8bit') : $length, '8bit') : substr($str, $start, ($length === null) ? strlen($str) : $length); + } + + protected function _parse() + { + // Document data holders + $this->sharedstrings = []; + $this->sheets = []; +// $this->styles = array(); +// $m1 = 0; // memory_get_peak_usage( true ); + // Read relations and search for officeDocument + if ($relations = $this->getEntryXML('_rels/.rels')) { + foreach ($relations->Relationship as $rel) { + $rel_type = basename(trim((string)$rel['Type'])); // officeDocument + $rel_target = $this->_getTarget('', (string)$rel['Target']); // /xl/workbook.xml or xl/workbook.xml + + if ($rel_type === 'officeDocument' && $workbook = $this->getEntryXML($rel_target)) { + $index_rId = []; // [0 => rId1] + + $index = 0; + foreach ($workbook->sheets->sheet as $s) { + $a = []; + foreach ($s->attributes() as $k => $v) { + $a[(string)$k] = (string)$v; + } + $this->sheetMetaData[$index] = $a; + $index_rId[$index] = (string)$s['id']; + $index++; + } + if ((int)$workbook->workbookPr['date1904'] === 1) { + $this->date1904 = 1; + } + + + if ($workbookRelations = $this->getEntryXML(dirname($rel_target) . '/_rels/workbook.xml.rels')) { + // Loop relations for workbook and extract sheets... + foreach ($workbookRelations->Relationship as $workbookRelation) { + $wrel_type = basename(trim((string)$workbookRelation['Type'])); // worksheet + $wrel_path = $this->_getTarget(dirname($rel_target), (string)$workbookRelation['Target']); + if (!$this->entryExists($wrel_path)) { + continue; + } + + + if ($wrel_type === 'worksheet') { // Sheets + if ($sheet = $this->getEntryXML($wrel_path)) { + $index = array_search((string)$workbookRelation['Id'], $index_rId, true); + $this->sheets[$index] = $sheet; + $this->sheetFiles[$index] = $wrel_path; + } + } elseif ($wrel_type === 'sharedStrings') { + if ($sharedStrings = $this->getEntryXML($wrel_path)) { + foreach ($sharedStrings->si as $val) { + if (isset($val->t)) { + $this->sharedstrings[] = (string)$val->t; + } elseif (isset($val->r)) { + $this->sharedstrings[] = $this->_parseRichText($val); + } + } + } + } elseif ($wrel_type === 'styles') { + $this->styles = $this->getEntryXML($wrel_path); + + // number formats + $this->nf = []; + if (isset($this->styles->numFmts->numFmt)) { + foreach ($this->styles->numFmts->numFmt as $v) { + $this->nf[(int)$v['numFmtId']] = (string)$v['formatCode']; + } + } + + $this->cellFormats = []; + if (isset($this->styles->cellXfs->xf)) { + foreach ($this->styles->cellXfs->xf as $v) { + $x = [ + 'format' => null + ]; + foreach ($v->attributes() as $k1 => $v1) { + $x[ $k1 ] = (int) $v1; + } + if (isset($x['numFmtId'])) { + if (isset($this->nf[$x['numFmtId']])) { + $x['format'] = $this->nf[$x['numFmtId']]; + } elseif (isset(self::$CF[$x['numFmtId']])) { + $x['format'] = self::$CF[$x['numFmtId']]; + } + } + + $this->cellFormats[] = $x; + } + } + } elseif ($wrel_type === 'theme') { + $this->theme = $this->getEntryXML($wrel_path); + } + } + + break; + } + // reptile hack :: find active sheet from workbook.xml + foreach ($workbook->bookViews->workbookView as $s) { + if (!empty($s['activeTab'])) { + $this->activeSheet = (int)$s['activeTab']; + } + } + } + } + } + +// $m2 = memory_get_peak_usage(true); +// echo __FUNCTION__.' M='.round( ($m2-$m1) / 1048576, 2).'MB'.PHP_EOL; + + if (count($this->sheets)) { + // Sort sheets + ksort($this->sheets); + + return true; + } + + return false; + } + + public function getEntryXML($name) + { + if ($entry_xml = $this->getEntryData($name)) { + $this->deleteEntry($name); // economy memory + // dirty remove namespace prefixes and empty rows + $entry_xml = preg_replace('/xmlns[^=]*="[^"]*"/i', '', $entry_xml); // remove namespaces + $entry_xml .= ' '; // force run garbage collector + $entry_xml = preg_replace('/[a-zA-Z0-9]+:([a-zA-Z0-9]+="[^"]+")/', '$1', $entry_xml); // remove namespaced attrs + $entry_xml .= ' '; + $entry_xml = preg_replace('/<[a-zA-Z0-9]+:([^>]+)>/', '<$1>', $entry_xml); // fix namespaced openned tags + $entry_xml .= ' '; + $entry_xml = preg_replace('/<\/[a-zA-Z0-9]+:([^>]+)>/', '$1>', $entry_xml); // fix namespaced closed tags + $entry_xml .= ' '; + + if (strpos($name, '/sheet')) { // dirty skip empty rows + // remove + $entry_xml = preg_replace('/]+>\s*(\s*)+<\/row>/', '', $entry_xml, -1, $cnt); + $entry_xml .= ' '; + // remove + $entry_xml = preg_replace('/]*\/>/', '', $entry_xml, -1, $cnt2); + $entry_xml .= ' '; + // remove + $entry_xml = preg_replace('/]*><\/row>/', '', $entry_xml, -1, $cnt3); + $entry_xml .= ' '; + if ($cnt || $cnt2 || $cnt3) { + $entry_xml = preg_replace('//', '', $entry_xml); + $entry_xml .= ' '; + } +// file_put_contents( basename( $name ), $entry_xml ); // @to do comment!!! + } + $entry_xml = trim($entry_xml); + +// $m1 = memory_get_usage(); + // XML External Entity (XXE) Prevention, libxml_disable_entity_loader deprecated in PHP 8 + if (LIBXML_VERSION < 20900 && function_exists('libxml_disable_entity_loader')) { + $_old = libxml_disable_entity_loader(); + } + + $_old_uie = libxml_use_internal_errors(true); + + $entry_xmlobj = simplexml_load_string($entry_xml, 'SimpleXMLElement', LIBXML_COMPACT | LIBXML_PARSEHUGE); + + libxml_use_internal_errors($_old_uie); + + if (LIBXML_VERSION < 20900 && function_exists('libxml_disable_entity_loader')) { + /** @noinspection PhpUndefinedVariableInspection */ + libxml_disable_entity_loader($_old); + } + +// $m2 = memory_get_usage(); +// echo round( ($m2-$m1) / (1024 * 1024), 2).' MB'.PHP_EOL; + + if ($entry_xmlobj) { + return $entry_xmlobj; + } + $e = libxml_get_last_error(); + if ($e) { + $this->error(3, 'XML-entry ' . $name . ' parser error ' . $e->message . ' line ' . $e->line); + } + } else { + $this->error(4, 'XML-entry not found ' . $name); + } + + return false; + } + + // sheets numeration: 1,2,3.... + + public function getEntryData($name) + { + $name = ltrim(str_replace('\\', '/', $name), '/'); + $dir = $this->_strtoupper(dirname($name)); + $name = $this->_strtoupper(basename($name)); + foreach ($this->package['entries'] as &$entry) { + if ($this->_strtoupper($entry['path']) === $dir && $this->_strtoupper($entry['name']) === $name) { + if ($entry['error']) { + return false; + } + switch ($entry['cm']) { + case -1: + case 0: // Stored + // Here is nothing to do, the file ist flat. + break; + case 8: // Deflated + $entry['data'] = gzinflate($entry['data']); + break; + case 12: // BZIP2 + if (extension_loaded('bz2')) { + $entry['data'] = bzdecompress($entry['data']); + } else { + $entry['error'] = 7; + $entry['error_message'] = 'PHP BZIP2 extension not available.'; + } + break; + default: + $entry['error'] = 6; + $entry['error_msg'] = 'De-/Compression method '.$entry['cm'].' is not supported.'; + } + if (!$entry['error'] && $entry['cm'] > -1) { + $entry['cm'] = -1; + if ($entry['data'] === false) { + $entry['error'] = 2; + $entry['error_msg'] = 'Decompression of data failed.'; + } elseif ($this->_strlen($entry['data']) !== (int)$entry['ucs']) { + $entry['error'] = 3; + $entry['error_msg'] = 'Uncompressed size is not equal with the value in header information.'; + } elseif (crc32($entry['data']) !== $entry['crc']) { + $entry['error'] = 4; + $entry['error_msg'] = 'CRC32 checksum is not equal with the value in header information.'; + } + } + + return $entry['data']; + } + } + unset($entry); + $this->error(5, 'Entry not found ' . ($dir ? $dir . '/' : '') . $name); + + return false; + } + public function deleteEntry($name) + { + $name = ltrim(str_replace('\\', '/', $name), '/'); + $dir = $this->_strtoupper(dirname($name)); + $name = $this->_strtoupper(basename($name)); + foreach ($this->package['entries'] as $k => $entry) { + if ($this->_strtoupper($entry['path']) === $dir && $this->_strtoupper($entry['name']) === $name) { + unset($this->package['entries'][$k]); + return true; + } + } + return false; + } + + protected function _strtoupper($str) + { + return (ini_get('mbstring.func_overload') & 2) ? mb_strtoupper($str, '8bit') : strtoupper($str); + } + + protected function _getTarget($base, $target) + { + $target = trim($target); + if (strpos($target, '/') === 0) { + return $this->_substr($target, 1); + } + $target = ($base ? $base . '/' : '') . $target; + // a/b/../c -> a/c + $parts = explode('/', $target); + $abs = []; + foreach ($parts as $p) { + if ('.' === $p) { + continue; + } + if ('..' === $p) { + array_pop($abs); + } else { + $abs[] = $p; + } + } + return implode('/', $abs); + } + + /* + * @param string $name Filename in archive + * @return SimpleXMLElement|bool + */ + + public function entryExists($name) + { + // 0.6.6 + $dir = $this->_strtoupper(dirname($name)); + $name = $this->_strtoupper(basename($name)); + foreach ($this->package['entries'] as $entry) { + if ($this->_strtoupper($entry['path']) === $dir && $this->_strtoupper($entry['name']) === $name) { + return true; + } + } + + return false; + } + + protected function _parseRichText($is = null) + { + $value = []; + + if (isset($is->t)) { + $value[] = (string)$is->t; + } elseif (isset($is->r)) { + foreach ($is->r as $run) { + $value[] = (string)$run->t; + } + } + + return implode('', $value); + } + + public static function parseFile($filename, $debug = false) + { + return self::parse($filename, false, $debug); + } + + public static function parse($filename, $is_data = false, $debug = false) + { + $xlsx = new self(); + $xlsx->debug = $debug; + if ($xlsx->_unzip($filename, $is_data)) { + $xlsx->_parse(); + } + if ($xlsx->success()) { + return $xlsx; + } + self::parseError($xlsx->error()); + self::parseErrno($xlsx->errno()); + + return false; + } + + public function success() + { + return !$this->error; + } + + // https://github.com/shuchkin/simplexlsx#gets-extend-cell-info-by--rowsex + + public static function parseError($set = false) + { + static $error = false; + + return $set ? $error = $set : $error; + } + + public static function parseErrno($set = false) + { + static $errno = false; + + return $set ? $errno = $set : $errno; + } + + public function errno() + { + return $this->errno; + } + + public static function parseData($data, $debug = false) + { + return self::parse($data, true, $debug); + } + + + + public function worksheet($worksheetIndex = 0) + { + + + if (isset($this->sheets[$worksheetIndex])) { + $ws = $this->sheets[$worksheetIndex]; + + if (!isset($this->hyperlinks[$worksheetIndex]) && isset($ws->hyperlinks)) { + $this->hyperlinks[$worksheetIndex] = []; + $sheet_rels = str_replace('worksheets', 'worksheets/_rels', $this->sheetFiles[$worksheetIndex]) . '.rels'; + $link_ids = []; + + if ($rels = $this->getEntryXML($sheet_rels)) { + // hyperlink +// $rel_base = dirname( $sheet_rels ); + foreach ($rels->Relationship as $rel) { + $rel_type = basename(trim((string)$rel['Type'])); + if ($rel_type === 'hyperlink') { + $rel_id = (string)$rel['Id']; + $rel_target = (string)$rel['Target']; + $link_ids[$rel_id] = $rel_target; + } + } + } + foreach ($ws->hyperlinks->hyperlink as $hyperlink) { + $ref = (string)$hyperlink['ref']; + if ($this->_strpos($ref, ':') > 0) { // A1:A8 -> A1 + $ref = explode(':', $ref); + $ref = $ref[0]; + } +// $this->hyperlinks[ $worksheetIndex ][ $ref ] = (string) $hyperlink['display']; + $loc = (string)$hyperlink['location']; + $id = (string)$hyperlink['id']; + if ($id) { + $href = $link_ids[$id] . ($loc ? '#' . $loc : ''); + } else { + $href = $loc; + } + $this->hyperlinks[$worksheetIndex][$ref] = $href; + } + } + + return $ws; + } + $this->error(6, 'Worksheet not found ' . $worksheetIndex); + + return false; + } + + protected function _strpos($haystack, $needle, $offset = 0) + { + return (ini_get('mbstring.func_overload') & 2) ? mb_strpos($haystack, $needle, $offset, '8bit') : strpos($haystack, $needle, $offset); + } + + /** + * returns [numCols,numRows] of worksheet + * + * @param int $worksheetIndex + * + * @return array + */ + public function dimension($worksheetIndex = 0) + { + + if (($ws = $this->worksheet($worksheetIndex)) === false) { + return [0, 0]; + } + /* @var SimpleXMLElement $ws */ + + $ref = (string)$ws->dimension['ref']; + + if ($this->_strpos($ref, ':') !== false) { + $d = explode(':', $ref); + $idx = $this->getIndex($d[1]); + + return [$idx[0] + 1, $idx[1] + 1]; + } + /* + if ( $ref !== '' ) { // 0.6.8 + $index = $this->getIndex( $ref ); + + return [ $index[0] + 1, $index[1] + 1 ]; + } + */ + + // slow method + $maxC = $maxR = 0; + $iR = -1; + foreach ($ws->sheetData->row as $row) { + $iR++; + $iC = -1; + foreach ($row->c as $c) { + $iC++; + $idx = $this->getIndex((string)$c['r']); + $x = $idx[0]; + $y = $idx[1]; + if ($x > -1) { + if ($x > $maxC) { + $maxC = $x; + } + if ($y > $maxR) { + $maxR = $y; + } + } else { + if ($iC > $maxC) { + $maxC = $iC; + } + if ($iR > $maxR) { + $maxR = $iR; + } + } + } + } + + return [$maxC + 1, $maxR + 1]; + } + + public function getIndex($cell = 'A1') + { + + if (preg_match('/([A-Z]+)(\d+)/', $cell, $m)) { + $col = $m[1]; + $row = $m[2]; + + $colLen = $this->_strlen($col); + $index = 0; + + for ($i = $colLen - 1; $i >= 0; $i--) { + $index += (ord($col[$i]) - 64) * pow(26, $colLen - $i - 1); + } + + return [$index - 1, $row - 1]; + } + +// $this->error( 'Invalid cell index ' . $cell ); + + return [-1, -1]; + } + + public function value($cell) + { + // Determine data type + $dataType = (string)$cell['t']; + + if ($dataType === '' || $dataType === 'n') { // number + $s = (int)$cell['s']; + if ($s > 0 && isset($this->cellFormats[$s])) { + if (array_key_exists('format', $this->cellFormats[$s])) { + $format = $this->cellFormats[$s]['format']; + if (preg_match('/[mM]/', preg_replace('/\"[^"]+\"/', '', $format))) { // [mm]onth,AM|PM + $dataType = 'D'; + } + } else { + $dataType = 'n'; + } + } + } + + $value = ''; + + switch ($dataType) { + case 's': + // Value is a shared string + if ((string)$cell->v !== '') { + $value = $this->sharedstrings[(int)$cell->v]; + } + break; + + case 'str': // formula? + if ((string)$cell->v !== '') { + $value = (string)$cell->v; + } + break; + + case 'b': + // Value is boolean + $value = (string)$cell->v; + if ($value === '0') { + $value = false; + } elseif ($value === '1') { + $value = true; + } else { + $value = (bool)$cell->v; + } + + break; + + case 'inlineStr': + // Value is rich text inline + $value = $this->_parseRichText($cell->is); + + break; + + case 'e': + // Value is an error message + if ((string)$cell->v !== '') { + $value = (string)$cell->v; + } + break; + + case 'D': + // Date as float + if (!empty($cell->v)) { + $value = $this->datetimeFormat ? gmdate($this->datetimeFormat, $this->unixstamp((float)$cell->v)) : (float)$cell->v; + } + break; + + case 'd': + // Date as ISO YYYY-MM-DD + if ((string)$cell->v !== '') { + $value = (string)$cell->v; + } + break; + + default: + // Value is a string + $value = (string)$cell->v; + + // Check for numeric values + if (is_numeric($value)) { + /** @noinspection TypeUnsafeComparisonInspection */ + if ($value == (int)$value) { + $value = (int)$value; + } /** @noinspection TypeUnsafeComparisonInspection */ elseif ($value == (float)$value) { + $value = (float)$value; + } + } + } + + return $value; + } + + public function unixstamp($excelDateTime) + { + + $d = floor($excelDateTime); // days since 1900 or 1904 + $t = $excelDateTime - $d; + + if ($this->date1904) { + $d += 1462; + } + + $t = (abs($d) > 0) ? ($d - 25569) * 86400 + round($t * 86400) : round($t * 86400); + + return (int)$t; + } + + public function href($worksheetIndex, $cell) + { + $ref = (string)$cell['r']; + return isset($this->hyperlinks[$worksheetIndex][$ref]) ? $this->hyperlinks[$worksheetIndex][$ref] : ''; + } + + public function toHTML($worksheetIndex = 0) + { + $s = ''; + foreach ($this->readRows($worksheetIndex) as $r) { + $s .= ''; + foreach ($r as $c) { + $s .= '' . ($c === '' ? ' ' : htmlspecialchars($c, ENT_QUOTES)) . ''; + } + $s .= "\r\n"; + } + $s .= ''; + + return $s; + } + public function toHTMLEx($worksheetIndex = 0) + { + $s = ''; + $y = 0; + foreach ($this->readRowsEx($worksheetIndex) as $r) { + $s .= ''; + $x = 0; + foreach ($r as $c) { + $tag = 'td'; + $css = $c['css']; + if ($y === 0) { + $tag = 'th'; + $css .= $c['width'] ? 'width: '.round($c['width'] * 0.47, 2).'em;' : ''; + } + + if ($x === 0 && $c['height']) { + $css .= 'height: '.round($c['height'] * 1.3333).'px;'; + } + $s .= '<'.$tag.' style="'.$css.'" nowrap>' . ($c['value'] === '' ? ' ' : htmlspecialchars($c['value'], ENT_QUOTES)) . ''.$tag.'>'; + $x++; + } + $s .= "\r\n"; + $y++; + } + $s .= ''; + + return $s; + } + public function rows($worksheetIndex = 0, $limit = 0) + { + return iterator_to_array($this->readRows($worksheetIndex, $limit), false); + } + // thx Gonzo + /** + * @param $worksheetIndex + * @param $limit + * @return \Generator + */ + public function readRows($worksheetIndex = 0, $limit = 0) + { + + if (($ws = $this->worksheet($worksheetIndex)) === false) { + return; + } + $dim = $this->dimension($worksheetIndex); + $numCols = $dim[0]; + $numRows = $dim[1]; + + $emptyRow = []; + for ($i = 0; $i < $numCols; $i++) { + $emptyRow[] = ''; + } + + $curR = 0; + $_limit = $limit; + /* @var SimpleXMLElement $ws */ + foreach ($ws->sheetData->row as $row) { + $r = $emptyRow; + $curC = 0; + foreach ($row->c as $c) { + // detect skipped cols + $idx = $this->getIndex((string)$c['r']); + $x = $idx[0]; + $y = $idx[1]; + + if ($x > -1) { + $curC = $x; + while ($curR < $y) { + yield $emptyRow; + $curR++; + $_limit--; + if ($_limit === 0) { + return; + } + } + } + $r[$curC] = $this->value($c); + $curC++; + } + yield $r; + + $curR++; + $_limit--; + if ($_limit === 0) { + return; + } + } + while ($curR < $numRows) { + yield $emptyRow; + $curR++; + $_limit--; + if ($_limit === 0) { + return; + } + } + } + + public function rowsEx($worksheetIndex = 0, $limit = 0) + { + return iterator_to_array($this->readRowsEx($worksheetIndex, $limit), false); + } + // https://github.com/shuchkin/simplexlsx#gets-extend-cell-info-by--rowsex + /** + * @param $worksheetIndex + * @param $limit + * @return \Generator|null + */ + public function readRowsEx($worksheetIndex = 0, $limit = 0) + { + if (!$this->rowsExReader) { + require_once __DIR__ . '/SimpleXLSXEx.php'; + $this->rowsExReader = new SimpleXLSXEx($this); + } + return $this->rowsExReader->readRowsEx($worksheetIndex, $limit); + } + + /** + * Returns cell value + * VERY SLOW! Use ->rows() or ->rowsEx() + * + * @param int $worksheetIndex + * @param string|array $cell ref or coords, D12 or [3,12] + * + * @return mixed Returns NULL if not found + */ + public function getCell($worksheetIndex = 0, $cell = 'A1') + { + + if (($ws = $this->worksheet($worksheetIndex)) === false) { + return false; + } + if (is_array($cell)) { + $cell = $this->_num2name($cell[0]) . $cell[1];// [3,21] -> D21 + } + if (is_string($cell)) { + $result = $ws->sheetData->xpath("row/c[@r='" . $cell . "']"); + if (count($result)) { + return $this->value($result[0]); + } + } + + return null; + } + + protected function _num2name($num) + { + $numeric = ($num - 1) % 26; + $letter = chr(65 + $numeric); + $num2 = (int)(($num - 1) / 26); + if ($num2 > 0) { + return $this->_num2name($num2) . $letter; + } + return $letter; + } + + public function getSheets() + { + return $this->sheets; + } + + public function sheetsCount() + { + return count($this->sheets); + } + + public function sheetName($worksheetIndex) + { + $sn = $this->sheetNames(); + if (isset($sn[$worksheetIndex])) { + return $sn[$worksheetIndex]; + } + + return false; + } + + public function sheetNames() + { + $a = []; + foreach ($this->sheetMetaData as $k => $v) { + $a[$k] = $v['name']; + } + return $a; + } + public function sheetMeta($worksheetIndex = null) + { + if ($worksheetIndex === null) { + return $this->sheetMetaData; + } + return isset($this->sheetMetaData[$worksheetIndex]) ? $this->sheetMetaData[$worksheetIndex] : false; + } + public function isHiddenSheet($worksheetIndex) + { + return isset($this->sheetMetaData[$worksheetIndex]['state']) && $this->sheetMetaData[$worksheetIndex]['state'] === 'hidden'; + } + + public function getStyles() + { + return $this->styles; + } + + public function getPackage() + { + return $this->package; + } + + public function setDateTimeFormat($value) + { + $this->datetimeFormat = is_string($value) ? $value : false; + } +} diff --git a/Distro/database/SimpleXLSXEx.php b/Distro/database/SimpleXLSXEx.php new file mode 100644 index 00000000..27b43b40 --- /dev/null +++ b/Distro/database/SimpleXLSXEx.php @@ -0,0 +1,617 @@ + '000000', + 1 => 'FFFFFF', + 2 => 'FF0000', + 3 => '00FF00', + 4 => '0000FF', + 5 => 'FFFF00', + 6 => 'FF00FF', + 7 => '00FFFF', + 8 => '000000', + 9 => 'FFFFFF', + 10 => 'FF0000', + 11 => '00FF00', + 12 => '0000FF', + 13 => 'FFFF00', + 14 => 'FF00FF', + 15 => '00FFFF', + 16 => '800000', + 17 => '008000', + 18 => '000080', + 19 => '808000', + 20 => '800080', + 21 => '008080', + 22 => 'C0C0C0', + 23 => '808080', + 24 => '9999FF', + 25 => '993366', + 26 => 'FFFFCC', + 27 => 'CCFFFF', + 28 => '660066', + 29 => 'FF8080', + 30 => '0066CC', + 31 => 'CCCCFF', + 32 => '000080', + 33 => 'FF00FF', + 34 => 'FFFF00', + 35 => '00FFFF', + 36 => '800080', + 37 => '800000', + 38 => '008080', + 39 => '0000FF', + 40 => '00CCFF', + 41 => 'CCFFFF', + 42 => 'CCFFCC', + 43 => 'FFFF99', + 44 => '99CCFF', + 45 => 'FF99CC', + 46 => 'CC99FF', + 47 => 'FFCC99', + 48 => '3366FF', + 49 => '33CCCC', + 50 => '99CC00', + 51 => 'FFCC00', + 52 => 'FF9900', + 53 => 'FF6600', + 54 => '666699', + 55 => '969696', + 56 => '003366', + 57 => '339966', + 58 => '003300', + 59 => '333300', + 60 => '993300', + 61 => '993366', + 62 => '333399', + 63 => '333333', + 64 => '000000', // System Foreground + 65 => 'FFFFFF', // System Background' + ]; + public static $CH = [ + 0 => 'ANSI_CHARSET', + 1 => 'DEFAULT_CHARSET', + 2 => 'SYMBOL_CHARSET', + 77 => 'MAC_CHARSET', + 128 => 'SHIFTJIS_CHARSET', + //129 => 'HANGEUL_CHARSET', + 129 => 'HANGUL_CHARSET', + 130 => 'JOHAB_CHARSET', + 134 => 'GB2312_CHARSET', + 136 => 'CHINESEBIG5_CHARSET', + 161 => 'GREEK_CHARSET', + 162 => 'TURKISH_CHARSET', + 163 => 'VIETNAMESE_CHARSET', + 177 => 'HEBREW_CHARSET', + 178 => 'ARABIC_CHARSET', + 186 => 'BALTIC_CHARSET', + 204 => 'RUSSIAN_CHARSET', + 222 => 'THAI_CHARSET', + 238 => 'EASTEUROPE_CHARSET', + 255 => 'OEM_CHARSET' + ]; + public $xlsx; + public $themeColors; + public $fonts; + public $fills; + public $borders; + public $cellStyles; + public $css; + + public function __construct(SimpleXLSX $xlsx) + { + $this->xlsx = $xlsx; + $this->readThemeColors(); + $this->readFonts(); + $this->readFills(); + $this->readBorders(); + $this->readXfs(); + } + public function readThemeColors() + { + $this->themeColors = []; + if (isset($this->xlsx->theme->themeElements->clrScheme)) { + $colors12 = ['lt1', 'dk1', 'lt2', 'dk2','accent1','accent2','accent3','accent4','accent5', + 'accent6','hlink','folHlink']; + foreach ($colors12 as $c) { + $v = $this->xlsx->theme->themeElements->clrScheme->{$c}; + if (isset($v->sysClr)) { + $this->themeColors[] = (string) $v->sysClr['lastClr']; + } elseif (isset($v->srgbClr)) { + $this->themeColors[] = (string) $v->srgbClr['val']; + } else { + $this->themeColors[] = null; + } + } + } + } + + + public function readFonts() + { + // fonts + $this->fonts = []; + if (isset($this->xlsx->styles->fonts->font)) { + foreach ($this->xlsx->styles->fonts->font as $v) { + $u = ''; + if (isset($v->u)) { + $u = isset($v->u['val']) ? (string) $v->u['val'] : 'single'; + } + $f = [ + 'b' => isset($v->b) && ($v->b['val'] === null || $v->b['val']), + 'i' => isset($v->i) && ($v->i['val'] === null || $v->i['val']), + 'u' => $u, + 'strike' => isset($v->strike) && ($v->strike['val'] === null || $v->strike['val']), + 'sz' => isset($v->sz['val']) ? (int) $v->sz['val'] : 11, + 'color' => $this->getColorValue($v->color), + 'name' => isset($v->name['val']) ? (string) $v->name['val'] : 'Calibri', + 'family' => isset($v->family['val']) ? (int) $v->family['val'] : 2, + 'charset' => isset($v->charset['val']) ? (int) $v->charset['val'] : 1, + 'scheme' => isset($v->scheme['val']) ? (string) $v->scheme['val'] : 'minor' + ]; + $this->fonts[] = $f; + } + } + } + public function readFills() + { + // fills + $this->fills = []; + if (isset($this->xlsx->styles->fills->fill)) { + foreach ($this->xlsx->styles->fills->fill as $v) { + if (isset($v->patternFill)) { + $this->fills[] = [ + 'pattern' => isset($v->patternFill['patternType']) ? (string) $v->patternFill['patternType'] : 'none', + 'fgcolor' => $this->getColorValue($v->patternFill->fgColor), + 'bgcolor' => $this->getColorValue($v->patternFill->bgColor) + ]; + } + } + } + } + public function readBorders() + { + $this->borders = []; + if (isset($this->xlsx->styles->borders->border)) { + foreach ($this->xlsx->styles->borders->border as $v) { + $this->borders[] = [ + 'left' => [ + 'style' => (string) $v->left['style'], + 'color' => $this->getColorValue($v->left->color) + ], + 'right' => [ + 'style' => (string) $v->right['style'], + 'color' => $this->getColorValue($v->right->color) + ], + 'top' => [ + 'style' => (string) $v->top['style'], + 'color' => $this->getColorValue($v->top->color) + ], + 'bottom' => [ + 'style' => (string) $v->bottom['style'], + 'color' => $this->getColorValue($v->bottom->color) + ], + 'diagonal' => [ + 'style' => (string) $v->diagonal['style'], + 'color' => $this->getColorValue($v->diagonal->color) + ], + 'horizontal' => [ + 'style' => (string) $v->horizontal['style'], + 'color' => $this->getColorValue($v->horizontal->color) + ], + 'vertical' => [ + 'style' => (string) $v->vertical['style'], + 'color' => $this->getColorValue($v->vertical->color) + ], + 'diagonalUp' => (bool) $v['diagonalUp'], + 'diagonalDown' => (bool) $v['diagonalDown'], + 'outline' => !(isset($v['outline'])) || $v['outline'] + ]; + } + } + } + + public function readXfs() + { + // cellStyles + $this->cellStyles = []; + if (isset($this->xlsx->styles->cellStyleXfs->xf)) { + foreach ($this->xlsx->styles->cellStyleXfs->xf as $v) { + $x = []; + foreach ($v->attributes() as $k1 => $v1) { + $x[ $k1 ] = (int) $v1; + } + if (isset($v->alignment)) { + foreach ($v->alignment->attributes() as $k1 => $v1) { + $x['alignment'][$k1] = (string) $v1; + } + } + $this->cellStyles[] = $x; + } + } + // css + $this->css = []; + // xf + if (isset($this->xlsx->styles->cellXfs->xf)) { + $k = 0; + foreach ($this->xlsx->styles->cellXfs->xf as $v) { + $cf = &$this->xlsx->cellFormats[$k]; + + // alignment + $alignment = []; + if (isset($v->alignment)) { + foreach ($v->alignment->attributes() as $k1 => $v1) { + $alignment[$k1] = (string)$v1; + } + } + + if (isset($cf['xfId'], $this->cellStyles[ $cf['xfId'] ])) { + $s = $this->cellStyles[$cf['xfId']]; + if (!empty($s['applyNumberFormat'])) { + $cf['numFmtId'] = $s['numFmtId']; + } + if (!empty($s['applyFont'])) { + $cf['fontId'] = $s['fontId']; + } + if (!empty($s['applyBorder'])) { + $cf['borderId'] = $s['borderId']; + } + if (!empty($s['applyAlignment'])) { + $alignment = $s['alignment']; + } + } + $cf['alignment'] = $alignment; + + $align = null; + if (isset($alignment['horizontal'])) { + $align = $alignment['horizontal']; + if ($align === 'centerContinuous') { + $align = 'center'; + } + if ($align === 'distributed') { + $align = 'justify'; + } + if ($align === 'general') { + $align = null; + } + } + $cf['align'] = $align; + + $valign = null; + if (isset($alignment['vertical'])) { + $valign = $alignment['vertical']; + if ($valign === 'center' || $valign === 'distributed' || $valign === 'justify') { + $valign = 'middle'; + } + } + $cf['valign'] = $valign; + + // font + if (isset($cf['fontId'])) { + $cf['font'] = $this->fonts[$cf['fontId']]['name']; + $cf['color'] = $this->fonts[$cf['fontId']]['color']; + $cf['f-size'] = $this->fonts[$cf['fontId']]['sz']; + $cf['f-b'] = $this->fonts[$cf['fontId']]['b']; + $cf['f-i'] = $this->fonts[$cf['fontId']]['i']; + $cf['f-u'] = $this->fonts[$cf['fontId']]['u']; + $cf['f-strike'] = $this->fonts[$cf['fontId']]['strike']; + } else { + $cf['font'] = null; + $cf['color'] = null; + $cf['f-size'] = null; + $cf['f-b'] = null; + $cf['f-i'] = null; + $cf['f-u'] = null; + $cf['f-strike'] = null; + } + + // fill + $cf['bgcolor'] = isset($cf['fillId']) ? $this->fills[ $cf['fillId'] ]['fgcolor'] : null; + + // borders + if (isset($cf['borderId'], $this->borders[ $cf['borderId'] ])) { + $border = $this->borders[ $cf['borderId'] ]; + + $borders = ['left', 'right', 'top', 'bottom']; + foreach ($borders as $b) { + $cf['b-' . $b.'-color'] = $border[$b]['color']; + if ($border[$b]['style'] === '' || $border[$b]['style'] === 'none') { + $cf['b-' . $b.'-style'] = ''; + $cf['b-' . $b.'-color'] = ''; + } elseif ($border[$b]['style'] === 'dashDot' + || $border[$b]['style'] === 'dashDotDot' + || $border[$b]['style'] === 'dashed' + ) { + $cf['b-' . $b.'-style'] = 'dashed'; + } else { + $cf['b-' . $b.'-style'] = 'solid'; + } + } + } else { + $cf['b-top-style'] = null; + $cf['b-right-style'] = null; + $cf['b-bottom-style'] = null; + $cf['b-left-style'] = null; + } + + $css = ''; + + if ($cf['color']) { + $css .= 'color: #'.$cf['color'].';'; + } + if ($cf['font']) { + $css .= 'font-family: '.$cf['font'].';'; + } + if ($cf['f-size']) { +// $css .= 'font-size: '.($cf['f-size'] * 0.352806).'mm;'; + $css .= 'font-size: '.(round($cf['f-size'] * 1.3333) + 2).'px;'; + } + if ($cf['f-b']) { + $css .= 'font-weight: bold;'; + } + if ($cf['f-i']) { + $css .= 'font-style: italic;'; + } + if ($cf['f-u']) { + $css .= 'text-decoration: underline;'; + } + if ($cf['f-strike']) { + $css .= 'text-decoration: line-through;'; + } + if ($cf['bgcolor']) { + $css .= 'background-color: #' . $cf['bgcolor'] . ';'; + } + if ($cf['align']) { + $css .= 'text-align: '.$cf['align'].';'; + } + if ($cf['valign']) { + $css .= 'vertical-align: '.$cf['valign'].';'; + } + if ($cf['b-top-style']) { + $css .= 'border-top-style: '.$cf['b-top-style'].';'; + $css .= 'border-top-color: #'.$cf['b-top-color'].';'; + $css .= 'border-top-width: thin;'; + } + if ($cf['b-right-style']) { + $css .= 'border-right-style: '.$cf['b-right-style'].';'; + $css .= 'border-right-color: #'.$cf['b-right-color'].';'; + $css .= 'border-right-width: thin;'; + } + if ($cf['b-bottom-style']) { + $css .= 'border-bottom-style: '.$cf['b-bottom-style'].';'; + $css .= 'border-bottom-color: #'.$cf['b-bottom-color'].';'; + $css .= 'border-bottom-width: thin;'; + } + if ($cf['b-left-style']) { + $css .= 'border-left-style: '.$cf['b-left-style'].';'; + $css .= 'border-left-color: #'.$cf['b-left-color'].';'; + $css .= 'border-left-width: thin;'; + } + $this->css[$k] = $css; + + $k++; + } + } + } + + public function readRowsEx($worksheetIndex = 0, $limit = 0) + { + if (($ws = $this->xlsx->worksheet($worksheetIndex)) === false) { + return; + } + + $dim = $this->xlsx->dimension($worksheetIndex); + $numCols = $dim[0]; + $numRows = $dim[1]; + + /*$emptyRow = array(); + for ($i = 0; $i < $numCols; $i++) { + $emptyRow[] = null; + } + */ + $cols = []; + for ($i = 0; $i < $numCols; $i++) { + $cols[] = ['s' => 0, 'hidden' => false, 'width' => 0]; + } +// $hiddenCols = []; + /* @var SimpleXMLElement $ws */ + if (isset($ws->cols)) { + foreach ($ws->cols->col as $col) { + $min = (int)$col['min']; + $max = (int)$col['max']; + if (($max-$min) > 100) { + $max = $min; + } + for ($i = $min; $i <= $max; $i++) { + $cols[$i-1] = [ + 's' => (int)$col['style'], + 'hidden' => (bool)$col['hidden'], + 'width' => $col['customWidth'] ? (float) $col['width'] : 0 + ]; + } + } + } + + $curR = 0; + $_limit = $limit; + + foreach ($ws->sheetData->row as $row) { + $curC = 0; + + $r_idx = (int)$row['r']; + $r_style = ['s' => 0, 'hidden' => (bool)$row['hidden'], 'height' => 0]; + if ($row['customFormat']) { + $r_style['s'] = (int)$row['s']; + } + if ($row['customHeight']) { + $r_style['height'] = (int)$row['ht']; + } + + $cells = []; + for ($i = 0; $i < $numCols; $i++) { + $cells[] = null; + } + + foreach ($row->c as $c) { + $r = (string)$c['r']; + $t = (string)$c['t']; + $s = (int)$c['s']; + + $idx = $this->xlsx->getIndex($r); + $x = $idx[0]; + $y = $idx[1]; + + if ($x > -1) { + $curC = $x; + if ($curC >= $numCols) { + $numCols = $curC + 1; + } + while ($curR < $y) { + $emptyRow = []; + for ($i = 0; $i < $numCols; $i++) { + $emptyRow[] = $this->valueEx($cols[$i], $i, $curR); + } + yield $emptyRow; + $curR++; + + $_limit--; + if ($_limit === 0) { + return; + } + } + } + $data = [ + 'type' => $t, + 'name' => $r, + 'value' => $this->xlsx->value($c), + 'href' => $this->xlsx->href($worksheetIndex, $c), + 'f' => (string)$c->f, + 'r' => $r_idx, + 's' => ($s > 0) ? $s : $cols[$curC]['s'], + 'hidden' => $r_style['hidden'] || $cols[$curC]['hidden'], + 'width' => $cols[$curC]['width'], + 'height' => $r_style['height'] + ]; + $cells[$curC] = $this->valueEx($data, $curC, $curR); + + $curC++; + } + // check empty cells + for ($i = 0; $i < $numCols; $i++) { + if ($cells[$i] === null) { + if ($r_style['s'] > 0) { + $data = $r_style; + } else { + $data = $cols[$i]; + } + $data['width'] = $cols[$i]['width']; + $data['height'] = $r_style['height']; + $cells[$i] = $this->valueEx($data, $i, $curR); + } + } + + yield $cells; + + $curR++; + $_limit--; + if ($_limit === 0) { + break; + } + } + + while ($curR < $numRows) { + $emptyRow = []; + for ($i = 0; $i < $numCols; $i++) { + $data = $cols[$i]; + $emptyRow[] = $this->valueEx($data, $i, $curR); + } + yield $emptyRow; + $curR++; + $_limit--; + if ($_limit === 0) { + return; + } + } + } + + protected function valueEx($data, $x = null, $y = null) + { + + $r = [ + 'type' => '', + 'name' => '', + 'value' => '', + 'href' => '', + 'f' => '', + 'format' => '', + 's' => 0, + 'css' => '', + 'r' => '', + 'hidden' => false, + 'width' => 0, + 'height' => 0 + ]; + foreach ($data as $k => $v) { + if (isset($r[$k])) { + $r[$k] = $v; + } + } + $st = &$this->xlsx->cellFormats[$r['s']]; + $r['format'] = $st['format']; + $r['css'] = &$this->css[ $r['s'] ]; + if ($r['value'] !== '' && !$st['align'] && !in_array($r['type'], ['s','str','inlineStr','e'], true)) { + $r['css'] .= 'text-align: right;'; + } + + if (!$r['name']) { + $c = ''; + for ($k = $x; $k >= 0; $k = (int)($k / 26) - 1) { + $c = chr($k % 26 + 65) . $c; + } + $r['name'] = $c . ($y + 1); + $r['r'] = $y+1; + } + return $r; + } + public function getColorValue(SimpleXMLElement $a = null, $default = '') + { + if ($a === null) { + return $default; + } + $c = $default; // auto + if ($a['rgb'] !== null) { + $c = substr((string) $a['rgb'], 2); // FFCCBBAA -> CCBBAA + } elseif ($a['indexed'] !== null && isset(static::$IC[ (int) $a['indexed'] ])) { + $c = static::$IC[ (int) $a['indexed'] ]; + } elseif ($a['theme'] !== null && isset($this->themeColors[ (int) $a['theme'] ])) { + $c = $this->themeColors[ (int) $a['theme'] ]; + } + if ($a['tint'] !== null) { + list($r,$g,$b) = array_map('hexdec', str_split($c, 2)); + $tint = (float) $a['tint']; + if ($tint > 0) { + $r += (255 - $r) * $tint; + $g += (255 - $g) * $tint; + $b += (255 - $b) * $tint; + } else { + $r += $r * $tint; + $g += $g * $tint; + $b += $b * $tint; + } + $c = strtoupper( + str_pad(dechex((int) $r), 2, '0', 0) . + str_pad(dechex((int) $g), 2, '0', 0) . + str_pad(dechex((int) $b), 2, '0', 0) + ); + } + return $c; + } +} diff --git a/Distro/database/SimpleXLSXGen.php b/Distro/database/SimpleXLSXGen.php new file mode 100644 index 00000000..a7279d2d --- /dev/null +++ b/Distro/database/SimpleXLSXGen.php @@ -0,0 +1,1333 @@ +subject = ''; + $this->title = ''; + $this->author = ''; + $this->company = ''; + $this->manager = ''; + $this->description = ''; + $this->keywords = ''; + $this->category = ''; + $this->language = 'en-US'; + $this->lastModifiedBy = ''; + $this->application = __CLASS__; + + $this->curSheet = -1; + $this->defaultFont = 'Calibri'; + $this->defaultFontSize = 10; + $this->rtl = false; + $this->sheets = []; + $this->SI = []; // sharedStrings index + $this->SI_KEYS = []; // & keys + + // https://c-rex.net/projects/samples/ooxml/e1/Part4/OOXML_P4_DOCX_numFmts_topic_ID0E6KK6.html + $this->NF = [ + self::N_RUB => '#,##0.00\ "₽"', + self::N_DOLLAR => '[$$-1]#,##0.00', + self::N_EURO => '#,##0.00\ [$€-1]' + ]; + $this->NF_KEYS = array_flip($this->NF); + + $this->BR_STYLE = [ + self::B_NONE => 'none', + self::B_THIN => 'thin', + self::B_MEDIUM => 'medium', + self::B_DASHED => 'dashed', + self::B_DOTTED => 'dotted', + self::B_THICK => 'thick', + self::B_DOUBLE => 'double', + self::B_HAIR => 'hair', + self::B_MEDIUM_DASHED => 'mediumDashed', + self::B_DASH_DOT => 'dashDot', + self::B_MEDIUM_DASH_DOT => 'mediumDashDot', + self::B_DASH_DOT_DOT => 'dashDotDot', + self::B_MEDIUM_DASH_DOT_DOT => 'mediumDashDotDot', + self::B_SLANT_DASH_DOT => 'slantDashDot' + ]; + + $this->XF = [ // styles 0 - num fmt, 1 - align, 2 - font, 3 - fill, 4 - font color, 5 - bgcolor, 6 - border, 7 - font size + [self::N_NORMAL, self::A_DEFAULT, self::F_NORMAL, self::FL_NONE, 0, 0, '', 0], + [self::N_NORMAL, self::A_DEFAULT, self::F_NORMAL, self::FL_GRAY_125, 0, 0, '', 0], // hack + ]; + $this->XF_KEYS[implode('-', $this->XF[0])] = 0; // & keys + $this->XF_KEYS[implode('-', $this->XF[1])] = 1; + $this->template = [ + '_rels/.rels' => ''."\r\n" + .''."\r\n" + .''."\r\n" + .''."\r\n" + .''."\r\n" + .'', + 'docProps/app.xml' => ''."\r\n" + .''."\r\n" + .'0'."\r\n" + .'{APP}'."\r\n" + .'{COMPANY}'."\r\n" + .'{MANAGER}'."\r\n" + .'', + 'docProps/core.xml' => ''."\r\n" + .''."\r\n" + .'{DATE}'."\r\n" + .'{TITLE}'."\r\n" + .'{SUBJECT}'."\r\n" + .'{AUTHOR}'."\r\n" + .'{LAST_MODIFY_BY}'."\r\n" + .'{KEYWORD}'."\r\n" + .'{DESCRIPTION}'."\r\n" + .'{CATEGORY}'."\r\n" + .'{LANGUAGE}'."\r\n" + .'{DATE}'."\r\n" + .'1'."\r\n" + .'', + 'xl/_rels/workbook.xml.rels' => ''."\r\n" + .'' + ."\r\n{RELS}\r\n", + 'xl/worksheets/sheet1.xml' => ''."\r\n" + . '' . "\r\n" + .''."\r\n" + ."{SHEETVIEWS}\r\n{COLS}\r\n{ROWS}\r\n{AUTOFILTER}{MERGECELLS}{HYPERLINKS}{VML}", + 'xl/worksheets/_rels/sheet1.xml.rels' => ''."\r\n" + .'{RELS}', + 'xl/sharedStrings.xml' => ''."\r\n" + .'{STRINGS}', + 'xl/styles.xml' => ''."\r\n" + .'' + ."\r\n{NUMFMTS}\r\n{FONTS}\r\n{FILLS}\r\n{BORDERS}\r\n" + .'' + ."\r\n{XF}\r\n" + .'', + 'xl/workbook.xml' => ''."\r\n" + .''."\r\n" + .'{SHEETS}', + 'xl/comments1.xml' => ''."\r\n" + . '' . "\r\n" + . '{AUTHORS}' . "\r\n" + . '{COMMENTS}' . "\r\n" + . '', + 'xl/drawings/vmlDrawing1.vml' => '' . "\r\n" + . '' . "\r\n" + .'' . "\r\n" + .'{SHAPES}', + '[Content_Types].xml' => ''."\r\n" + .''."\r\n" + .'' . "\r\n" + .'' . "\r\n" + .'' . "\r\n" + .''."\r\n" + .''."\r\n" + .''."\r\n" + .' +' + ."\r\n{TYPES}", + ]; + } + public static function create($title = null) + { + $xlsx = new static(); + if ($title) { + $xlsx->setTitle($title); + } + return $xlsx; + } + + public static function fromArray(array $rows, $sheetName = null) + { + $xlsx = new static(); + $xlsx->addSheet($rows, $sheetName); + if ($sheetName) { + $xlsx->setTitle($sheetName); + } + return $xlsx; + } + + public function addSheet(array $rows, $name = null) + { + $this->curSheet++; + if ($name === null) { // autogenerated sheet names + $name = ($this->title ? mb_substr($this->title, 0, 31) : 'Sheet') . ($this->curSheet + 1); + } else { + $name = mb_substr($name, 0, 31); + $names = []; + foreach ($this->sheets as $sh) { + $names[mb_strtoupper($sh['name'])] = 1; + } + for ($i = 0; $i < 100; $i++) { + $postfix = ' (' . $i . ')'; + $new_name = ($i === 0) ? $name : $name . $postfix; + if (mb_strlen($new_name) > 31) { + $new_name = mb_substr($name, 0, 31 - mb_strlen($postfix)) . $postfix; + } + $NEW_NAME = mb_strtoupper($new_name); + if (!isset($names[$NEW_NAME])) { + $name = $new_name; + break; + } + } + } + $this->sheets[$this->curSheet] = ['name' => $name, 'relidx' => 0, 'hyperlinks' => [], 'comments' => [], 'mergecells' => [], 'colwidth' => [], 'autofilter' => '', 'frozen' => '']; + if (isset($rows[0]) && is_array($rows[0])) { + $this->sheets[$this->curSheet]['rows'] = $rows; + } else { + $this->sheets[$this->curSheet]['rows'] = []; + } + return $this; + } + + public function __toString() + { + $fh = fopen('php://memory', 'wb'); + if (!$fh) { + return ''; + } + if (!$this->_write($fh)) { + fclose($fh); + return ''; + } + $size = ftell($fh); + fseek($fh, 0); + return (string)fread($fh, $size); + } + + public function save() + { + return $this->saveAs(($this->title ?: gmdate('YmdHi')) . '.xlsx'); + } + public function saveAs($filename) + { + $fh = fopen(str_replace(["\0","\r","\n","\t",'"'], '', $filename), 'wb'); + if (!$fh) { + return false; + } + if (!$this->_write($fh)) { + fclose($fh); + return false; + } + fclose($fh); + return true; + } + + public function download() + { + return $this->downloadAs(($this->title ?: gmdate('YmdHi')) . '.xlsx'); + } + + public function downloadAs($filename) + { + $fh = fopen('php://memory', 'wb'); + if (!$fh) { + return false; + } + if (!$this->_write($fh)) { + fclose($fh); + return false; + } + $size = ftell($fh); + header('Content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); + header('Content-Disposition: attachment; filename="' . str_replace(["\0","\r","\n","\t",'"'], '', $filename) . '"'); + header('Last-Modified: ' . gmdate('D, d M Y H:i:s \G\M\T', time())); + header('Content-Length: ' . $size); + while (ob_get_level()) { + ob_end_clean(); + } + fseek($fh, 0); + //Some servers disable fpassthru function. The alternative, stream_get_contents, use more memory + if (function_exists('fpassthru')) { + fpassthru($fh); + } else { + echo stream_get_contents($fh); + } + fclose($fh); + return true; + } + + protected function _write($fh) + { + $dirSignatureE = "\x50\x4b\x05\x06"; // end of central dir signature + $zipComments = 'Generated by ' . __CLASS__ . ' PHP class, thanks sergey.shuchkin@gmail.com'; + if (!$fh) { + return false; + } + $cdrec = ''; // central directory content + $entries = 0; // number of zipped files + $cnt_sheets = count($this->sheets); + if ($cnt_sheets === 0) { + $this->addSheet([], 'No data'); + $cnt_sheets = 1; + } + foreach ($this->template as $cfilename => $template) { + if ($cfilename === 'xl/_rels/workbook.xml.rels') { + $s = ''; + for ($i = 0; $i < $cnt_sheets; $i++) { + $s .= '\r\n"; + } + $s .= '' . "\r\n"; + $s .= ''; + + $template = str_replace('{RELS}', $s, $template); + $this->_writeEntry($fh, $cdrec, $cfilename, $template); + $entries++; + } elseif ($cfilename === 'xl/workbook.xml') { + $s = ''; + foreach ($this->sheets as $k => $v) { + $s .= ''; + } + $search = ['{SHEETS}', '{APP}']; + $replace = [$s, self::esc($this->application)]; + $template = str_replace($search, $replace, $template); + $this->_writeEntry($fh, $cdrec, $cfilename, $template); + $entries++; + } elseif ($cfilename === 'docProps/app.xml') { + $search = ['{APP}', '{COMPANY}', '{MANAGER}']; + $replace = [self::esc($this->application), self::esc($this->company), self::esc($this->manager)]; + $template = str_replace($search, $replace, $template); + $this->_writeEntry($fh, $cdrec, $cfilename, $template); + $entries++; + } elseif ($cfilename === 'docProps/core.xml') { + $search = ['{DATE}', '{AUTHOR}', '{TITLE}', '{SUBJECT}', '{KEYWORD}', '{DESCRIPTION}', '{CATEGORY}', '{LANGUAGE}', '{LAST_MODIFY_BY}']; + $replace = [gmdate('Y-m-d\TH:i:s\Z'), self::esc($this->author), self::esc($this->title), self::esc($this->subject), self::esc($this->keywords), self::esc($this->description), self::esc($this->category), self::esc($this->language), self::esc($this->lastModifiedBy)]; + $template = str_replace($search, $replace, $template); + $this->_writeEntry($fh, $cdrec, $cfilename, $template); + $entries++; + } elseif ($cfilename === 'xl/sharedStrings.xml') { + $si_cnt = count($this->SI); + if ($si_cnt) { + $si = []; + foreach ($this->SI as $s) { + $si[] = '' . (preg_match('/^\s|\s$/', $s) ? '' . $s . '' : '' . $s . '') . ''; + } + $template = str_replace(['{CNT}', '{STRINGS}'], [$si_cnt, implode("\r\n", $si)], $template); + $this->_writeEntry($fh, $cdrec, $cfilename, $template); + $entries++; + } + } elseif ($cfilename === 'xl/worksheets/sheet1.xml') { + foreach ($this->sheets as $k => $v) { + $filename = 'xl/worksheets/sheet' . ($k + 1) . '.xml'; + $xml = $this->_sheetToXML($k, $template); + $this->_writeEntry($fh, $cdrec, $filename, $xml); + $entries++; + } + $xml = null; + } elseif ($cfilename === 'xl/worksheets/_rels/sheet1.xml.rels') { + foreach ($this->sheets as $k => $v) { + $R = []; + if (count($v['comments'])) { + $this->sheets[$k]['relidx']++; + $R[] = ''; + $R[] = ''; + } + foreach ($v['hyperlinks'] as $h) { + if ($h['ID']) { + $R[] = ''; + } + } + if (count($R)) { + $filename = 'xl/worksheets/_rels/sheet' . ($k + 1) . '.xml.rels'; + $xml = str_replace('{RELS}', implode("\r\n", $R), $template); + $this->_writeEntry($fh, $cdrec, $filename, $xml); + $entries++; + } + } + $xml = null; + } elseif ($cfilename === 'xl/comments1.xml') { + foreach ($this->sheets as $k => $v) { + $C = []; + $A = []; + foreach ($v['comments'] as $com) { + $A[$com['A']] = count($A); + } + foreach ($v['comments'] as $com) { + $C[] = '' . "\r\n" + . ($com['A'] ? ('' . $com['A'] . ":\r\n" .'' . "\r\n") : '') + .'' . self::esc($com['T']) . '' . "\r\n" +// .'' . self::esc($com['T']) . ($com['A'] ? "\r\n\t-" . $com['A'] : '') . '' . "\r\n" + . ''; + } + if (count($C)) { + $filename = 'xl/comments' . ($k + 1) . '.xml'; + $xml = str_replace( + array('{AUTHORS}', '{COMMENTS}'), + array('' . implode("\r\n", array_keys($A)) . '', + implode("\r\n", $C)), $template + ); + $this->_writeEntry($fh, $cdrec, $filename, $xml); + $entries++; + } + } + $xml = null; + } elseif ($cfilename === 'xl/drawings/vmlDrawing1.vml') { + foreach ($this->sheets as $k => $v) { + if (count($v['comments'])) { + $S = []; + foreach ($v['comments'] as $k2 => $com) { +// Anchor: LeftColumn, LeftOffset, TopRow, TopOffset, RightColumn, RightOffset, BottomRow, BottomOffset + $a = [ + $com['C'], + 15, + $com['R'], + 10, + $com['C'] + 4, + 15, + $com['R'] + 4, + 4 + ]; + $S[] = '' . "\r\n" + . ' ' . "\r\n" + . ' ' . "\r\n" + . ' ' . "\r\n" + . ' ' . "\r\n" + . ' ' . "\r\n" + . ' ' . "\r\n" + . ' ' . implode(', ', $a) .'' . "\r\n" + . ' False' . "\r\n" + . ' ' . ($com['R'] - 1) . '' . "\r\n" + . ' ' . ($com['C'] - 1) . '' . "\r\n" + . ' ' . "\r\n" + . ''; + } + $filename = 'xl/drawings/vmlDrawing' . ($k + 1) . '.vml'; + $xml = str_replace('{SHAPES}', "\r\n" . implode("\r\n", $S) . "\r\n", $template); + $this->_writeEntry($fh, $cdrec, $filename, $xml); + $entries++; + } + } + $xml = null; + } elseif ($cfilename === '[Content_Types].xml') { + $TYPES = []; + foreach ($this->sheets as $k => $v) { + $TYPES[] = ''; + if (count($v['comments'])) { + $TYPES[] = ''; + } + } + $template = str_replace('{TYPES}', implode("\r\n", $TYPES), $template); + $this->_writeEntry($fh, $cdrec, $cfilename, $template); + $entries++; + } elseif ($cfilename === 'xl/styles.xml') { + $NF = $XF = $FONTS = $F_KEYS = $FILLS = $FL_KEYS = []; + $BR = ['']; + $BR_KEYS = [0 => 0]; + foreach ($this->NF as $k => $v) { + $NF[] = ''; + } + foreach ($this->XF as $xf) { + // 0 - num fmt, 1 - align, 2 - font, 3 - fill, 4 - font color, 5 - bgcolor, 6 - border, 7 - font size + // fonts + $F_KEY = $xf[2] . '-' . $xf[4] . '-' . $xf[7]; + if (isset($F_KEYS[$F_KEY])) { + $F_ID = $F_KEYS[$F_KEY]; + } else { + $F_ID = $F_KEYS[$F_KEY] = count($FONTS); + $FONTS[] = '' + . ($xf[7] ? '' : '') + . ($xf[2] & self::F_BOLD ? '' : '') + . ($xf[2] & self::F_ITALIC ? '' : '') + . ($xf[2] & self::F_UNDERLINE ? '' : '') + . ($xf[2] & self::F_STRIKE ? '' : '') + . ($xf[2] & self::F_HYPERLINK ? '' : '') + . ($xf[2] & self::F_COLOR ? '' : '') + . ''; + } + // fills + $FL_KEY = $xf[3] . '-' . $xf[5]; + if (isset($FL_KEYS[$FL_KEY])) { + $FL_ID = $FL_KEYS[$FL_KEY]; + } else { + $FL_ID = $FL_KEYS[$FL_KEY] = count($FILLS); + $FILLS[] = '' : ' />') + . ''; + } + $align = ''; + if ($xf[1] & self::A_LEFT) { + $align .= ' horizontal="left"'; + } elseif ($xf[1] & self::A_RIGHT) { + $align .= ' horizontal="right"'; + } elseif ($xf[1] & self::A_CENTER) { + $align .= ' horizontal="center"'; + } + if ($xf[1] & self::A_TOP) { + $align .= ' vertical="top"'; + } elseif ($xf[1] & self::A_MIDDLE) { + $align .= ' vertical="center"'; + } elseif ($xf[1] & self::A_BOTTOM) { + $align .= ' vertical="bottom"'; + } + if ($xf[1] & self::A_WRAPTEXT) { + $align .= ' wrapText="1"'; + } + + // border + $BR_ID = 0; + if ($xf[6] !== '') { + $b = $xf[6]; + if (isset($BR_KEYS[$b])) { + $BR_ID = $BR_KEYS[$b]; + } else { + $BR_ID = count($BR_KEYS); + $BR_KEYS[$b] = $BR_ID; + $border = ''; + $ba = explode(' ', $b); + if (!isset($ba[1])) { + $ba[] = $ba[0]; + $ba[] = $ba[0]; + $ba[] = $ba[0]; + } + if (!isset($ba[4])) { // diagonal + $ba[] = 'none'; + } + $sides = ['left' => 3, 'right' => 1, 'top' => 0, 'bottom' => 2, 'diagonal' => 4]; + foreach ($sides as $side => $idx) { + $s = 'thin'; + $c = ''; + $va = explode('#', $ba[$idx]); + if (isset($va[1])) { + $s = $va[0] === '' ? 'thin' : $va[0]; + $c = $va[1]; + } elseif (in_array($va[0], $this->BR_STYLE, true)) { + $s = $va[0]; + } else { + $c = $va[0]; + } + if (strlen($c) === 6) { + $c = 'FF' . $c; + } + if ($s && $s !== 'none') { + $border .= '<' . $side . ' style="' . $s . '">' + . '' + . '' . $side . '>'; + } else { + $border .= '<' . $side . '/>'; + } + } + $border .= ''; + $BR[] = $border; + } + } + $XF[] = ' 0 ? ' applyNumberFormat="1"' : '') + . ($F_ID > 0 ? ' applyFont="1"' : '') + . ($FL_ID > 0 ? ' applyFill="1"' : '') + . ($BR_ID > 0 ? ' applyBorder="1"' : '') + . ($align ? ' applyAlignment="1">' : '/>'); + } + // wrap collections + array_unshift($NF, ''); + $NF[] = ''; + array_unshift($XF, ''); + $XF[] = ''; + array_unshift($FONTS, ''); + $FONTS[] = ''; + array_unshift($FILLS, ''); + $FILLS[] = ''; + array_unshift($BR, ''); + $BR[] = ''; + + $template = str_replace( + ['{NUMFMTS}', '{FONTS}', '{XF}', '{FILLS}', '{BORDERS}'], + [implode("\r\n", $NF), implode("\r\n", $FONTS), implode("\r\n", $XF), implode("\r\n", $FILLS), implode("\r\n", $BR)], + $template + ); + $this->_writeEntry($fh, $cdrec, $cfilename, $template); + $entries++; + } else { + $this->_writeEntry($fh, $cdrec, $cfilename, $template); + $entries++; + } + } + $before_cd = ftell($fh); + fwrite($fh, $cdrec); + // end of central dir + fwrite($fh, $dirSignatureE); + fwrite($fh, pack('v', 0)); // number of this disk + fwrite($fh, pack('v', 0)); // number of the disk with the start of the central directory + fwrite($fh, pack('v', $entries)); // total # of entries "on this disk" + fwrite($fh, pack('v', $entries)); // total # of entries overall + fwrite($fh, pack('V', mb_strlen($cdrec, '8bit'))); // size of central dir + fwrite($fh, pack('V', $before_cd)); // offset to start of central dir + fwrite($fh, pack('v', mb_strlen($zipComments, '8bit'))); // .zip file comment length + fwrite($fh, $zipComments); + + return true; + } + + protected function _writeEntry($fh, &$cdrec, $cfilename, $data) + { + $zipSignature = "\x50\x4b\x03\x04"; // local file header signature + $dirSignature = "\x50\x4b\x01\x02"; // central dir header signature + + $e = []; + $e['uncsize'] = mb_strlen($data, '8bit'); + // if data to compress is too small, just store it + if ($e['uncsize'] < 256) { + $e['comsize'] = $e['uncsize']; + $e['vneeded'] = 10; + $e['cmethod'] = 0; + $zdata = $data; + } else { // otherwise, compress it + $zdata = gzcompress($data); + $zdata = substr(substr($zdata, 0, -4), 2); // fix crc bug (thanks to Eric Mueller) + $e['comsize'] = mb_strlen($zdata, '8bit'); + $e['vneeded'] = 10; + $e['cmethod'] = 8; + } + $e['bitflag'] = 0; + $e['crc_32'] = crc32($data); + + // Convert date and time to DOS Format, and set then + $date = getdate(); + $e['dostime'] = ( + (($date['year'] - 1980) << 25) + | ($date['mon'] << 21) + | ($date['mday'] << 16) + | ($date['hours'] << 11) + | ($date['minutes'] << 5) + | ($date['seconds'] >> 1) + ); + + $e['offset'] = ftell($fh); + + fwrite($fh, $zipSignature); + fwrite($fh, pack('v', $e['vneeded'])); // version_needed + fwrite($fh, pack('v', $e['bitflag'])); // general_bit_flag + fwrite($fh, pack('v', $e['cmethod'])); // compression_method + fwrite($fh, pack('V', $e['dostime'])); // lastmod datetime + fwrite($fh, pack('V', $e['crc_32'])); // crc-32 + fwrite($fh, pack('V', $e['comsize'])); // compressed_size + fwrite($fh, pack('V', $e['uncsize'])); // uncompressed_size + fwrite($fh, pack('v', mb_strlen($cfilename, '8bit'))); // file_name_length + fwrite($fh, pack('v', 0)); // extra_field_length + fwrite($fh, $cfilename); // file_name + // ignoring extra_field + fwrite($fh, $zdata); + + // Append it to central dir + $e['external_attributes'] = (substr($cfilename, -1) === '/' && !$zdata) ? 16 : 32; // Directory or file name + $e['comments'] = ''; + + $cdrec .= $dirSignature; + $cdrec .= "\x0\x0"; // version made by + $cdrec .= pack('v', $e['vneeded']); // version needed to extract + $cdrec .= "\x0\x0"; // general bit flag + $cdrec .= pack('v', $e['cmethod']); // compression method + $cdrec .= pack('V', $e['dostime']); // lastmod datetime + $cdrec .= pack('V', $e['crc_32']); // crc32 + $cdrec .= pack('V', $e['comsize']); // compressed filesize + $cdrec .= pack('V', $e['uncsize']); // uncompressed filesize + $cdrec .= pack('v', mb_strlen($cfilename, '8bit')); // file name length + $cdrec .= pack('v', 0); // extra field length + $cdrec .= pack('v', mb_strlen($e['comments'], '8bit')); // file comment length + $cdrec .= pack('v', 0); // disk number start + $cdrec .= pack('v', 0); // internal file attributes + $cdrec .= pack('V', $e['external_attributes']); // internal file attributes + $cdrec .= pack('V', $e['offset']); // relative offset of local header + $cdrec .= $cfilename; + $cdrec .= $e['comments']; + } + + protected function _sheetToXML($idx, $template) + { + // locale floats fr_FR 1.234,56 -> 1234.56 + $_loc = setlocale(LC_NUMERIC, 0); + setlocale(LC_NUMERIC, 'C'); + $COLS = []; + $ROWS = []; + $VML = []; + // $SHEETVIEWS = 'rtl ? ' rightToLeft="1"' : '').'>'; + $SHEETVIEWS = ''; + $PANE = ''; + if (count($this->sheets[$idx]['rows'])) { + $ROWS[] = ''; + if ($this->sheets[$idx]['frozen'] !== '' || isset($this->sheets[$idx]['frozen'][0]) || isset($this->sheets[$idx]['frozen'][1])) { + // $AC = 'A1'; // Active Cell + $x = $y = 0; + if (is_string($this->sheets[$idx]['frozen'])) { + $AC = $this->sheets[$idx]['frozen']; + self::cell2coord($AC, $x, $y); + } else { + if (isset($this->sheets[$idx]['frozen'][0])) { + $x = $this->sheets[$idx]['frozen'][0]; + } + if (isset($this->sheets[$idx]['frozen'][1])) { + $y = $this->sheets[$idx]['frozen'][1]; + } + $AC = self::coord2cell($x, $y); + } + if ($x > 0 || $y > 0) { + $split = ''; + if ($x > 0) { + $split .= ' xSplit="' . $x . '"'; + } + if ($y > 0) { + $split .= ' ySplit="' . $y . '"'; + } + $activepane = 'bottomRight'; + if ($x > 0 && $y === 0) { + $activepane = 'topRight'; + } + if ($x === 0 && $y > 0) { + $activepane = 'bottomLeft'; + } + $PANE .= ''; + $PANE .= ''; + } + } + if ($this->rtl || $PANE) { + $SHEETVIEWS .= ' +rtl ? ' rightToLeft="1"' : ''); + $SHEETVIEWS .= $PANE ? ">\r\n" . $PANE . "\r\n" : ' />'; + $SHEETVIEWS .= "\r\n"; + } + $CUR_ROW = 0; + $COL = []; + foreach ($this->sheets[$idx]['rows'] as $r) { + $CUR_ROW++; + $row = ''; + $CUR_COL = 0; + $RH = 0; // row height + foreach ($r as $v) { + $CUR_COL++; + if (!isset($COL[$CUR_COL])) { + $COL[$CUR_COL] = 0; + } + $cname = self::coord2cell($CUR_COL-1) . $CUR_ROW; + if ($v === null || $v === '') { + $row .= ''; + continue; + } + $ct = $cv = $cf = null; + $N = $NF = $A = $F = $FL = $C = $BG = $FS = $FR = 0; + $BR = ''; + if (is_string($v)) { + if ($v[0] === "\0") { // RAW value as string + $v = substr($v, 1); + $vl = mb_strlen($v); + } else { + if (strpos($v, '<') !== false) { // tags? + if (preg_match('//s', $v, $m)) { + $com = trim($m[1]); + $a = $this->author; + if (preg_match('/^([^:]+): (.*)$/us', $com, $m2)) { + $a = $m2[1]; + /** @noinspection MultiAssignmentUsageInspection */ + $com = $m2[2]; + } + $this->sheets[$idx]['comments'][] = ['C' => $CUR_COL, 'R' => $CUR_ROW, 'N' => $cname, 'T' => $com, 'A' => $a]; + $v = str_replace($m[0], '', $v); + } + if (strpos($v, '') !== false) { + $F += self::F_BOLD; + } + if (strpos($v, '') !== false) { + $F += self::F_ITALIC; + } + if (strpos($v, '') !== false) { + $F += self::F_UNDERLINE; + } + if (strpos($v, '') !== false) { + $F += self::F_STRIKE; + } + if (preg_match('/