Initial work on adapting code to PSR-2 standards

This commit is contained in:
Mark Baker 2013-06-23 16:30:50 +01:00
parent 89ccb90e8d
commit 1549cc42ca
179 changed files with 69651 additions and 69718 deletions

View File

@ -24,6 +24,7 @@
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*
* Based on:
* SplClassLoader implementation that implements the technical interoperability
* standards for PHP 5.3 namespaces and class names.
*
@ -53,10 +54,10 @@ namespace PHPExcel;
*/
class Autoloader
{
private $_fileExtension = '.php';
private $_namespace;
private $_includePath;
private $_namespaceSeparator = '\\';
private $fileExtension = '.php';
private $namespace;
private $includePath;
private $namespaceSeparator = '\\';
/**
* Creates a new SplClassLoader that loads classes of the
@ -67,8 +68,8 @@ class Autoloader
*/
public function __construct($namespace = null, $includePath = null)
{
$this->_namespace = $namespace;
$this->_includePath = $includePath;
$this->namespace = $namespace;
$this->includePath = $includePath;
}
/**
@ -78,7 +79,7 @@ class Autoloader
*/
public function setNamespaceSeparator($sep)
{
$this->_namespaceSeparator = $sep;
$this->namespaceSeparator = $sep;
}
/**
@ -88,7 +89,7 @@ class Autoloader
*/
public function getNamespaceSeparator()
{
return $this->_namespaceSeparator;
return $this->namespaceSeparator;
}
/**
@ -98,7 +99,7 @@ class Autoloader
*/
public function setIncludePath($includePath)
{
$this->_includePath = $includePath;
$this->includePath = $includePath;
}
/**
@ -108,7 +109,7 @@ class Autoloader
*/
public function getIncludePath()
{
return $this->_includePath;
return $this->includePath;
}
/**
@ -118,7 +119,7 @@ class Autoloader
*/
public function setFileExtension($fileExtension)
{
$this->_fileExtension = $fileExtension;
$this->fileExtension = $fileExtension;
}
/**
@ -128,7 +129,7 @@ class Autoloader
*/
public function getFileExtension()
{
return $this->_fileExtension;
return $this->fileExtension;
}
/**
@ -155,17 +156,23 @@ class Autoloader
*/
public function loadClass($className)
{
if (null === $this->_namespace || $this->_namespace.$this->_namespaceSeparator === substr($className, 0, strlen($this->_namespace.$this->_namespaceSeparator))) {
// $fileName = '';
// $namespace = '';
// if (false !== ($lastNsPos = strripos($className, $this->_namespaceSeparator))) {
// $namespace = substr($className, 0, $lastNsPos);
// $className = substr($className, $lastNsPos + 1);
// $fileName = str_replace($this->_namespaceSeparator, DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
// }
$fileName = str_replace(array('\\','_'), DIRECTORY_SEPARATOR, $className) . $this->_fileExtension;
require ($this->_includePath !== null ? $this->_includePath . DIRECTORY_SEPARATOR : '') . $fileName;
}
if (null === $this->namespace ||
$this->namespace.$this->namespaceSeparator ===
substr($className, 0, strlen($this->namespace.$this->namespaceSeparator))
) {
// $fileName = '';
// $namespace = '';
// if (false !== ($lastNsPos = strripos($className, $this->_namespaceSeparator))) {
// $namespace = substr($className, 0, $lastNsPos);
// $className = substr($className, $lastNsPos + 1);
// $fileName = str_replace(
// $this->_namespaceSeparator,
// DIRECTORY_SEPARATOR,
// $namespace
// ) . DIRECTORY_SEPARATOR;
// }
$fileName = str_replace(array('\\','_'), DIRECTORY_SEPARATOR, $className) . $this->fileExtension;
require ($this->includePath !== null ? $this->includePath . DIRECTORY_SEPARATOR : '') . $fileName;
}
}
}

View File

@ -112,7 +112,7 @@ class CachedObjectStorage_APC extends CachedObjectStorage_CacheBase implements C
}
// Check if the requested entry still exists in apc
$success = apc_fetch($this->_cachePrefix.$pCoord.'.cache');
if ($success === FALSE) {
if ($success === false) {
// Entry no longer exists in APC, so clear it from the cache array
parent::deleteCacheData($pCoord);
throw new Exception('Cell entry '.$pCoord.' no longer exists in APC cache');
@ -140,7 +140,7 @@ class CachedObjectStorage_APC extends CachedObjectStorage_CacheBase implements C
// Check if the entry that has been requested actually exists
if (parent::isDataSet($pCoord)) {
$obj = apc_fetch($this->_cachePrefix.$pCoord.'.cache');
if ($obj === FALSE) {
if ($obj === false) {
// Entry no longer exists in APC, so clear it from the cache array
parent::deleteCacheData($pCoord);
throw new Exception('Cell entry '.$pCoord.' no longer exists in APC cache');
@ -161,18 +161,18 @@ class CachedObjectStorage_APC extends CachedObjectStorage_CacheBase implements C
} // function getCacheData()
/**
* Get a list of all cell addresses currently held in cache
*
* @return array of string
*/
public function getCellList() {
if ($this->_currentObjectID !== null) {
$this->_storeData();
}
/**
* Get a list of all cell addresses currently held in cache
*
* @return array of string
*/
public function getCellList() {
if ($this->_currentObjectID !== null) {
$this->_storeData();
}
return parent::getCellList();
}
return parent::getCellList();
}
/**
@ -208,7 +208,7 @@ class CachedObjectStorage_APC extends CachedObjectStorage_CacheBase implements C
foreach($cacheList as $cellID) {
if ($cellID != $this->_currentObjectID) {
$obj = apc_fetch($this->_cachePrefix.$cellID.'.cache');
if ($obj === FALSE) {
if ($obj === false) {
// Entry no longer exists in APC, so clear it from the cache array
parent::deleteCacheData($cellID);
throw new Exception('Cell entry '.$cellID.' no longer exists in APC');
@ -229,7 +229,7 @@ class CachedObjectStorage_APC extends CachedObjectStorage_CacheBase implements C
* @return void
*/
public function unsetWorksheetCells() {
if ($this->_currentObject !== NULL) {
if ($this->_currentObject !== null) {
$this->_currentObject->detach();
$this->_currentObject = $this->_currentObjectID = null;
}
@ -253,7 +253,7 @@ class CachedObjectStorage_APC extends CachedObjectStorage_CacheBase implements C
public function __construct(Worksheet $parent, $arguments) {
$cacheTime = (isset($arguments['cacheTime'])) ? $arguments['cacheTime'] : 600;
if ($this->_cachePrefix === NULL) {
if ($this->_cachePrefix === null) {
$baseUnique = $this->_getUniqueID();
$this->_cachePrefix = substr(md5($baseUnique),0,8).'.';
$this->_cacheTime = $cacheTime;
@ -282,13 +282,12 @@ class CachedObjectStorage_APC extends CachedObjectStorage_CacheBase implements C
*/
public static function cacheMethodIsAvailable() {
if (!function_exists('apc_store')) {
return FALSE;
return false;
}
if (apc_sma_info() === FALSE) {
return FALSE;
if (apc_sma_info() === false) {
return false;
}
return TRUE;
return true;
}
}

View File

@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\CachedObjectStorage
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@ -37,284 +37,283 @@ namespace PHPExcel;
*/
abstract class CachedObjectStorage_CacheBase {
/**
* Parent worksheet
*
* @var PHPExcel\Worksheet
*/
protected $_parent;
/**
* Parent worksheet
*
* @var PHPExcel\Worksheet
*/
protected $_parent;
/**
* The currently active Cell
*
* @var PHPExcel\Cell
*/
protected $_currentObject = null;
/**
* The currently active Cell
*
* @var PHPExcel\Cell
*/
protected $_currentObject = null;
/**
* Coordinate address of the currently active Cell
*
* @var string
*/
protected $_currentObjectID = null;
/**
* Coordinate address of the currently active Cell
*
* @var string
*/
protected $_currentObjectID = null;
/**
* Flag indicating whether the currently active Cell requires saving
*
* @var boolean
*/
protected $_currentCellIsDirty = true;
/**
* Flag indicating whether the currently active Cell requires saving
*
* @var boolean
*/
protected $_currentCellIsDirty = true;
/**
* An array of cells or cell pointers for the worksheet cells held in this cache,
* and indexed by their coordinate address within the worksheet
*
* @var array of mixed
*/
protected $_cellCache = array();
/**
* An array of cells or cell pointers for the worksheet cells held in this cache,
* and indexed by their coordinate address within the worksheet
*
* @var array of mixed
*/
protected $_cellCache = array();
/**
* Initialise this new cell collection
*
* @param PHPExcel\Worksheet $parent The worksheet for this cell collection
*/
public function __construct(Worksheet $parent) {
// Set our parent worksheet.
// This is maintained within the cache controller to facilitate re-attaching it to PHPExcel\Cell objects when
// they are woken from a serialized state
$this->_parent = $parent;
} // function __construct()
/**
* Initialise this new cell collection
*
* @param PHPExcel\Worksheet $parent The worksheet for this cell collection
*/
public function __construct(Worksheet $parent) {
// Set our parent worksheet.
// This is maintained within the cache controller to facilitate re-attaching it to PHPExcel\Cell objects when
// they are woken from a serialized state
$this->_parent = $parent;
} // function __construct()
/**
* Return the parent worksheet for this cell collection
*
* @return PHPExcel\Worksheet
*/
public function getParent()
{
return $this->_parent;
}
/**
* Return the parent worksheet for this cell collection
*
* @return PHPExcel\Worksheet
*/
public function getParent()
{
return $this->_parent;
}
/**
* Is a value set in the current PHPExcel\CachedObjectStorage_ICache for an indexed cell?
*
* @param string $pCoord Coordinate address of the cell to check
* @return boolean
*/
public function isDataSet($pCoord) {
if ($pCoord === $this->_currentObjectID) {
return true;
}
// Check if the requested entry exists in the cache
return isset($this->_cellCache[$pCoord]);
} // function isDataSet()
/**
* Is a value set in the current PHPExcel\CachedObjectStorage_ICache for an indexed cell?
*
* @param string $pCoord Coordinate address of the cell to check
* @return boolean
*/
public function isDataSet($pCoord) {
if ($pCoord === $this->_currentObjectID) {
return true;
}
// Check if the requested entry exists in the cache
return isset($this->_cellCache[$pCoord]);
} // function isDataSet()
/**
* Move a cell object from one address to another
*
* @param string $fromAddress Current address of the cell to move
* @param string $toAddress Destination address of the cell to move
* @return boolean
*/
public function moveCell($fromAddress, $toAddress) {
if ($fromAddress === $this->_currentObjectID) {
$this->_currentObjectID = $toAddress;
}
$this->_currentCellIsDirty = true;
if (isset($this->_cellCache[$fromAddress])) {
$this->_cellCache[$toAddress] = &$this->_cellCache[$fromAddress];
unset($this->_cellCache[$fromAddress]);
}
/**
* Move a cell object from one address to another
*
* @param string $fromAddress Current address of the cell to move
* @param string $toAddress Destination address of the cell to move
* @return boolean
*/
public function moveCell($fromAddress, $toAddress) {
if ($fromAddress === $this->_currentObjectID) {
$this->_currentObjectID = $toAddress;
}
$this->_currentCellIsDirty = true;
if (isset($this->_cellCache[$fromAddress])) {
$this->_cellCache[$toAddress] = &$this->_cellCache[$fromAddress];
unset($this->_cellCache[$fromAddress]);
}
return TRUE;
} // function moveCell()
return true;
} // function moveCell()
/**
* Add or Update a cell in cache
*
* @param PHPExcel\Cell $cell Cell to update
* @return void
* @throws PHPExcel\Exception
* @param PHPExcel\Cell $cell Cell to update
* @return void
* @throws PHPExcel\Exception
*/
public function updateCacheData(Cell $cell) {
return $this->addCacheData($cell->getCoordinate(),$cell);
} // function updateCacheData()
public function updateCacheData(Cell $cell) {
return $this->addCacheData($cell->getCoordinate(),$cell);
} // function updateCacheData()
/**
* Delete a cell in cache identified by coordinate address
*
* @param string $pCoord Coordinate address of the cell to delete
* @throws PHPExcel\Exception
* @param string $pCoord Coordinate address of the cell to delete
* @throws PHPExcel\Exception
*/
public function deleteCacheData($pCoord) {
if ($pCoord === $this->_currentObjectID) {
$this->_currentObject->detach();
$this->_currentObjectID = $this->_currentObject = null;
}
public function deleteCacheData($pCoord) {
if ($pCoord === $this->_currentObjectID) {
$this->_currentObject->detach();
$this->_currentObjectID = $this->_currentObject = null;
}
if (is_object($this->_cellCache[$pCoord])) {
$this->_cellCache[$pCoord]->detach();
unset($this->_cellCache[$pCoord]);
}
$this->_currentCellIsDirty = false;
} // function deleteCacheData()
if (is_object($this->_cellCache[$pCoord])) {
$this->_cellCache[$pCoord]->detach();
unset($this->_cellCache[$pCoord]);
}
$this->_currentCellIsDirty = false;
} // function deleteCacheData()
/**
* Get a list of all cell addresses currently held in cache
*
* @return array of string
*/
public function getCellList() {
return array_keys($this->_cellCache);
} // function getCellList()
/**
* Get a list of all cell addresses currently held in cache
*
* @return array of string
*/
public function getCellList() {
return array_keys($this->_cellCache);
} // function getCellList()
/**
* Sort the list of all cell addresses currently held in cache by row and column
*
* @return void
*/
public function getSortedCellList() {
$sortKeys = array();
foreach ($this->getCellList() as $coord) {
sscanf($coord,'%[A-Z]%d', $column, $row);
$sortKeys[sprintf('%09d%3s',$row,$column)] = $coord;
}
ksort($sortKeys);
/**
* Sort the list of all cell addresses currently held in cache by row and column
*
* @return void
*/
public function getSortedCellList() {
$sortKeys = array();
foreach ($this->getCellList() as $coord) {
sscanf($coord,'%[A-Z]%d', $column, $row);
$sortKeys[sprintf('%09d%3s',$row,$column)] = $coord;
}
ksort($sortKeys);
return array_values($sortKeys);
} // function sortCellList()
return array_values($sortKeys);
} // function sortCellList()
/**
* Get highest worksheet column and highest row that have cell records
*
* @return array Highest column name and highest row number
*/
public function getHighestRowAndColumn()
{
// Lookup highest column and highest row
$col = array('A' => '1A');
$row = array(1);
foreach ($this->getCellList() as $coord) {
sscanf($coord,'%[A-Z]%d', $c, $r);
$row[$r] = $r;
$col[$c] = strlen($c).$c;
}
if (!empty($row)) {
// Determine highest column and row
$highestRow = max($row);
$highestColumn = substr(max($col),1);
}
/**
* Get highest worksheet column and highest row that have cell records
*
* @return array Highest column name and highest row number
*/
public function getHighestRowAndColumn()
{
// Lookup highest column and highest row
$col = array('A' => '1A');
$row = array(1);
foreach ($this->getCellList() as $coord) {
sscanf($coord,'%[A-Z]%d', $c, $r);
$row[$r] = $r;
$col[$c] = strlen($c).$c;
}
if (!empty($row)) {
// Determine highest column and row
$highestRow = max($row);
$highestColumn = substr(max($col),1);
}
return array( 'row' => $highestRow,
'column' => $highestColumn
);
}
return array( 'row' => $highestRow,
'column' => $highestColumn
);
}
/**
* Return the cell address of the currently active cell object
*
* @return string
*/
public function getCurrentAddress()
{
return $this->_currentObjectID;
}
/**
* Return the cell address of the currently active cell object
*
* @return string
*/
public function getCurrentAddress()
{
return $this->_currentObjectID;
}
/**
* Return the column address of the currently active cell object
*
* @return string
*/
public function getCurrentColumn()
{
sscanf($this->_currentObjectID, '%[A-Z]%d', $column, $row);
return $column;
}
/**
* Return the column address of the currently active cell object
*
* @return string
*/
public function getCurrentColumn()
{
sscanf($this->_currentObjectID, '%[A-Z]%d', $column, $row);
return $column;
}
/**
* Return the row address of the currently active cell object
*
* @return string
*/
public function getCurrentRow()
{
sscanf($this->_currentObjectID, '%[A-Z]%d', $column, $row);
return $row;
}
/**
* Return the row address of the currently active cell object
*
* @return string
*/
public function getCurrentRow()
{
sscanf($this->_currentObjectID, '%[A-Z]%d', $column, $row);
return $row;
}
/**
* Get highest worksheet column
*
* @return string Highest column name
*/
public function getHighestColumn()
{
$colRow = $this->getHighestRowAndColumn();
return $colRow['column'];
}
/**
* Get highest worksheet column
*
* @return string Highest column name
*/
public function getHighestColumn()
{
$colRow = $this->getHighestRowAndColumn();
return $colRow['column'];
}
/**
* Get highest worksheet row
*
* @return int Highest row number
*/
public function getHighestRow()
{
$colRow = $this->getHighestRowAndColumn();
return $colRow['row'];
}
/**
* Get highest worksheet row
*
* @return int Highest row number
*/
public function getHighestRow()
{
$colRow = $this->getHighestRowAndColumn();
return $colRow['row'];
}
/**
* Generate a unique ID for cache referencing
*
* @return string Unique Reference
*/
protected function _getUniqueID() {
if (function_exists('posix_getpid')) {
$baseUnique = posix_getpid();
} else {
$baseUnique = mt_rand();
}
return uniqid($baseUnique,true);
}
/**
* Generate a unique ID for cache referencing
*
* @return string Unique Reference
*/
protected function _getUniqueID() {
if (function_exists('posix_getpid')) {
$baseUnique = posix_getpid();
} else {
$baseUnique = mt_rand();
}
return uniqid($baseUnique,true);
}
/**
* Clone the cell collection
*
* @param PHPExcel\Worksheet $parent The new worksheet
* @return void
*/
public function copyCellCollection(Worksheet $parent) {
$this->_currentCellIsDirty;
/**
* Clone the cell collection
*
* @param PHPExcel\Worksheet $parent The new worksheet
* @return void
*/
public function copyCellCollection(Worksheet $parent) {
$this->_currentCellIsDirty;
$this->_storeData();
$this->_parent = $parent;
if (($this->_currentObject !== NULL) && (is_object($this->_currentObject))) {
$this->_currentObject->attach($this);
}
} // function copyCellCollection()
$this->_parent = $parent;
if (($this->_currentObject !== null) && (is_object($this->_currentObject))) {
$this->_currentObject->attach($this);
}
} // function copyCellCollection()
/**
* Identify whether the caching method is currently available
* Some methods are dependent on the availability of certain extensions being enabled in the PHP build
*
* @return boolean
*/
public static function cacheMethodIsAvailable() {
return true;
}
/**
* Identify whether the caching method is currently available
* Some methods are dependent on the availability of certain extensions being enabled in the PHP build
*
* @return boolean
*/
public static function cacheMethodIsAvailable() {
return true;
}
}

View File

@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\CachedObjectStorage
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@ -37,185 +37,186 @@ namespace PHPExcel;
*/
class CachedObjectStorage_DiscISAM extends CachedObjectStorage_CacheBase implements CachedObjectStorage_ICache {
/**
* Name of the file for this cache
*
* @var string
*/
private $_fileName = NULL;
/**
* Name of the file for this cache
*
* @var string
*/
private $_fileName = null;
/**
* File handle for this cache file
*
* @var resource
*/
private $_fileHandle = NULL;
/**
* File handle for this cache file
*
* @var resource
*/
private $_fileHandle = null;
/**
* Directory/Folder where the cache file is located
*
* @var string
*/
private $_cacheDirectory = NULL;
/**
* Directory/Folder where the cache file is located
*
* @var string
*/
private $_cacheDirectory = null;
/**
* Store cell data in cache for the current cell object if it's "dirty",
* and the 'nullify' the current cell object
*
* @return void
* @throws PHPExcel\Exception
* @return void
* @throws PHPExcel\Exception
*/
protected function _storeData() {
if ($this->_currentCellIsDirty) {
$this->_currentObject->detach();
protected function _storeData() {
if ($this->_currentCellIsDirty) {
$this->_currentObject->detach();
fseek($this->_fileHandle,0,SEEK_END);
$offset = ftell($this->_fileHandle);
fwrite($this->_fileHandle, serialize($this->_currentObject));
$this->_cellCache[$this->_currentObjectID] = array('ptr' => $offset,
'sz' => ftell($this->_fileHandle) - $offset
);
$this->_currentCellIsDirty = false;
}
$this->_currentObjectID = $this->_currentObject = null;
} // function _storeData()
fseek($this->_fileHandle, 0, SEEK_END);
$offset = ftell($this->_fileHandle);
fwrite($this->_fileHandle, serialize($this->_currentObject));
$this->_cellCache[$this->_currentObjectID] = array(
'ptr' => $offset,
'sz' => ftell($this->_fileHandle) - $offset
);
$this->_currentCellIsDirty = false;
}
$this->_currentObjectID = $this->_currentObject = null;
} // function _storeData()
/**
* Add or Update a cell in cache identified by coordinate address
*
* @param string $pCoord Coordinate address of the cell to update
* @param PHPExcel\Cell $cell Cell to update
* @return void
* @throws PHPExcel\Exception
* @param string $pCoord Coordinate address of the cell to update
* @param PHPExcel\Cell $cell Cell to update
* @return void
* @throws PHPExcel\Exception
*/
public function addCacheData($pCoord, Cell $cell) {
if (($pCoord !== $this->_currentObjectID) && ($this->_currentObjectID !== null)) {
$this->_storeData();
}
public function addCacheData($pCoord, Cell $cell) {
if (($pCoord !== $this->_currentObjectID) && ($this->_currentObjectID !== null)) {
$this->_storeData();
}
$this->_currentObjectID = $pCoord;
$this->_currentObject = $cell;
$this->_currentCellIsDirty = true;
$this->_currentObjectID = $pCoord;
$this->_currentObject = $cell;
$this->_currentCellIsDirty = true;
return $cell;
} // function addCacheData()
return $cell;
} // function addCacheData()
/**
* Get cell at a specific coordinate
*
* @param string $pCoord Coordinate of the cell
* @throws PHPExcel\Exception
* @return PHPExcel\Cell Cell that was found, or null if not found
* @param string $pCoord Coordinate of the cell
* @throws PHPExcel\Exception
* @return PHPExcel\Cell Cell that was found, or null if not found
*/
public function getCacheData($pCoord) {
if ($pCoord === $this->_currentObjectID) {
return $this->_currentObject;
}
$this->_storeData();
public function getCacheData($pCoord) {
if ($pCoord === $this->_currentObjectID) {
return $this->_currentObject;
}
$this->_storeData();
// Check if the entry that has been requested actually exists
if (!isset($this->_cellCache[$pCoord])) {
// Return null if requested entry doesn't exist in cache
return null;
}
// Check if the entry that has been requested actually exists
if (!isset($this->_cellCache[$pCoord])) {
// Return null if requested entry doesn't exist in cache
return null;
}
// Set current entry to the requested entry
$this->_currentObjectID = $pCoord;
fseek($this->_fileHandle,$this->_cellCache[$pCoord]['ptr']);
$this->_currentObject = unserialize(fread($this->_fileHandle,$this->_cellCache[$pCoord]['sz']));
// Set current entry to the requested entry
$this->_currentObjectID = $pCoord;
fseek($this->_fileHandle,$this->_cellCache[$pCoord]['ptr']);
$this->_currentObject = unserialize(fread($this->_fileHandle,$this->_cellCache[$pCoord]['sz']));
// Re-attach this as the cell's parent
$this->_currentObject->attach($this);
// Return requested entry
return $this->_currentObject;
} // function getCacheData()
// Return requested entry
return $this->_currentObject;
} // function getCacheData()
/**
* Get a list of all cell addresses currently held in cache
*
* @return array of string
*/
public function getCellList() {
if ($this->_currentObjectID !== null) {
$this->_storeData();
}
/**
* Get a list of all cell addresses currently held in cache
*
* @return array of string
*/
public function getCellList() {
if ($this->_currentObjectID !== null) {
$this->_storeData();
}
return parent::getCellList();
}
return parent::getCellList();
}
/**
* Clone the cell collection
*
* @param PHPExcel\Worksheet $parent The new worksheet
* @return void
*/
public function copyCellCollection(Worksheet $parent) {
parent::copyCellCollection($parent);
// Get a new id for the new file name
$baseUnique = $this->_getUniqueID();
$newFileName = $this->_cacheDirectory.'/PHPExcel.'.$baseUnique.'.cache';
// Copy the existing cell cache file
copy ($this->_fileName,$newFileName);
$this->_fileName = $newFileName;
// Open the copied cell cache file
$this->_fileHandle = fopen($this->_fileName,'a+');
} // function copyCellCollection()
/**
* Clone the cell collection
*
* @param PHPExcel\Worksheet $parent The new worksheet
* @return void
*/
public function copyCellCollection(Worksheet $parent) {
parent::copyCellCollection($parent);
// Get a new id for the new file name
$baseUnique = $this->_getUniqueID();
$newFileName = $this->_cacheDirectory.'/PHPExcel.'.$baseUnique.'.cache';
// Copy the existing cell cache file
copy ($this->_fileName,$newFileName);
$this->_fileName = $newFileName;
// Open the copied cell cache file
$this->_fileHandle = fopen($this->_fileName,'a+');
} // function copyCellCollection()
/**
* Clear the cell collection and disconnect from our parent
*
* @return void
*/
public function unsetWorksheetCells() {
if(!is_null($this->_currentObject)) {
$this->_currentObject->detach();
$this->_currentObject = $this->_currentObjectID = null;
}
$this->_cellCache = array();
/**
* Clear the cell collection and disconnect from our parent
*
* @return void
*/
public function unsetWorksheetCells() {
if(!is_null($this->_currentObject)) {
$this->_currentObject->detach();
$this->_currentObject = $this->_currentObjectID = null;
}
$this->_cellCache = array();
// detach ourself from the worksheet, so that it can then delete this object successfully
$this->_parent = null;
// detach ourself from the worksheet, so that it can then delete this object successfully
$this->_parent = null;
// Close down the temporary cache file
$this->__destruct();
} // function unsetWorksheetCells()
// Close down the temporary cache file
$this->__destruct();
} // function unsetWorksheetCells()
/**
* Initialise this new cell collection
*
* @param PHPExcel\Worksheet $parent The worksheet for this cell collection
* @param array of mixed $arguments Additional initialisation arguments
*/
public function __construct(Worksheet $parent, $arguments) {
$this->_cacheDirectory = ((isset($arguments['dir'])) && ($arguments['dir'] !== NULL))
? $arguments['dir']
: Shared_File::sys_get_temp_dir();
/**
* Initialise this new cell collection
*
* @param PHPExcel\Worksheet $parent The worksheet for this cell collection
* @param array of mixed $arguments Additional initialisation arguments
*/
public function __construct(Worksheet $parent, $arguments) {
$this->_cacheDirectory = ((isset($arguments['dir'])) && ($arguments['dir'] !== nul))
? $arguments['dir']
: Shared_File::sys_get_temp_dir();
parent::__construct($parent);
if (is_null($this->_fileHandle)) {
$baseUnique = $this->_getUniqueID();
$this->_fileName = $this->_cacheDirectory.'/PHPExcel.'.$baseUnique.'.cache';
$this->_fileHandle = fopen($this->_fileName,'a+');
}
} // function __construct()
parent::__construct($parent);
if (is_null($this->_fileHandle)) {
$baseUnique = $this->_getUniqueID();
$this->_fileName = $this->_cacheDirectory.'/PHPExcel.'.$baseUnique.'.cache';
$this->_fileHandle = fopen($this->_fileName,'a+');
}
} // function __construct()
/**
* Destroy this cell collection
*/
public function __destruct() {
if (!is_null($this->_fileHandle)) {
fclose($this->_fileHandle);
unlink($this->_fileName);
}
$this->_fileHandle = null;
} // function __destruct()
/**
* Destroy this cell collection
*/
public function __destruct() {
if (!is_null($this->_fileHandle)) {
fclose($this->_fileHandle);
unlink($this->_fileName);
}
$this->_fileHandle = null;
} // function __destruct()
}

View File

@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\CachedObjectStorage
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@ -40,75 +40,74 @@ interface CachedObjectStorage_ICache
/**
* Add or Update a cell in cache identified by coordinate address
*
* @param string $pCoord Coordinate address of the cell to update
* @param PHPExcel\Cell $cell Cell to update
* @return void
* @throws PHPExcel\Exception
* @param string $pCoord Coordinate address of the cell to update
* @param PHPExcel\Cell $cell Cell to update
* @return void
* @throws PHPExcel\Exception
*/
public function addCacheData($pCoord, Cell $cell);
public function addCacheData($pCoord, Cell $cell);
/**
* Add or Update a cell in cache
*
* @param PHPExcel\Cell $cell Cell to update
* @return void
* @throws PHPExcel\Exception
* @param PHPExcel\Cell $cell Cell to update
* @return void
* @throws PHPExcel\Exception
*/
public function updateCacheData(Cell $cell);
public function updateCacheData(Cell $cell);
/**
* Fetch a cell from cache identified by coordinate address
*
* @param string $pCoord Coordinate address of the cell to retrieve
* @return PHPExcel\Cell Cell that was found, or null if not found
* @throws PHPExcel\Exception
* @param string $pCoord Coordinate address of the cell to retrieve
* @return PHPExcel\Cell Cell that was found, or null if not found
* @throws PHPExcel\Exception
*/
public function getCacheData($pCoord);
public function getCacheData($pCoord);
/**
* Delete a cell in cache identified by coordinate address
*
* @param string $pCoord Coordinate address of the cell to delete
* @throws PHPExcel\Exception
* @param string $pCoord Coordinate address of the cell to delete
* @throws PHPExcel\Exception
*/
public function deleteCacheData($pCoord);
public function deleteCacheData($pCoord);
/**
* Is a value set in the current PHPExcel\CachedObjectStorage_ICache for an indexed cell?
*
* @param string $pCoord Coordinate address of the cell to check
* @return boolean
*/
public function isDataSet($pCoord);
/**
* Is a value set in the current PHPExcel\CachedObjectStorage_ICache for an indexed cell?
*
* @param string $pCoord Coordinate address of the cell to check
* @return boolean
*/
public function isDataSet($pCoord);
/**
* Get a list of all cell addresses currently held in cache
*
* @return array of string
*/
public function getCellList();
/**
* Get a list of all cell addresses currently held in cache
*
* @return array of string
*/
public function getCellList();
/**
* Get the list of all cell addresses currently held in cache sorted by column and row
*
* @return void
*/
public function getSortedCellList();
/**
* Get the list of all cell addresses currently held in cache sorted by column and row
*
* @return void
*/
public function getSortedCellList();
/**
* Clone the cell collection
*
* @param PHPExcel\Worksheet $parent The new worksheet
* @return void
*/
public function copyCellCollection(Worksheet $parent);
/**
* Identify whether the caching method is currently available
* Some methods are dependent on the availability of certain extensions being enabled in the PHP build
*
* @return boolean
*/
public static function cacheMethodIsAvailable();
/**
* Clone the cell collection
*
* @param PHPExcel\Worksheet $parent The new worksheet
* @return void
*/
public function copyCellCollection(Worksheet $parent);
/**
* Identify whether the caching method is currently available
* Some methods are dependent on the availability of certain extensions being enabled in the PHP build
*
* @return boolean
*/
public static function cacheMethodIsAvailable();
}

View File

@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\CachedObjectStorage
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@ -41,114 +41,114 @@ class CachedObjectStorage_Igbinary extends CachedObjectStorage_CacheBase impleme
* Store cell data in cache for the current cell object if it's "dirty",
* and the 'nullify' the current cell object
*
* @return void
* @throws PHPExcel\Exception
* @return void
* @throws PHPExcel\Exception
*/
protected function _storeData() {
if ($this->_currentCellIsDirty) {
$this->_currentObject->detach();
protected function _storeData() {
if ($this->_currentCellIsDirty) {
$this->_currentObject->detach();
$this->_cellCache[$this->_currentObjectID] = igbinary_serialize($this->_currentObject);
$this->_currentCellIsDirty = false;
}
$this->_currentObjectID = $this->_currentObject = null;
} // function _storeData()
$this->_cellCache[$this->_currentObjectID] = igbinary_serialize($this->_currentObject);
$this->_currentCellIsDirty = false;
}
$this->_currentObjectID = $this->_currentObject = null;
} // function _storeData()
/**
* Add or Update a cell in cache identified by coordinate address
*
* @param string $pCoord Coordinate address of the cell to update
* @param PHPExcel\Cell $cell Cell to update
* @return void
* @throws PHPExcel\Exception
* @param string $pCoord Coordinate address of the cell to update
* @param PHPExcel\Cell $cell Cell to update
* @return void
* @throws PHPExcel\Exception
*/
public function addCacheData($pCoord, Cell $cell) {
if (($pCoord !== $this->_currentObjectID) && ($this->_currentObjectID !== null)) {
$this->_storeData();
}
public function addCacheData($pCoord, Cell $cell) {
if (($pCoord !== $this->_currentObjectID) && ($this->_currentObjectID !== null)) {
$this->_storeData();
}
$this->_currentObjectID = $pCoord;
$this->_currentObject = $cell;
$this->_currentCellIsDirty = true;
$this->_currentObjectID = $pCoord;
$this->_currentObject = $cell;
$this->_currentCellIsDirty = true;
return $cell;
} // function addCacheData()
return $cell;
} // function addCacheData()
/**
* Get cell at a specific coordinate
*
* @param string $pCoord Coordinate of the cell
* @throws PHPExcel\Exception
* @return PHPExcel\Cell Cell that was found, or null if not found
* @param string $pCoord Coordinate of the cell
* @throws PHPExcel\Exception
* @return PHPExcel\Cell Cell that was found, or null if not found
*/
public function getCacheData($pCoord) {
if ($pCoord === $this->_currentObjectID) {
return $this->_currentObject;
}
$this->_storeData();
public function getCacheData($pCoord) {
if ($pCoord === $this->_currentObjectID) {
return $this->_currentObject;
}
$this->_storeData();
// Check if the entry that has been requested actually exists
if (!isset($this->_cellCache[$pCoord])) {
// Return null if requested entry doesn't exist in cache
return null;
}
// Check if the entry that has been requested actually exists
if (!isset($this->_cellCache[$pCoord])) {
// Return null if requested entry doesn't exist in cache
return null;
}
// Set current entry to the requested entry
$this->_currentObjectID = $pCoord;
$this->_currentObject = igbinary_unserialize($this->_cellCache[$pCoord]);
// Set current entry to the requested entry
$this->_currentObjectID = $pCoord;
$this->_currentObject = igbinary_unserialize($this->_cellCache[$pCoord]);
// Re-attach this as the cell's parent
$this->_currentObject->attach($this);
// Return requested entry
return $this->_currentObject;
} // function getCacheData()
// Return requested entry
return $this->_currentObject;
} // function getCacheData()
/**
* Get a list of all cell addresses currently held in cache
*
* @return array of string
*/
public function getCellList() {
if ($this->_currentObjectID !== null) {
$this->_storeData();
}
/**
* Get a list of all cell addresses currently held in cache
*
* @return array of string
*/
public function getCellList() {
if ($this->_currentObjectID !== null) {
$this->_storeData();
}
return parent::getCellList();
}
return parent::getCellList();
}
/**
* Clear the cell collection and disconnect from our parent
*
* @return void
*/
public function unsetWorksheetCells() {
if(!is_null($this->_currentObject)) {
$this->_currentObject->detach();
$this->_currentObject = $this->_currentObjectID = null;
}
$this->_cellCache = array();
/**
* Clear the cell collection and disconnect from our parent
*
* @return void
*/
public function unsetWorksheetCells() {
if(!is_null($this->_currentObject)) {
$this->_currentObject->detach();
$this->_currentObject = $this->_currentObjectID = null;
}
$this->_cellCache = array();
// detach ourself from the worksheet, so that it can then delete this object successfully
$this->_parent = null;
} // function unsetWorksheetCells()
// detach ourself from the worksheet, so that it can then delete this object successfully
$this->_parent = null;
} // function unsetWorksheetCells()
/**
* Identify whether the caching method is currently available
* Some methods are dependent on the availability of certain extensions being enabled in the PHP build
*
* @return boolean
*/
public static function cacheMethodIsAvailable() {
if (!function_exists('igbinary_serialize')) {
return false;
}
/**
* Identify whether the caching method is currently available
* Some methods are dependent on the availability of certain extensions being enabled in the PHP build
*
* @return boolean
*/
public static function cacheMethodIsAvailable() {
if (!function_exists('igbinary_serialize')) {
return false;
}
return true;
}
return true;
}
}

View File

@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\CachedObjectStorage
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@ -37,279 +37,279 @@ namespace PHPExcel;
*/
class CachedObjectStorage_Memcache extends CachedObjectStorage_CacheBase implements CachedObjectStorage_ICache {
/**
* Prefix used to uniquely identify cache data for this worksheet
*
* @var string
*/
private $_cachePrefix = null;
/**
* Prefix used to uniquely identify cache data for this worksheet
*
* @var string
*/
private $_cachePrefix = null;
/**
* Cache timeout
*
* @var integer
*/
private $_cacheTime = 600;
/**
* Cache timeout
*
* @var integer
*/
private $_cacheTime = 600;
/**
* Memcache interface
*
* @var resource
*/
private $_memcache = null;
/**
* Memcache interface
*
* @var resource
*/
private $_memcache = null;
/**
* Store cell data in cache for the current cell object if it's "dirty",
* and the 'nullify' the current cell object
*
* @return void
* @throws PHPExcel\Exception
* @return void
* @throws PHPExcel\Exception
*/
protected function _storeData() {
if ($this->_currentCellIsDirty) {
$this->_currentObject->detach();
protected function _storeData() {
if ($this->_currentCellIsDirty) {
$this->_currentObject->detach();
$obj = serialize($this->_currentObject);
if (!$this->_memcache->replace($this->_cachePrefix.$this->_currentObjectID.'.cache',$obj,NULL,$this->_cacheTime)) {
if (!$this->_memcache->add($this->_cachePrefix.$this->_currentObjectID.'.cache',$obj,NULL,$this->_cacheTime)) {
$this->__destruct();
throw new Exception('Failed to store cell '.$this->_currentObjectID.' in MemCache');
}
}
$this->_currentCellIsDirty = false;
}
$this->_currentObjectID = $this->_currentObject = null;
} // function _storeData()
$obj = serialize($this->_currentObject);
if (!$this->_memcache->replace($this->_cachePrefix.$this->_currentObjectID.'.cache',$obj, null, $this->_cacheTime)) {
if (!$this->_memcache->add($this->_cachePrefix.$this->_currentObjectID.'.cache',$obj, null, $this->_cacheTime)) {
$this->__destruct();
throw new Exception('Failed to store cell '.$this->_currentObjectID.' in MemCache');
}
}
$this->_currentCellIsDirty = false;
}
$this->_currentObjectID = $this->_currentObject = null;
} // function _storeData()
/**
* Add or Update a cell in cache identified by coordinate address
*
* @param string $pCoord Coordinate address of the cell to update
* @param PHPExcel\Cell $cell Cell to update
* @return void
* @throws PHPExcel\Exception
* @param string $pCoord Coordinate address of the cell to update
* @param PHPExcel\Cell $cell Cell to update
* @return void
* @throws PHPExcel\Exception
*/
public function addCacheData($pCoord, Cell $cell) {
if (($pCoord !== $this->_currentObjectID) && ($this->_currentObjectID !== null)) {
$this->_storeData();
}
$this->_cellCache[$pCoord] = true;
public function addCacheData($pCoord, Cell $cell) {
if (($pCoord !== $this->_currentObjectID) && ($this->_currentObjectID !== null)) {
$this->_storeData();
}
$this->_cellCache[$pCoord] = true;
$this->_currentObjectID = $pCoord;
$this->_currentObject = $cell;
$this->_currentCellIsDirty = true;
$this->_currentObjectID = $pCoord;
$this->_currentObject = $cell;
$this->_currentCellIsDirty = true;
return $cell;
} // function addCacheData()
return $cell;
} // function addCacheData()
/**
* Is a value set in the current PHPExcel\CachedObjectStorage_ICache for an indexed cell?
*
* @param string $pCoord Coordinate address of the cell to check
* @return void
* @return boolean
*/
public function isDataSet($pCoord) {
// Check if the requested entry is the current object, or exists in the cache
if (parent::isDataSet($pCoord)) {
if ($this->_currentObjectID == $pCoord) {
return true;
}
// Check if the requested entry still exists in Memcache
$success = $this->_memcache->get($this->_cachePrefix.$pCoord.'.cache');
if ($success === false) {
// Entry no longer exists in Memcache, so clear it from the cache array
parent::deleteCacheData($pCoord);
throw new Exception('Cell entry '.$pCoord.' no longer exists in MemCache');
}
return true;
}
return false;
} // function isDataSet()
/**
* Is a value set in the current PHPExcel\CachedObjectStorage_ICache for an indexed cell?
*
* @param string $pCoord Coordinate address of the cell to check
* @return void
* @return boolean
*/
public function isDataSet($pCoord) {
// Check if the requested entry is the current object, or exists in the cache
if (parent::isDataSet($pCoord)) {
if ($this->_currentObjectID == $pCoord) {
return true;
}
// Check if the requested entry still exists in Memcache
$success = $this->_memcache->get($this->_cachePrefix.$pCoord.'.cache');
if ($success === false) {
// Entry no longer exists in Memcache, so clear it from the cache array
parent::deleteCacheData($pCoord);
throw new Exception('Cell entry '.$pCoord.' no longer exists in MemCache');
}
return true;
}
return false;
} // function isDataSet()
/**
/**
* Get cell at a specific coordinate
*
* @param string $pCoord Coordinate of the cell
* @throws PHPExcel\Exception
* @return PHPExcel\Cell Cell that was found, or null if not found
* @param string $pCoord Coordinate of the cell
* @throws PHPExcel\Exception
* @return PHPExcel\Cell Cell that was found, or null if not found
*/
public function getCacheData($pCoord) {
if ($pCoord === $this->_currentObjectID) {
return $this->_currentObject;
}
$this->_storeData();
public function getCacheData($pCoord) {
if ($pCoord === $this->_currentObjectID) {
return $this->_currentObject;
}
$this->_storeData();
// Check if the entry that has been requested actually exists
if (parent::isDataSet($pCoord)) {
$obj = $this->_memcache->get($this->_cachePrefix.$pCoord.'.cache');
if ($obj === false) {
// Entry no longer exists in Memcache, so clear it from the cache array
parent::deleteCacheData($pCoord);
throw new Exception('Cell entry '.$pCoord.' no longer exists in MemCache');
}
} else {
// Return null if requested entry doesn't exist in cache
return null;
}
// Check if the entry that has been requested actually exists
if (parent::isDataSet($pCoord)) {
$obj = $this->_memcache->get($this->_cachePrefix.$pCoord.'.cache');
if ($obj === false) {
// Entry no longer exists in Memcache, so clear it from the cache array
parent::deleteCacheData($pCoord);
throw new Exception('Cell entry '.$pCoord.' no longer exists in MemCache');
}
} else {
// Return null if requested entry doesn't exist in cache
return null;
}
// Set current entry to the requested entry
$this->_currentObjectID = $pCoord;
$this->_currentObject = unserialize($obj);
// Set current entry to the requested entry
$this->_currentObjectID = $pCoord;
$this->_currentObject = unserialize($obj);
// Re-attach this as the cell's parent
$this->_currentObject->attach($this);
// Return requested entry
return $this->_currentObject;
} // function getCacheData()
// Return requested entry
return $this->_currentObject;
} // function getCacheData()
/**
* Get a list of all cell addresses currently held in cache
*
* @return array of string
*/
public function getCellList() {
if ($this->_currentObjectID !== null) {
$this->_storeData();
}
/**
* Get a list of all cell addresses currently held in cache
*
* @return array of string
*/
public function getCellList() {
if ($this->_currentObjectID !== null) {
$this->_storeData();
}
return parent::getCellList();
}
return parent::getCellList();
}
/**
* Delete a cell in cache identified by coordinate address
*
* @param string $pCoord Coordinate address of the cell to delete
* @throws PHPExcel\Exception
* @param string $pCoord Coordinate address of the cell to delete
* @throws PHPExcel\Exception
*/
public function deleteCacheData($pCoord) {
// Delete the entry from Memcache
$this->_memcache->delete($this->_cachePrefix.$pCoord.'.cache');
public function deleteCacheData($pCoord) {
// Delete the entry from Memcache
$this->_memcache->delete($this->_cachePrefix.$pCoord.'.cache');
// Delete the entry from our cell address array
parent::deleteCacheData($pCoord);
} // function deleteCacheData()
// Delete the entry from our cell address array
parent::deleteCacheData($pCoord);
} // function deleteCacheData()
/**
* Clone the cell collection
*
* @param PHPExcel\Worksheet $parent The new worksheet
* @throws PHPExcel\Exception
* @return void
*/
public function copyCellCollection(Worksheet $parent) {
parent::copyCellCollection($parent);
// Get a new id for the new file name
$baseUnique = $this->_getUniqueID();
$newCachePrefix = substr(md5($baseUnique),0,8).'.';
$cacheList = $this->getCellList();
foreach($cacheList as $cellID) {
if ($cellID != $this->_currentObjectID) {
$obj = $this->_memcache->get($this->_cachePrefix.$cellID.'.cache');
if ($obj === false) {
// Entry no longer exists in Memcache, so clear it from the cache array
parent::deleteCacheData($cellID);
throw new Exception('Cell entry '.$cellID.' no longer exists in MemCache');
}
if (!$this->_memcache->add($newCachePrefix.$cellID.'.cache',$obj,NULL,$this->_cacheTime)) {
$this->__destruct();
throw new Exception('Failed to store cell '.$cellID.' in MemCache');
}
}
}
$this->_cachePrefix = $newCachePrefix;
}
/**
* Clone the cell collection
*
* @param PHPExcel\Worksheet $parent The new worksheet
* @throws PHPExcel\Exception
* @return void
*/
public function copyCellCollection(Worksheet $parent) {
parent::copyCellCollection($parent);
// Get a new id for the new file name
$baseUnique = $this->_getUniqueID();
$newCachePrefix = substr(md5($baseUnique),0,8).'.';
$cacheList = $this->getCellList();
foreach($cacheList as $cellID) {
if ($cellID != $this->_currentObjectID) {
$obj = $this->_memcache->get($this->_cachePrefix.$cellID.'.cache');
if ($obj === false) {
// Entry no longer exists in Memcache, so clear it from the cache array
parent::deleteCacheData($cellID);
throw new Exception('Cell entry '.$cellID.' no longer exists in MemCache');
}
if (!$this->_memcache->add($newCachePrefix.$cellID.'.cache', $obj, null, $this->_cacheTime)) {
$this->__destruct();
throw new Exception('Failed to store cell '.$cellID.' in MemCache');
}
}
}
$this->_cachePrefix = $newCachePrefix;
}
/**
* Clear the cell collection and disconnect from our parent
*
* @return void
*/
public function unsetWorksheetCells() {
if(!is_null($this->_currentObject)) {
$this->_currentObject->detach();
$this->_currentObject = $this->_currentObjectID = null;
}
/**
* Clear the cell collection and disconnect from our parent
*
* @return void
*/
public function unsetWorksheetCells() {
if(!is_null($this->_currentObject)) {
$this->_currentObject->detach();
$this->_currentObject = $this->_currentObjectID = null;
}
// Flush the Memcache cache
$this->__destruct();
// Flush the Memcache cache
$this->__destruct();
$this->_cellCache = array();
$this->_cellCache = array();
// detach ourself from the worksheet, so that it can then delete this object successfully
$this->_parent = null;
} // function unsetWorksheetCells()
// detach ourself from the worksheet, so that it can then delete this object successfully
$this->_parent = null;
} // function unsetWorksheetCells()
/**
* Initialise this new cell collection
*
* @param PHPExcel\Worksheet $parent The worksheet for this cell collection
* @param array of mixed $arguments Additional initialisation arguments
*/
public function __construct(Worksheet $parent, $arguments) {
$memcacheServer = (isset($arguments['memcacheServer'])) ? $arguments['memcacheServer'] : 'localhost';
$memcachePort = (isset($arguments['memcachePort'])) ? $arguments['memcachePort'] : 11211;
$cacheTime = (isset($arguments['cacheTime'])) ? $arguments['cacheTime'] : 600;
/**
* Initialise this new cell collection
*
* @param PHPExcel\Worksheet $parent The worksheet for this cell collection
* @param array of mixed $arguments Additional initialisation arguments
*/
public function __construct(Worksheet $parent, $arguments) {
$memcacheServer = (isset($arguments['memcacheServer'])) ? $arguments['memcacheServer'] : 'localhost';
$memcachePort = (isset($arguments['memcachePort'])) ? $arguments['memcachePort'] : 11211;
$cacheTime = (isset($arguments['cacheTime'])) ? $arguments['cacheTime'] : 600;
if (is_null($this->_cachePrefix)) {
$baseUnique = $this->_getUniqueID();
$this->_cachePrefix = substr(md5($baseUnique),0,8).'.';
if (is_null($this->_cachePrefix)) {
$baseUnique = $this->_getUniqueID();
$this->_cachePrefix = substr(md5($baseUnique),0,8).'.';
// Set a new Memcache object and connect to the Memcache server
$this->_memcache = new Memcache();
if (!$this->_memcache->addServer($memcacheServer, $memcachePort, false, 50, 5, 5, true, array($this, 'failureCallback'))) {
throw new Exception('Could not connect to MemCache server at '.$memcacheServer.':'.$memcachePort);
}
$this->_cacheTime = $cacheTime;
// Set a new Memcache object and connect to the Memcache server
$this->_memcache = new Memcache();
if (!$this->_memcache->addServer($memcacheServer, $memcachePort, false, 50, 5, 5, true, array($this, 'failureCallback'))) {
throw new Exception('Could not connect to MemCache server at '.$memcacheServer.':'.$memcachePort);
}
$this->_cacheTime = $cacheTime;
parent::__construct($parent);
}
}
parent::__construct($parent);
}
}
/**
* Memcache error handler
*
* @param string $host Memcache server
* @param integer $port Memcache port
* @throws PHPExcel\Exception
*/
public function failureCallback($host, $port) {
throw new Exception('memcache '.$host.':'.$port.' failed');
}
/**
* Memcache error handler
*
* @param string $host Memcache server
* @param integer $port Memcache port
* @throws PHPExcel\Exception
*/
public function failureCallback($host, $port) {
throw new Exception('memcache '.$host.':'.$port.' failed');
}
/**
* Destroy this cell collection
*/
public function __destruct() {
$cacheList = $this->getCellList();
foreach($cacheList as $cellID) {
$this->_memcache->delete($this->_cachePrefix.$cellID.'.cache');
}
} // function __destruct()
/**
* Destroy this cell collection
*/
public function __destruct() {
$cacheList = $this->getCellList();
foreach($cacheList as $cellID) {
$this->_memcache->delete($this->_cachePrefix.$cellID.'.cache');
}
} // function __destruct()
/**
* Identify whether the caching method is currently available
* Some methods are dependent on the availability of certain extensions being enabled in the PHP build
*
* @return boolean
*/
public static function cacheMethodIsAvailable() {
if (!function_exists('memcache_add')) {
return false;
}
/**
* Identify whether the caching method is currently available
* Some methods are dependent on the availability of certain extensions being enabled in the PHP build
*
* @return boolean
*/
public static function cacheMethodIsAvailable() {
if (!function_exists('memcache_add')) {
return false;
}
return true;
}
return true;
}
}

View File

@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\CachedObjectStorage
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@ -40,88 +40,88 @@ class CachedObjectStorage_Memory extends CachedObjectStorage_CacheBase implement
/**
* Dummy method callable from CacheBase, but unused by Memory cache
*
* @return void
* @return void
*/
protected function _storeData() {
} // function _storeData()
protected function _storeData() {
} // function _storeData()
/**
* Add or Update a cell in cache identified by coordinate address
*
* @param string $pCoord Coordinate address of the cell to update
* @param PHPExcel\Cell $cell Cell to update
* @return PHPExcel\Cell
* @throws PHPExcel\Exception
* @param string $pCoord Coordinate address of the cell to update
* @param PHPExcel\Cell $cell Cell to update
* @return PHPExcel\Cell
* @throws PHPExcel\Exception
*/
public function addCacheData($pCoord, Cell $cell) {
$this->_cellCache[$pCoord] = $cell;
public function addCacheData($pCoord, Cell $cell) {
$this->_cellCache[$pCoord] = $cell;
// Set current entry to the new/updated entry
$this->_currentObjectID = $pCoord;
// Set current entry to the new/updated entry
$this->_currentObjectID = $pCoord;
return $cell;
} // function addCacheData()
return $cell;
} // function addCacheData()
/**
* Get cell at a specific coordinate
*
* @param string $pCoord Coordinate of the cell
* @throws PHPExcel\Exception
* @return PHPExcel\Cell Cell that was found, or null if not found
* @param string $pCoord Coordinate of the cell
* @throws PHPExcel\Exception
* @return PHPExcel\Cell Cell that was found, or null if not found
*/
public function getCacheData($pCoord) {
// Check if the entry that has been requested actually exists
if (!isset($this->_cellCache[$pCoord])) {
$this->_currentObjectID = NULL;
// Return null if requested entry doesn't exist in cache
return null;
}
public function getCacheData($pCoord) {
// Check if the entry that has been requested actually exists
if (!isset($this->_cellCache[$pCoord])) {
$this->_currentObjectID = null;
// Return null if requested entry doesn't exist in cache
return null;
}
// Set current entry to the requested entry
$this->_currentObjectID = $pCoord;
// Set current entry to the requested entry
$this->_currentObjectID = $pCoord;
// Return requested entry
return $this->_cellCache[$pCoord];
} // function getCacheData()
// Return requested entry
return $this->_cellCache[$pCoord];
} // function getCacheData()
/**
* Clone the cell collection
*
* @param PHPExcel\Worksheet $parent The new worksheet
* @return void
*/
public function copyCellCollection(Worksheet $parent) {
parent::copyCellCollection($parent);
/**
* Clone the cell collection
*
* @param PHPExcel\Worksheet $parent The new worksheet
* @return void
*/
public function copyCellCollection(Worksheet $parent) {
parent::copyCellCollection($parent);
$newCollection = array();
foreach($this->_cellCache as $k => &$cell) {
$newCollection[$k] = clone $cell;
$newCollection[$k]->attach($this);
}
$newCollection = array();
foreach($this->_cellCache as $k => &$cell) {
$newCollection[$k] = clone $cell;
$newCollection[$k]->attach($this);
}
$this->_cellCache = $newCollection;
}
$this->_cellCache = $newCollection;
}
/**
* Clear the cell collection and disconnect from our parent
*
* @return void
*/
public function unsetWorksheetCells() {
// Because cells are all stored as intact objects in memory, we need to detach each one from the parent
foreach($this->_cellCache as $k => &$cell) {
$cell->detach();
$this->_cellCache[$k] = null;
}
unset($cell);
/**
* Clear the cell collection and disconnect from our parent
*
* @return void
*/
public function unsetWorksheetCells() {
// Because cells are all stored as intact objects in memory, we need to detach each one from the parent
foreach($this->_cellCache as $k => &$cell) {
$cell->detach();
$this->_cellCache[$k] = null;
}
unset($cell);
$this->_cellCache = array();
$this->_cellCache = array();
// detach ourself from the worksheet, so that it can then delete this object successfully
$this->_parent = null;
} // function unsetWorksheetCells()
// detach ourself from the worksheet, so that it can then delete this object successfully
$this->_parent = null;
} // function unsetWorksheetCells()
}

View File

@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\CachedObjectStorage
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@ -41,99 +41,99 @@ class CachedObjectStorage_MemoryGZip extends CachedObjectStorage_CacheBase imple
* Store cell data in cache for the current cell object if it's "dirty",
* and the 'nullify' the current cell object
*
* @return void
* @throws PHPExcel\Exception
* @return void
* @throws PHPExcel\Exception
*/
protected function _storeData() {
if ($this->_currentCellIsDirty) {
$this->_currentObject->detach();
protected function _storeData() {
if ($this->_currentCellIsDirty) {
$this->_currentObject->detach();
$this->_cellCache[$this->_currentObjectID] = gzdeflate(serialize($this->_currentObject));
$this->_currentCellIsDirty = false;
}
$this->_currentObjectID = $this->_currentObject = null;
} // function _storeData()
$this->_cellCache[$this->_currentObjectID] = gzdeflate(serialize($this->_currentObject));
$this->_currentCellIsDirty = false;
}
$this->_currentObjectID = $this->_currentObject = null;
} // function _storeData()
/**
* Add or Update a cell in cache identified by coordinate address
*
* @param string $pCoord Coordinate address of the cell to update
* @param PHPExcel\Cell $cell Cell to update
* @return void
* @throws PHPExcel\Exception
* @param string $pCoord Coordinate address of the cell to update
* @param PHPExcel\Cell $cell Cell to update
* @return void
* @throws PHPExcel\Exception
*/
public function addCacheData($pCoord, Cell $cell) {
if (($pCoord !== $this->_currentObjectID) && ($this->_currentObjectID !== null)) {
$this->_storeData();
}
public function addCacheData($pCoord, Cell $cell) {
if (($pCoord !== $this->_currentObjectID) && ($this->_currentObjectID !== null)) {
$this->_storeData();
}
$this->_currentObjectID = $pCoord;
$this->_currentObject = $cell;
$this->_currentCellIsDirty = true;
$this->_currentObjectID = $pCoord;
$this->_currentObject = $cell;
$this->_currentCellIsDirty = true;
return $cell;
} // function addCacheData()
return $cell;
} // function addCacheData()
/**
* Get cell at a specific coordinate
*
* @param string $pCoord Coordinate of the cell
* @throws PHPExcel\Exception
* @return PHPExcel\Cell Cell that was found, or null if not found
* @param string $pCoord Coordinate of the cell
* @throws PHPExcel\Exception
* @return PHPExcel\Cell Cell that was found, or null if not found
*/
public function getCacheData($pCoord) {
if ($pCoord === $this->_currentObjectID) {
return $this->_currentObject;
}
$this->_storeData();
public function getCacheData($pCoord) {
if ($pCoord === $this->_currentObjectID) {
return $this->_currentObject;
}
$this->_storeData();
// Check if the entry that has been requested actually exists
if (!isset($this->_cellCache[$pCoord])) {
// Return null if requested entry doesn't exist in cache
return null;
}
// Check if the entry that has been requested actually exists
if (!isset($this->_cellCache[$pCoord])) {
// Return null if requested entry doesn't exist in cache
return null;
}
// Set current entry to the requested entry
$this->_currentObjectID = $pCoord;
$this->_currentObject = unserialize(gzinflate($this->_cellCache[$pCoord]));
// Set current entry to the requested entry
$this->_currentObjectID = $pCoord;
$this->_currentObject = unserialize(gzinflate($this->_cellCache[$pCoord]));
// Re-attach this as the cell's parent
$this->_currentObject->attach($this);
// Return requested entry
return $this->_currentObject;
} // function getCacheData()
// Return requested entry
return $this->_currentObject;
} // function getCacheData()
/**
* Get a list of all cell addresses currently held in cache
*
* @return array of string
*/
public function getCellList() {
if ($this->_currentObjectID !== null) {
$this->_storeData();
}
/**
* Get a list of all cell addresses currently held in cache
*
* @return array of string
*/
public function getCellList() {
if ($this->_currentObjectID !== null) {
$this->_storeData();
}
return parent::getCellList();
}
return parent::getCellList();
}
/**
* Clear the cell collection and disconnect from our parent
*
* @return void
*/
public function unsetWorksheetCells() {
if(!is_null($this->_currentObject)) {
$this->_currentObject->detach();
$this->_currentObject = $this->_currentObjectID = null;
}
$this->_cellCache = array();
/**
* Clear the cell collection and disconnect from our parent
*
* @return void
*/
public function unsetWorksheetCells() {
if(!is_null($this->_currentObject)) {
$this->_currentObject->detach();
$this->_currentObject = $this->_currentObjectID = null;
}
$this->_cellCache = array();
// detach ourself from the worksheet, so that it can then delete this object successfully
$this->_parent = null;
} // function unsetWorksheetCells()
// detach ourself from the worksheet, so that it can then delete this object successfully
$this->_parent = null;
} // function unsetWorksheetCells()
}

View File

@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\CachedObjectStorage
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@ -41,99 +41,99 @@ class CachedObjectStorage_MemorySerialized extends CachedObjectStorage_CacheBase
* Store cell data in cache for the current cell object if it's "dirty",
* and the 'nullify' the current cell object
*
* @return void
* @throws PHPExcel\Exception
* @return void
* @throws PHPExcel\Exception
*/
protected function _storeData() {
if ($this->_currentCellIsDirty) {
$this->_currentObject->detach();
protected function _storeData() {
if ($this->_currentCellIsDirty) {
$this->_currentObject->detach();
$this->_cellCache[$this->_currentObjectID] = serialize($this->_currentObject);
$this->_currentCellIsDirty = false;
}
$this->_currentObjectID = $this->_currentObject = null;
} // function _storeData()
$this->_cellCache[$this->_currentObjectID] = serialize($this->_currentObject);
$this->_currentCellIsDirty = false;
}
$this->_currentObjectID = $this->_currentObject = null;
} // function _storeData()
/**
* Add or Update a cell in cache identified by coordinate address
*
* @param string $pCoord Coordinate address of the cell to update
* @param PHPExcel\Cell $cell Cell to update
* @return void
* @throws PHPExcel\Exception
* @param string $pCoord Coordinate address of the cell to update
* @param PHPExcel\Cell $cell Cell to update
* @return void
* @throws PHPExcel\Exception
*/
public function addCacheData($pCoord, Cell $cell) {
if (($pCoord !== $this->_currentObjectID) && ($this->_currentObjectID !== null)) {
$this->_storeData();
}
public function addCacheData($pCoord, Cell $cell) {
if (($pCoord !== $this->_currentObjectID) && ($this->_currentObjectID !== null)) {
$this->_storeData();
}
$this->_currentObjectID = $pCoord;
$this->_currentObject = $cell;
$this->_currentCellIsDirty = true;
$this->_currentObjectID = $pCoord;
$this->_currentObject = $cell;
$this->_currentCellIsDirty = true;
return $cell;
} // function addCacheData()
return $cell;
} // function addCacheData()
/**
* Get cell at a specific coordinate
*
* @param string $pCoord Coordinate of the cell
* @throws PHPExcel\Exception
* @return PHPExcel\Cell Cell that was found, or null if not found
* @param string $pCoord Coordinate of the cell
* @throws PHPExcel\Exception
* @return PHPExcel\Cell Cell that was found, or null if not found
*/
public function getCacheData($pCoord) {
if ($pCoord === $this->_currentObjectID) {
return $this->_currentObject;
}
$this->_storeData();
public function getCacheData($pCoord) {
if ($pCoord === $this->_currentObjectID) {
return $this->_currentObject;
}
$this->_storeData();
// Check if the entry that has been requested actually exists
if (!isset($this->_cellCache[$pCoord])) {
// Return null if requested entry doesn't exist in cache
return null;
}
// Check if the entry that has been requested actually exists
if (!isset($this->_cellCache[$pCoord])) {
// Return null if requested entry doesn't exist in cache
return null;
}
// Set current entry to the requested entry
$this->_currentObjectID = $pCoord;
$this->_currentObject = unserialize($this->_cellCache[$pCoord]);
// Set current entry to the requested entry
$this->_currentObjectID = $pCoord;
$this->_currentObject = unserialize($this->_cellCache[$pCoord]);
// Re-attach this as the cell's parent
$this->_currentObject->attach($this);
// Return requested entry
return $this->_currentObject;
} // function getCacheData()
// Return requested entry
return $this->_currentObject;
} // function getCacheData()
/**
* Get a list of all cell addresses currently held in cache
*
* @return array of string
*/
public function getCellList() {
if ($this->_currentObjectID !== null) {
$this->_storeData();
}
/**
* Get a list of all cell addresses currently held in cache
*
* @return array of string
*/
public function getCellList() {
if ($this->_currentObjectID !== null) {
$this->_storeData();
}
return parent::getCellList();
}
return parent::getCellList();
}
/**
* Clear the cell collection and disconnect from our parent
*
* @return void
*/
public function unsetWorksheetCells() {
if(!is_null($this->_currentObject)) {
$this->_currentObject->detach();
$this->_currentObject = $this->_currentObjectID = null;
}
$this->_cellCache = array();
/**
* Clear the cell collection and disconnect from our parent
*
* @return void
*/
public function unsetWorksheetCells() {
if(!is_null($this->_currentObject)) {
$this->_currentObject->detach();
$this->_currentObject = $this->_currentObjectID = null;
}
$this->_cellCache = array();
// detach ourself from the worksheet, so that it can then delete this object successfully
$this->_parent = null;
} // function unsetWorksheetCells()
// detach ourself from the worksheet, so that it can then delete this object successfully
$this->_parent = null;
} // function unsetWorksheetCells()
}

View File

@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\CachedObjectStorage
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@ -35,172 +35,172 @@
*/
class CachedObjectStorage_PHPTemp extends CachedObjectStorage_CacheBase implements CachedObjectStorage_ICache {
/**
* Name of the file for this cache
*
* @var string
*/
private $_fileHandle = null;
/**
* Name of the file for this cache
*
* @var string
*/
private $_fileHandle = null;
/**
* Memory limit to use before reverting to file cache
*
* @var integer
*/
private $_memoryCacheSize = null;
/**
* Memory limit to use before reverting to file cache
*
* @var integer
*/
private $_memoryCacheSize = null;
/**
* Store cell data in cache for the current cell object if it's "dirty",
* and the 'nullify' the current cell object
*
* @return void
* @throws PHPExcel\Exception
* @return void
* @throws PHPExcel\Exception
*/
protected function _storeData() {
if ($this->_currentCellIsDirty) {
$this->_currentObject->detach();
protected function _storeData() {
if ($this->_currentCellIsDirty) {
$this->_currentObject->detach();
fseek($this->_fileHandle,0,SEEK_END);
$offset = ftell($this->_fileHandle);
fwrite($this->_fileHandle, serialize($this->_currentObject));
$this->_cellCache[$this->_currentObjectID] = array('ptr' => $offset,
'sz' => ftell($this->_fileHandle) - $offset
);
$this->_currentCellIsDirty = false;
}
$this->_currentObjectID = $this->_currentObject = null;
} // function _storeData()
fseek($this->_fileHandle,0,SEEK_END);
$offset = ftell($this->_fileHandle);
fwrite($this->_fileHandle, serialize($this->_currentObject));
$this->_cellCache[$this->_currentObjectID] = array('ptr' => $offset,
'sz' => ftell($this->_fileHandle) - $offset
);
$this->_currentCellIsDirty = false;
}
$this->_currentObjectID = $this->_currentObject = null;
} // function _storeData()
/**
* Add or Update a cell in cache identified by coordinate address
*
* @param string $pCoord Coordinate address of the cell to update
* @param PHPExcel\Cell $cell Cell to update
* @return void
* @throws PHPExcel\Exception
* @param string $pCoord Coordinate address of the cell to update
* @param PHPExcel\Cell $cell Cell to update
* @return void
* @throws PHPExcel\Exception
*/
public function addCacheData($pCoord, Cell $cell) {
if (($pCoord !== $this->_currentObjectID) && ($this->_currentObjectID !== null)) {
$this->_storeData();
}
public function addCacheData($pCoord, Cell $cell) {
if (($pCoord !== $this->_currentObjectID) && ($this->_currentObjectID !== null)) {
$this->_storeData();
}
$this->_currentObjectID = $pCoord;
$this->_currentObject = $cell;
$this->_currentCellIsDirty = true;
$this->_currentObjectID = $pCoord;
$this->_currentObject = $cell;
$this->_currentCellIsDirty = true;
return $cell;
} // function addCacheData()
return $cell;
} // function addCacheData()
/**
* Get cell at a specific coordinate
*
* @param string $pCoord Coordinate of the cell
* @throws PHPExcel\Exception
* @return PHPExcel\Cell Cell that was found, or null if not found
* @param string $pCoord Coordinate of the cell
* @throws PHPExcel\Exception
* @return PHPExcel\Cell Cell that was found, or null if not found
*/
public function getCacheData($pCoord) {
if ($pCoord === $this->_currentObjectID) {
return $this->_currentObject;
}
$this->_storeData();
public function getCacheData($pCoord) {
if ($pCoord === $this->_currentObjectID) {
return $this->_currentObject;
}
$this->_storeData();
// Check if the entry that has been requested actually exists
if (!isset($this->_cellCache[$pCoord])) {
// Return null if requested entry doesn't exist in cache
return null;
}
// Check if the entry that has been requested actually exists
if (!isset($this->_cellCache[$pCoord])) {
// Return null if requested entry doesn't exist in cache
return null;
}
// Set current entry to the requested entry
$this->_currentObjectID = $pCoord;
fseek($this->_fileHandle,$this->_cellCache[$pCoord]['ptr']);
$this->_currentObject = unserialize(fread($this->_fileHandle,$this->_cellCache[$pCoord]['sz']));
// Set current entry to the requested entry
$this->_currentObjectID = $pCoord;
fseek($this->_fileHandle,$this->_cellCache[$pCoord]['ptr']);
$this->_currentObject = unserialize(fread($this->_fileHandle,$this->_cellCache[$pCoord]['sz']));
// Re-attach this as the cell's parent
$this->_currentObject->attach($this);
// Return requested entry
return $this->_currentObject;
} // function getCacheData()
// Return requested entry
return $this->_currentObject;
} // function getCacheData()
/**
* Get a list of all cell addresses currently held in cache
*
* @return array of string
*/
public function getCellList() {
if ($this->_currentObjectID !== null) {
$this->_storeData();
}
/**
* Get a list of all cell addresses currently held in cache
*
* @return array of string
*/
public function getCellList() {
if ($this->_currentObjectID !== null) {
$this->_storeData();
}
return parent::getCellList();
}
return parent::getCellList();
}
/**
* Clone the cell collection
*
* @param PHPExcel\Worksheet $parent The new worksheet
* @return void
*/
public function copyCellCollection(Worksheet $parent) {
parent::copyCellCollection($parent);
// Open a new stream for the cell cache data
$newFileHandle = fopen('php://temp/maxmemory:'.$this->_memoryCacheSize,'a+');
// Copy the existing cell cache data to the new stream
fseek($this->_fileHandle,0);
while (!feof($this->_fileHandle)) {
fwrite($newFileHandle,fread($this->_fileHandle, 1024));
}
$this->_fileHandle = $newFileHandle;
} // function copyCellCollection()
/**
* Clone the cell collection
*
* @param PHPExcel\Worksheet $parent The new worksheet
* @return void
*/
public function copyCellCollection(Worksheet $parent) {
parent::copyCellCollection($parent);
// Open a new stream for the cell cache data
$newFileHandle = fopen('php://temp/maxmemory:'.$this->_memoryCacheSize,'a+');
// Copy the existing cell cache data to the new stream
fseek($this->_fileHandle,0);
while (!feof($this->_fileHandle)) {
fwrite($newFileHandle,fread($this->_fileHandle, 1024));
}
$this->_fileHandle = $newFileHandle;
} // function copyCellCollection()
/**
* Clear the cell collection and disconnect from our parent
*
* @return void
*/
public function unsetWorksheetCells() {
if(!is_null($this->_currentObject)) {
$this->_currentObject->detach();
$this->_currentObject = $this->_currentObjectID = null;
}
$this->_cellCache = array();
/**
* Clear the cell collection and disconnect from our parent
*
* @return void
*/
public function unsetWorksheetCells() {
if(!is_null($this->_currentObject)) {
$this->_currentObject->detach();
$this->_currentObject = $this->_currentObjectID = null;
}
$this->_cellCache = array();
// detach ourself from the worksheet, so that it can then delete this object successfully
$this->_parent = null;
// detach ourself from the worksheet, so that it can then delete this object successfully
$this->_parent = null;
// Close down the php://temp file
$this->__destruct();
} // function unsetWorksheetCells()
// Close down the php://temp file
$this->__destruct();
} // function unsetWorksheetCells()
/**
* Initialise this new cell collection
*
* @param PHPExcel\Worksheet $parent The worksheet for this cell collection
* @param array of mixed $arguments Additional initialisation arguments
*/
public function __construct(Worksheet $parent, $arguments) {
$this->_memoryCacheSize = (isset($arguments['memoryCacheSize'])) ? $arguments['memoryCacheSize'] : '1MB';
/**
* Initialise this new cell collection
*
* @param PHPExcel\Worksheet $parent The worksheet for this cell collection
* @param array of mixed $arguments Additional initialisation arguments
*/
public function __construct(Worksheet $parent, $arguments) {
$this->_memoryCacheSize = (isset($arguments['memoryCacheSize'])) ? $arguments['memoryCacheSize'] : '1MB';
parent::__construct($parent);
if (is_null($this->_fileHandle)) {
$this->_fileHandle = fopen('php://temp/maxmemory:'.$this->_memoryCacheSize,'a+');
}
} // function __construct()
parent::__construct($parent);
if (is_null($this->_fileHandle)) {
$this->_fileHandle = fopen('php://temp/maxmemory:'.$this->_memoryCacheSize,'a+');
}
} // function __construct()
/**
* Destroy this cell collection
*/
public function __destruct() {
if (!is_null($this->_fileHandle)) {
fclose($this->_fileHandle);
}
$this->_fileHandle = null;
} // function __destruct()
/**
* Destroy this cell collection
*/
public function __destruct() {
if (!is_null($this->_fileHandle)) {
fclose($this->_fileHandle);
}
$this->_fileHandle = null;
} // function __destruct()
}

View File

@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\CachedObjectStorage
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@ -37,272 +37,271 @@ namespace PHPExcel;
*/
class CachedObjectStorage_SQLite extends CachedObjectStorage_CacheBase implements CachedObjectStorage_ICache {
/**
* Database table name
*
* @var string
*/
private $_TableName = null;
/**
* Database table name
*
* @var string
*/
private $_TableName = null;
/**
* Database handle
*
* @var resource
*/
private $_DBHandle = null;
/**
* Database handle
*
* @var resource
*/
private $_DBHandle = null;
/**
* Store cell data in cache for the current cell object if it's "dirty",
* and the 'nullify' the current cell object
*
* @return void
* @throws PHPExcel\Exception
* @return void
* @throws PHPExcel\Exception
*/
protected function _storeData() {
if ($this->_currentCellIsDirty) {
$this->_currentObject->detach();
protected function _storeData() {
if ($this->_currentCellIsDirty) {
$this->_currentObject->detach();
if (!$this->_DBHandle->queryExec("INSERT OR REPLACE INTO kvp_".$this->_TableName." VALUES('".$this->_currentObjectID."','".sqlite_escape_string(serialize($this->_currentObject))."')"))
throw new Exception(sqlite_error_string($this->_DBHandle->lastError()));
$this->_currentCellIsDirty = false;
}
$this->_currentObjectID = $this->_currentObject = null;
} // function _storeData()
if (!$this->_DBHandle->queryExec("INSERT OR REPLACE INTO kvp_".$this->_TableName." VALUES('".$this->_currentObjectID."','".sqlite_escape_string(serialize($this->_currentObject))."')"))
throw new Exception(sqlite_error_string($this->_DBHandle->lastError()));
$this->_currentCellIsDirty = false;
}
$this->_currentObjectID = $this->_currentObject = null;
} // function _storeData()
/**
* Add or Update a cell in cache identified by coordinate address
*
* @param string $pCoord Coordinate address of the cell to update
* @param PHPExcel\Cell $cell Cell to update
* @return void
* @throws PHPExcel\Exception
* @param string $pCoord Coordinate address of the cell to update
* @param PHPExcel\Cell $cell Cell to update
* @return void
* @throws PHPExcel\Exception
*/
public function addCacheData($pCoord, Cell $cell) {
if (($pCoord !== $this->_currentObjectID) && ($this->_currentObjectID !== null)) {
$this->_storeData();
}
public function addCacheData($pCoord, Cell $cell) {
if (($pCoord !== $this->_currentObjectID) && ($this->_currentObjectID !== null)) {
$this->_storeData();
}
$this->_currentObjectID = $pCoord;
$this->_currentObject = $cell;
$this->_currentCellIsDirty = true;
$this->_currentObjectID = $pCoord;
$this->_currentObject = $cell;
$this->_currentCellIsDirty = true;
return $cell;
} // function addCacheData()
return $cell;
} // function addCacheData()
/**
* Get cell at a specific coordinate
*
* @param string $pCoord Coordinate of the cell
* @throws PHPExcel\Exception
* @return PHPExcel\Cell Cell that was found, or null if not found
* @param string $pCoord Coordinate of the cell
* @throws PHPExcel\Exception
* @return PHPExcel\Cell Cell that was found, or null if not found
*/
public function getCacheData($pCoord) {
if ($pCoord === $this->_currentObjectID) {
return $this->_currentObject;
}
$this->_storeData();
public function getCacheData($pCoord) {
if ($pCoord === $this->_currentObjectID) {
return $this->_currentObject;
}
$this->_storeData();
$query = "SELECT value FROM kvp_".$this->_TableName." WHERE id='".$pCoord."'";
$cellResultSet = $this->_DBHandle->query($query,SQLITE_ASSOC);
if ($cellResultSet === false) {
throw new Exception(sqlite_error_string($this->_DBHandle->lastError()));
} elseif ($cellResultSet->numRows() == 0) {
// Return null if requested entry doesn't exist in cache
return null;
}
$query = "SELECT value FROM kvp_".$this->_TableName." WHERE id='".$pCoord."'";
$cellResultSet = $this->_DBHandle->query($query,SQLITE_ASSOC);
if ($cellResultSet === false) {
throw new Exception(sqlite_error_string($this->_DBHandle->lastError()));
} elseif ($cellResultSet->numRows() == 0) {
// Return null if requested entry doesn't exist in cache
return null;
}
// Set current entry to the requested entry
$this->_currentObjectID = $pCoord;
// Set current entry to the requested entry
$this->_currentObjectID = $pCoord;
$cellResult = $cellResultSet->fetchSingle();
$this->_currentObject = unserialize($cellResult);
$cellResult = $cellResultSet->fetchSingle();
$this->_currentObject = unserialize($cellResult);
// Re-attach this as the cell's parent
$this->_currentObject->attach($this);
// Return requested entry
return $this->_currentObject;
} // function getCacheData()
// Return requested entry
return $this->_currentObject;
} // function getCacheData()
/**
* Is a value set for an indexed cell?
*
* @param string $pCoord Coordinate address of the cell to check
* @return boolean
*/
public function isDataSet($pCoord) {
if ($pCoord === $this->_currentObjectID) {
return true;
}
/**
* Is a value set for an indexed cell?
*
* @param string $pCoord Coordinate address of the cell to check
* @return boolean
*/
public function isDataSet($pCoord) {
if ($pCoord === $this->_currentObjectID) {
return true;
}
// Check if the requested entry exists in the cache
$query = "SELECT id FROM kvp_".$this->_TableName." WHERE id='".$pCoord."'";
$cellResultSet = $this->_DBHandle->query($query,SQLITE_ASSOC);
if ($cellResultSet === false) {
throw new Exception(sqlite_error_string($this->_DBHandle->lastError()));
} elseif ($cellResultSet->numRows() == 0) {
// Return null if requested entry doesn't exist in cache
return false;
}
return true;
} // function isDataSet()
// Check if the requested entry exists in the cache
$query = "SELECT id FROM kvp_".$this->_TableName." WHERE id='".$pCoord."'";
$cellResultSet = $this->_DBHandle->query($query,SQLITE_ASSOC);
if ($cellResultSet === false) {
throw new Exception(sqlite_error_string($this->_DBHandle->lastError()));
} elseif ($cellResultSet->numRows() == 0) {
// Return null if requested entry doesn't exist in cache
return false;
}
return true;
} // function isDataSet()
/**
* Delete a cell in cache identified by coordinate address
*
* @param string $pCoord Coordinate address of the cell to delete
* @throws PHPExcel\Exception
* @param string $pCoord Coordinate address of the cell to delete
* @throws PHPExcel\Exception
*/
public function deleteCacheData($pCoord) {
if ($pCoord === $this->_currentObjectID) {
$this->_currentObject->detach();
$this->_currentObjectID = $this->_currentObject = null;
}
public function deleteCacheData($pCoord) {
if ($pCoord === $this->_currentObjectID) {
$this->_currentObject->detach();
$this->_currentObjectID = $this->_currentObject = null;
}
// Check if the requested entry exists in the cache
$query = "DELETE FROM kvp_".$this->_TableName." WHERE id='".$pCoord."'";
if (!$this->_DBHandle->queryExec($query))
throw new Exception(sqlite_error_string($this->_DBHandle->lastError()));
// Check if the requested entry exists in the cache
$query = "DELETE FROM kvp_".$this->_TableName." WHERE id='".$pCoord."'";
if (!$this->_DBHandle->queryExec($query))
throw new Exception(sqlite_error_string($this->_DBHandle->lastError()));
$this->_currentCellIsDirty = false;
} // function deleteCacheData()
$this->_currentCellIsDirty = false;
} // function deleteCacheData()
/**
* Move a cell object from one address to another
*
* @param string $fromAddress Current address of the cell to move
* @param string $toAddress Destination address of the cell to move
* @return boolean
*/
public function moveCell($fromAddress, $toAddress) {
if ($fromAddress === $this->_currentObjectID) {
$this->_currentObjectID = $toAddress;
}
/**
* Move a cell object from one address to another
*
* @param string $fromAddress Current address of the cell to move
* @param string $toAddress Destination address of the cell to move
* @return boolean
*/
public function moveCell($fromAddress, $toAddress) {
if ($fromAddress === $this->_currentObjectID) {
$this->_currentObjectID = $toAddress;
}
$query = "DELETE FROM kvp_".$this->_TableName." WHERE id='".$toAddress."'";
$result = $this->_DBHandle->exec($query);
if ($result === false)
throw new Exception($this->_DBHandle->lastErrorMsg());
$query = "DELETE FROM kvp_".$this->_TableName." WHERE id='".$toAddress."'";
$result = $this->_DBHandle->exec($query);
if ($result === false)
throw new Exception($this->_DBHandle->lastErrorMsg());
$query = "UPDATE kvp_".$this->_TableName." SET id='".$toAddress."' WHERE id='".$fromAddress."'";
$result = $this->_DBHandle->exec($query);
if ($result === false)
throw new Exception($this->_DBHandle->lastErrorMsg());
$query = "UPDATE kvp_".$this->_TableName." SET id='".$toAddress."' WHERE id='".$fromAddress."'";
$result = $this->_DBHandle->exec($query);
if ($result === false)
throw new Exception($this->_DBHandle->lastErrorMsg());
return TRUE;
} // function moveCell()
return true;
} // function moveCell()
/**
* Get a list of all cell addresses currently held in cache
*
* @return array of string
*/
public function getCellList() {
if ($this->_currentObjectID !== null) {
$this->_storeData();
}
/**
* Get a list of all cell addresses currently held in cache
*
* @return array of string
*/
public function getCellList() {
if ($this->_currentObjectID !== null) {
$this->_storeData();
}
$query = "SELECT id FROM kvp_".$this->_TableName;
$cellIdsResult = $this->_DBHandle->unbufferedQuery($query,SQLITE_ASSOC);
if ($cellIdsResult === false)
throw new Exception(sqlite_error_string($this->_DBHandle->lastError()));
$query = "SELECT id FROM kvp_".$this->_TableName;
$cellIdsResult = $this->_DBHandle->unbufferedQuery($query,SQLITE_ASSOC);
if ($cellIdsResult === false)
throw new Exception(sqlite_error_string($this->_DBHandle->lastError()));
$cellKeys = array();
foreach($cellIdsResult as $row) {
$cellKeys[] = $row['id'];
}
$cellKeys = array();
foreach($cellIdsResult as $row) {
$cellKeys[] = $row['id'];
}
return $cellKeys;
} // function getCellList()
return $cellKeys;
} // function getCellList()
/**
* Clone the cell collection
*
* @param PHPExcel\Worksheet $parent The new worksheet
* @return void
*/
public function copyCellCollection(Worksheet $parent) {
$this->_currentCellIsDirty;
/**
* Clone the cell collection
*
* @param PHPExcel\Worksheet $parent The new worksheet
* @return void
*/
public function copyCellCollection(Worksheet $parent) {
$this->_currentCellIsDirty;
$this->_storeData();
// Get a new id for the new table name
$tableName = str_replace('.','_',$this->_getUniqueID());
if (!$this->_DBHandle->queryExec('CREATE TABLE kvp_'.$tableName.' (id VARCHAR(12) PRIMARY KEY, value BLOB)
AS SELECT * FROM kvp_'.$this->_TableName))
throw new Exception(sqlite_error_string($this->_DBHandle->lastError()));
// Get a new id for the new table name
$tableName = str_replace('.','_',$this->_getUniqueID());
if (!$this->_DBHandle->queryExec('CREATE TABLE kvp_'.$tableName.' (id VARCHAR(12) PRIMARY KEY, value BLOB)
AS SELECT * FROM kvp_'.$this->_TableName))
throw new Exception(sqlite_error_string($this->_DBHandle->lastError()));
// Copy the existing cell cache file
$this->_TableName = $tableName;
} // function copyCellCollection()
// Copy the existing cell cache file
$this->_TableName = $tableName;
} // function copyCellCollection()
/**
* Clear the cell collection and disconnect from our parent
*
* @return void
*/
public function unsetWorksheetCells() {
if(!is_null($this->_currentObject)) {
$this->_currentObject->detach();
$this->_currentObject = $this->_currentObjectID = null;
}
// detach ourself from the worksheet, so that it can then delete this object successfully
$this->_parent = null;
/**
* Clear the cell collection and disconnect from our parent
*
* @return void
*/
public function unsetWorksheetCells() {
if(!is_null($this->_currentObject)) {
$this->_currentObject->detach();
$this->_currentObject = $this->_currentObjectID = null;
}
// detach ourself from the worksheet, so that it can then delete this object successfully
$this->_parent = null;
// Close down the temporary cache file
$this->__destruct();
} // function unsetWorksheetCells()
// Close down the temporary cache file
$this->__destruct();
} // function unsetWorksheetCells()
/**
* Initialise this new cell collection
*
* @param PHPExcel\Worksheet $parent The worksheet for this cell collection
*/
public function __construct(Worksheet $parent) {
parent::__construct($parent);
if (is_null($this->_DBHandle)) {
$this->_TableName = str_replace('.','_',$this->_getUniqueID());
$_DBName = ':memory:';
/**
* Initialise this new cell collection
*
* @param PHPExcel\Worksheet $parent The worksheet for this cell collection
*/
public function __construct(Worksheet $parent) {
parent::__construct($parent);
if (is_null($this->_DBHandle)) {
$this->_TableName = str_replace('.','_',$this->_getUniqueID());
$_DBName = ':memory:';
$this->_DBHandle = new SQLiteDatabase($_DBName);
if ($this->_DBHandle === false)
throw new Exception(sqlite_error_string($this->_DBHandle->lastError()));
if (!$this->_DBHandle->queryExec('CREATE TABLE kvp_'.$this->_TableName.' (id VARCHAR(12) PRIMARY KEY, value BLOB)'))
throw new Exception(sqlite_error_string($this->_DBHandle->lastError()));
}
} // function __construct()
$this->_DBHandle = new SQLiteDatabase($_DBName);
if ($this->_DBHandle === false)
throw new Exception(sqlite_error_string($this->_DBHandle->lastError()));
if (!$this->_DBHandle->queryExec('CREATE TABLE kvp_'.$this->_TableName.' (id VARCHAR(12) PRIMARY KEY, value BLOB)'))
throw new Exception(sqlite_error_string($this->_DBHandle->lastError()));
}
} // function __construct()
/**
* Destroy this cell collection
*/
public function __destruct() {
if (!is_null($this->_DBHandle)) {
$this->_DBHandle->queryExec('DROP TABLE kvp_'.$this->_TableName);
}
$this->_DBHandle = null;
} // function __destruct()
/**
* Destroy this cell collection
*/
public function __destruct() {
if (!is_null($this->_DBHandle)) {
$this->_DBHandle->queryExec('DROP TABLE kvp_'.$this->_TableName);
}
$this->_DBHandle = null;
} // function __destruct()
/**
* Identify whether the caching method is currently available
* Some methods are dependent on the availability of certain extensions being enabled in the PHP build
*
* @return boolean
*/
public static function cacheMethodIsAvailable() {
if (!function_exists('sqlite_open')) {
return false;
}
return true;
}
/**
* Identify whether the caching method is currently available
* Some methods are dependent on the availability of certain extensions being enabled in the PHP build
*
* @return boolean
*/
public static function cacheMethodIsAvailable() {
if (!function_exists('sqlite_open')) {
return false;
}
return true;
}
}

View File

@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\CachedObjectStorage
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@ -37,311 +37,310 @@ namespace PHPExcel;
*/
class CachedObjectStorage_SQLite3 extends CachedObjectStorage_CacheBase implements CachedObjectStorage_ICache {
/**
* Database table name
*
* @var string
*/
private $_TableName = null;
/**
* Database table name
*
* @var string
*/
private $_TableName = null;
/**
* Database handle
*
* @var resource
*/
private $_DBHandle = null;
/**
* Database handle
*
* @var resource
*/
private $_DBHandle = null;
/**
* Prepared statement for a SQLite3 select query
*
* @var SQLite3Stmt
*/
private $_selectQuery;
/**
* Prepared statement for a SQLite3 select query
*
* @var SQLite3Stmt
*/
private $_selectQuery;
/**
* Prepared statement for a SQLite3 insert query
*
* @var SQLite3Stmt
*/
private $_insertQuery;
/**
* Prepared statement for a SQLite3 insert query
*
* @var SQLite3Stmt
*/
private $_insertQuery;
/**
* Prepared statement for a SQLite3 update query
*
* @var SQLite3Stmt
*/
private $_updateQuery;
/**
* Prepared statement for a SQLite3 update query
*
* @var SQLite3Stmt
*/
private $_updateQuery;
/**
* Prepared statement for a SQLite3 delete query
*
* @var SQLite3Stmt
*/
private $_deleteQuery;
/**
* Prepared statement for a SQLite3 delete query
*
* @var SQLite3Stmt
*/
private $_deleteQuery;
/**
* Store cell data in cache for the current cell object if it's "dirty",
* and the 'nullify' the current cell object
*
* @return void
* @throws PHPExcel\Exception
* @return void
* @throws PHPExcel\Exception
*/
protected function _storeData() {
if ($this->_currentCellIsDirty) {
$this->_currentObject->detach();
protected function _storeData() {
if ($this->_currentCellIsDirty) {
$this->_currentObject->detach();
$this->_insertQuery->bindValue('id',$this->_currentObjectID,SQLITE3_TEXT);
$this->_insertQuery->bindValue('data',serialize($this->_currentObject),SQLITE3_BLOB);
$result = $this->_insertQuery->execute();
if ($result === false)
throw new Exception($this->_DBHandle->lastErrorMsg());
$this->_currentCellIsDirty = false;
}
$this->_currentObjectID = $this->_currentObject = null;
} // function _storeData()
$this->_insertQuery->bindValue('id',$this->_currentObjectID,SQLITE3_TEXT);
$this->_insertQuery->bindValue('data',serialize($this->_currentObject),SQLITE3_BLOB);
$result = $this->_insertQuery->execute();
if ($result === false)
throw new Exception($this->_DBHandle->lastErrorMsg());
$this->_currentCellIsDirty = false;
}
$this->_currentObjectID = $this->_currentObject = null;
} // function _storeData()
/**
* Add or Update a cell in cache identified by coordinate address
*
* @param string $pCoord Coordinate address of the cell to update
* @param PHPExcel\Cell $cell Cell to update
* @return void
* @throws PHPExcel\Exception
* @param string $pCoord Coordinate address of the cell to update
* @param PHPExcel\Cell $cell Cell to update
* @return void
* @throws PHPExcel\Exception
*/
public function addCacheData($pCoord, Cell $cell) {
if (($pCoord !== $this->_currentObjectID) && ($this->_currentObjectID !== null)) {
$this->_storeData();
}
public function addCacheData($pCoord, Cell $cell) {
if (($pCoord !== $this->_currentObjectID) && ($this->_currentObjectID !== null)) {
$this->_storeData();
}
$this->_currentObjectID = $pCoord;
$this->_currentObject = $cell;
$this->_currentCellIsDirty = true;
$this->_currentObjectID = $pCoord;
$this->_currentObject = $cell;
$this->_currentCellIsDirty = true;
return $cell;
} // function addCacheData()
return $cell;
} // function addCacheData()
/**
* Get cell at a specific coordinate
*
* @param string $pCoord Coordinate of the cell
* @throws PHPExcel\Exception
* @return PHPExcel\Cell Cell that was found, or null if not found
* @param string $pCoord Coordinate of the cell
* @throws PHPExcel\Exception
* @return PHPExcel\Cell Cell that was found, or null if not found
*/
public function getCacheData($pCoord) {
if ($pCoord === $this->_currentObjectID) {
return $this->_currentObject;
}
$this->_storeData();
public function getCacheData($pCoord) {
if ($pCoord === $this->_currentObjectID) {
return $this->_currentObject;
}
$this->_storeData();
$this->_selectQuery->bindValue('id',$pCoord,SQLITE3_TEXT);
$cellResult = $this->_selectQuery->execute();
if ($cellResult === FALSE) {
throw new Exception($this->_DBHandle->lastErrorMsg());
}
$cellData = $cellResult->fetchArray(SQLITE3_ASSOC);
if ($cellData === FALSE) {
// Return null if requested entry doesn't exist in cache
return NULL;
}
$this->_selectQuery->bindValue('id',$pCoord,SQLITE3_TEXT);
$cellResult = $this->_selectQuery->execute();
if ($cellResult === false) {
throw new Exception($this->_DBHandle->lastErrorMsg());
}
$cellData = $cellResult->fetchArray(SQLITE3_ASSOC);
if ($cellData === false) {
// Return null if requested entry doesn't exist in cache
return null;
}
// Set current entry to the requested entry
$this->_currentObjectID = $pCoord;
// Set current entry to the requested entry
$this->_currentObjectID = $pCoord;
$this->_currentObject = unserialize($cellData['value']);
$this->_currentObject = unserialize($cellData['value']);
// Re-attach this as the cell's parent
$this->_currentObject->attach($this);
// Return requested entry
return $this->_currentObject;
} // function getCacheData()
/**
* Is a value set for an indexed cell?
*
* @param string $pCoord Coordinate address of the cell to check
* @return boolean
*/
public function isDataSet($pCoord) {
if ($pCoord === $this->_currentObjectID) {
return TRUE;
}
// Check if the requested entry exists in the cache
$this->_selectQuery->bindValue('id',$pCoord,SQLITE3_TEXT);
$cellResult = $this->_selectQuery->execute();
if ($cellResult === FALSE) {
throw new Exception($this->_DBHandle->lastErrorMsg());
}
$cellData = $cellResult->fetchArray(SQLITE3_ASSOC);
return ($cellData === FALSE) ? FALSE : TRUE;
} // function isDataSet()
// Return requested entry
return $this->_currentObject;
} // function getCacheData()
/**
* Delete a cell in cache identified by coordinate address
* Is a value set for an indexed cell?
*
* @param string $pCoord Coordinate address of the cell to delete
* @throws PHPExcel\Exception
* @param string $pCoord Coordinate address of the cell to check
* @return boolean
*/
public function deleteCacheData($pCoord) {
if ($pCoord === $this->_currentObjectID) {
$this->_currentObject->detach();
$this->_currentObjectID = $this->_currentObject = NULL;
}
public function isDataSet($pCoord) {
if ($pCoord === $this->_currentObjectID) {
return true;
}
// Check if the requested entry exists in the cache
$this->_deleteQuery->bindValue('id',$pCoord,SQLITE3_TEXT);
$result = $this->_deleteQuery->execute();
if ($result === FALSE)
throw new Exception($this->_DBHandle->lastErrorMsg());
// Check if the requested entry exists in the cache
$this->_selectQuery->bindValue('id',$pCoord,SQLITE3_TEXT);
$cellResult = $this->_selectQuery->execute();
if ($cellResult === false) {
throw new Exception($this->_DBHandle->lastErrorMsg());
}
$cellData = $cellResult->fetchArray(SQLITE3_ASSOC);
$this->_currentCellIsDirty = FALSE;
} // function deleteCacheData()
return ($cellData === false) ? false : true;
} // function isDataSet()
/**
* Move a cell object from one address to another
*
* @param string $fromAddress Current address of the cell to move
* @param string $toAddress Destination address of the cell to move
* @return boolean
*/
public function moveCell($fromAddress, $toAddress) {
if ($fromAddress === $this->_currentObjectID) {
$this->_currentObjectID = $toAddress;
}
/**
* Delete a cell in cache identified by coordinate address
*
* @param string $pCoord Coordinate address of the cell to delete
* @throws PHPExcel\Exception
*/
public function deleteCacheData($pCoord) {
if ($pCoord === $this->_currentObjectID) {
$this->_currentObject->detach();
$this->_currentObjectID = $this->_currentObject = null;
}
$this->_deleteQuery->bindValue('id',$toAddress,SQLITE3_TEXT);
$result = $this->_deleteQuery->execute();
if ($result === false)
throw new Exception($this->_DBHandle->lastErrorMsg());
// Check if the requested entry exists in the cache
$this->_deleteQuery->bindValue('id',$pCoord,SQLITE3_TEXT);
$result = $this->_deleteQuery->execute();
if ($result === false)
throw new Exception($this->_DBHandle->lastErrorMsg());
$this->_updateQuery->bindValue('toid',$toAddress,SQLITE3_TEXT);
$this->_updateQuery->bindValue('fromid',$fromAddress,SQLITE3_TEXT);
$result = $this->_updateQuery->execute();
if ($result === false)
throw new Exception($this->_DBHandle->lastErrorMsg());
return TRUE;
} // function moveCell()
$this->_currentCellIsDirty = false;
} // function deleteCacheData()
/**
* Get a list of all cell addresses currently held in cache
*
* @return array of string
*/
public function getCellList() {
if ($this->_currentObjectID !== null) {
$this->_storeData();
}
/**
* Move a cell object from one address to another
*
* @param string $fromAddress Current address of the cell to move
* @param string $toAddress Destination address of the cell to move
* @return boolean
*/
public function moveCell($fromAddress, $toAddress) {
if ($fromAddress === $this->_currentObjectID) {
$this->_currentObjectID = $toAddress;
}
$query = "SELECT id FROM kvp_".$this->_TableName;
$cellIdsResult = $this->_DBHandle->query($query);
if ($cellIdsResult === false)
throw new Exception($this->_DBHandle->lastErrorMsg());
$this->_deleteQuery->bindValue('id',$toAddress,SQLITE3_TEXT);
$result = $this->_deleteQuery->execute();
if ($result === false)
throw new Exception($this->_DBHandle->lastErrorMsg());
$cellKeys = array();
while ($row = $cellIdsResult->fetchArray(SQLITE3_ASSOC)) {
$cellKeys[] = $row['id'];
}
$this->_updateQuery->bindValue('toid',$toAddress,SQLITE3_TEXT);
$this->_updateQuery->bindValue('fromid',$fromAddress,SQLITE3_TEXT);
$result = $this->_updateQuery->execute();
if ($result === false)
throw new Exception($this->_DBHandle->lastErrorMsg());
return $cellKeys;
} // function getCellList()
return true;
} // function moveCell()
/**
* Clone the cell collection
*
* @param PHPExcel\Worksheet $parent The new worksheet
* @return void
*/
public function copyCellCollection(Worksheet $parent) {
$this->_currentCellIsDirty;
/**
* Get a list of all cell addresses currently held in cache
*
* @return array of string
*/
public function getCellList() {
if ($this->_currentObjectID !== null) {
$this->_storeData();
}
$query = "SELECT id FROM kvp_".$this->_TableName;
$cellIdsResult = $this->_DBHandle->query($query);
if ($cellIdsResult === false)
throw new Exception($this->_DBHandle->lastErrorMsg());
$cellKeys = array();
while ($row = $cellIdsResult->fetchArray(SQLITE3_ASSOC)) {
$cellKeys[] = $row['id'];
}
return $cellKeys;
} // function getCellList()
/**
* Clone the cell collection
*
* @param PHPExcel\Worksheet $parent The new worksheet
* @return void
*/
public function copyCellCollection(Worksheet $parent) {
$this->_currentCellIsDirty;
$this->_storeData();
// Get a new id for the new table name
$tableName = str_replace('.','_',$this->_getUniqueID());
if (!$this->_DBHandle->exec('CREATE TABLE kvp_'.$tableName.' (id VARCHAR(12) PRIMARY KEY, value BLOB)
AS SELECT * FROM kvp_'.$this->_TableName))
throw new Exception($this->_DBHandle->lastErrorMsg());
// Get a new id for the new table name
$tableName = str_replace('.','_',$this->_getUniqueID());
if (!$this->_DBHandle->exec('CREATE TABLE kvp_'.$tableName.' (id VARCHAR(12) PRIMARY KEY, value BLOB)
AS SELECT * FROM kvp_'.$this->_TableName))
throw new Exception($this->_DBHandle->lastErrorMsg());
// Copy the existing cell cache file
$this->_TableName = $tableName;
} // function copyCellCollection()
// Copy the existing cell cache file
$this->_TableName = $tableName;
} // function copyCellCollection()
/**
* Clear the cell collection and disconnect from our parent
*
* @return void
*/
public function unsetWorksheetCells() {
if(!is_null($this->_currentObject)) {
$this->_currentObject->detach();
$this->_currentObject = $this->_currentObjectID = null;
}
// detach ourself from the worksheet, so that it can then delete this object successfully
$this->_parent = null;
/**
* Clear the cell collection and disconnect from our parent
*
* @return void
*/
public function unsetWorksheetCells() {
if(!is_null($this->_currentObject)) {
$this->_currentObject->detach();
$this->_currentObject = $this->_currentObjectID = null;
}
// detach ourself from the worksheet, so that it can then delete this object successfully
$this->_parent = null;
// Close down the temporary cache file
$this->__destruct();
} // function unsetWorksheetCells()
// Close down the temporary cache file
$this->__destruct();
} // function unsetWorksheetCells()
/**
* Initialise this new cell collection
*
* @param PHPExcel\Worksheet $parent The worksheet for this cell collection
*/
public function __construct(Worksheet $parent) {
parent::__construct($parent);
if (is_null($this->_DBHandle)) {
$this->_TableName = str_replace('.','_',$this->_getUniqueID());
$_DBName = ':memory:';
/**
* Initialise this new cell collection
*
* @param PHPExcel\Worksheet $parent The worksheet for this cell collection
*/
public function __construct(Worksheet $parent) {
parent::__construct($parent);
if (is_null($this->_DBHandle)) {
$this->_TableName = str_replace('.','_',$this->_getUniqueID());
$_DBName = ':memory:';
$this->_DBHandle = new SQLite3($_DBName);
if ($this->_DBHandle === false)
throw new Exception($this->_DBHandle->lastErrorMsg());
if (!$this->_DBHandle->exec('CREATE TABLE kvp_'.$this->_TableName.' (id VARCHAR(12) PRIMARY KEY, value BLOB)'))
throw new Exception($this->_DBHandle->lastErrorMsg());
}
$this->_DBHandle = new SQLite3($_DBName);
if ($this->_DBHandle === false)
throw new Exception($this->_DBHandle->lastErrorMsg());
if (!$this->_DBHandle->exec('CREATE TABLE kvp_'.$this->_TableName.' (id VARCHAR(12) PRIMARY KEY, value BLOB)'))
throw new Exception($this->_DBHandle->lastErrorMsg());
}
$this->_selectQuery = $this->_DBHandle->prepare("SELECT value FROM kvp_".$this->_TableName." WHERE id = :id");
$this->_insertQuery = $this->_DBHandle->prepare("INSERT OR REPLACE INTO kvp_".$this->_TableName." VALUES(:id,:data)");
$this->_updateQuery = $this->_DBHandle->prepare("UPDATE kvp_".$this->_TableName." SET id=:toId WHERE id=:fromId");
$this->_deleteQuery = $this->_DBHandle->prepare("DELETE FROM kvp_".$this->_TableName." WHERE id = :id");
} // function __construct()
$this->_selectQuery = $this->_DBHandle->prepare("SELECT value FROM kvp_".$this->_TableName." WHERE id = :id");
$this->_insertQuery = $this->_DBHandle->prepare("INSERT OR REPLACE INTO kvp_".$this->_TableName." VALUES(:id,:data)");
$this->_updateQuery = $this->_DBHandle->prepare("UPDATE kvp_".$this->_TableName." SET id=:toId WHERE id=:fromId");
$this->_deleteQuery = $this->_DBHandle->prepare("DELETE FROM kvp_".$this->_TableName." WHERE id = :id");
} // function __construct()
/**
* Destroy this cell collection
*/
public function __destruct() {
if (!is_null($this->_DBHandle)) {
$this->_DBHandle->exec('DROP TABLE kvp_'.$this->_TableName);
$this->_DBHandle->close();
}
$this->_DBHandle = null;
} // function __destruct()
/**
* Destroy this cell collection
*/
public function __destruct() {
if (!is_null($this->_DBHandle)) {
$this->_DBHandle->exec('DROP TABLE kvp_'.$this->_TableName);
$this->_DBHandle->close();
}
$this->_DBHandle = null;
} // function __destruct()
/**
* Identify whether the caching method is currently available
* Some methods are dependent on the availability of certain extensions being enabled in the PHP build
*
* @return boolean
*/
public static function cacheMethodIsAvailable() {
if (!class_exists('SQLite3',FALSE)) {
return false;
}
return true;
}
/**
* Identify whether the caching method is currently available
* Some methods are dependent on the availability of certain extensions being enabled in the PHP build
*
* @return boolean
*/
public static function cacheMethodIsAvailable() {
if (!class_exists('SQLite3', false)) {
return false;
}
return true;
}
}

View File

@ -19,10 +19,10 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category PHPExcel
* @package PHPExcel\CachedObjectStorage
* @package PHPExcel\CachedObjectStorage
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@ -32,265 +32,265 @@ namespace PHPExcel;
* PHPExcel\CachedObjectStorage_Wincache
*
* @category PHPExcel
* @package PHPExcel\CachedObjectStorage
* @package PHPExcel\CachedObjectStorage
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
*/
class CachedObjectStorage_Wincache extends CachedObjectStorage_CacheBase implements CachedObjectStorage_ICache {
/**
* Prefix used to uniquely identify cache data for this worksheet
*
* @var string
*/
private $_cachePrefix = null;
/**
* Prefix used to uniquely identify cache data for this worksheet
*
* @var string
*/
private $_cachePrefix = null;
/**
* Cache timeout
*
* @var integer
*/
private $_cacheTime = 600;
/**
* Cache timeout
*
* @var integer
*/
private $_cacheTime = 600;
/**
* Store cell data in cache for the current cell object if it's "dirty",
* and the 'nullify' the current cell object
*
* @return void
* @throws PHPExcel\Exception
* @return void
* @throws PHPExcel\Exception
*/
protected function _storeData() {
if ($this->_currentCellIsDirty) {
$this->_currentObject->detach();
protected function _storeData() {
if ($this->_currentCellIsDirty) {
$this->_currentObject->detach();
$obj = serialize($this->_currentObject);
if (wincache_ucache_exists($this->_cachePrefix.$this->_currentObjectID.'.cache')) {
if (!wincache_ucache_set($this->_cachePrefix.$this->_currentObjectID.'.cache', $obj, $this->_cacheTime)) {
$this->__destruct();
throw new Exception('Failed to store cell '.$this->_currentObjectID.' in WinCache');
}
} else {
if (!wincache_ucache_add($this->_cachePrefix.$this->_currentObjectID.'.cache', $obj, $this->_cacheTime)) {
$this->__destruct();
throw new Exception('Failed to store cell '.$this->_currentObjectID.' in WinCache');
}
}
$this->_currentCellIsDirty = false;
}
$obj = serialize($this->_currentObject);
if (wincache_ucache_exists($this->_cachePrefix.$this->_currentObjectID.'.cache')) {
if (!wincache_ucache_set($this->_cachePrefix.$this->_currentObjectID.'.cache', $obj, $this->_cacheTime)) {
$this->__destruct();
throw new Exception('Failed to store cell '.$this->_currentObjectID.' in WinCache');
}
} else {
if (!wincache_ucache_add($this->_cachePrefix.$this->_currentObjectID.'.cache', $obj, $this->_cacheTime)) {
$this->__destruct();
throw new Exception('Failed to store cell '.$this->_currentObjectID.' in WinCache');
}
}
$this->_currentCellIsDirty = false;
}
$this->_currentObjectID = $this->_currentObject = null;
} // function _storeData()
$this->_currentObjectID = $this->_currentObject = null;
} // function _storeData()
/**
* Add or Update a cell in cache identified by coordinate address
*
* @param string $pCoord Coordinate address of the cell to update
* @param PHPExcel\Cell $cell Cell to update
* @return void
* @throws PHPExcel\Exception
*/
public function addCacheData($pCoord, Cell $cell) {
if (($pCoord !== $this->_currentObjectID) && ($this->_currentObjectID !== null)) {
$this->_storeData();
}
$this->_cellCache[$pCoord] = true;
/**
* Add or Update a cell in cache identified by coordinate address
*
* @param string $pCoord Coordinate address of the cell to update
* @param PHPExcel\Cell $cell Cell to update
* @return void
* @throws PHPExcel\Exception
*/
public function addCacheData($pCoord, Cell $cell) {
if (($pCoord !== $this->_currentObjectID) && ($this->_currentObjectID !== null)) {
$this->_storeData();
}
$this->_cellCache[$pCoord] = true;
$this->_currentObjectID = $pCoord;
$this->_currentObject = $cell;
$this->_currentCellIsDirty = true;
$this->_currentObjectID = $pCoord;
$this->_currentObject = $cell;
$this->_currentCellIsDirty = true;
return $cell;
} // function addCacheData()
return $cell;
} // function addCacheData()
/**
* Is a value set in the current PHPExcel\CachedObjectStorage_ICache for an indexed cell?
*
* @param string $pCoord Coordinate address of the cell to check
* @return boolean
*/
public function isDataSet($pCoord) {
// Check if the requested entry is the current object, or exists in the cache
if (parent::isDataSet($pCoord)) {
if ($this->_currentObjectID == $pCoord) {
return true;
}
// Check if the requested entry still exists in cache
$success = wincache_ucache_exists($this->_cachePrefix.$pCoord.'.cache');
if ($success === false) {
// Entry no longer exists in Wincache, so clear it from the cache array
parent::deleteCacheData($pCoord);
throw new Exception('Cell entry '.$pCoord.' no longer exists in WinCache');
}
return true;
}
return false;
} // function isDataSet()
/**
* Is a value set in the current PHPExcel\CachedObjectStorage_ICache for an indexed cell?
*
* @param string $pCoord Coordinate address of the cell to check
* @return boolean
*/
public function isDataSet($pCoord) {
// Check if the requested entry is the current object, or exists in the cache
if (parent::isDataSet($pCoord)) {
if ($this->_currentObjectID == $pCoord) {
return true;
}
// Check if the requested entry still exists in cache
$success = wincache_ucache_exists($this->_cachePrefix.$pCoord.'.cache');
if ($success === false) {
// Entry no longer exists in Wincache, so clear it from the cache array
parent::deleteCacheData($pCoord);
throw new Exception('Cell entry '.$pCoord.' no longer exists in WinCache');
}
return true;
}
return false;
} // function isDataSet()
/**
* Get cell at a specific coordinate
*
* @param string $pCoord Coordinate of the cell
* @throws PHPExcel\Exception
* @return PHPExcel\Cell Cell that was found, or null if not found
*/
public function getCacheData($pCoord) {
if ($pCoord === $this->_currentObjectID) {
return $this->_currentObject;
}
$this->_storeData();
/**
* Get cell at a specific coordinate
*
* @param string $pCoord Coordinate of the cell
* @throws PHPExcel\Exception
* @return PHPExcel\Cell Cell that was found, or null if not found
*/
public function getCacheData($pCoord) {
if ($pCoord === $this->_currentObjectID) {
return $this->_currentObject;
}
$this->_storeData();
// Check if the entry that has been requested actually exists
$obj = null;
if (parent::isDataSet($pCoord)) {
$success = false;
$obj = wincache_ucache_get($this->_cachePrefix.$pCoord.'.cache', $success);
if ($success === false) {
// Entry no longer exists in WinCache, so clear it from the cache array
parent::deleteCacheData($pCoord);
throw new Exception('Cell entry '.$pCoord.' no longer exists in WinCache');
}
} else {
// Return null if requested entry doesn't exist in cache
return null;
}
// Check if the entry that has been requested actually exists
$obj = null;
if (parent::isDataSet($pCoord)) {
$success = false;
$obj = wincache_ucache_get($this->_cachePrefix.$pCoord.'.cache', $success);
if ($success === false) {
// Entry no longer exists in WinCache, so clear it from the cache array
parent::deleteCacheData($pCoord);
throw new Exception('Cell entry '.$pCoord.' no longer exists in WinCache');
}
} else {
// Return null if requested entry doesn't exist in cache
return null;
}
// Set current entry to the requested entry
$this->_currentObjectID = $pCoord;
$this->_currentObject = unserialize($obj);
// Set current entry to the requested entry
$this->_currentObjectID = $pCoord;
$this->_currentObject = unserialize($obj);
// Re-attach this as the cell's parent
$this->_currentObject->attach($this);
// Return requested entry
return $this->_currentObject;
} // function getCacheData()
// Return requested entry
return $this->_currentObject;
} // function getCacheData()
/**
* Get a list of all cell addresses currently held in cache
*
* @return array of string
*/
public function getCellList() {
if ($this->_currentObjectID !== null) {
$this->_storeData();
}
/**
* Get a list of all cell addresses currently held in cache
*
* @return array of string
*/
public function getCellList() {
if ($this->_currentObjectID !== null) {
$this->_storeData();
}
return parent::getCellList();
}
return parent::getCellList();
}
/**
* Delete a cell in cache identified by coordinate address
*
* @param string $pCoord Coordinate address of the cell to delete
* @throws PHPExcel\Exception
*/
public function deleteCacheData($pCoord) {
// Delete the entry from Wincache
wincache_ucache_delete($this->_cachePrefix.$pCoord.'.cache');
/**
* Delete a cell in cache identified by coordinate address
*
* @param string $pCoord Coordinate address of the cell to delete
* @throws PHPExcel\Exception
*/
public function deleteCacheData($pCoord) {
// Delete the entry from Wincache
wincache_ucache_delete($this->_cachePrefix.$pCoord.'.cache');
// Delete the entry from our cell address array
parent::deleteCacheData($pCoord);
} // function deleteCacheData()
// Delete the entry from our cell address array
parent::deleteCacheData($pCoord);
} // function deleteCacheData()
/**
* Clone the cell collection
*
* @param PHPExcel\Worksheet $parent The new worksheet
* @return void
*/
public function copyCellCollection(Worksheet $parent) {
parent::copyCellCollection($parent);
// Get a new id for the new file name
$baseUnique = $this->_getUniqueID();
$newCachePrefix = substr(md5($baseUnique),0,8).'.';
$cacheList = $this->getCellList();
foreach($cacheList as $cellID) {
if ($cellID != $this->_currentObjectID) {
$success = false;
$obj = wincache_ucache_get($this->_cachePrefix.$cellID.'.cache', $success);
if ($success === false) {
// Entry no longer exists in WinCache, so clear it from the cache array
parent::deleteCacheData($cellID);
throw new Exception('Cell entry '.$cellID.' no longer exists in Wincache');
}
if (!wincache_ucache_add($newCachePrefix.$cellID.'.cache', $obj, $this->_cacheTime)) {
$this->__destruct();
throw new Exception('Failed to store cell '.$cellID.' in Wincache');
}
}
}
$this->_cachePrefix = $newCachePrefix;
} // function copyCellCollection()
/**
* Clone the cell collection
*
* @param PHPExcel\Worksheet $parent The new worksheet
* @return void
*/
public function copyCellCollection(Worksheet $parent) {
parent::copyCellCollection($parent);
// Get a new id for the new file name
$baseUnique = $this->_getUniqueID();
$newCachePrefix = substr(md5($baseUnique),0,8).'.';
$cacheList = $this->getCellList();
foreach($cacheList as $cellID) {
if ($cellID != $this->_currentObjectID) {
$success = false;
$obj = wincache_ucache_get($this->_cachePrefix.$cellID.'.cache', $success);
if ($success === false) {
// Entry no longer exists in WinCache, so clear it from the cache array
parent::deleteCacheData($cellID);
throw new Exception('Cell entry '.$cellID.' no longer exists in Wincache');
}
if (!wincache_ucache_add($newCachePrefix.$cellID.'.cache', $obj, $this->_cacheTime)) {
$this->__destruct();
throw new Exception('Failed to store cell '.$cellID.' in Wincache');
}
}
}
$this->_cachePrefix = $newCachePrefix;
} // function copyCellCollection()
/**
* Clear the cell collection and disconnect from our parent
*
* @return void
*/
public function unsetWorksheetCells() {
if(!is_null($this->_currentObject)) {
$this->_currentObject->detach();
$this->_currentObject = $this->_currentObjectID = null;
}
/**
* Clear the cell collection and disconnect from our parent
*
* @return void
*/
public function unsetWorksheetCells() {
if(!is_null($this->_currentObject)) {
$this->_currentObject->detach();
$this->_currentObject = $this->_currentObjectID = null;
}
// Flush the WinCache cache
$this->__destruct();
// Flush the WinCache cache
$this->__destruct();
$this->_cellCache = array();
$this->_cellCache = array();
// detach ourself from the worksheet, so that it can then delete this object successfully
$this->_parent = null;
} // function unsetWorksheetCells()
// detach ourself from the worksheet, so that it can then delete this object successfully
$this->_parent = null;
} // function unsetWorksheetCells()
/**
* Initialise this new cell collection
*
* @param PHPExcel\Worksheet $parent The worksheet for this cell collection
* @param array of mixed $arguments Additional initialisation arguments
*/
public function __construct(Worksheet $parent, $arguments) {
$cacheTime = (isset($arguments['cacheTime'])) ? $arguments['cacheTime'] : 600;
/**
* Initialise this new cell collection
*
* @param PHPExcel\Worksheet $parent The worksheet for this cell collection
* @param array of mixed $arguments Additional initialisation arguments
*/
public function __construct(Worksheet $parent, $arguments) {
$cacheTime = (isset($arguments['cacheTime'])) ? $arguments['cacheTime'] : 600;
if (is_null($this->_cachePrefix)) {
$baseUnique = $this->_getUniqueID();
$this->_cachePrefix = substr(md5($baseUnique),0,8).'.';
$this->_cacheTime = $cacheTime;
if (is_null($this->_cachePrefix)) {
$baseUnique = $this->_getUniqueID();
$this->_cachePrefix = substr(md5($baseUnique),0,8).'.';
$this->_cacheTime = $cacheTime;
parent::__construct($parent);
}
} // function __construct()
parent::__construct($parent);
}
} // function __construct()
/**
* Destroy this cell collection
*/
public function __destruct() {
$cacheList = $this->getCellList();
foreach($cacheList as $cellID) {
wincache_ucache_delete($this->_cachePrefix.$cellID.'.cache');
}
} // function __destruct()
/**
* Destroy this cell collection
*/
public function __destruct() {
$cacheList = $this->getCellList();
foreach($cacheList as $cellID) {
wincache_ucache_delete($this->_cachePrefix.$cellID.'.cache');
}
} // function __destruct()
/**
* Identify whether the caching method is currently available
* Some methods are dependent on the availability of certain extensions being enabled in the PHP build
*
* @return boolean
*/
public static function cacheMethodIsAvailable() {
if (!function_exists('wincache_ucache_add')) {
return false;
}
/**
* Identify whether the caching method is currently available
* Some methods are dependent on the availability of certain extensions being enabled in the PHP build
*
* @return boolean
*/
public static function cacheMethodIsAvailable() {
if (!function_exists('wincache_ucache_add')) {
return false;
}
return true;
}
return true;
}
}

View File

@ -56,14 +56,14 @@ class CachedObjectStorageFactory
*
* @var string
*/
protected static $_cacheStorageMethod = NULL;
protected static $_cacheStorageMethod = null;
/**
* Name of the class used for cell cacheing
*
* @var string
*/
protected static $_cacheStorageClass = NULL;
protected static $_cacheStorageClass = null;
/**
@ -103,18 +103,18 @@ class CachedObjectStorageFactory
self::cache_to_phpTemp => array( 'memoryCacheSize' => '1MB'
),
self::cache_to_discISAM => array(
'dir' => NULL
'dir' => null
),
self::cache_to_apc => array(
'cacheTime' => 600
'cacheTime' => 600
),
self::cache_to_memcache => array(
'memcacheServer' => 'localhost',
'memcacheServer' => 'localhost',
'memcachePort' => 11211,
'cacheTime' => 600
),
self::cache_to_wincache => array(
'cacheTime' => 600
'cacheTime' => 600
),
self::cache_to_sqlite => array(
),
@ -134,7 +134,7 @@ class CachedObjectStorageFactory
/**
* Return the current cache storage method
*
* @return string|NULL
* @return string|null
**/
public static function getCacheStorageMethod()
{
@ -145,7 +145,7 @@ class CachedObjectStorageFactory
/**
* Return the current cache storage class
*
* @return PHPExcel\CachedObjectStorage_ICache|NULL
* @return PHPExcel\CachedObjectStorage_ICache|null
**/
public static function getCacheStorageClass()
{
@ -192,15 +192,15 @@ class CachedObjectStorageFactory
**/
public static function initialize($method = self::cache_in_memory, $arguments = array())
{
if (!in_array($method,self::$_storageMethods)) {
return FALSE;
if (!in_array($method, self::$_storageMethods)) {
return false;
}
$cacheStorageClass = __NAMESPACE__ . '\CachedObjectStorage_'.$method;
if (!call_user_func(
array($cacheStorageClass, 'cacheMethodIsAvailable')
)) {
return FALSE;
return false;
}
self::$_storageMethodParameters[$method] = self::$_storageMethodDefaultParameters[$method];
@ -210,11 +210,11 @@ class CachedObjectStorageFactory
}
}
if (self::$_cacheStorageMethod === NULL) {
if (self::$_cacheStorageMethod === null) {
self::$_cacheStorageClass = 'CachedObjectStorage_' . $method;
self::$_cacheStorageMethod = $method;
}
return TRUE;
return true;
} // function initialize()
@ -226,8 +226,8 @@ class CachedObjectStorageFactory
**/
public static function getInstance(Worksheet $parent)
{
$cacheMethodIsAvailable = TRUE;
if (self::$_cacheStorageMethod === NULL) {
$cacheMethodIsAvailable = true;
if (self::$_cacheStorageMethod === null) {
$cacheMethodIsAvailable = self::initialize();
}
@ -236,12 +236,12 @@ class CachedObjectStorageFactory
$instance = new $cacheStorageClass( $parent,
self::$_storageMethodParameters[self::$_cacheStorageMethod]
);
if ($instance !== NULL) {
if ($instance !== null) {
return $instance;
}
}
return FALSE;
return false;
} // function getInstance()
@ -249,11 +249,10 @@ class CachedObjectStorageFactory
* Clear the cache storage
*
**/
public static function finalize()
{
self::$_cacheStorageMethod = NULL;
self::$_cacheStorageClass = NULL;
self::$_storageMethodParameters = array();
}
public static function finalize()
{
self::$_cacheStorageMethod = null;
self::$_cacheStorageClass = null;
self::$_storageMethodParameters = array();
}
}

View File

@ -21,8 +21,8 @@
* @category PHPExcel
* @package PHPExcel\Calculation
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@ -31,70 +31,69 @@ namespace PHPExcel;
/**
* PHPExcel\CalcEngine_CyclicReferenceStack
*
* @category PHPExcel\CalcEngine_CyclicReferenceStack
* @package PHPExcel\Calculation
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @category PHPExcel\CalcEngine_CyclicReferenceStack
* @package PHPExcel\Calculation
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
*/
class CalcEngine_CyclicReferenceStack {
/**
* The call stack for calculated cells
*
* @var mixed[]
*/
private $_stack = array();
/**
* The call stack for calculated cells
*
* @var mixed[]
*/
private $stack = array();
/**
* Return the number of entries on the stack
*
* @return integer
*/
public function count() {
return count($this->_stack);
}
/**
* Return the number of entries on the stack
*
* @return integer
*/
public function count() {
return count($this->stack);
}
/**
* Push a new entry onto the stack
*
* @param mixed $value
*/
public function push($value) {
$this->_stack[] = $value;
} // function push()
/**
* Push a new entry onto the stack
*
* @param mixed $value
*/
public function push($value) {
$this->stack[] = $value;
} // function push()
/**
* Pop the last entry from the stack
*
* @return mixed
*/
public function pop() {
return array_pop($this->_stack);
} // function pop()
/**
* Pop the last entry from the stack
*
* @return mixed
*/
public function pop() {
return array_pop($this->stack);
} // function pop()
/**
* Test to see if a specified entry exists on the stack
*
* @param mixed $value The value to test
*/
public function onStack($value) {
return in_array($value, $this->_stack);
}
/**
* Test to see if a specified entry exists on the stack
*
* @param mixed $value The value to test
*/
public function onStack($value) {
return in_array($value, $this->stack);
}
/**
* Clear the stack
*/
public function clear() {
$this->_stack = array();
} // function push()
/**
* Return an array of all entries on the stack
*
* @return mixed[]
*/
public function showStack() {
return $this->_stack;
}
/**
* Clear the stack
*/
public function clear() {
$this->stack = array();
} // function push()
/**
* Return an array of all entries on the stack
*
* @return mixed[]
*/
public function showStack() {
return $this->stack;
}
}

View File

@ -21,8 +21,8 @@
* @category PHPExcel
* @package PHPExcel\Calculation
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
namespace PHPExcel;
@ -30,126 +30,124 @@ namespace PHPExcel;
/**
* PHPExcel\CalcEngine_Logger
*
* @category PHPExcel
* @package PHPExcel\Calculation
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @category PHPExcel
* @package PHPExcel\Calculation
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
*/
class CalcEngine_Logger {
/**
* Flag to determine whether a debug log should be generated by the calculation engine
* If true, then a debug log will be generated
* If false, then a debug log will not be generated
*
* @var boolean
*/
private $_writeDebugLog = FALSE;
/**
* Flag to determine whether a debug log should be generated by the calculation engine
* If true, then a debug log will be generated
* If false, then a debug log will not be generated
*
* @var boolean
*/
private $_writeDebugLog = false;
/**
* Flag to determine whether a debug log should be echoed by the calculation engine
* If true, then a debug log will be echoed
* If false, then a debug log will not be echoed
* A debug log can only be echoed if it is generated
*
* @var boolean
*/
private $_echoDebugLog = FALSE;
/**
* Flag to determine whether a debug log should be echoed by the calculation engine
* If true, then a debug log will be echoed
* If false, then a debug log will not be echoed
* A debug log can only be echoed if it is generated
*
* @var boolean
*/
private $_echoDebugLog = false;
/**
* The debug log generated by the calculation engine
*
* @var string[]
*/
private $_debugLog = array();
/**
* The debug log generated by the calculation engine
*
* @var string[]
*/
private $_debugLog = array();
/**
* The calculation engine cell reference stack
*
* @var PHPExcel\CalcEngine_CyclicReferenceStack
*/
private $_cellStack;
/**
* The calculation engine cell reference stack
*
* @var PHPExcel\CalcEngine_CyclicReferenceStack
*/
private $_cellStack;
/**
* Instantiate a Calculation engine logger
*
* @param PHPExcel\CalcEngine_CyclicReferenceStack $stack
*/
public function __construct(CalcEngine_CyclicReferenceStack $stack) {
$this->_cellStack = $stack;
}
/**
* Instantiate a Calculation engine logger
*
* @param PHPExcel\CalcEngine_CyclicReferenceStack $stack
*/
public function __construct(CalcEngine_CyclicReferenceStack $stack) {
$this->_cellStack = $stack;
}
/**
* Enable/Disable Calculation engine logging
*
* @param boolean $pValue
*/
public function setWriteDebugLog($pValue = FALSE) {
$this->_writeDebugLog = $pValue;
}
/**
* Enable/Disable Calculation engine logging
*
* @param boolean $pValue
*/
public function setWriteDebugLog($pValue = false) {
$this->_writeDebugLog = $pValue;
}
/**
* Return whether calculation engine logging is enabled or disabled
*
* @return boolean
*/
public function getWriteDebugLog() {
return $this->_writeDebugLog;
}
/**
* Return whether calculation engine logging is enabled or disabled
*
* @return boolean
*/
public function getWriteDebugLog() {
return $this->_writeDebugLog;
}
/**
* Enable/Disable echoing of debug log information
*
* @param boolean $pValue
*/
public function setEchoDebugLog($pValue = FALSE) {
$this->_echoDebugLog = $pValue;
}
/**
* Enable/Disable echoing of debug log information
*
* @param boolean $pValue
*/
public function setEchoDebugLog($pValue = false) {
$this->_echoDebugLog = $pValue;
}
/**
* Return whether echoing of debug log information is enabled or disabled
*
* @return boolean
*/
public function getEchoDebugLog() {
return $this->_echoDebugLog;
}
/**
* Return whether echoing of debug log information is enabled or disabled
*
* @return boolean
*/
public function getEchoDebugLog() {
return $this->_echoDebugLog;
}
/**
* Write an entry to the calculation engine debug log
*/
public function writeDebugLog() {
// Only write the debug log if logging is enabled
if ($this->_writeDebugLog) {
$message = implode(func_get_args());
$cellReference = implode(' -> ', $this->_cellStack->showStack());
if ($this->_echoDebugLog) {
echo $cellReference,
($this->_cellStack->count() > 0 ? ' => ' : ''),
$message,
PHP_EOL;
}
$this->_debugLog[] = $cellReference .
($this->_cellStack->count() > 0 ? ' => ' : '') .
$message;
}
} // function _writeDebug()
/**
* Write an entry to the calculation engine debug log
*/
public function writeDebugLog() {
// Only write the debug log if logging is enabled
if ($this->_writeDebugLog) {
$message = implode(func_get_args());
$cellReference = implode(' -> ', $this->_cellStack->showStack());
if ($this->_echoDebugLog) {
echo $cellReference,
($this->_cellStack->count() > 0 ? ' => ' : ''),
$message,
PHP_EOL;
}
$this->_debugLog[] = $cellReference .
($this->_cellStack->count() > 0 ? ' => ' : '') .
$message;
}
}
/**
* Clear the calculation engine debug log
*/
public function clearLog() {
$this->_debugLog = array();
} // function flushLogger()
/**
* Return the calculation engine debug log
*
* @return string[]
*/
public function getLog() {
return $this->_debugLog;
} // function flushLogger()
/**
* Clear the calculation engine debug log
*/
public function clearLog() {
$this->_debugLog = array();
}
/**
* Return the calculation engine debug log
*
* @return string[]
*/
public function getLog() {
return $this->_debugLog;
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -21,8 +21,8 @@
* @category PHPExcel
* @package PHPExcel\Calculation
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@ -34,19 +34,19 @@
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
*/
class Calculation_Exception extends Exception {
/**
* Error handler callback
*
* @param mixed $code
* @param mixed $string
* @param mixed $file
* @param mixed $line
* @param mixed $context
*/
public static function errorHandlerCallback($code, $string, $file, $line, $context) {
$e = new self($string, $code);
$e->line = $line;
$e->file = $file;
throw $e;
}
/**
* Error handler callback
*
* @param mixed $code
* @param mixed $string
* @param mixed $file
* @param mixed $line
* @param mixed $context
*/
public static function errorHandlerCallback($code, $string, $file, $line, $context) {
$e = new self($string, $code);
$e->line = $line;
$e->file = $file;
throw $e;
}
}

View File

@ -21,8 +21,8 @@
* @category PHPExcel
* @package PHPExcel\Calculation
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
/**
@ -33,17 +33,17 @@
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
*/
class Calculation_ExceptionHandler {
/**
* Register errorhandler
*/
public function __construct() {
set_error_handler(array(__NAMESPACE__ . '\Calculation_Exception', 'errorHandlerCallback'), E_ALL);
}
/**
* Register errorhandler
*/
public function __construct() {
set_error_handler(array(__NAMESPACE__ . '\Calculation_Exception', 'errorHandlerCallback'), E_ALL);
}
/**
* Unregister errorhandler
*/
public function __destruct() {
restore_error_handler();
}
/**
* Unregister errorhandler
*/
public function __destruct() {
restore_error_handler();
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -21,32 +21,32 @@
* @category PHPExcel
* @package PHPExcel\Calculation
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
/*
PARTLY BASED ON:
Copyright (c) 2007 E. W. Bachtal, Inc.
Copyright (c) 2007 E. W. Bachtal, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
Permission is hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial
portions of the Software.
The above copyright notice and this permission notice shall be included in all copies or substantial
portions of the Software.
The software is provided "as is", without warranty of any kind, express or implied, including but not
limited to the warranties of merchantability, fitness for a particular purpose and noninfringement. In
no event shall the authors or copyright holders be liable for any claim, damages or other liability,
whether in an action of contract, tort or otherwise, arising from, out of or in connection with the
software or the use or other dealings in the software.
The software is provided "as is", without warranty of any kind, express or implied, including but not
limited to the warranties of merchantability, fitness for a particular purpose and noninfringement. In
no event shall the authors or copyright holders be liable for any claim, damages or other liability,
whether in an action of contract, tort or otherwise, arising from, out of or in connection with the
software or the use or other dealings in the software.
http://ewbi.blogs.com/develops/2007/03/excel_formula_p.html
http://ewbi.blogs.com/develops/2004/12/excel_formula_p.html
http://ewbi.blogs.com/develops/2007/03/excel_formula_p.html
http://ewbi.blogs.com/develops/2004/12/excel_formula_p.html
*/
@ -60,66 +60,66 @@ namespace PHPExcel;
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
*/
class Calculation_FormulaToken {
/* Token types */
const TOKEN_TYPE_NOOP = 'Noop';
const TOKEN_TYPE_OPERAND = 'Operand';
const TOKEN_TYPE_FUNCTION = 'Function';
const TOKEN_TYPE_SUBEXPRESSION = 'Subexpression';
const TOKEN_TYPE_ARGUMENT = 'Argument';
const TOKEN_TYPE_OPERATORPREFIX = 'OperatorPrefix';
const TOKEN_TYPE_OPERATORINFIX = 'OperatorInfix';
const TOKEN_TYPE_OPERATORPOSTFIX = 'OperatorPostfix';
const TOKEN_TYPE_WHITESPACE = 'Whitespace';
const TOKEN_TYPE_UNKNOWN = 'Unknown';
/* Token types */
const TOKEN_TYPE_NOOP = 'Noop';
const TOKEN_TYPE_OPERAND = 'Operand';
const TOKEN_TYPE_FUNCTION = 'Function';
const TOKEN_TYPE_SUBEXPRESSION = 'Subexpression';
const TOKEN_TYPE_ARGUMENT = 'Argument';
const TOKEN_TYPE_OPERATORPREFIX = 'OperatorPrefix';
const TOKEN_TYPE_OPERATORINFIX = 'OperatorInfix';
const TOKEN_TYPE_OPERATORPOSTFIX = 'OperatorPostfix';
const TOKEN_TYPE_WHITESPACE = 'Whitespace';
const TOKEN_TYPE_UNKNOWN = 'Unknown';
/* Token subtypes */
const TOKEN_SUBTYPE_NOTHING = 'Nothing';
const TOKEN_SUBTYPE_START = 'Start';
const TOKEN_SUBTYPE_STOP = 'Stop';
const TOKEN_SUBTYPE_TEXT = 'Text';
const TOKEN_SUBTYPE_NUMBER = 'Number';
const TOKEN_SUBTYPE_LOGICAL = 'Logical';
const TOKEN_SUBTYPE_ERROR = 'Error';
const TOKEN_SUBTYPE_RANGE = 'Range';
const TOKEN_SUBTYPE_MATH = 'Math';
const TOKEN_SUBTYPE_CONCATENATION = 'Concatenation';
const TOKEN_SUBTYPE_INTERSECTION = 'Intersection';
const TOKEN_SUBTYPE_UNION = 'Union';
/* Token subtypes */
const TOKEN_SUBTYPE_NOTHING = 'Nothing';
const TOKEN_SUBTYPE_START = 'Start';
const TOKEN_SUBTYPE_STOP = 'Stop';
const TOKEN_SUBTYPE_TEXT = 'Text';
const TOKEN_SUBTYPE_NUMBER = 'Number';
const TOKEN_SUBTYPE_LOGICAL = 'Logical';
const TOKEN_SUBTYPE_ERROR = 'Error';
const TOKEN_SUBTYPE_RANGE = 'Range';
const TOKEN_SUBTYPE_MATH = 'Math';
const TOKEN_SUBTYPE_CONCATENATION = 'Concatenation';
const TOKEN_SUBTYPE_INTERSECTION = 'Intersection';
const TOKEN_SUBTYPE_UNION = 'Union';
/**
* Value
*
* @var string
*/
private $_value;
/**
* Value
*
* @var string
*/
private $_value;
/**
* Token Type (represented by TOKEN_TYPE_*)
*
* @var string
*/
private $_tokenType;
/**
* Token Type (represented by TOKEN_TYPE_*)
*
* @var string
*/
private $_tokenType;
/**
* Token SubType (represented by TOKEN_SUBTYPE_*)
*
* @var string
*/
private $_tokenSubType;
/**
* Token SubType (represented by TOKEN_SUBTYPE_*)
*
* @var string
*/
private $_tokenSubType;
/**
* Create a new PHPExcel\Calculation_FormulaToken
*
* @param string $pValue
* @param string $pTokenType Token type (represented by TOKEN_TYPE_*)
* @param string $pTokenSubType Token Subtype (represented by TOKEN_SUBTYPE_*)
* @param string $pValue
* @param string $pTokenType Token type (represented by TOKEN_TYPE_*)
* @param string $pTokenSubType Token Subtype (represented by TOKEN_SUBTYPE_*)
*/
public function __construct($pValue, $pTokenType = Calculation_FormulaToken::TOKEN_TYPE_UNKNOWN, $pTokenSubType = Calculation_FormulaToken::TOKEN_SUBTYPE_NOTHING)
{
// Initialise values
$this->_value = $pValue;
$this->_tokenType = $pTokenType;
$this->_tokenSubType = $pTokenSubType;
// Initialise values
$this->_value = $pValue;
$this->_tokenType = $pTokenType;
$this->_tokenSubType = $pTokenSubType;
}
/**
@ -128,16 +128,16 @@ class Calculation_FormulaToken {
* @return string
*/
public function getValue() {
return $this->_value;
return $this->_value;
}
/**
* Set Value
*
* @param string $value
* @param string $value
*/
public function setValue($value) {
$this->_value = $value;
$this->_value = $value;
}
/**
@ -146,16 +146,16 @@ class Calculation_FormulaToken {
* @return string
*/
public function getTokenType() {
return $this->_tokenType;
return $this->_tokenType;
}
/**
* Set Token Type
*
* @param string $value
* @param string $value
*/
public function setTokenType($value = Calculation_FormulaToken::TOKEN_TYPE_UNKNOWN) {
$this->_tokenType = $value;
$this->_tokenType = $value;
}
/**
@ -164,15 +164,15 @@ class Calculation_FormulaToken {
* @return string
*/
public function getTokenSubType() {
return $this->_tokenSubType;
return $this->_tokenSubType;
}
/**
* Set Token SubType
*
* @param string $value
* @param string $value
*/
public function setTokenSubType($value = Calculation_FormulaToken::TOKEN_SUBTYPE_NOTHING) {
$this->_tokenSubType = $value;
$this->_tokenSubType = $value;
}
}

View File

@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\Calculation
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@ -36,58 +36,58 @@ namespace PHPExcel;
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
*/
class Calculation_Function {
/* Function categories */
const CATEGORY_CUBE = 'Cube';
const CATEGORY_DATABASE = 'Database';
const CATEGORY_DATE_AND_TIME = 'Date and Time';
const CATEGORY_ENGINEERING = 'Engineering';
const CATEGORY_FINANCIAL = 'Financial';
const CATEGORY_INFORMATION = 'Information';
const CATEGORY_LOGICAL = 'Logical';
const CATEGORY_LOOKUP_AND_REFERENCE = 'Lookup and Reference';
const CATEGORY_MATH_AND_TRIG = 'Math and Trig';
const CATEGORY_STATISTICAL = 'Statistical';
const CATEGORY_TEXT_AND_DATA = 'Text and Data';
/* Function categories */
const CATEGORY_CUBE = 'Cube';
const CATEGORY_DATABASE = 'Database';
const CATEGORY_DATE_AND_TIME = 'Date and Time';
const CATEGORY_ENGINEERING = 'Engineering';
const CATEGORY_FINANCIAL = 'Financial';
const CATEGORY_INFORMATION = 'Information';
const CATEGORY_LOGICAL = 'Logical';
const CATEGORY_LOOKUP_AND_REFERENCE = 'Lookup and Reference';
const CATEGORY_MATH_AND_TRIG = 'Math and Trig';
const CATEGORY_STATISTICAL = 'Statistical';
const CATEGORY_TEXT_AND_DATA = 'Text and Data';
/**
* Category (represented by CATEGORY_*)
*
* @var string
*/
private $_category;
/**
* Category (represented by CATEGORY_*)
*
* @var string
*/
private $_category;
/**
* Excel name
*
* @var string
*/
private $_excelName;
/**
* Excel name
*
* @var string
*/
private $_excelName;
/**
* PHPExcel name
*
* @var string
*/
private $_phpExcelName;
/**
* PHPExcel name
*
* @var string
*/
private $_phpExcelName;
/**
* Create a new PHPExcel\Calculation_Function
*
* @param string $pCategory Category (represented by CATEGORY_*)
* @param string $pExcelName Excel function name
* @param string $pPHPExcelName PHPExcel function mapping
* @throws PHPExcel\Calculation_Exception
* @param string $pCategory Category (represented by CATEGORY_*)
* @param string $pExcelName Excel function name
* @param string $pPHPExcelName PHPExcel function mapping
* @throws PHPExcel\Calculation_Exception
*/
public function __construct($pCategory = NULL, $pExcelName = NULL, $pPHPExcelName = NULL)
public function __construct($pCategory = null, $pExcelName = null, $pPHPExcelName = null)
{
if (($pCategory !== NULL) && ($pExcelName !== NULL) && ($pPHPExcelName !== NULL)) {
// Initialise values
$this->_category = $pCategory;
$this->_excelName = $pExcelName;
$this->_phpExcelName = $pPHPExcelName;
} else {
throw new Calculation_Exception("Invalid parameters passed.");
}
if (($pCategory !== null) && ($pExcelName !== null) && ($pPHPExcelName !== null)) {
// Initialise values
$this->_category = $pCategory;
$this->_excelName = $pExcelName;
$this->_phpExcelName = $pPHPExcelName;
} else {
throw new Calculation_Exception("Invalid parameters passed.");
}
}
/**
@ -96,21 +96,21 @@ class Calculation_Function {
* @return string
*/
public function getCategory() {
return $this->_category;
return $this->_category;
}
/**
* Set Category (represented by CATEGORY_*)
*
* @param string $value
* @throws PHPExcel\Calculation_Exception
* @param string $value
* @throws PHPExcel\Calculation_Exception
*/
public function setCategory($value = null) {
if (!is_null($value)) {
$this->_category = $value;
} else {
throw new Calculation_Exception("Invalid parameter passed.");
}
if (!is_null($value)) {
$this->_category = $value;
} else {
throw new Calculation_Exception("Invalid parameter passed.");
}
}
/**
@ -119,16 +119,16 @@ class Calculation_Function {
* @return string
*/
public function getExcelName() {
return $this->_excelName;
return $this->_excelName;
}
/**
* Set Excel name
*
* @param string $value
* @param string $value
*/
public function setExcelName($value) {
$this->_excelName = $value;
$this->_excelName = $value;
}
/**
@ -137,15 +137,15 @@ class Calculation_Function {
* @return string
*/
public function getPHPExcelName() {
return $this->_phpExcelName;
return $this->_phpExcelName;
}
/**
* Set PHPExcel name
*
* @param string $value
* @param string $value
*/
public function setPHPExcelName($value) {
$this->_phpExcelName = $value;
$this->_phpExcelName = $value;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -18,11 +18,11 @@
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category PHPExcel
* @package PHPExcel\Calculation
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
* @category PHPExcel
* @package PHPExcel\Calculation
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@ -31,250 +31,249 @@ namespace PHPExcel;
/**
* PHPExcel\Calculation_Logical
*
* @category PHPExcel
* @package PHPExcel\Calculation
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @category PHPExcel
* @package PHPExcel\Calculation
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
*/
class Calculation_Logical {
/**
* TRUE
*
* Returns the boolean TRUE.
*
* Excel Function:
* =TRUE()
*
* @access public
* @category Logical Functions
* @return boolean True
*/
public static function TRUE() {
return TRUE;
} // function TRUE()
/**
* TRUE
*
* Returns the boolean TRUE.
*
* Excel Function:
* =TRUE()
*
* @access public
* @category Logical Functions
* @return boolean True
*/
public static function TRUE() {
return true;
} // function TRUE()
/**
* FALSE
*
* Returns the boolean FALSE.
*
* Excel Function:
* =FALSE()
*
* @access public
* @category Logical Functions
* @return boolean False
*/
public static function FALSE() {
return FALSE;
} // function FALSE()
/**
* FALSE
*
* Returns the boolean FALSE.
*
* Excel Function:
* =FALSE()
*
* @access public
* @category Logical Functions
* @return boolean False
*/
public static function FALSE() {
return false;
} // function FALSE()
/**
* LOGICAL_AND
*
* Returns boolean TRUE if all its arguments are TRUE; returns FALSE if one or more argument is FALSE.
*
* Excel Function:
* =AND(logical1[,logical2[, ...]])
*
* The arguments must evaluate to logical values such as TRUE or FALSE, or the arguments must be arrays
* or references that contain logical values.
*
* Boolean arguments are treated as True or False as appropriate
* Integer or floating point arguments are treated as True, except for 0 or 0.0 which are False
* If any argument value is a string, or a Null, the function returns a #VALUE! error, unless the string holds
* the value TRUE or FALSE, in which case it is evaluated as the corresponding boolean value
*
* @access public
* @category Logical Functions
* @param mixed $arg,... Data values
* @return boolean The logical AND of the arguments.
*/
public static function LOGICAL_AND() {
// Return value
$returnValue = TRUE;
/**
* LOGICAL_AND
*
* Returns boolean TRUE if all its arguments are TRUE; returns FALSE if one or more argument is FALSE.
*
* Excel Function:
* =AND(logical1[,logical2[, ...]])
*
* The arguments must evaluate to logical values such as TRUE or FALSE, or the arguments must be arrays
* or references that contain logical values.
*
* Boolean arguments are treated as True or False as appropriate
* Integer or floating point arguments are treated as True, except for 0 or 0.0 which are False
* If any argument value is a string, or a Null, the function returns a #VALUE! error, unless the string holds
* the value TRUE or FALSE, in which case it is evaluated as the corresponding boolean value
*
* @access public
* @category Logical Functions
* @param mixed $arg,... Data values
* @return boolean The logical AND of the arguments.
*/
public static function LOGICAL_AND() {
// Return value
$returnValue = TRUE;
// Loop through the arguments
$aArgs = Calculation_Functions::flattenArray(func_get_args());
$argCount = -1;
foreach ($aArgs as $argCount => $arg) {
// Is it a boolean value?
if (is_bool($arg)) {
$returnValue = $returnValue && $arg;
} elseif ((is_numeric($arg)) && (!is_string($arg))) {
$returnValue = $returnValue && ($arg != 0);
} elseif (is_string($arg)) {
$arg = strtoupper($arg);
if (($arg == 'TRUE') || ($arg == Calculation::getTRUE())) {
$arg = TRUE;
} elseif (($arg == 'FALSE') || ($arg == Calculation::getFALSE())) {
$arg = FALSE;
} else {
return Calculation_Functions::VALUE();
}
$returnValue = $returnValue && ($arg != 0);
}
}
// Loop through the arguments
$aArgs = Calculation_Functions::flattenArray(func_get_args());
$argCount = -1;
foreach ($aArgs as $argCount => $arg) {
// Is it a boolean value?
if (is_bool($arg)) {
$returnValue = $returnValue && $arg;
} elseif ((is_numeric($arg)) && (!is_string($arg))) {
$returnValue = $returnValue && ($arg != 0);
} elseif (is_string($arg)) {
$arg = strtoupper($arg);
if (($arg == 'TRUE') || ($arg == Calculation::getTRUE())) {
$arg = true;
} elseif (($arg == 'FALSE') || ($arg == Calculation::getFALSE())) {
$arg = false;
} else {
return Calculation_Functions::VALUE();
}
$returnValue = $returnValue && ($arg != 0);
}
}
// Return
if ($argCount < 0) {
return Calculation_Functions::VALUE();
}
return $returnValue;
} // function LOGICAL_AND()
// Return
if ($argCount < 0) {
return Calculation_Functions::VALUE();
}
return $returnValue;
} // function LOGICAL_AND()
/**
* LOGICAL_OR
*
* Returns boolean TRUE if any argument is TRUE; returns FALSE if all arguments are FALSE.
*
* Excel Function:
* =OR(logical1[,logical2[, ...]])
*
* The arguments must evaluate to logical values such as TRUE or FALSE, or the arguments must be arrays
* or references that contain logical values.
*
* Boolean arguments are treated as True or False as appropriate
* Integer or floating point arguments are treated as True, except for 0 or 0.0 which are False
* If any argument value is a string, or a Null, the function returns a #VALUE! error, unless the string holds
* the value TRUE or FALSE, in which case it is evaluated as the corresponding boolean value
*
* @access public
* @category Logical Functions
* @param mixed $arg,... Data values
* @return boolean The logical OR of the arguments.
*/
public static function LOGICAL_OR() {
// Return value
$returnValue = FALSE;
/**
* LOGICAL_OR
*
* Returns boolean TRUE if any argument is TRUE; returns FALSE if all arguments are FALSE.
*
* Excel Function:
* =OR(logical1[,logical2[, ...]])
*
* The arguments must evaluate to logical values such as TRUE or FALSE, or the arguments must be arrays
* or references that contain logical values.
*
* Boolean arguments are treated as True or False as appropriate
* Integer or floating point arguments are treated as True, except for 0 or 0.0 which are False
* If any argument value is a string, or a Null, the function returns a #VALUE! error, unless the string holds
* the value TRUE or FALSE, in which case it is evaluated as the corresponding boolean value
*
* @access public
* @category Logical Functions
* @param mixed $arg,... Data values
* @return boolean The logical OR of the arguments.
*/
public static function LOGICAL_OR() {
// Return value
$returnValue = false;
// Loop through the arguments
$aArgs = Calculation_Functions::flattenArray(func_get_args());
$argCount = -1;
foreach ($aArgs as $argCount => $arg) {
// Is it a boolean value?
if (is_bool($arg)) {
$returnValue = $returnValue || $arg;
} elseif ((is_numeric($arg)) && (!is_string($arg))) {
$returnValue = $returnValue || ($arg != 0);
} elseif (is_string($arg)) {
$arg = strtoupper($arg);
if (($arg == 'TRUE') || ($arg == Calculation::getTRUE())) {
$arg = TRUE;
} elseif (($arg == 'FALSE') || ($arg == Calculation::getFALSE())) {
$arg = FALSE;
} else {
return Calculation_Functions::VALUE();
}
$returnValue = $returnValue || ($arg != 0);
}
}
// Loop through the arguments
$aArgs = Calculation_Functions::flattenArray(func_get_args());
$argCount = -1;
foreach ($aArgs as $argCount => $arg) {
// Is it a boolean value?
if (is_bool($arg)) {
$returnValue = $returnValue || $arg;
} elseif ((is_numeric($arg)) && (!is_string($arg))) {
$returnValue = $returnValue || ($arg != 0);
} elseif (is_string($arg)) {
$arg = strtoupper($arg);
if (($arg == 'TRUE') || ($arg == Calculation::getTRUE())) {
$arg = true;
} elseif (($arg == 'FALSE') || ($arg == Calculation::getFALSE())) {
$arg = false;
} else {
return Calculation_Functions::VALUE();
}
$returnValue = $returnValue || ($arg != 0);
}
}
// Return
if ($argCount < 0) {
return Calculation_Functions::VALUE();
}
return $returnValue;
} // function LOGICAL_OR()
// Return
if ($argCount < 0) {
return Calculation_Functions::VALUE();
}
return $returnValue;
} // function LOGICAL_OR()
/**
* NOT
*
* Returns the boolean inverse of the argument.
*
* Excel Function:
* =NOT(logical)
*
* The argument must evaluate to a logical value such as TRUE or FALSE
*
* Boolean arguments are treated as True or False as appropriate
* Integer or floating point arguments are treated as True, except for 0 or 0.0 which are False
* If any argument value is a string, or a Null, the function returns a #VALUE! error, unless the string holds
* the value TRUE or FALSE, in which case it is evaluated as the corresponding boolean value
*
* @access public
* @category Logical Functions
* @param mixed $logical A value or expression that can be evaluated to TRUE or FALSE
* @return boolean The boolean inverse of the argument.
*/
public static function NOT($logical=FALSE) {
$logical = Calculation_Functions::flattenSingleValue($logical);
if (is_string($logical)) {
$logical = strtoupper($logical);
if (($logical == 'TRUE') || ($logical == Calculation::getTRUE())) {
return FALSE;
} elseif (($logical == 'FALSE') || ($logical == Calculation::getFALSE())) {
return TRUE;
} else {
return Calculation_Functions::VALUE();
}
}
/**
* NOT
*
* Returns the boolean inverse of the argument.
*
* Excel Function:
* =NOT(logical)
*
* The argument must evaluate to a logical value such as TRUE or FALSE
*
* Boolean arguments are treated as True or False as appropriate
* Integer or floating point arguments are treated as True, except for 0 or 0.0 which are False
* If any argument value is a string, or a Null, the function returns a #VALUE! error, unless the string holds
* the value TRUE or FALSE, in which case it is evaluated as the corresponding boolean value
*
* @access public
* @category Logical Functions
* @param mixed $logical A value or expression that can be evaluated to TRUE or FALSE
* @return boolean The boolean inverse of the argument.
*/
public static function NOT($logical=false) {
$logical = Calculation_Functions::flattenSingleValue($logical);
if (is_string($logical)) {
$logical = strtoupper($logical);
if (($logical == 'TRUE') || ($logical == Calculation::getTRUE())) {
return false;
} elseif (($logical == 'FALSE') || ($logical == Calculation::getFALSE())) {
return true;
} else {
return Calculation_Functions::VALUE();
}
}
return !$logical;
} // function NOT()
return !$logical;
} // function NOT()
/**
* STATEMENT_IF
*
* Returns one value if a condition you specify evaluates to TRUE and another value if it evaluates to FALSE.
*
* Excel Function:
* =IF(condition[,returnIfTrue[,returnIfFalse]])
*
* Condition is any value or expression that can be evaluated to TRUE or FALSE.
* For example, A10=100 is a logical expression; if the value in cell A10 is equal to 100,
* the expression evaluates to TRUE. Otherwise, the expression evaluates to FALSE.
* This argument can use any comparison calculation operator.
* ReturnIfTrue is the value that is returned if condition evaluates to TRUE.
* For example, if this argument is the text string "Within budget" and the condition argument evaluates to TRUE,
* then the IF function returns the text "Within budget"
* If condition is TRUE and ReturnIfTrue is blank, this argument returns 0 (zero). To display the word TRUE, use
* the logical value TRUE for this argument.
* ReturnIfTrue can be another formula.
* ReturnIfFalse is the value that is returned if condition evaluates to FALSE.
* For example, if this argument is the text string "Over budget" and the condition argument evaluates to FALSE,
* then the IF function returns the text "Over budget".
* If condition is FALSE and ReturnIfFalse is omitted, then the logical value FALSE is returned.
* If condition is FALSE and ReturnIfFalse is blank, then the value 0 (zero) is returned.
* ReturnIfFalse can be another formula.
*
* @access public
* @category Logical Functions
* @param mixed $condition Condition to evaluate
* @param mixed $returnIfTrue Value to return when condition is true
* @param mixed $returnIfFalse Optional value to return when condition is false
* @return mixed The value of returnIfTrue or returnIfFalse determined by condition
*/
public static function STATEMENT_IF($condition = TRUE, $returnIfTrue = 0, $returnIfFalse = FALSE) {
$condition = (is_null($condition)) ? TRUE : (boolean) Calculation_Functions::flattenSingleValue($condition);
$returnIfTrue = (is_null($returnIfTrue)) ? 0 : Calculation_Functions::flattenSingleValue($returnIfTrue);
$returnIfFalse = (is_null($returnIfFalse)) ? FALSE : Calculation_Functions::flattenSingleValue($returnIfFalse);
/**
* STATEMENT_IF
*
* Returns one value if a condition you specify evaluates to TRUE and another value if it evaluates to FALSE.
*
* Excel Function:
* =IF(condition[,returnIfTrue[,returnIfFalse]])
*
* Condition is any value or expression that can be evaluated to TRUE or FALSE.
* For example, A10=100 is a logical expression; if the value in cell A10 is equal to 100,
* the expression evaluates to TRUE. Otherwise, the expression evaluates to FALSE.
* This argument can use any comparison calculation operator.
* ReturnIfTrue is the value that is returned if condition evaluates to TRUE.
* For example, if this argument is the text string "Within budget" and the condition argument evaluates to TRUE,
* then the IF function returns the text "Within budget"
* If condition is TRUE and ReturnIfTrue is blank, this argument returns 0 (zero). To display the word TRUE, use
* the logical value TRUE for this argument.
* ReturnIfTrue can be another formula.
* ReturnIfFalse is the value that is returned if condition evaluates to FALSE.
* For example, if this argument is the text string "Over budget" and the condition argument evaluates to FALSE,
* then the IF function returns the text "Over budget".
* If condition is FALSE and ReturnIfFalse is omitted, then the logical value FALSE is returned.
* If condition is FALSE and ReturnIfFalse is blank, then the value 0 (zero) is returned.
* ReturnIfFalse can be another formula.
*
* @access public
* @category Logical Functions
* @param mixed $condition Condition to evaluate
* @param mixed $returnIfTrue Value to return when condition is true
* @param mixed $returnIfFalse Optional value to return when condition is false
* @return mixed The value of returnIfTrue or returnIfFalse determined by condition
*/
public static function STATEMENT_IF($condition = true, $returnIfTrue = 0, $returnIfFalse = false) {
$condition = (is_null($condition)) ? true : (boolean) Calculation_Functions::flattenSingleValue($condition);
$returnIfTrue = (is_null($returnIfTrue)) ? 0 : Calculation_Functions::flattenSingleValue($returnIfTrue);
$returnIfFalse = (is_null($returnIfFalse)) ? false : Calculation_Functions::flattenSingleValue($returnIfFalse);
return ($condition) ? $returnIfTrue : $returnIfFalse;
} // function STATEMENT_IF()
return ($condition) ? $returnIfTrue : $returnIfFalse;
} // function STATEMENT_IF()
/**
* IFERROR
*
* Excel Function:
* =IFERROR(testValue,errorpart)
*
* @access public
* @category Logical Functions
* @param mixed $testValue Value to check, is also the value returned when no error
* @param mixed $errorpart Value to return when testValue is an error condition
* @return mixed The value of errorpart or testValue determined by error condition
*/
public static function IFERROR($testValue = '', $errorpart = '') {
$testValue = (is_null($testValue)) ? '' : Calculation_Functions::flattenSingleValue($testValue);
$errorpart = (is_null($errorpart)) ? '' : Calculation_Functions::flattenSingleValue($errorpart);
return self::STATEMENT_IF(Calculation_Functions::IS_ERROR($testValue), $errorpart, $testValue);
} // function IFERROR()
/**
* IFERROR
*
* Excel Function:
* =IFERROR(testValue,errorpart)
*
* @access public
* @category Logical Functions
* @param mixed $testValue Value to check, is also the value returned when no error
* @param mixed $errorpart Value to return when testValue is an error condition
* @return mixed The value of errorpart or testValue determined by error condition
*/
public static function IFERROR($testValue = '', $errorpart = '') {
$testValue = (is_null($testValue)) ? '' : Calculation_Functions::flattenSingleValue($testValue);
$errorpart = (is_null($errorpart)) ? '' : Calculation_Functions::flattenSingleValue($errorpart);
return self::STATEMENT_IF(Calculation_Functions::IS_ERROR($testValue), $errorpart, $testValue);
} // function IFERROR()
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -21,8 +21,8 @@
* @category PHPExcel
* @package PHPExcel\Calculation
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@ -31,87 +31,87 @@ namespace PHPExcel;
/**
* PHPExcel\Calculation_Token_Stack
*
* @category PHPExcel\Calculation_Token_Stack
* @package PHPExcel\Calculation
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @category PHPExcel\Calculation_Token_Stack
* @package PHPExcel\Calculation
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
*/
class Calculation_Token_Stack {
/**
* The parser stack for formulae
*
* @var mixed[]
*/
private $_stack = array();
/**
* The parser stack for formulae
*
* @var mixed[]
*/
private $stack = array();
/**
* Count of entries in the parser stack
*
* @var integer
*/
private $_count = 0;
/**
* Count of entries in the parser stack
*
* @var integer
*/
private $count = 0;
/**
* Return the number of entries on the stack
*
* @return integer
*/
public function count() {
return $this->_count;
} // function count()
/**
* Return the number of entries on the stack
*
* @return integer
*/
public function count() {
return $this->count;
} // function count()
/**
* Push a new entry onto the stack
*
* @param mixed $type
* @param mixed $value
* @param mixed $reference
*/
public function push($type, $value, $reference = NULL) {
$this->_stack[$this->_count++] = array('type' => $type,
'value' => $value,
'reference' => $reference
);
if ($type == 'Function') {
$localeFunction = Calculation::_localeFunc($value);
if ($localeFunction != $value) {
$this->_stack[($this->_count - 1)]['localeValue'] = $localeFunction;
}
}
} // function push()
/**
* Push a new entry onto the stack
*
* @param mixed $type
* @param mixed $value
* @param mixed $reference
*/
public function push($type, $value, $reference = null) {
$this->stack[$this->count++] = array(
'type' => $type,
'value' => $value,
'reference' => $reference
);
if ($type == 'Function') {
$localeFunction = Calculation::_localeFunc($value);
if ($localeFunction != $value) {
$this->stack[($this->count - 1)]['localeValue'] = $localeFunction;
}
}
} // function push()
/**
* Pop the last entry from the stack
*
* @return mixed
*/
public function pop() {
if ($this->_count > 0) {
return $this->_stack[--$this->_count];
}
return NULL;
} // function pop()
/**
* Pop the last entry from the stack
*
* @return mixed
*/
public function pop() {
if ($this->count > 0) {
return $this->stack[--$this->count];
}
return null;
} // function pop()
/**
* Return an entry from the stack without removing it
*
* @param integer $n number indicating how far back in the stack we want to look
* @return mixed
*/
public function last($n = 1) {
if ($this->_count - $n < 0) {
return NULL;
}
return $this->_stack[$this->_count - $n];
} // function last()
/**
* Clear the stack
*/
function clear() {
$this->_stack = array();
$this->_count = 0;
}
/**
* Return an entry from the stack without removing it
*
* @param integer $n number indicating how far back in the stack we want to look
* @return mixed
*/
public function last($n = 1) {
if ($this->count - $n < 0) {
return null;
}
return $this->stack[$this->count - $n];
} // function last()
/**
* Clear the stack
*/
function clear() {
$this->stack = array();
$this->count = 0;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -61,7 +61,7 @@ class Cell_AdvancedValueBinder extends Cell_DefaultValueBinder implements Cell_I
$cell->setValueExplicit( TRUE, Cell_DataType::TYPE_BOOL);
return true;
} elseif($value == Calculation::getFALSE()) {
$cell->setValueExplicit( FALSE, Cell_DataType::TYPE_BOOL);
$cell->setValueExplicit( false, Cell_DataType::TYPE_BOOL);
return true;
}
@ -168,12 +168,12 @@ class Cell_AdvancedValueBinder extends Cell_DefaultValueBinder implements Cell_I
}
// Check for newline character "\n"
if (strpos($value, "\n") !== FALSE) {
if (strpos($value, "\n") !== false) {
$value = Shared_String::SanitizeUTF8($value);
$cell->setValueExplicit($value, Cell_DataType::TYPE_STRING);
// Set style
$cell->getWorksheet()->getStyle( $cell->getCoordinate() )
->getAlignment()->setWrapText(TRUE);
->getAlignment()->setWrapText(true);
return true;
}
}

View File

@ -44,5 +44,5 @@ interface Cell_IValueBinder
* @param mixed $value Value to bind in cell
* @return boolean
*/
public function bindValue(Cell $cell, $value = NULL);
public function bindValue(Cell $cell, $value = null);
}

File diff suppressed because it is too large Load Diff

View File

@ -18,11 +18,11 @@
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category PHPExcel
* @package PHPExcel\Chart
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
* @category PHPExcel
* @package PHPExcel\Chart
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@ -31,326 +31,325 @@ namespace PHPExcel;
/**
* PHPExcel\Chart_DataSeries
*
* @category PHPExcel
* @package PHPExcel\Chart
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @category PHPExcel
* @package PHPExcel\Chart
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
*/
class Chart_DataSeries
{
const TYPE_BARCHART = 'barChart';
const TYPE_BARCHART_3D = 'bar3DChart';
const TYPE_LINECHART = 'lineChart';
const TYPE_LINECHART_3D = 'line3DChart';
const TYPE_AREACHART = 'areaChart';
const TYPE_AREACHART_3D = 'area3DChart';
const TYPE_PIECHART = 'pieChart';
const TYPE_PIECHART_3D = 'pie3DChart';
const TYPE_DOUGHTNUTCHART = 'doughnutChart';
const TYPE_DONUTCHART = self::TYPE_DOUGHTNUTCHART; // Synonym
const TYPE_SCATTERCHART = 'scatterChart';
const TYPE_SURFACECHART = 'surfaceChart';
const TYPE_SURFACECHART_3D = 'surface3DChart';
const TYPE_RADARCHART = 'radarChart';
const TYPE_BUBBLECHART = 'bubbleChart';
const TYPE_STOCKCHART = 'stockChart';
const TYPE_BARCHART = 'barChart';
const TYPE_BARCHART_3D = 'bar3DChart';
const TYPE_LINECHART = 'lineChart';
const TYPE_LINECHART_3D = 'line3DChart';
const TYPE_AREACHART = 'areaChart';
const TYPE_AREACHART_3D = 'area3DChart';
const TYPE_PIECHART = 'pieChart';
const TYPE_PIECHART_3D = 'pie3DChart';
const TYPE_DOUGHTNUTCHART = 'doughnutChart';
const TYPE_DONUTCHART = self::TYPE_DOUGHTNUTCHART; // Synonym
const TYPE_SCATTERCHART = 'scatterChart';
const TYPE_SURFACECHART = 'surfaceChart';
const TYPE_SURFACECHART_3D = 'surface3DChart';
const TYPE_RADARCHART = 'radarChart';
const TYPE_BUBBLECHART = 'bubbleChart';
const TYPE_STOCKCHART = 'stockChart';
const GROUPING_CLUSTERED = 'clustered';
const GROUPING_STACKED = 'stacked';
const GROUPING_PERCENT_STACKED = 'percentStacked';
const GROUPING_STANDARD = 'standard';
const GROUPING_CLUSTERED = 'clustered';
const GROUPING_STACKED = 'stacked';
const GROUPING_PERCENT_STACKED = 'percentStacked';
const GROUPING_STANDARD = 'standard';
const DIRECTION_BAR = 'bar';
const DIRECTION_HORIZONTAL = self::DIRECTION_BAR;
const DIRECTION_COL = 'col';
const DIRECTION_COLUMN = self::DIRECTION_COL;
const DIRECTION_VERTICAL = self::DIRECTION_COL;
const DIRECTION_BAR = 'bar';
const DIRECTION_HORIZONTAL = self::DIRECTION_BAR;
const DIRECTION_COL = 'col';
const DIRECTION_COLUMN = self::DIRECTION_COL;
const DIRECTION_VERTICAL = self::DIRECTION_COL;
const STYLE_LINEMARKER = 'lineMarker';
const STYLE_SMOOTHMARKER = 'smoothMarker';
const STYLE_MARKER = 'marker';
const STYLE_FILLED = 'filled';
const STYLE_LINEMARKER = 'lineMarker';
const STYLE_SMOOTHMARKER = 'smoothMarker';
const STYLE_MARKER = 'marker';
const STYLE_FILLED = 'filled';
/**
* Series Plot Type
*
* @var string
*/
private $_plotType = null;
/**
* Series Plot Type
*
* @var string
*/
private $_plotType = null;
/**
* Plot Grouping Type
*
* @var boolean
*/
private $_plotGrouping = null;
/**
* Plot Grouping Type
*
* @var boolean
*/
private $_plotGrouping = null;
/**
* Plot Direction
*
* @var boolean
*/
private $_plotDirection = null;
/**
* Plot Direction
*
* @var boolean
*/
private $_plotDirection = null;
/**
* Plot Style
*
* @var string
*/
private $_plotStyle = null;
/**
* Plot Style
*
* @var string
*/
private $_plotStyle = null;
/**
* Order of plots in Series
*
* @var array of integer
*/
private $_plotOrder = array();
/**
* Order of plots in Series
*
* @var array of integer
*/
private $_plotOrder = array();
/**
* Plot Label
*
* @var array of PHPExcel\Chart_DataSeriesValues
*/
private $_plotLabel = array();
/**
* Plot Label
*
* @var array of PHPExcel\Chart_DataSeriesValues
*/
private $_plotLabel = array();
/**
* Plot Category
*
* @var array of PHPExcel\Chart_DataSeriesValues
*/
private $_plotCategory = array();
/**
* Plot Category
*
* @var array of PHPExcel\Chart_DataSeriesValues
*/
private $_plotCategory = array();
/**
* Smooth Line
*
* @var string
*/
private $_smoothLine = null;
/**
* Smooth Line
*
* @var string
*/
private $_smoothLine = null;
/**
* Plot Values
*
* @var array of PHPExcel\Chart_DataSeriesValues
*/
private $_plotValues = array();
/**
* Plot Values
*
* @var array of PHPExcel\Chart_DataSeriesValues
*/
private $_plotValues = array();
/**
* Create a new PHPExcel\Chart_DataSeries
*/
public function __construct($plotType = null, $plotGrouping = null, $plotOrder = array(), $plotLabel = array(), $plotCategory = array(), $plotValues = array(), $smoothLine = null, $plotStyle = null)
{
$this->_plotType = $plotType;
$this->_plotGrouping = $plotGrouping;
$this->_plotOrder = $plotOrder;
$keys = array_keys($plotValues);
$this->_plotValues = $plotValues;
if ((count($plotLabel) == 0) || (is_null($plotLabel[$keys[0]]))) {
$plotLabel[$keys[0]] = new Chart_DataSeriesValues();
}
/**
* Create a new PHPExcel\Chart_DataSeries
*/
public function __construct($plotType = null, $plotGrouping = null, $plotOrder = array(), $plotLabel = array(), $plotCategory = array(), $plotValues = array(), $smoothLine = null, $plotStyle = null)
{
$this->_plotType = $plotType;
$this->_plotGrouping = $plotGrouping;
$this->_plotOrder = $plotOrder;
$keys = array_keys($plotValues);
$this->_plotValues = $plotValues;
if ((count($plotLabel) == 0) || (is_null($plotLabel[$keys[0]]))) {
$plotLabel[$keys[0]] = new Chart_DataSeriesValues();
}
$this->_plotLabel = $plotLabel;
if ((count($plotCategory) == 0) || (is_null($plotCategory[$keys[0]]))) {
$plotCategory[$keys[0]] = new Chart_DataSeriesValues();
}
$this->_plotCategory = $plotCategory;
$this->_smoothLine = $smoothLine;
$this->_plotStyle = $plotStyle;
}
$this->_plotLabel = $plotLabel;
if ((count($plotCategory) == 0) || (is_null($plotCategory[$keys[0]]))) {
$plotCategory[$keys[0]] = new Chart_DataSeriesValues();
}
$this->_plotCategory = $plotCategory;
$this->_smoothLine = $smoothLine;
$this->_plotStyle = $plotStyle;
}
/**
* Get Plot Type
*
* @return string
*/
public function getPlotType() {
return $this->_plotType;
}
/**
* Get Plot Type
*
* @return string
*/
public function getPlotType() {
return $this->_plotType;
}
/**
* Set Plot Type
*
* @param string $plotType
*/
public function setPlotType($plotType = '') {
$this->_plotType = $plotType;
}
/**
* Set Plot Type
*
* @param string $plotType
*/
public function setPlotType($plotType = '') {
$this->_plotType = $plotType;
}
/**
* Get Plot Grouping Type
*
* @return string
*/
public function getPlotGrouping() {
return $this->_plotGrouping;
}
/**
* Get Plot Grouping Type
*
* @return string
*/
public function getPlotGrouping() {
return $this->_plotGrouping;
}
/**
* Set Plot Grouping Type
*
* @param string $groupingType
*/
public function setPlotGrouping($groupingType = null) {
$this->_plotGrouping = $groupingType;
}
/**
* Set Plot Grouping Type
*
* @param string $groupingType
*/
public function setPlotGrouping($groupingType = null) {
$this->_plotGrouping = $groupingType;
}
/**
* Get Plot Direction
*
* @return string
*/
public function getPlotDirection() {
return $this->_plotDirection;
}
/**
* Get Plot Direction
*
* @return string
*/
public function getPlotDirection() {
return $this->_plotDirection;
}
/**
* Set Plot Direction
*
* @param string $plotDirection
*/
public function setPlotDirection($plotDirection = null) {
$this->_plotDirection = $plotDirection;
}
/**
* Set Plot Direction
*
* @param string $plotDirection
*/
public function setPlotDirection($plotDirection = null) {
$this->_plotDirection = $plotDirection;
}
/**
* Get Plot Order
*
* @return string
*/
public function getPlotOrder() {
return $this->_plotOrder;
}
/**
* Get Plot Order
*
* @return string
*/
public function getPlotOrder() {
return $this->_plotOrder;
}
/**
* Get Plot Labels
*
* @return array of PHPExcel\Chart_DataSeriesValues
*/
public function getPlotLabels() {
return $this->_plotLabel;
}
/**
* Get Plot Labels
*
* @return array of PHPExcel\Chart_DataSeriesValues
*/
public function getPlotLabels() {
return $this->_plotLabel;
}
/**
* Get Plot Label by Index
*
* @return PHPExcel\Chart_DataSeriesValues
*/
public function getPlotLabelByIndex($index) {
$keys = array_keys($this->_plotLabel);
if (in_array($index,$keys)) {
return $this->_plotLabel[$index];
} elseif(isset($keys[$index])) {
return $this->_plotLabel[$keys[$index]];
}
return false;
}
/**
* Get Plot Label by Index
*
* @return PHPExcel\Chart_DataSeriesValues
*/
public function getPlotLabelByIndex($index) {
$keys = array_keys($this->_plotLabel);
if (in_array($index,$keys)) {
return $this->_plotLabel[$index];
} elseif(isset($keys[$index])) {
return $this->_plotLabel[$keys[$index]];
}
return false;
}
/**
* Get Plot Categories
*
* @return array of PHPExcel\Chart_DataSeriesValues
*/
public function getPlotCategories() {
return $this->_plotCategory;
}
/**
* Get Plot Categories
*
* @return array of PHPExcel\Chart_DataSeriesValues
*/
public function getPlotCategories() {
return $this->_plotCategory;
}
/**
* Get Plot Category by Index
*
* @return PHPExcel\Chart_DataSeriesValues
*/
public function getPlotCategoryByIndex($index) {
$keys = array_keys($this->_plotCategory);
if (in_array($index,$keys)) {
return $this->_plotCategory[$index];
} elseif(isset($keys[$index])) {
return $this->_plotCategory[$keys[$index]];
}
return false;
}
/**
* Get Plot Category by Index
*
* @return PHPExcel\Chart_DataSeriesValues
*/
public function getPlotCategoryByIndex($index) {
$keys = array_keys($this->_plotCategory);
if (in_array($index,$keys)) {
return $this->_plotCategory[$index];
} elseif(isset($keys[$index])) {
return $this->_plotCategory[$keys[$index]];
}
return false;
}
/**
* Get Plot Style
*
* @return string
*/
public function getPlotStyle() {
return $this->_plotStyle;
}
/**
* Get Plot Style
*
* @return string
*/
public function getPlotStyle() {
return $this->_plotStyle;
}
/**
* Set Plot Style
*
* @param string $plotStyle
*/
public function setPlotStyle($plotStyle = null) {
$this->_plotStyle = $plotStyle;
}
/**
* Set Plot Style
*
* @param string $plotStyle
*/
public function setPlotStyle($plotStyle = null) {
$this->_plotStyle = $plotStyle;
}
/**
* Get Plot Values
*
* @return array of PHPExcel\Chart_DataSeriesValues
*/
public function getPlotValues() {
return $this->_plotValues;
}
/**
* Get Plot Values
*
* @return array of PHPExcel\Chart_DataSeriesValues
*/
public function getPlotValues() {
return $this->_plotValues;
}
/**
* Get Plot Values by Index
*
* @return PHPExcel\Chart_DataSeriesValues
*/
public function getPlotValuesByIndex($index) {
$keys = array_keys($this->_plotValues);
if (in_array($index,$keys)) {
return $this->_plotValues[$index];
} elseif(isset($keys[$index])) {
return $this->_plotValues[$keys[$index]];
}
return false;
}
/**
* Get Plot Values by Index
*
* @return PHPExcel\Chart_DataSeriesValues
*/
public function getPlotValuesByIndex($index) {
$keys = array_keys($this->_plotValues);
if (in_array($index,$keys)) {
return $this->_plotValues[$index];
} elseif(isset($keys[$index])) {
return $this->_plotValues[$keys[$index]];
}
return false;
}
/**
* Get Number of Plot Series
*
* @return integer
*/
public function getPlotSeriesCount() {
return count($this->_plotValues);
}
/**
* Get Number of Plot Series
*
* @return integer
*/
public function getPlotSeriesCount() {
return count($this->_plotValues);
}
/**
* Get Smooth Line
*
* @return boolean
*/
public function getSmoothLine() {
return $this->_smoothLine;
}
/**
* Get Smooth Line
*
* @return boolean
*/
public function getSmoothLine() {
return $this->_smoothLine;
}
/**
* Set Smooth Line
*
* @param boolean $smoothLine
*/
public function setSmoothLine($smoothLine = TRUE) {
$this->_smoothLine = $smoothLine;
}
public function refresh(Worksheet $worksheet) {
foreach($this->_plotValues as $plotValues) {
if ($plotValues !== NULL)
$plotValues->refresh($worksheet, TRUE);
}
foreach($this->_plotLabel as $plotValues) {
if ($plotValues !== NULL)
$plotValues->refresh($worksheet, TRUE);
}
foreach($this->_plotCategory as $plotValues) {
if ($plotValues !== NULL)
$plotValues->refresh($worksheet, FALSE);
}
}
/**
* Set Smooth Line
*
* @param boolean $smoothLine
*/
public function setSmoothLine($smoothLine = TRUE) {
$this->_smoothLine = $smoothLine;
}
public function refresh(Worksheet $worksheet) {
foreach($this->_plotValues as $plotValues) {
if ($plotValues !== null)
$plotValues->refresh($worksheet, TRUE);
}
foreach($this->_plotLabel as $plotValues) {
if ($plotValues !== null)
$plotValues->refresh($worksheet, TRUE);
}
foreach($this->_plotCategory as $plotValues) {
if ($plotValues !== null)
$plotValues->refresh($worksheet, false);
}
}
}

View File

@ -18,11 +18,11 @@
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category PHPExcel
* @package PHPExcel\Chart
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
* @category PHPExcel
* @package PHPExcel\Chart
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@ -31,299 +31,298 @@ namespace PHPExcel;
/**
* PHPExcel\Chart_DataSeriesValues
*
* @category PHPExcel
* @package PHPExcel\Chart
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @category PHPExcel
* @package PHPExcel\Chart
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
*/
class Chart_DataSeriesValues
{
const DATASERIES_TYPE_STRING = 'String';
const DATASERIES_TYPE_NUMBER = 'Number';
const DATASERIES_TYPE_STRING = 'String';
const DATASERIES_TYPE_NUMBER = 'Number';
private static $_dataTypeValues = array(
self::DATASERIES_TYPE_STRING,
self::DATASERIES_TYPE_NUMBER,
);
private static $_dataTypeValues = array(
self::DATASERIES_TYPE_STRING,
self::DATASERIES_TYPE_NUMBER,
);
/**
* Series Data Type
*
* @var string
*/
private $_dataType = null;
/**
* Series Data Type
*
* @var string
*/
private $_dataType = null;
/**
* Series Data Source
*
* @var string
*/
private $_dataSource = null;
/**
* Series Data Source
*
* @var string
*/
private $_dataSource = null;
/**
* Format Code
*
* @var string
*/
private $_formatCode = null;
/**
* Format Code
*
* @var string
*/
private $_formatCode = null;
/**
* Series Point Marker
*
* @var string
*/
private $_marker = null;
/**
* Series Point Marker
*
* @var string
*/
private $_marker = null;
/**
* Point Count (The number of datapoints in the dataseries)
*
* @var integer
*/
private $_pointCount = 0;
/**
* Point Count (The number of datapoints in the dataseries)
*
* @var integer
*/
private $_pointCount = 0;
/**
* Data Values
*
* @var array of mixed
*/
private $_dataValues = array();
/**
* Data Values
*
* @var array of mixed
*/
private $_dataValues = array();
/**
* Create a new PHPExcel\Chart_DataSeriesValues object
*/
public function __construct($dataType = self::DATASERIES_TYPE_NUMBER, $dataSource = null, $formatCode = null, $pointCount = 0, $dataValues = array(), $marker = null)
{
$this->setDataType($dataType);
$this->_dataSource = $dataSource;
$this->_formatCode = $formatCode;
$this->_pointCount = $pointCount;
$this->_dataValues = $dataValues;
$this->_marker = $marker;
}
/**
* Create a new PHPExcel\Chart_DataSeriesValues object
*/
public function __construct($dataType = self::DATASERIES_TYPE_NUMBER, $dataSource = null, $formatCode = null, $pointCount = 0, $dataValues = array(), $marker = null)
{
$this->setDataType($dataType);
$this->_dataSource = $dataSource;
$this->_formatCode = $formatCode;
$this->_pointCount = $pointCount;
$this->_dataValues = $dataValues;
$this->_marker = $marker;
}
/**
* Get Series Data Type
*
* @return string
*/
public function getDataType() {
return $this->_dataType;
}
/**
* Get Series Data Type
*
* @return string
*/
public function getDataType() {
return $this->_dataType;
}
/**
* Set Series Data Type
*
* @param string $dataType Datatype of this data series
* Typical values are:
* PHPExcel\Chart_DataSeriesValues::DATASERIES_TYPE_STRING
* Normally used for axis point values
* PHPExcel\Chart_DataSeriesValues::DATASERIES_TYPE_NUMBER
* Normally used for chart data values
* @return PHPExcel\Chart_DataSeriesValues
*/
public function setDataType($dataType = self::DATASERIES_TYPE_NUMBER) {
if (!in_array($dataType, self::$_dataTypeValues)) {
throw new Chart_Exception('Invalid datatype for chart data series values');
}
$this->_dataType = $dataType;
/**
* Set Series Data Type
*
* @param string $dataType Datatype of this data series
* Typical values are:
* PHPExcel\Chart_DataSeriesValues::DATASERIES_TYPE_STRING
* Normally used for axis point values
* PHPExcel\Chart_DataSeriesValues::DATASERIES_TYPE_NUMBER
* Normally used for chart data values
* @return PHPExcel\Chart_DataSeriesValues
*/
public function setDataType($dataType = self::DATASERIES_TYPE_NUMBER) {
if (!in_array($dataType, self::$_dataTypeValues)) {
throw new Chart_Exception('Invalid datatype for chart data series values');
}
$this->_dataType = $dataType;
return $this;
}
return $this;
}
/**
* Get Series Data Source (formula)
*
* @return string
*/
public function getDataSource() {
return $this->_dataSource;
}
/**
* Get Series Data Source (formula)
*
* @return string
*/
public function getDataSource() {
return $this->_dataSource;
}
/**
* Set Series Data Source (formula)
*
* @param string $dataSource
* @return PHPExcel\Chart_DataSeriesValues
*/
public function setDataSource($dataSource = null, $refreshDataValues = true) {
$this->_dataSource = $dataSource;
/**
* Set Series Data Source (formula)
*
* @param string $dataSource
* @return PHPExcel\Chart_DataSeriesValues
*/
public function setDataSource($dataSource = null, $refreshDataValues = true) {
$this->_dataSource = $dataSource;
if ($refreshDataValues) {
// TO DO
}
if ($refreshDataValues) {
// TO DO
}
return $this;
}
return $this;
}
/**
* Get Point Marker
*
* @return string
*/
public function getPointMarker() {
return $this->_marker;
}
/**
* Get Point Marker
*
* @return string
*/
public function getPointMarker() {
return $this->_marker;
}
/**
* Set Point Marker
*
* @param string $marker
* @return PHPExcel\Chart_DataSeriesValues
*/
public function setPointMarker($marker = null) {
$this->_marker = $marker;
/**
* Set Point Marker
*
* @param string $marker
* @return PHPExcel\Chart_DataSeriesValues
*/
public function setPointMarker($marker = null) {
$this->_marker = $marker;
return $this;
}
return $this;
}
/**
* Get Series Format Code
*
* @return string
*/
public function getFormatCode() {
return $this->_formatCode;
}
/**
* Get Series Format Code
*
* @return string
*/
public function getFormatCode() {
return $this->_formatCode;
}
/**
* Set Series Format Code
*
* @param string $formatCode
* @return PHPExcel\Chart_DataSeriesValues
*/
public function setFormatCode($formatCode = null) {
$this->_formatCode = $formatCode;
/**
* Set Series Format Code
*
* @param string $formatCode
* @return PHPExcel\Chart_DataSeriesValues
*/
public function setFormatCode($formatCode = null) {
$this->_formatCode = $formatCode;
return $this;
}
return $this;
}
/**
* Get Series Point Count
*
* @return integer
*/
public function getPointCount() {
return $this->_pointCount;
}
/**
* Get Series Point Count
*
* @return integer
*/
public function getPointCount() {
return $this->_pointCount;
}
/**
* Identify if the Data Series is a multi-level or a simple series
*
* @return boolean
*/
public function isMultiLevelSeries() {
if (count($this->_dataValues) > 0) {
return is_array($this->_dataValues[0]);
}
return null;
}
/**
* Identify if the Data Series is a multi-level or a simple series
*
* @return boolean
*/
public function isMultiLevelSeries() {
if (count($this->_dataValues) > 0) {
return is_array($this->_dataValues[0]);
}
return null;
}
/**
* Return the level count of a multi-level Data Series
*
* @return boolean
*/
public function multiLevelCount() {
$levelCount = 0;
foreach($this->_dataValues as $dataValueSet) {
$levelCount = max($levelCount,count($dataValueSet));
}
return $levelCount;
}
/**
* Return the level count of a multi-level Data Series
*
* @return boolean
*/
public function multiLevelCount() {
$levelCount = 0;
foreach($this->_dataValues as $dataValueSet) {
$levelCount = max($levelCount,count($dataValueSet));
}
return $levelCount;
}
/**
* Get Series Data Values
*
* @return array of mixed
*/
public function getDataValues() {
return $this->_dataValues;
}
/**
* Get Series Data Values
*
* @return array of mixed
*/
public function getDataValues() {
return $this->_dataValues;
}
/**
* Get the first Series Data value
*
* @return mixed
*/
public function getDataValue() {
$count = count($this->_dataValues);
if ($count == 0) {
return null;
} elseif ($count == 1) {
return $this->_dataValues[0];
}
return $this->_dataValues;
}
/**
* Get the first Series Data value
*
* @return mixed
*/
public function getDataValue() {
$count = count($this->_dataValues);
if ($count == 0) {
return null;
} elseif ($count == 1) {
return $this->_dataValues[0];
}
return $this->_dataValues;
}
/**
* Set Series Data Values
*
* @param array $dataValues
* @param boolean $refreshDataSource
* TRUE - refresh the value of _dataSource based on the values of $dataValues
* FALSE - don't change the value of _dataSource
* @return PHPExcel\Chart_DataSeriesValues
*/
public function setDataValues($dataValues = array(), $refreshDataSource = TRUE) {
$this->_dataValues = Calculation_Functions::flattenArray($dataValues);
$this->_pointCount = count($dataValues);
/**
* Set Series Data Values
*
* @param array $dataValues
* @param boolean $refreshDataSource
* TRUE - refresh the value of _dataSource based on the values of $dataValues
* FALSE - don't change the value of _dataSource
* @return PHPExcel\Chart_DataSeriesValues
*/
public function setDataValues($dataValues = array(), $refreshDataSource = TRUE) {
$this->_dataValues = Calculation_Functions::flattenArray($dataValues);
$this->_pointCount = count($dataValues);
if ($refreshDataSource) {
// TO DO
}
if ($refreshDataSource) {
// TO DO
}
return $this;
}
return $this;
}
private function _stripNulls($var) {
return $var !== NULL;
}
private function _stripNulls($var) {
return $var !== null;
}
public function refresh(Worksheet $worksheet, $flatten = TRUE) {
if ($this->_dataSource !== NULL) {
$calcEngine = Calculation::getInstance($worksheet->getParent());
$newDataValues = Calculation::_unwrapResult(
$calcEngine->_calculateFormulaValue(
'='.$this->_dataSource,
NULL,
$worksheet->getCell('A1')
)
);
if ($flatten) {
$this->_dataValues = Calculation_Functions::flattenArray($newDataValues);
foreach($this->_dataValues as &$dataValue) {
if ((!empty($dataValue)) && ($dataValue[0] == '#')) {
$dataValue = 0.0;
}
}
unset($dataValue);
} else {
$cellRange = explode('!',$this->_dataSource);
if (count($cellRange) > 1) {
list(,$cellRange) = $cellRange;
}
public function refresh(Worksheet $worksheet, $flatten = TRUE) {
if ($this->_dataSource !== null) {
$calcEngine = Calculation::getInstance($worksheet->getParent());
$newDataValues = Calculation::_unwrapResult(
$calcEngine->_calculateFormulaValue(
'='.$this->_dataSource,
null,
$worksheet->getCell('A1')
)
);
if ($flatten) {
$this->_dataValues = Calculation_Functions::flattenArray($newDataValues);
foreach($this->_dataValues as &$dataValue) {
if ((!empty($dataValue)) && ($dataValue[0] == '#')) {
$dataValue = 0.0;
}
}
unset($dataValue);
} else {
$cellRange = explode('!',$this->_dataSource);
if (count($cellRange) > 1) {
list(,$cellRange) = $cellRange;
}
$dimensions = Cell::rangeDimension(str_replace('$','',$cellRange));
if (($dimensions[0] == 1) || ($dimensions[1] == 1)) {
$this->_dataValues = Calculation_Functions::flattenArray($newDataValues);
} else {
$newArray = array_values(array_shift($newDataValues));
foreach($newArray as $i => $newDataSet) {
$newArray[$i] = array($newDataSet);
}
$dimensions = Cell::rangeDimension(str_replace('$','',$cellRange));
if (($dimensions[0] == 1) || ($dimensions[1] == 1)) {
$this->_dataValues = Calculation_Functions::flattenArray($newDataValues);
} else {
$newArray = array_values(array_shift($newDataValues));
foreach($newArray as $i => $newDataSet) {
$newArray[$i] = array($newDataSet);
}
foreach($newDataValues as $newDataSet) {
$i = 0;
foreach($newDataSet as $newDataVal) {
array_unshift($newArray[$i++],$newDataVal);
}
}
$this->_dataValues = $newArray;
}
}
$this->_pointCount = count($this->_dataValues);
}
}
foreach($newDataValues as $newDataSet) {
$i = 0;
foreach($newDataSet as $newDataVal) {
array_unshift($newArray[$i++],$newDataVal);
}
}
$this->_dataValues = $newArray;
}
}
$this->_pointCount = count($this->_dataValues);
}
}
}

View File

@ -21,8 +21,8 @@
* @category PHPExcel
* @package PHPExcel\Chart
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@ -36,19 +36,19 @@ namespace PHPExcel;
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
*/
class Chart_Exception extends Exception {
/**
* Error handler callback
*
* @param mixed $code
* @param mixed $string
* @param mixed $file
* @param mixed $line
* @param mixed $context
*/
public static function errorHandlerCallback($code, $string, $file, $line, $context) {
$e = new self($string, $code);
$e->line = $line;
$e->file = $file;
throw $e;
}
/**
* Error handler callback
*
* @param mixed $code
* @param mixed $string
* @param mixed $file
* @param mixed $line
* @param mixed $context
*/
public static function errorHandlerCallback($code, $string, $file, $line, $context) {
$e = new self($string, $code);
$e->line = $line;
$e->file = $file;
throw $e;
}
}

View File

@ -18,11 +18,11 @@
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category PHPExcel
* @package PHPExcel\Chart
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
* @category PHPExcel
* @package PHPExcel\Chart
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@ -31,389 +31,388 @@ namespace PHPExcel;
/**
* PHPExcel\Chart_Layout
*
* @category PHPExcel
* @package PHPExcel\Chart
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @category PHPExcel
* @package PHPExcel\Chart
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
*/
class Chart_Layout
{
/**
* layoutTarget
*
* @var string
*/
private $_layoutTarget = NULL;
/**
* layoutTarget
*
* @var string
*/
private $_layoutTarget = null;
/**
* X Mode
*
* @var string
*/
private $_xMode = NULL;
/**
* X Mode
*
* @var string
*/
private $_xMode = null;
/**
* Y Mode
*
* @var string
*/
private $_yMode = NULL;
/**
* Y Mode
*
* @var string
*/
private $_yMode = null;
/**
* X-Position
*
* @var float
*/
private $_xPos = NULL;
/**
* X-Position
*
* @var float
*/
private $_xPos = null;
/**
* Y-Position
*
* @var float
*/
private $_yPos = NULL;
/**
* Y-Position
*
* @var float
*/
private $_yPos = null;
/**
* width
*
* @var float
*/
private $_width = NULL;
/**
* width
*
* @var float
*/
private $_width = null;
/**
* height
*
* @var float
*/
private $_height = NULL;
/**
* height
*
* @var float
*/
private $_height = null;
/**
* show legend key
* Specifies that legend keys should be shown in data labels
*
* @var boolean
*/
private $_showLegendKey = NULL;
/**
* show legend key
* Specifies that legend keys should be shown in data labels
*
* @var boolean
*/
private $_showLegendKey = null;
/**
* show value
* Specifies that the value should be shown in a data label.
*
* @var boolean
*/
private $_showVal = NULL;
/**
* show value
* Specifies that the value should be shown in a data label.
*
* @var boolean
*/
private $_showVal = null;
/**
* show category name
* Specifies that the category name should be shown in the data label.
*
* @var boolean
*/
private $_showCatName = NULL;
/**
* show category name
* Specifies that the category name should be shown in the data label.
*
* @var boolean
*/
private $_showCatName = null;
/**
* show data series name
* Specifies that the series name should be shown in the data label.
*
* @var boolean
*/
private $_showSerName = NULL;
/**
* show data series name
* Specifies that the series name should be shown in the data label.
*
* @var boolean
*/
private $_showSerName = null;
/**
* show percentage
* Specifies that the percentage should be shown in the data label.
*
* @var boolean
*/
private $_showPercent = NULL;
/**
* show percentage
* Specifies that the percentage should be shown in the data label.
*
* @var boolean
*/
private $_showPercent = null;
/**
* show bubble size
*
* @var boolean
*/
private $_showBubbleSize = NULL;
/**
* show bubble size
*
* @var boolean
*/
private $_showBubbleSize = null;
/**
* show leader lines
* Specifies that leader lines should be shown for the data label.
*
* @var boolean
*/
private $_showLeaderLines = NULL;
/**
* show leader lines
* Specifies that leader lines should be shown for the data label.
*
* @var boolean
*/
private $_showLeaderLines = null;
/**
* Create a new PHPExcel\Chart_Layout
*/
public function __construct($layout=array())
{
if (isset($layout['layoutTarget'])) { $this->_layoutTarget = $layout['layoutTarget']; }
if (isset($layout['xMode'])) { $this->_xMode = $layout['xMode']; }
if (isset($layout['yMode'])) { $this->_yMode = $layout['yMode']; }
if (isset($layout['x'])) { $this->_xPos = (float) $layout['x']; }
if (isset($layout['y'])) { $this->_yPos = (float) $layout['y']; }
if (isset($layout['w'])) { $this->_width = (float) $layout['w']; }
if (isset($layout['h'])) { $this->_height = (float) $layout['h']; }
}
/**
* Create a new PHPExcel\Chart_Layout
*/
public function __construct($layout=array())
{
if (isset($layout['layoutTarget'])) { $this->_layoutTarget = $layout['layoutTarget']; }
if (isset($layout['xMode'])) { $this->_xMode = $layout['xMode']; }
if (isset($layout['yMode'])) { $this->_yMode = $layout['yMode']; }
if (isset($layout['x'])) { $this->_xPos = (float) $layout['x']; }
if (isset($layout['y'])) { $this->_yPos = (float) $layout['y']; }
if (isset($layout['w'])) { $this->_width = (float) $layout['w']; }
if (isset($layout['h'])) { $this->_height = (float) $layout['h']; }
}
/**
* Get Layout Target
*
* @return string
*/
public function getLayoutTarget() {
return $this->_layoutTarget;
}
/**
* Get Layout Target
*
* @return string
*/
public function getLayoutTarget() {
return $this->_layoutTarget;
}
/**
* Set Layout Target
*
* @param Layout Target $value
*/
public function setLayoutTarget($value) {
$this->_layoutTarget = $value;
}
/**
* Set Layout Target
*
* @param Layout Target $value
*/
public function setLayoutTarget($value) {
$this->_layoutTarget = $value;
}
/**
* Get X-Mode
*
* @return string
*/
public function getXMode() {
return $this->_xMode;
}
/**
* Get X-Mode
*
* @return string
*/
public function getXMode() {
return $this->_xMode;
}
/**
* Set X-Mode
*
* @param X-Mode $value
*/
public function setXMode($value) {
$this->_xMode = $value;
}
/**
* Set X-Mode
*
* @param X-Mode $value
*/
public function setXMode($value) {
$this->_xMode = $value;
}
/**
* Get Y-Mode
*
* @return string
*/
public function getYMode() {
return $this->_xMode;
}
/**
* Get Y-Mode
*
* @return string
*/
public function getYMode() {
return $this->_xMode;
}
/**
* Set Y-Mode
*
* @param Y-Mode $value
*/
public function setYMode($value) {
$this->_xMode = $value;
}
/**
* Set Y-Mode
*
* @param Y-Mode $value
*/
public function setYMode($value) {
$this->_xMode = $value;
}
/**
* Get X-Position
*
* @return number
*/
public function getXPosition() {
return $this->_xPos;
}
/**
* Get X-Position
*
* @return number
*/
public function getXPosition() {
return $this->_xPos;
}
/**
* Set X-Position
*
* @param X-Position $value
*/
public function setXPosition($value) {
$this->_xPos = $value;
}
/**
* Set X-Position
*
* @param X-Position $value
*/
public function setXPosition($value) {
$this->_xPos = $value;
}
/**
* Get Y-Position
*
* @return number
*/
public function getYPosition() {
return $this->_yPos;
}
/**
* Get Y-Position
*
* @return number
*/
public function getYPosition() {
return $this->_yPos;
}
/**
* Set Y-Position
*
* @param Y-Position $value
*/
public function setYPosition($value) {
$this->_yPos = $value;
}
/**
* Set Y-Position
*
* @param Y-Position $value
*/
public function setYPosition($value) {
$this->_yPos = $value;
}
/**
* Get Width
*
* @return number
*/
public function getWidth() {
return $this->_width;
}
/**
* Get Width
*
* @return number
*/
public function getWidth() {
return $this->_width;
}
/**
* Set Width
*
* @param Width $value
*/
public function setWidth($value) {
$this->_width = $value;
}
/**
* Set Width
*
* @param Width $value
*/
public function setWidth($value) {
$this->_width = $value;
}
/**
* Get Height
*
* @return number
*/
public function getHeight() {
return $this->_height;
}
/**
* Get Height
*
* @return number
*/
public function getHeight() {
return $this->_height;
}
/**
* Set Height
*
* @param Height $value
*/
public function setHeight($value) {
$this->_height = $value;
}
/**
* Set Height
*
* @param Height $value
*/
public function setHeight($value) {
$this->_height = $value;
}
/**
* Get show legend key
*
* @return boolean
*/
public function getShowLegendKey() {
return $this->_showLegendKey;
}
/**
* Get show legend key
*
* @return boolean
*/
public function getShowLegendKey() {
return $this->_showLegendKey;
}
/**
* Set show legend key
* Specifies that legend keys should be shown in data labels.
*
* @param boolean $value Show legend key
*/
public function setShowLegendKey($value) {
$this->_showLegendKey = $value;
}
/**
* Set show legend key
* Specifies that legend keys should be shown in data labels.
*
* @param boolean $value Show legend key
*/
public function setShowLegendKey($value) {
$this->_showLegendKey = $value;
}
/**
* Get show value
*
* @return boolean
*/
public function getShowVal() {
return $this->_showVal;
}
/**
* Get show value
*
* @return boolean
*/
public function getShowVal() {
return $this->_showVal;
}
/**
* Set show val
* Specifies that the value should be shown in data labels.
*
* @param boolean $value Show val
*/
public function setShowVal($value) {
$this->_showVal = $value;
}
/**
* Set show val
* Specifies that the value should be shown in data labels.
*
* @param boolean $value Show val
*/
public function setShowVal($value) {
$this->_showVal = $value;
}
/**
* Get show category name
*
* @return boolean
*/
public function getShowCatName() {
return $this->_showCatName;
}
/**
* Get show category name
*
* @return boolean
*/
public function getShowCatName() {
return $this->_showCatName;
}
/**
* Set show cat name
* Specifies that the category name should be shown in data labels.
*
* @param boolean $value Show cat name
*/
public function setShowCatName($value) {
$this->_showCatName = $value;
}
/**
* Set show cat name
* Specifies that the category name should be shown in data labels.
*
* @param boolean $value Show cat name
*/
public function setShowCatName($value) {
$this->_showCatName = $value;
}
/**
* Get show data series name
*
* @return boolean
*/
public function getShowSerName() {
return $this->_showSerName;
}
/**
* Get show data series name
*
* @return boolean
*/
public function getShowSerName() {
return $this->_showSerName;
}
/**
* Set show ser name
* Specifies that the series name should be shown in data labels.
*
* @param boolean $value Show ser name
*/
public function setShowSerName($value) {
$this->_showSerName = $value;
}
/**
* Set show ser name
* Specifies that the series name should be shown in data labels.
*
* @param boolean $value Show ser name
*/
public function setShowSerName($value) {
$this->_showSerName = $value;
}
/**
* Get show percentage
*
* @return boolean
*/
public function getShowPercent() {
return $this->_showPercent;
}
/**
* Get show percentage
*
* @return boolean
*/
public function getShowPercent() {
return $this->_showPercent;
}
/**
* Set show percentage
* Specifies that the percentage should be shown in data labels.
*
* @param boolean $value Show percentage
*/
public function setShowPercent($value) {
$this->_showPercent = $value;
}
/**
* Set show percentage
* Specifies that the percentage should be shown in data labels.
*
* @param boolean $value Show percentage
*/
public function setShowPercent($value) {
$this->_showPercent = $value;
}
/**
* Get show bubble size
*
* @return boolean
*/
public function getShowBubbleSize() {
return $this->_showBubbleSize;
}
/**
* Get show bubble size
*
* @return boolean
*/
public function getShowBubbleSize() {
return $this->_showBubbleSize;
}
/**
* Set show bubble size
* Specifies that the bubble size should be shown in data labels.
*
* @param boolean $value Show bubble size
*/
public function setShowBubbleSize($value) {
$this->_showBubbleSize = $value;
}
/**
* Set show bubble size
* Specifies that the bubble size should be shown in data labels.
*
* @param boolean $value Show bubble size
*/
public function setShowBubbleSize($value) {
$this->_showBubbleSize = $value;
}
/**
* Get show leader lines
*
* @return boolean
*/
public function getShowLeaderLines() {
return $this->_showLeaderLines;
}
/**
* Set show leader lines
* Specifies that leader lines should be shown in data labels.
*
* @param boolean $value Show leader lines
*/
public function setShowLeaderLines($value) {
$this->_showLeaderLines = $value;
}
/**
* Get show leader lines
*
* @return boolean
*/
public function getShowLeaderLines() {
return $this->_showLeaderLines;
}
/**
* Set show leader lines
* Specifies that leader lines should be shown in data labels.
*
* @param boolean $value Show leader lines
*/
public function setShowLeaderLines($value) {
$this->_showLeaderLines = $value;
}
}

View File

@ -18,11 +18,11 @@
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category PHPExcel
* @package PHPExcel\Chart
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
* @category PHPExcel
* @package PHPExcel\Chart
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@ -31,143 +31,142 @@ namespace PHPExcel;
/**
* PHPExcel\Chart_Legend
*
* @category PHPExcel
* @package PHPExcel\Chart
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @category PHPExcel
* @package PHPExcel\Chart
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
*/
class Chart_Legend
{
/** Legend positions */
const xlLegendPositionBottom = -4107; // Below the chart.
const xlLegendPositionCorner = 2; // In the upper right-hand corner of the chart border.
const xlLegendPositionCustom = -4161; // A custom position.
const xlLegendPositionLeft = -4131; // Left of the chart.
const xlLegendPositionRight = -4152; // Right of the chart.
const xlLegendPositionTop = -4160; // Above the chart.
/** Legend positions */
const xlLegendPositionBottom = -4107; // Below the chart.
const xlLegendPositionCorner = 2; // In the upper right-hand corner of the chart border.
const xlLegendPositionCustom = -4161; // A custom position.
const xlLegendPositionLeft = -4131; // Left of the chart.
const xlLegendPositionRight = -4152; // Right of the chart.
const xlLegendPositionTop = -4160; // Above the chart.
const POSITION_RIGHT = 'r';
const POSITION_LEFT = 'l';
const POSITION_BOTTOM = 'b';
const POSITION_TOP = 't';
const POSITION_TOPRIGHT = 'tr';
const POSITION_RIGHT = 'r';
const POSITION_LEFT = 'l';
const POSITION_BOTTOM = 'b';
const POSITION_TOP = 't';
const POSITION_TOPRIGHT = 'tr';
private static $_positionXLref = array( self::xlLegendPositionBottom => self::POSITION_BOTTOM,
self::xlLegendPositionCorner => self::POSITION_TOPRIGHT,
self::xlLegendPositionCustom => '??',
self::xlLegendPositionLeft => self::POSITION_LEFT,
self::xlLegendPositionRight => self::POSITION_RIGHT,
self::xlLegendPositionTop => self::POSITION_TOP
);
private static $_positionXLref = array( self::xlLegendPositionBottom => self::POSITION_BOTTOM,
self::xlLegendPositionCorner => self::POSITION_TOPRIGHT,
self::xlLegendPositionCustom => '??',
self::xlLegendPositionLeft => self::POSITION_LEFT,
self::xlLegendPositionRight => self::POSITION_RIGHT,
self::xlLegendPositionTop => self::POSITION_TOP
);
/**
* Legend position
*
* @var string
*/
private $_position = self::POSITION_RIGHT;
/**
* Legend position
*
* @var string
*/
private $_position = self::POSITION_RIGHT;
/**
* Allow overlay of other elements?
*
* @var boolean
*/
private $_overlay = TRUE;
/**
* Allow overlay of other elements?
*
* @var boolean
*/
private $_overlay = TRUE;
/**
* Legend Layout
*
* @var PHPExcel\Chart_Layout
*/
private $_layout = NULL;
/**
* Legend Layout
*
* @var PHPExcel\Chart_Layout
*/
private $_layout = null;
/**
* Create a new PHPExcel\Chart_Legend
*/
public function __construct($position = self::POSITION_RIGHT, Chart_Layout $layout = NULL, $overlay = FALSE)
{
$this->setPosition($position);
$this->_layout = $layout;
$this->setOverlay($overlay);
}
/**
* Create a new PHPExcel\Chart_Legend
*/
public function __construct($position = self::POSITION_RIGHT, Chart_Layout $layout = null, $overlay = false)
{
$this->setPosition($position);
$this->_layout = $layout;
$this->setOverlay($overlay);
}
/**
* Get legend position as an excel string value
*
* @return string
*/
public function getPosition() {
return $this->_position;
}
/**
* Get legend position as an excel string value
*
* @return string
*/
public function getPosition() {
return $this->_position;
}
/**
* Get legend position using an excel string value
*
* @param string $position
*/
public function setPosition($position = self::POSITION_RIGHT) {
if (!in_array($position,self::$_positionXLref)) {
return false;
}
/**
* Get legend position using an excel string value
*
* @param string $position
*/
public function setPosition($position = self::POSITION_RIGHT) {
if (!in_array($position,self::$_positionXLref)) {
return false;
}
$this->_position = $position;
return true;
}
$this->_position = $position;
return true;
}
/**
* Get legend position as an Excel internal numeric value
*
* @return number
*/
public function getPositionXL() {
return array_search($this->_position,self::$_positionXLref);
}
/**
* Get legend position as an Excel internal numeric value
*
* @return number
*/
public function getPositionXL() {
return array_search($this->_position,self::$_positionXLref);
}
/**
* Set legend position using an Excel internal numeric value
*
* @param number $positionXL
*/
public function setPositionXL($positionXL = self::xlLegendPositionRight) {
if (!array_key_exists($positionXL,self::$_positionXLref)) {
return false;
}
/**
* Set legend position using an Excel internal numeric value
*
* @param number $positionXL
*/
public function setPositionXL($positionXL = self::xlLegendPositionRight) {
if (!array_key_exists($positionXL,self::$_positionXLref)) {
return false;
}
$this->_position = self::$_positionXLref[$positionXL];
return true;
}
$this->_position = self::$_positionXLref[$positionXL];
return true;
}
/**
* Get allow overlay of other elements?
*
* @return boolean
*/
public function getOverlay() {
return $this->_overlay;
}
/**
* Get allow overlay of other elements?
*
* @return boolean
*/
public function getOverlay() {
return $this->_overlay;
}
/**
* Set allow overlay of other elements?
*
* @param boolean $overlay
* @return boolean
*/
public function setOverlay($overlay = FALSE) {
if (!is_bool($overlay)) {
return false;
}
/**
* Set allow overlay of other elements?
*
* @param boolean $overlay
* @return boolean
*/
public function setOverlay($overlay = false) {
if (!is_bool($overlay)) {
return false;
}
$this->_overlay = $overlay;
return true;
}
/**
* Get Layout
*
* @return PHPExcel\Chart_Layout
*/
public function getLayout() {
return $this->_layout;
}
$this->_overlay = $overlay;
return true;
}
/**
* Get Layout
*
* @return PHPExcel\Chart_Layout
*/
public function getLayout() {
return $this->_layout;
}
}

View File

@ -18,11 +18,11 @@
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category PHPExcel
* @package PHPExcel\Chart
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
* @category PHPExcel
* @package PHPExcel\Chart
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@ -31,97 +31,97 @@ namespace PHPExcel;
/**
* PHPExcel\Chart_PlotArea
*
* @category PHPExcel
* @package PHPExcel\Chart
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @category PHPExcel
* @package PHPExcel\Chart
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
*/
class Chart_PlotArea
{
/**
* PlotArea Layout
*
* @var PHPExcel\Chart_Layout
*/
private $_layout = null;
/**
* PlotArea Layout
*
* @var PHPExcel\Chart_Layout
*/
private $_layout = null;
/**
* Plot Series
*
* @var array of PHPExcel\Chart_DataSeries
*/
private $_plotSeries = array();
/**
* Plot Series
*
* @var array of PHPExcel\Chart_DataSeries
*/
private $_plotSeries = array();
/**
* Create a new PHPExcel\Chart_PlotArea
*/
public function __construct(Chart_Layout $layout = null, $plotSeries = array())
{
$this->_layout = $layout;
$this->_plotSeries = $plotSeries;
}
/**
* Create a new PHPExcel\Chart_PlotArea
*/
public function __construct(Chart_Layout $layout = null, $plotSeries = array())
{
$this->_layout = $layout;
$this->_plotSeries = $plotSeries;
}
/**
* Get Layout
*
* @return PHPExcel\Chart_Layout
*/
public function getLayout() {
return $this->_layout;
}
/**
* Get Layout
*
* @return PHPExcel\Chart_Layout
*/
public function getLayout() {
return $this->_layout;
}
/**
* Get Number of Plot Groups
*
* @return array of PHPExcel\Chart_DataSeries
*/
public function getPlotGroupCount() {
return count($this->_plotSeries);
}
/**
* Get Number of Plot Groups
*
* @return array of PHPExcel\Chart_DataSeries
*/
public function getPlotGroupCount() {
return count($this->_plotSeries);
}
/**
* Get Number of Plot Series
*
* @return integer
*/
public function getPlotSeriesCount() {
$seriesCount = 0;
foreach($this->_plotSeries as $plot) {
$seriesCount += $plot->getPlotSeriesCount();
}
return $seriesCount;
}
/**
* Get Number of Plot Series
*
* @return integer
*/
public function getPlotSeriesCount() {
$seriesCount = 0;
foreach($this->_plotSeries as $plot) {
$seriesCount += $plot->getPlotSeriesCount();
}
return $seriesCount;
}
/**
* Get Plot Series
*
* @return array of PHPExcel\Chart_DataSeries
*/
public function getPlotGroup() {
return $this->_plotSeries;
}
/**
* Get Plot Series
*
* @return array of PHPExcel\Chart_DataSeries
*/
public function getPlotGroup() {
return $this->_plotSeries;
}
/**
* Get Plot Series by Index
*
* @return PHPExcel\Chart_DataSeries
*/
public function getPlotGroupByIndex($index) {
return $this->_plotSeries[$index];
}
/**
* Get Plot Series by Index
*
* @return PHPExcel\Chart_DataSeries
*/
public function getPlotGroupByIndex($index) {
return $this->_plotSeries[$index];
}
/**
* Set Plot Series
*
* @param [PHPExcel\Chart_DataSeries]
*/
public function setPlotSeries($plotSeries = array()) {
$this->_plotSeries = $plotSeries;
}
/**
* Set Plot Series
*
* @param [PHPExcel\Chart_DataSeries]
*/
public function setPlotSeries($plotSeries = array()) {
$this->_plotSeries = $plotSeries;
}
public function refresh(Worksheet $worksheet) {
foreach($this->_plotSeries as $plotSeries) {
$plotSeries->refresh($worksheet);
}
}
public function refresh(Worksheet $worksheet) {
foreach($this->_plotSeries as $plotSeries) {
$plotSeries->refresh($worksheet);
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -18,11 +18,11 @@
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category PHPExcel
* @package PHPExcel\Chart
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
* @category PHPExcel
* @package PHPExcel\Chart
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@ -31,61 +31,61 @@ namespace PHPExcel;
/**
* PHPExcel\Chart_Title
*
* @category PHPExcel
* @package PHPExcel\Chart
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @category PHPExcel
* @package PHPExcel\Chart
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
*/
class Chart_Title
{
/**
* Title Caption
*
* @var string
*/
private $_caption = null;
/**
* Title Caption
*
* @var string
*/
private $_caption = null;
/**
* Title Layout
*
* @var PHPExcel\Chart_Layout
*/
private $_layout = null;
/**
* Title Layout
*
* @var PHPExcel\Chart_Layout
*/
private $_layout = null;
/**
* Create a new PHPExcel\Chart_Title
*/
public function __construct($caption = null, Chart_Layout $layout = null)
{
$this->_caption = $caption;
$this->_layout = $layout;
}
/**
* Create a new PHPExcel\Chart_Title
*/
public function __construct($caption = null, Chart_Layout $layout = null)
{
$this->_caption = $caption;
$this->_layout = $layout;
}
/**
* Get caption
*
* @return string
*/
public function getCaption() {
return $this->_caption;
}
/**
* Get caption
*
* @return string
*/
public function getCaption() {
return $this->_caption;
}
/**
* Set caption
*
* @param string $caption
*/
public function setCaption($caption = null) {
$this->_caption = $caption;
}
/**
* Set caption
*
* @param string $caption
*/
public function setCaption($caption = null) {
$this->_caption = $caption;
}
/**
* Get Layout
*
* @return PHPExcel\Chart_Layout
*/
public function getLayout() {
return $this->_layout;
}
/**
* Get Layout
*
* @return PHPExcel\Chart_Layout
*/
public function getLayout() {
return $this->_layout;
}
}

View File

@ -108,10 +108,10 @@ class Comment implements IComparable
public function __construct()
{
// Initialise variables
$this->_author = 'Author';
$this->_text = new RichText();
$this->_fillColor = new Style_Color('FFFFFFE1');
$this->_alignment = Style_Alignment::HORIZONTAL_GENERAL;
$this->_author = 'Author';
$this->_text = new RichText();
$this->_fillColor = new Style_Color('FFFFFFE1');
$this->_alignment = Style_Alignment::HORIZONTAL_GENERAL;
}
/**
@ -325,5 +325,4 @@ class Comment implements IComparable
public function __toString() {
return $this->_text->getPlainText();
}
}

View File

@ -38,7 +38,7 @@ namespace PHPExcel;
class DocumentProperties
{
/** constants */
const PROPERTY_TYPE_BOOLEAN = 'b';
const PROPERTY_TYPE_BOOLEAN = 'b';
const PROPERTY_TYPE_INTEGER = 'i';
const PROPERTY_TYPE_FLOAT = 'f';
const PROPERTY_TYPE_DATE = 'd';
@ -197,7 +197,7 @@ class DocumentProperties
* @return PHPExcel\DocumentProperties
*/
public function setCreated($pValue = null) {
if ($pValue === NULL) {
if ($pValue === null) {
$pValue = time();
} elseif (is_string($pValue)) {
if (is_numeric($pValue)) {
@ -227,7 +227,7 @@ class DocumentProperties
* @return PHPExcel\DocumentProperties
*/
public function setModified($pValue = null) {
if ($pValue === NULL) {
if ($pValue === null) {
$pValue = time();
} elseif (is_string($pValue)) {
if (is_numeric($pValue)) {
@ -432,20 +432,20 @@ class DocumentProperties
* @param string $propertyName
* @param mixed $propertyValue
* @param string $propertyType
* 'i' : Integer
* 'i' : Integer
* 'f' : Floating Point
* 's' : String
* 'd' : Date/Time
* 'b' : Boolean
* @return PHPExcel\DocumentProperties
*/
public function setCustomProperty($propertyName,$propertyValue='',$propertyType=NULL) {
if (($propertyType === NULL) || (!in_array($propertyType,array(self::PROPERTY_TYPE_INTEGER,
public function setCustomProperty($propertyName,$propertyValue='',$propertyType=null) {
if (($propertyType === null) || (!in_array($propertyType,array(self::PROPERTY_TYPE_INTEGER,
self::PROPERTY_TYPE_FLOAT,
self::PROPERTY_TYPE_STRING,
self::PROPERTY_TYPE_DATE,
self::PROPERTY_TYPE_BOOLEAN)))) {
if ($propertyValue === NULL) {
if ($propertyValue === null) {
$propertyType = self::PROPERTY_TYPE_STRING;
} elseif (is_float($propertyValue)) {
$propertyType = self::PROPERTY_TYPE_FLOAT;
@ -482,7 +482,7 @@ class DocumentProperties
return '';
break;
case 'null' : // Null
return NULL;
return null;
break;
case 'i1' : // 1-Byte Signed Integer
case 'i2' : // 2-Byte Signed Integer
@ -585,5 +585,4 @@ class DocumentProperties
}
return self::PROPERTY_TYPE_UNKNOWN;
}
}

View File

@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@ -37,40 +37,40 @@ namespace PHPExcel;
*/
class DocumentSecurity
{
/**
* LockRevision
*
* @var boolean
*/
protected $_lockRevision = false;
/**
* LockRevision
*
* @var boolean
*/
protected $_lockRevision = false;
/**
* LockStructure
*
* @var boolean
*/
protected $_lockStructure = false;
/**
* LockStructure
*
* @var boolean
*/
protected $_lockStructure = false;
/**
* LockWindows
*
* @var boolean
*/
protected $_lockWindows = false;
/**
* LockWindows
*
* @var boolean
*/
protected $_lockWindows = false;
/**
* RevisionsPassword
*
* @var string
*/
protected $_revisionsPassword = '';
/**
* RevisionsPassword
*
* @var string
*/
protected $_revisionsPassword = '';
/**
* WorkbookPassword
*
* @var string
*/
protected $_workbookPassword = '';
/**
* WorkbookPassword
*
* @var string
*/
protected $_workbookPassword = '';
/**
* Create a new PHPExcel\DocumentSecurity
@ -85,9 +85,9 @@ class DocumentSecurity
* @return boolean
*/
function isSecurityEnabled() {
return $this->_lockRevision ||
$this->_lockStructure ||
$this->_lockWindows;
return $this->_lockRevision ||
$this->_lockStructure ||
$this->_lockWindows;
}
/**
@ -96,7 +96,7 @@ class DocumentSecurity
* @return boolean
*/
function getLockRevision() {
return $this->_lockRevision;
return $this->_lockRevision;
}
/**
@ -106,8 +106,8 @@ class DocumentSecurity
* @return PHPExcel\DocumentSecurity
*/
function setLockRevision($pValue = false) {
$this->_lockRevision = $pValue;
return $this;
$this->_lockRevision = $pValue;
return $this;
}
/**
@ -116,7 +116,7 @@ class DocumentSecurity
* @return boolean
*/
function getLockStructure() {
return $this->_lockStructure;
return $this->_lockStructure;
}
/**
@ -126,8 +126,8 @@ class DocumentSecurity
* @return PHPExcel\DocumentSecurity
*/
function setLockStructure($pValue = false) {
$this->_lockStructure = $pValue;
return $this;
$this->_lockStructure = $pValue;
return $this;
}
/**
@ -136,7 +136,7 @@ class DocumentSecurity
* @return boolean
*/
function getLockWindows() {
return $this->_lockWindows;
return $this->_lockWindows;
}
/**
@ -146,8 +146,8 @@ class DocumentSecurity
* @return PHPExcel\DocumentSecurity
*/
function setLockWindows($pValue = false) {
$this->_lockWindows = $pValue;
return $this;
$this->_lockWindows = $pValue;
return $this;
}
/**
@ -156,22 +156,22 @@ class DocumentSecurity
* @return string
*/
function getRevisionsPassword() {
return $this->_revisionsPassword;
return $this->_revisionsPassword;
}
/**
* Set RevisionsPassword
*
* @param string $pValue
* @param boolean $pAlreadyHashed If the password has already been hashed, set this to true
* @param string $pValue
* @param boolean $pAlreadyHashed If the password has already been hashed, set this to true
* @return PHPExcel\DocumentSecurity
*/
function setRevisionsPassword($pValue = '', $pAlreadyHashed = false) {
if (!$pAlreadyHashed) {
$pValue = Shared_PasswordHasher::hashPassword($pValue);
}
$this->_revisionsPassword = $pValue;
return $this;
if (!$pAlreadyHashed) {
$pValue = Shared_PasswordHasher::hashPassword($pValue);
}
$this->_revisionsPassword = $pValue;
return $this;
}
/**
@ -180,35 +180,35 @@ class DocumentSecurity
* @return string
*/
function getWorkbookPassword() {
return $this->_workbookPassword;
return $this->_workbookPassword;
}
/**
* Set WorkbookPassword
*
* @param string $pValue
* @param boolean $pAlreadyHashed If the password has already been hashed, set this to true
* @param string $pValue
* @param boolean $pAlreadyHashed If the password has already been hashed, set this to true
* @return PHPExcel\DocumentSecurity
*/
function setWorkbookPassword($pValue = '', $pAlreadyHashed = false) {
if (!$pAlreadyHashed) {
$pValue = Shared_PasswordHasher::hashPassword($pValue);
}
$this->_workbookPassword = $pValue;
return $this;
if (!$pAlreadyHashed) {
$pValue = Shared_PasswordHasher::hashPassword($pValue);
}
$this->_workbookPassword = $pValue;
return $this;
}
/**
* Implement PHP __clone to create a deep clone, not just a shallow copy.
*/
public function __clone() {
$vars = get_object_vars($this);
foreach ($vars as $key => $value) {
if (is_object($value)) {
$this->$key = clone $value;
} else {
$this->$key = $value;
}
}
}
/**
* Implement PHP __clone to create a deep clone, not just a shallow copy.
*/
public function __clone() {
$vars = get_object_vars($this);
foreach ($vars as $key => $value) {
if (is_object($value)) {
$this->$key = clone $value;
} else {
$this->$key = $value;
}
}
}
}

View File

@ -19,10 +19,10 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category PHPExcel
* @package PHPExcel
* @package PHPExcel
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@ -32,173 +32,173 @@ namespace PHPExcel;
* PHPExcel\HashTable
*
* @category PHPExcel
* @package PHPExcel
* @package PHPExcel
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
*/
class HashTable
{
/**
* HashTable elements
*
* @var array
*/
public $_items = array();
/**
* HashTable elements
*
* @var array
*/
public $_items = array();
/**
* HashTable key map
*
* @var array
*/
public $_keyMap = array();
/**
* HashTable key map
*
* @var array
*/
public $_keyMap = array();
/**
* Create a new PHPExcel\HashTable
*
* @param PHPExcel\IComparable[] $pSource Optional source array to create HashTable from
* @throws PHPExcel\Exception
*/
public function __construct($pSource = null)
{
if ($pSource !== NULL) {
// Create HashTable
$this->addFromSource($pSource);
}
}
/**
* Create a new PHPExcel\HashTable
*
* @param PHPExcel\IComparable[] $pSource Optional source array to create HashTable from
* @throws PHPExcel\Exception
*/
public function __construct($pSource = null)
{
if ($pSource !== null) {
// Create HashTable
$this->addFromSource($pSource);
}
}
/**
* Add HashTable items from source
*
* @param PHPExcel\IComparable[] $pSource Source array to create HashTable from
* @throws PHPExcel\Exception
*/
public function addFromSource($pSource = null) {
// Check if an array was passed
if ($pSource == null) {
return;
} else if (!is_array($pSource)) {
throw new Exception('Invalid array parameter passed.');
}
/**
* Add HashTable items from source
*
* @param PHPExcel\IComparable[] $pSource Source array to create HashTable from
* @throws PHPExcel\Exception
*/
public function addFromSource($pSource = null) {
// Check if an array was passed
if ($pSource == null) {
return;
} else if (!is_array($pSource)) {
throw new Exception('Invalid array parameter passed.');
}
foreach ($pSource as $item) {
$this->add($item);
}
}
foreach ($pSource as $item) {
$this->add($item);
}
}
/**
* Add HashTable item
*
* @param PHPExcel\IComparable $pSource Item to add
* @throws PHPExcel\Exception
*/
public function add(IComparable $pSource = null) {
$hash = $pSource->getHashCode();
if (!isset($this->_items[$hash])) {
$this->_items[$hash] = $pSource;
$this->_keyMap[count($this->_items) - 1] = $hash;
}
}
/**
* Add HashTable item
*
* @param PHPExcel\IComparable $pSource Item to add
* @throws PHPExcel\Exception
*/
public function add(IComparable $pSource = null) {
$hash = $pSource->getHashCode();
if (!isset($this->_items[$hash])) {
$this->_items[$hash] = $pSource;
$this->_keyMap[count($this->_items) - 1] = $hash;
}
}
/**
* Remove HashTable item
*
* @param PHPExcel\IComparable $pSource Item to remove
* @throws PHPExcel\Exception
*/
public function remove(IComparable $pSource = null) {
$hash = $pSource->getHashCode();
if (isset($this->_items[$hash])) {
unset($this->_items[$hash]);
/**
* Remove HashTable item
*
* @param PHPExcel\IComparable $pSource Item to remove
* @throws PHPExcel\Exception
*/
public function remove(IComparable $pSource = null) {
$hash = $pSource->getHashCode();
if (isset($this->_items[$hash])) {
unset($this->_items[$hash]);
$deleteKey = -1;
foreach ($this->_keyMap as $key => $value) {
if ($deleteKey >= 0) {
$this->_keyMap[$key - 1] = $value;
}
$deleteKey = -1;
foreach ($this->_keyMap as $key => $value) {
if ($deleteKey >= 0) {
$this->_keyMap[$key - 1] = $value;
}
if ($value == $hash) {
$deleteKey = $key;
}
}
unset($this->_keyMap[count($this->_keyMap) - 1]);
}
}
if ($value == $hash) {
$deleteKey = $key;
}
}
unset($this->_keyMap[count($this->_keyMap) - 1]);
}
}
/**
* Clear HashTable
*
*/
public function clear() {
$this->_items = array();
$this->_keyMap = array();
}
/**
* Clear HashTable
*
*/
public function clear() {
$this->_items = array();
$this->_keyMap = array();
}
/**
* Count
*
* @return int
*/
public function count() {
return count($this->_items);
}
/**
* Count
*
* @return int
*/
public function count() {
return count($this->_items);
}
/**
* Get index for hash code
*
* @param string $pHashCode
* @return int Index
*/
public function getIndexForHashCode($pHashCode = '') {
return array_search($pHashCode, $this->_keyMap);
}
/**
* Get index for hash code
*
* @param string $pHashCode
* @return int Index
*/
public function getIndexForHashCode($pHashCode = '') {
return array_search($pHashCode, $this->_keyMap);
}
/**
* Get by index
*
* @param int $pIndex
* @return PHPExcel\IComparable
*
*/
public function getByIndex($pIndex = 0) {
if (isset($this->_keyMap[$pIndex])) {
return $this->getByHashCode( $this->_keyMap[$pIndex] );
}
/**
* Get by index
*
* @param int $pIndex
* @return PHPExcel\IComparable
*
*/
public function getByIndex($pIndex = 0) {
if (isset($this->_keyMap[$pIndex])) {
return $this->getByHashCode( $this->_keyMap[$pIndex] );
}
return null;
}
return null;
}
/**
* Get by hashcode
*
* @param string $pHashCode
* @return PHPExcel\IComparable
*
*/
public function getByHashCode($pHashCode = '') {
if (isset($this->_items[$pHashCode])) {
return $this->_items[$pHashCode];
}
/**
* Get by hashcode
*
* @param string $pHashCode
* @return PHPExcel\IComparable
*
*/
public function getByHashCode($pHashCode = '') {
if (isset($this->_items[$pHashCode])) {
return $this->_items[$pHashCode];
}
return null;
}
return null;
}
/**
* HashTable to array
*
* @return PHPExcel\IComparable[]
*/
public function toArray() {
return $this->_items;
}
/**
* HashTable to array
*
* @return PHPExcel\IComparable[]
*/
public function toArray() {
return $this->_items;
}
/**
* Implement PHP __clone to create a deep clone, not just a shallow copy.
*/
public function __clone() {
$vars = get_object_vars($this);
foreach ($vars as $key => $value) {
if (is_object($value)) {
$this->$key = clone $value;
}
}
}
/**
* Implement PHP __clone to create a deep clone, not just a shallow copy.
*/
public function __clone() {
$vars = get_object_vars($this);
foreach ($vars as $key => $value) {
if (is_object($value)) {
$this->$key = clone $value;
}
}
}
}

View File

@ -19,7 +19,7 @@
* @category PHPExcel
* @package PHPExcel
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@ -35,11 +35,10 @@ namespace PHPExcel;
*/
interface IComparable
{
/**
* Get hash code
*
* @return string Hash code
*/
public function getHashCode();
/**
* Get hash code
*
* @return string Hash code
*/
public function getHashCode();
}

View File

@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@ -37,244 +37,236 @@ namespace PHPExcel;
*/
class IOFactory
{
/**
* Search locations
*
* @var array
* @static
*/
protected static $_searchLocations = array(
array( 'type' => 'IWriter', 'path' => 'PHPExcel/Writer/{0}.php', 'class' => 'Writer_{0}' ),
array( 'type' => 'IReader', 'path' => 'PHPExcel/Reader/{0}.php', 'class' => 'Reader_{0}' )
);
/**
* Autoresolve classes
*
* @var array
* @static
*/
protected static $_autoResolveClasses = array(
'Excel2007',
'Excel5',
'Excel2003XML',
'OOCalc',
'SYLK',
'Gnumeric',
'HTML',
'CSV',
);
/**
* Search locations
*
* @var array
* @static
*/
protected static $_searchLocations = array(
array( 'type' => 'IWriter', 'path' => 'PHPExcel/Writer/{0}.php', 'class' => 'Writer_{0}' ),
array( 'type' => 'IReader', 'path' => 'PHPExcel/Reader/{0}.php', 'class' => 'Reader_{0}' )
);
/**
* Private constructor for PHPExcel\IOFactory
* Autoresolve classes
*
* @var array
* @static
*/
protected static $_autoResolveClasses = array(
'Excel2007',
'Excel5',
'Excel2003XML',
'OOCalc',
'SYLK',
'Gnumeric',
'HTML',
'CSV',
);
/**
* Private constructor for PHPExcel\IOFactory
*/
private function __construct() { }
/**
* Get search locations
*
* @static
* @access public
* @return array
* @static
* @return array
*/
public static function getSearchLocations() {
return self::$_searchLocations;
} // function getSearchLocations()
public static function getSearchLocations() {
return self::$_searchLocations;
} // function getSearchLocations()
/**
* Set search locations
*
* @static
* @access public
* @param array $value
* @throws PHPExcel\Reader_Exception
*/
public static function setSearchLocations($value) {
if (is_array($value)) {
self::$_searchLocations = $value;
} else {
throw new Reader_Exception('Invalid parameter passed.');
}
} // function setSearchLocations()
/**
* Set search locations
*
* @static
* @param array $value
* @throws PHPExcel\Reader_Exception
*/
public static function setSearchLocations($value) {
if (is_array($value)) {
self::$_searchLocations = $value;
} else {
throw new Reader_Exception('Invalid parameter passed.');
}
} // function setSearchLocations()
/**
* Add search location
*
* @static
* @access public
* @param string $type Example: IWriter
* @param string $location Example: PHPExcel/Writer/{0}.php
* @param string $classname Example: PHPExcel\Writer_{0}
*/
public static function addSearchLocation($type = '', $location = '', $classname = '') {
self::$_searchLocations[] = array( 'type' => $type, 'path' => $location, 'class' => $classname );
} // function addSearchLocation()
/**
* Add search location
*
* @static
* @param string $type Example: IWriter
* @param string $location Example: PHPExcel/Writer/{0}.php
* @param string $classname Example: PHPExcel\Writer_{0}
*/
public static function addSearchLocation($type = '', $location = '', $classname = '') {
self::$_searchLocations[] = array( 'type' => $type, 'path' => $location, 'class' => $classname );
} // function addSearchLocation()
/**
* Create PHPExcel\Writer_IWriter
*
* @static
* @access public
* @param PHPExcel $phpExcel
* @param string $writerType Example: Excel2007
* @return PHPExcel\Writer_IWriter
* @throws PHPExcel\Reader_Exception
*/
public static function createWriter(Workbook $phpExcel, $writerType = '') {
// Search type
$searchType = 'IWriter';
/**
* Create PHPExcel\Writer_IWriter
*
* @static
* @param PHPExcel $phpExcel
* @param string $writerType Example: Excel2007
* @return PHPExcel\Writer_IWriter
* @throws PHPExcel\Reader_Exception
*/
public static function createWriter(Workbook $phpExcel, $writerType = '') {
// Search type
$searchType = 'IWriter';
// Include class
foreach (self::$_searchLocations as $searchLocation) {
// Include class
foreach (self::$_searchLocations as $searchLocation) {
if ($searchLocation['type'] == $searchType) {
$className = __NAMESPACE__ . '\\' . str_replace('{0}', $writerType, $searchLocation['class']);
$className = __NAMESPACE__ . '\\' . str_replace('{0}', $writerType, $searchLocation['class']);
$instance = new $className($phpExcel);
if ($instance !== NULL) {
return $instance;
}
}
}
$instance = new $className($phpExcel);
if ($instance !== null) {
return $instance;
}
}
}
// Nothing found...
throw new Reader_Exception("No $searchType found for type $writerType");
} // function createWriter()
// Nothing found...
throw new Reader_Exception("No $searchType found for type $writerType");
} // function createWriter()
/**
* Create PHPExcel\Reader_IReader
*
* @static
* @access public
* @param string $readerType Example: Excel2007
* @return PHPExcel\Reader_IReader
* @throws PHPExcel\Reader_Exception
*/
public static function createReader($readerType = '') {
// Search type
$searchType = 'IReader';
/**
* Create PHPExcel\Reader_IReader
*
* @static
* @param string $readerType Example: Excel2007
* @return PHPExcel\Reader_IReader
* @throws PHPExcel\Reader_Exception
*/
public static function createReader($readerType = '') {
// Search type
$searchType = 'IReader';
// Include class
foreach (self::$_searchLocations as $searchLocation) {
if ($searchLocation['type'] == $searchType) {
$className = __NAMESPACE__ . '\\' . str_replace('{0}', $readerType, $searchLocation['class']);
// Include class
foreach (self::$_searchLocations as $searchLocation) {
if ($searchLocation['type'] == $searchType) {
$className = __NAMESPACE__ . '\\' . str_replace('{0}', $readerType, $searchLocation['class']);
$instance = new $className();
if ($instance !== NULL) {
return $instance;
}
}
}
$instance = new $className();
if ($instance !== null) {
return $instance;
}
}
}
// Nothing found...
throw new Reader_Exception("No $searchType found for type $readerType");
} // function createReader()
// Nothing found...
throw new Reader_Exception("No $searchType found for type $readerType");
} // function createReader()
/**
* Loads PHPExcel from file using automatic PHPExcel\Reader_IReader resolution
*
* @static
* @access public
* @param string $pFilename The name of the spreadsheet file
* @return PHPExcel
* @throws PHPExcel\Reader_Exception
*/
public static function load($pFilename) {
$reader = self::createReaderForFile($pFilename);
return $reader->load($pFilename);
} // function load()
/**
* Loads PHPExcel from file using automatic PHPExcel\Reader_IReader resolution
*
* @static
* @param string $pFilename The name of the spreadsheet file
* @return PHPExcel
* @throws PHPExcel\Reader_Exception
*/
public static function load($pFilename) {
$reader = self::createReaderForFile($pFilename);
return $reader->load($pFilename);
} // function load()
/**
* Identify file type using automatic PHPExcel\Reader_IReader resolution
*
* @static
* @access public
* @param string $pFilename The name of the spreadsheet file to identify
* @return string
* @throws PHPExcel\Reader_Exception
*/
public static function identify($pFilename) {
$reader = self::createReaderForFile($pFilename);
$className = get_class($reader);
$classType = explode('_',$className);
unset($reader);
return array_pop($classType);
} // function identify()
/**
* Identify file type using automatic PHPExcel\Reader_IReader resolution
*
* @static
* @param string $pFilename The name of the spreadsheet file to identify
* @return string
* @throws PHPExcel\Reader_Exception
*/
public static function identify($pFilename) {
$reader = self::createReaderForFile($pFilename);
$className = get_class($reader);
$classType = explode('_',$className);
unset($reader);
return array_pop($classType);
} // function identify()
/**
* Create PHPExcel\Reader_IReader for file using automatic PHPExcel\Reader_IReader resolution
*
* @static
* @access public
* @param string $pFilename The name of the spreadsheet file
* @return PHPExcel\Reader_IReader
* @throws PHPExcel\Reader_Exception
*/
public static function createReaderForFile($pFilename) {
/**
* Create PHPExcel\Reader_IReader for file using automatic PHPExcel\Reader_IReader resolution
*
* @static
* @param string $pFilename The name of the spreadsheet file
* @return PHPExcel\Reader_IReader
* @throws PHPExcel\Reader_Exception
*/
public static function createReaderForFile($pFilename) {
// First, lucky guess by inspecting file extension
$pathinfo = pathinfo($pFilename);
// First, lucky guess by inspecting file extension
$pathinfo = pathinfo($pFilename);
$extensionType = NULL;
if (isset($pathinfo['extension'])) {
switch (strtolower($pathinfo['extension'])) {
case 'xlsx': // Excel (OfficeOpenXML) Spreadsheet
case 'xlsm': // Excel (OfficeOpenXML) Macro Spreadsheet (macros will be discarded)
case 'xltx': // Excel (OfficeOpenXML) Template
case 'xltm': // Excel (OfficeOpenXML) Macro Template (macros will be discarded)
$extensionType = 'Excel2007';
break;
case 'xls': // Excel (BIFF) Spreadsheet
case 'xlt': // Excel (BIFF) Template
$extensionType = 'Excel5';
break;
case 'ods': // Open/Libre Offic Calc
case 'ots': // Open/Libre Offic Calc Template
$extensionType = 'OOCalc';
break;
case 'slk':
$extensionType = 'SYLK';
break;
case 'xml': // Excel 2003 SpreadSheetML
$extensionType = 'Excel2003XML';
break;
case 'gnumeric':
$extensionType = 'Gnumeric';
break;
case 'htm':
case 'html':
$extensionType = 'HTML';
break;
case 'csv':
// Do nothing
// We must not try to use CSV reader since it loads
// all files including Excel files etc.
break;
default:
break;
}
$extensionType = null;
if (isset($pathinfo['extension'])) {
switch (strtolower($pathinfo['extension'])) {
case 'xlsx': // Excel (OfficeOpenXML) Spreadsheet
case 'xlsm': // Excel (OfficeOpenXML) Macro Spreadsheet (macros will be discarded)
case 'xltx': // Excel (OfficeOpenXML) Template
case 'xltm': // Excel (OfficeOpenXML) Macro Template (macros will be discarded)
$extensionType = 'Excel2007';
break;
case 'xls': // Excel (BIFF) Spreadsheet
case 'xlt': // Excel (BIFF) Template
$extensionType = 'Excel5';
break;
case 'ods': // Open/Libre Offic Calc
case 'ots': // Open/Libre Offic Calc Template
$extensionType = 'OOCalc';
break;
case 'slk':
$extensionType = 'SYLK';
break;
case 'xml': // Excel 2003 SpreadSheetML
$extensionType = 'Excel2003XML';
break;
case 'gnumeric':
$extensionType = 'Gnumeric';
break;
case 'htm':
case 'html':
$extensionType = 'HTML';
break;
case 'csv':
// Do nothing
// We must not try to use CSV reader since it loads
// all files including Excel files etc.
break;
default:
break;
}
if ($extensionType !== NULL) {
$reader = self::createReader($extensionType);
// Let's see if we are lucky
if (isset($reader) && $reader->canRead($pFilename)) {
return $reader;
}
}
}
if ($extensionType !== null) {
$reader = self::createReader($extensionType);
// Let's see if we are lucky
if (isset($reader) && $reader->canRead($pFilename)) {
return $reader;
}
}
}
// If we reach here then "lucky guess" didn't give any result
// Try walking through all the options in self::$_autoResolveClasses
foreach (self::$_autoResolveClasses as $autoResolveClass) {
// Ignore our original guess, we know that won't work
if ($autoResolveClass !== $extensionType) {
$reader = self::createReader($autoResolveClass);
if ($reader->canRead($pFilename)) {
return $reader;
}
}
}
// If we reach here then "lucky guess" didn't give any result
// Try walking through all the options in self::$_autoResolveClasses
foreach (self::$_autoResolveClasses as $autoResolveClass) {
// Ignore our original guess, we know that won't work
if ($autoResolveClass !== $extensionType) {
$reader = self::createReader($autoResolveClass);
if ($reader->canRead($pFilename)) {
return $reader;
}
}
}
throw new Reader_Exception('Unable to identify a reader for this file');
} // function createReaderForFile()
throw new Reader_Exception('Unable to identify a reader for this file');
} // function createReaderForFile()
}

View File

@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@ -37,40 +37,40 @@ namespace PHPExcel;
*/
class NamedRange
{
/**
* Range name
*
* @var string
*/
protected $_name;
/**
* Range name
*
* @var string
*/
protected $_name;
/**
* Worksheet on which the named range can be resolved
*
* @var PHPExcel\Worksheet
*/
protected $_worksheet;
/**
* Worksheet on which the named range can be resolved
*
* @var PHPExcel\Worksheet
*/
protected $_worksheet;
/**
* Range of the referenced cells
*
* @var string
*/
protected $_range;
/**
* Range of the referenced cells
*
* @var string
*/
protected $_range;
/**
* Is the named range local? (i.e. can only be used on $this->_worksheet)
*
* @var bool
*/
protected $_localOnly;
/**
* Is the named range local? (i.e. can only be used on $this->_worksheet)
*
* @var bool
*/
protected $_localOnly;
/**
* Scope
*
* @var PHPExcel\Worksheet
*/
protected $_scope;
/**
* Scope
*
* @var PHPExcel\Worksheet
*/
protected $_scope;
/**
* Create a new NamedRange
@ -79,23 +79,23 @@ class NamedRange
* @param PHPExcel\Worksheet $pWorksheet
* @param string $pRange
* @param bool $pLocalOnly
* @param PHPExcel\Worksheet|null $pScope Scope. Only applies when $pLocalOnly = true. Null for global scope.
* @param PHPExcel\Worksheet|null $pScope Scope. Only applies when $pLocalOnly = true. Null for global scope.
* @throws PHPExcel\Exception
*/
public function __construct($pName = null, Worksheet $pWorksheet, $pRange = 'A1', $pLocalOnly = false, $pScope = null)
{
// Validate data
if (($pName === NULL) || ($pWorksheet === NULL) || ($pRange === NULL)) {
throw new Exception('Parameters can not be null.');
}
// Validate data
if (($pName === null) || ($pWorksheet === null) || ($pRange === null)) {
throw new Exception('Parameters can not be null.');
}
// Set local members
$this->_name = $pName;
$this->_worksheet = $pWorksheet;
$this->_range = $pRange;
$this->_localOnly = $pLocalOnly;
$this->_scope = ($pLocalOnly == true) ?
(($pScope == null) ? $pWorksheet : $pScope) : null;
// Set local members
$this->_name = $pName;
$this->_worksheet = $pWorksheet;
$this->_range = $pRange;
$this->_localOnly = $pLocalOnly;
$this->_scope = ($pLocalOnly == true) ?
(($pScope == null) ? $pWorksheet : $pScope) : null;
}
/**
@ -104,7 +104,7 @@ class NamedRange
* @return string
*/
public function getName() {
return $this->_name;
return $this->_name;
}
/**
@ -114,25 +114,25 @@ class NamedRange
* @return PHPExcel\NamedRange
*/
public function setName($value = null) {
if ($value !== NULL) {
// Old title
$oldTitle = $this->_name;
if ($value !== null) {
// Old title
$oldTitle = $this->_name;
// Re-attach
if ($this->_worksheet !== NULL) {
$this->_worksheet->getParent()->removeNamedRange($this->_name,$this->_worksheet);
}
$this->_name = $value;
// Re-attach
if ($this->_worksheet !== null) {
$this->_worksheet->getParent()->removeNamedRange($this->_name,$this->_worksheet);
}
$this->_name = $value;
if ($this->_worksheet !== NULL) {
$this->_worksheet->getParent()->addNamedRange($this);
}
if ($this->_worksheet !== null) {
$this->_worksheet->getParent()->addNamedRange($this);
}
// New title
$newTitle = $this->_name;
ReferenceHelper::getInstance()->updateNamedFormulas($this->_worksheet->getParent(), $oldTitle, $newTitle);
}
return $this;
// New title
$newTitle = $this->_name;
ReferenceHelper::getInstance()->updateNamedFormulas($this->_worksheet->getParent(), $oldTitle, $newTitle);
}
return $this;
}
/**
@ -141,7 +141,7 @@ class NamedRange
* @return PHPExcel\Worksheet
*/
public function getWorksheet() {
return $this->_worksheet;
return $this->_worksheet;
}
/**
@ -151,10 +151,10 @@ class NamedRange
* @return PHPExcel\NamedRange
*/
public function setWorksheet(Worksheet $worksheet = null) {
if ($worksheet !== NULL) {
$this->_worksheet = $worksheet;
}
return $this;
if ($worksheet !== null) {
$this->_worksheet = $worksheet;
}
return $this;
}
/**
@ -163,7 +163,7 @@ class NamedRange
* @return string
*/
public function getRange() {
return $this->_range;
return $this->_range;
}
/**
@ -173,10 +173,10 @@ class NamedRange
* @return PHPExcel\NamedRange
*/
public function setRange($value = null) {
if ($value !== NULL) {
$this->_range = $value;
}
return $this;
if ($value !== null) {
$this->_range = $value;
}
return $this;
}
/**
@ -185,7 +185,7 @@ class NamedRange
* @return bool
*/
public function getLocalOnly() {
return $this->_localOnly;
return $this->_localOnly;
}
/**
@ -195,30 +195,30 @@ class NamedRange
* @return PHPExcel\NamedRange
*/
public function setLocalOnly($value = false) {
$this->_localOnly = $value;
$this->_scope = $value ? $this->_worksheet : null;
return $this;
$this->_localOnly = $value;
$this->_scope = $value ? $this->_worksheet : null;
return $this;
}
/**
* Get scope
*
* @return PHPExcel\Worksheet|NULL
* @return PHPExcel\Worksheet|null
*/
public function getScope() {
return $this->_scope;
return $this->_scope;
}
/**
* Set scope
*
* @param PHPExcel\Worksheet|NULL $worksheet
* @param PHPExcel\Worksheet|null $worksheet
* @return PHPExcel\NamedRange
*/
public function setScope(Worksheet $worksheet = null) {
$this->_scope = $worksheet;
$this->_localOnly = ($worksheet == null) ? false : true;
return $this;
$this->_scope = $worksheet;
$this->_localOnly = ($worksheet === null) ? false : true;
return $this;
}
/**
@ -229,20 +229,20 @@ class NamedRange
* @return PHPExcel\NamedRange
*/
public static function resolveRange($pNamedRange = '', Worksheet $pSheet) {
return $pSheet->getParent()->getNamedRange($pNamedRange, $pSheet);
return $pSheet->getParent()->getNamedRange($pNamedRange, $pSheet);
}
/**
* Implement PHP __clone to create a deep clone, not just a shallow copy.
*/
public function __clone() {
$vars = get_object_vars($this);
foreach ($vars as $key => $value) {
if (is_object($value)) {
$this->$key = clone $value;
} else {
$this->$key = $value;
}
}
}
/**
* Implement PHP __clone to create a deep clone, not just a shallow copy.
*/
public function __clone() {
$vars = get_object_vars($this);
foreach ($vars as $key => $value) {
if (is_object($value)) {
$this->$key = clone $value;
} else {
$this->$key = $value;
}
}
}
}

View File

@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\Reader
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@ -31,199 +31,198 @@ namespace PHPExcel;
/**
* PHPExcel\Reader_Abstract
*
* @category PHPExcel
* @package PHPExcel\Reader
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @category PHPExcel
* @package PHPExcel\Reader
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
*/
abstract class Reader_Abstract implements Reader_IReader
{
/**
* Read data only?
* Identifies whether the Reader should only read data values for cells, and ignore any formatting information;
* or whether it should read both data and formatting
*
* @var boolean
*/
protected $_readDataOnly = FALSE;
/**
* Read data only?
* Identifies whether the Reader should only read data values for cells, and ignore any formatting information;
* or whether it should read both data and formatting
*
* @var boolean
*/
protected $_readDataOnly = false;
/**
* Read charts that are defined in the workbook?
* Identifies whether the Reader should read the definitions for any charts that exist in the workbook;
*
* @var boolean
*/
protected $_includeCharts = FALSE;
/**
* Read charts that are defined in the workbook?
* Identifies whether the Reader should read the definitions for any charts that exist in the workbook;
*
* @var boolean
*/
protected $_includeCharts = false;
/**
* Restrict which sheets should be loaded?
* This property holds an array of worksheet names to be loaded. If null, then all worksheets will be loaded.
*
* @var array of string
*/
protected $_loadSheetsOnly = NULL;
/**
* Restrict which sheets should be loaded?
* This property holds an array of worksheet names to be loaded. If null, then all worksheets will be loaded.
*
* @var array of string
*/
protected $_loadSheetsOnly = null;
/**
* PHPExcel\Reader_IReadFilter instance
*
* @var PHPExcel\Reader_IReadFilter
*/
protected $_readFilter = NULL;
/**
* PHPExcel\Reader_IReadFilter instance
*
* @var PHPExcel\Reader_IReadFilter
*/
protected $_readFilter = null;
protected $_fileHandle = NULL;
protected $_fileHandle = null;
/**
* Read data only?
* If this is true, then the Reader will only read data values for cells, it will not read any formatting information.
* If false (the default) it will read data and formatting.
*
* @return boolean
*/
public function getReadDataOnly() {
return $this->_readDataOnly;
}
/**
* Read data only?
* If this is true, then the Reader will only read data values for cells, it will not read any formatting information.
* If false (the default) it will read data and formatting.
*
* @return boolean
*/
public function getReadDataOnly() {
return $this->_readDataOnly;
}
/**
* Set read data only
* Set to true, to advise the Reader only to read data values for cells, and to ignore any formatting information.
* Set to false (the default) to advise the Reader to read both data and formatting for cells.
*
* @param boolean $pValue
*
* @return PHPExcel\Reader_IReader
*/
public function setReadDataOnly($pValue = FALSE) {
$this->_readDataOnly = $pValue;
return $this;
}
/**
* Set read data only
* Set to true, to advise the Reader only to read data values for cells, and to ignore any formatting information.
* Set to false (the default) to advise the Reader to read both data and formatting for cells.
*
* @param boolean $pValue
*
* @return PHPExcel\Reader_IReader
*/
public function setReadDataOnly($pValue = false) {
$this->_readDataOnly = $pValue;
return $this;
}
/**
* Read charts in workbook?
* If this is true, then the Reader will include any charts that exist in the workbook.
* Note that a ReadDataOnly value of false overrides, and charts won't be read regardless of the IncludeCharts value.
* If false (the default) it will ignore any charts defined in the workbook file.
*
* @return boolean
*/
public function getIncludeCharts() {
return $this->_includeCharts;
}
/**
* Read charts in workbook?
* If this is true, then the Reader will include any charts that exist in the workbook.
* Note that a ReadDataOnly value of false overrides, and charts won't be read regardless of the IncludeCharts value.
* If false (the default) it will ignore any charts defined in the workbook file.
*
* @return boolean
*/
public function getIncludeCharts() {
return $this->_includeCharts;
}
/**
* Set read charts in workbook
* Set to true, to advise the Reader to include any charts that exist in the workbook.
* Note that a ReadDataOnly value of false overrides, and charts won't be read regardless of the IncludeCharts value.
* Set to false (the default) to discard charts.
*
* @param boolean $pValue
*
* @return PHPExcel\Reader_IReader
*/
public function setIncludeCharts($pValue = FALSE) {
$this->_includeCharts = (boolean) $pValue;
return $this;
}
/**
* Set read charts in workbook
* Set to true, to advise the Reader to include any charts that exist in the workbook.
* Note that a ReadDataOnly value of false overrides, and charts won't be read regardless of the IncludeCharts value.
* Set to false (the default) to discard charts.
*
* @param boolean $pValue
*
* @return PHPExcel\Reader_IReader
*/
public function setIncludeCharts($pValue = false) {
$this->_includeCharts = (boolean) $pValue;
return $this;
}
/**
* Get which sheets to load
* Returns either an array of worksheet names (the list of worksheets that should be loaded), or a null
* indicating that all worksheets in the workbook should be loaded.
*
* @return mixed
*/
public function getLoadSheetsOnly()
{
return $this->_loadSheetsOnly;
}
/**
* Get which sheets to load
* Returns either an array of worksheet names (the list of worksheets that should be loaded), or a null
* indicating that all worksheets in the workbook should be loaded.
*
* @return mixed
*/
public function getLoadSheetsOnly()
{
return $this->_loadSheetsOnly;
}
/**
* Set which sheets to load
*
* @param mixed $value
* This should be either an array of worksheet names to be loaded, or a string containing a single worksheet name.
* If NULL, then it tells the Reader to read all worksheets in the workbook
*
* @return PHPExcel\Reader_IReader
*/
public function setLoadSheetsOnly($value = NULL)
{
$this->_loadSheetsOnly = is_array($value) ?
$value : array($value);
return $this;
}
/**
* Set which sheets to load
*
* @param mixed $value
* This should be either an array of worksheet names to be loaded, or a string containing a single worksheet name.
* If null, then it tells the Reader to read all worksheets in the workbook
*
* @return PHPExcel\Reader_IReader
*/
public function setLoadSheetsOnly($value = null)
{
$this->_loadSheetsOnly = is_array($value) ?
$value : array($value);
return $this;
}
/**
* Set all sheets to load
* Tells the Reader to load all worksheets from the workbook.
*
* @return PHPExcel\Reader_IReader
*/
public function setLoadAllSheets()
{
$this->_loadSheetsOnly = NULL;
return $this;
}
/**
* Set all sheets to load
* Tells the Reader to load all worksheets from the workbook.
*
* @return PHPExcel\Reader_IReader
*/
public function setLoadAllSheets()
{
$this->_loadSheetsOnly = null;
return $this;
}
/**
* Read filter
*
* @return PHPExcel\Reader_IReadFilter
*/
public function getReadFilter() {
return $this->_readFilter;
}
/**
* Read filter
*
* @return PHPExcel\Reader_IReadFilter
*/
public function getReadFilter() {
return $this->_readFilter;
}
/**
* Set read filter
*
* @param PHPExcel\Reader_IReadFilter $pValue
* @return PHPExcel\Reader_IReader
*/
public function setReadFilter(Reader_IReadFilter $pValue) {
$this->_readFilter = $pValue;
return $this;
}
/**
* Set read filter
*
* @param PHPExcel\Reader_IReadFilter $pValue
* @return PHPExcel\Reader_IReader
*/
public function setReadFilter(Reader_IReadFilter $pValue) {
$this->_readFilter = $pValue;
return $this;
}
/**
* Open file for reading
*
* @param string $pFilename
* @throws PHPExcel\Reader_Exception
* @return resource
*/
protected function _openFile($pFilename)
{
// Check if file exists
if (!file_exists($pFilename) || !is_readable($pFilename)) {
throw new Reader_Exception("Could not open " . $pFilename . " for reading! File does not exist.");
}
/**
* Open file for reading
*
* @param string $pFilename
* @throws PHPExcel\Reader_Exception
* @return resource
*/
protected function _openFile($pFilename)
{
// Check if file exists
if (!file_exists($pFilename) || !is_readable($pFilename)) {
throw new Reader_Exception("Could not open " . $pFilename . " for reading! File does not exist.");
}
// Open file
$this->_fileHandle = fopen($pFilename, 'r');
if ($this->_fileHandle === FALSE) {
throw new Reader_Exception("Could not open file " . $pFilename . " for reading.");
}
}
// Open file
$this->_fileHandle = fopen($pFilename, 'r');
if ($this->_fileHandle === false) {
throw new Reader_Exception("Could not open file " . $pFilename . " for reading.");
}
}
/**
* Can the current PHPExcel\Reader_IReader read the file?
*
* @param string $pFilename
* @return boolean
* @throws PHPExcel\Reader_Exception
*/
public function canRead($pFilename)
{
// Check if file exists
try {
$this->_openFile($pFilename);
} catch (Exception $e) {
return FALSE;
}
$readable = $this->_isValidFormat();
fclose ($this->_fileHandle);
return $readable;
}
/**
* Can the current PHPExcel\Reader_IReader read the file?
*
* @param string $pFilename
* @return boolean
* @throws PHPExcel\Reader_Exception
*/
public function canRead($pFilename)
{
// Check if file exists
try {
$this->_openFile($pFilename);
} catch (Exception $e) {
return false;
}
$readable = $this->_isValidFormat();
fclose ($this->_fileHandle);
return $readable;
}
}

View File

@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\Reader
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@ -37,372 +37,371 @@ namespace PHPExcel;
*/
class Reader_CSV extends Reader_Abstract implements Reader_IReader
{
/**
* Input encoding
*
* @access private
* @var string
*/
private $_inputEncoding = 'UTF-8';
/**
* Input encoding
*
* @access private
* @var string
*/
private $_inputEncoding = 'UTF-8';
/**
* Delimiter
*
* @access private
* @var string
*/
private $_delimiter = ',';
/**
* Delimiter
*
* @access private
* @var string
*/
private $_delimiter = ',';
/**
* Enclosure
*
* @access private
* @var string
*/
private $_enclosure = '"';
/**
* Enclosure
*
* @access private
* @var string
*/
private $_enclosure = '"';
/**
* Line ending
*
* @access private
* @var string
*/
private $_lineEnding = PHP_EOL;
/**
* Line ending
*
* @access private
* @var string
*/
private $_lineEnding = PHP_EOL;
/**
* Sheet index to read
*
* @access private
* @var int
*/
private $_sheetIndex = 0;
/**
* Sheet index to read
*
* @access private
* @var int
*/
private $_sheetIndex = 0;
/**
* Load rows contiguously
*
* @access private
* @var int
*/
private $_contiguous = false;
/**
* Load rows contiguously
*
* @access private
* @var int
*/
private $_contiguous = false;
/**
* Row counter for loading rows contiguously
*
* @var int
*/
private $_contiguousRow = -1;
/**
* Row counter for loading rows contiguously
*
* @var int
*/
private $_contiguousRow = -1;
/**
* Create a new PHPExcel\Reader_CSV
*/
public function __construct() {
$this->_readFilter = new Reader_DefaultReadFilter();
}
/**
* Create a new PHPExcel\Reader_CSV
*/
public function __construct() {
$this->_readFilter = new Reader_DefaultReadFilter();
}
/**
* Validate that the current file is a CSV file
*
* @return boolean
*/
protected function _isValidFormat()
{
return TRUE;
}
/**
* Validate that the current file is a CSV file
*
* @return boolean
*/
protected function _isValidFormat()
{
return TRUE;
}
/**
* Set input encoding
*
* @param string $pValue Input encoding
*/
public function setInputEncoding($pValue = 'UTF-8')
{
$this->_inputEncoding = $pValue;
return $this;
}
/**
* Set input encoding
*
* @param string $pValue Input encoding
*/
public function setInputEncoding($pValue = 'UTF-8')
{
$this->_inputEncoding = $pValue;
return $this;
}
/**
* Get input encoding
*
* @return string
*/
public function getInputEncoding()
{
return $this->_inputEncoding;
}
/**
* Get input encoding
*
* @return string
*/
public function getInputEncoding()
{
return $this->_inputEncoding;
}
/**
* Move filepointer past any BOM marker
*
*/
protected function _skipBOM()
{
rewind($this->_fileHandle);
/**
* Move filepointer past any BOM marker
*
*/
protected function _skipBOM()
{
rewind($this->_fileHandle);
switch ($this->_inputEncoding) {
case 'UTF-8':
fgets($this->_fileHandle, 4) == "\xEF\xBB\xBF" ?
fseek($this->_fileHandle, 3) : fseek($this->_fileHandle, 0);
break;
case 'UTF-16LE':
fgets($this->_fileHandle, 3) == "\xFF\xFE" ?
fseek($this->_fileHandle, 2) : fseek($this->_fileHandle, 0);
break;
case 'UTF-16BE':
fgets($this->_fileHandle, 3) == "\xFE\xFF" ?
fseek($this->_fileHandle, 2) : fseek($this->_fileHandle, 0);
break;
case 'UTF-32LE':
fgets($this->_fileHandle, 5) == "\xFF\xFE\x00\x00" ?
fseek($this->_fileHandle, 4) : fseek($this->_fileHandle, 0);
break;
case 'UTF-32BE':
fgets($this->_fileHandle, 5) == "\x00\x00\xFE\xFF" ?
fseek($this->_fileHandle, 4) : fseek($this->_fileHandle, 0);
break;
default:
break;
}
}
switch ($this->_inputEncoding) {
case 'UTF-8':
fgets($this->_fileHandle, 4) == "\xEF\xBB\xBF" ?
fseek($this->_fileHandle, 3) : fseek($this->_fileHandle, 0);
break;
case 'UTF-16LE':
fgets($this->_fileHandle, 3) == "\xFF\xFE" ?
fseek($this->_fileHandle, 2) : fseek($this->_fileHandle, 0);
break;
case 'UTF-16BE':
fgets($this->_fileHandle, 3) == "\xFE\xFF" ?
fseek($this->_fileHandle, 2) : fseek($this->_fileHandle, 0);
break;
case 'UTF-32LE':
fgets($this->_fileHandle, 5) == "\xFF\xFE\x00\x00" ?
fseek($this->_fileHandle, 4) : fseek($this->_fileHandle, 0);
break;
case 'UTF-32BE':
fgets($this->_fileHandle, 5) == "\x00\x00\xFE\xFF" ?
fseek($this->_fileHandle, 4) : fseek($this->_fileHandle, 0);
break;
default:
break;
}
}
/**
* Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns)
*
* @param string $pFilename
* @throws PHPExcel\Reader_Exception
*/
public function listWorksheetInfo($pFilename)
{
// Open file
$this->_openFile($pFilename);
if (!$this->_isValidFormat()) {
fclose ($this->_fileHandle);
throw new Reader_Exception($pFilename . " is an Invalid Spreadsheet file.");
}
$fileHandle = $this->_fileHandle;
/**
* Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns)
*
* @param string $pFilename
* @throws PHPExcel\Reader_Exception
*/
public function listWorksheetInfo($pFilename)
{
// Open file
$this->_openFile($pFilename);
if (!$this->_isValidFormat()) {
fclose ($this->_fileHandle);
throw new Reader_Exception($pFilename . " is an Invalid Spreadsheet file.");
}
$fileHandle = $this->_fileHandle;
// Skip BOM, if any
$this->_skipBOM();
// Skip BOM, if any
$this->_skipBOM();
$escapeEnclosures = array( "\\" . $this->_enclosure, $this->_enclosure . $this->_enclosure );
$escapeEnclosures = array( "\\" . $this->_enclosure, $this->_enclosure . $this->_enclosure );
$worksheetInfo = array();
$worksheetInfo[0]['worksheetName'] = 'Worksheet';
$worksheetInfo[0]['lastColumnLetter'] = 'A';
$worksheetInfo[0]['lastColumnIndex'] = 0;
$worksheetInfo[0]['totalRows'] = 0;
$worksheetInfo[0]['totalColumns'] = 0;
$worksheetInfo = array();
$worksheetInfo[0]['worksheetName'] = 'Worksheet';
$worksheetInfo[0]['lastColumnLetter'] = 'A';
$worksheetInfo[0]['lastColumnIndex'] = 0;
$worksheetInfo[0]['totalRows'] = 0;
$worksheetInfo[0]['totalColumns'] = 0;
// Loop through each line of the file in turn
while (($rowData = fgetcsv($fileHandle, 0, $this->_delimiter, $this->_enclosure)) !== FALSE) {
$worksheetInfo[0]['totalRows']++;
$worksheetInfo[0]['lastColumnIndex'] = max($worksheetInfo[0]['lastColumnIndex'], count($rowData) - 1);
}
// Loop through each line of the file in turn
while (($rowData = fgetcsv($fileHandle, 0, $this->_delimiter, $this->_enclosure)) !== false) {
$worksheetInfo[0]['totalRows']++;
$worksheetInfo[0]['lastColumnIndex'] = max($worksheetInfo[0]['lastColumnIndex'], count($rowData) - 1);
}
$worksheetInfo[0]['lastColumnLetter'] = Cell::stringFromColumnIndex($worksheetInfo[0]['lastColumnIndex']);
$worksheetInfo[0]['totalColumns'] = $worksheetInfo[0]['lastColumnIndex'] + 1;
$worksheetInfo[0]['lastColumnLetter'] = Cell::stringFromColumnIndex($worksheetInfo[0]['lastColumnIndex']);
$worksheetInfo[0]['totalColumns'] = $worksheetInfo[0]['lastColumnIndex'] + 1;
// Close file
fclose($fileHandle);
// Close file
fclose($fileHandle);
return $worksheetInfo;
}
return $worksheetInfo;
}
/**
* Loads PHPExcel from file
*
* @param string $pFilename
* @return PHPExcel
* @throws PHPExcel\Reader_Exception
*/
public function load($pFilename)
{
// Create new PHPExcel Workbook
$objPHPExcel = new Workbook();
/**
* Loads PHPExcel from file
*
* @param string $pFilename
* @return PHPExcel
* @throws PHPExcel\Reader_Exception
*/
public function load($pFilename)
{
// Create new PHPExcel Workbook
$objPHPExcel = new Workbook();
// Load into this instance
return $this->loadIntoExisting($pFilename, $objPHPExcel);
}
// Load into this instance
return $this->loadIntoExisting($pFilename, $objPHPExcel);
}
/**
* Loads PHPExcel from file into PHPExcel instance
*
* @param string $pFilename
* @param PHPExcel\Workbook $objPHPExcel
* @return PHPExcel
* @throws PHPExcel\Reader_Exception
*/
public function loadIntoExisting($pFilename, Workbook $objPHPExcel)
{
$lineEnding = ini_get('auto_detect_line_endings');
ini_set('auto_detect_line_endings', true);
/**
* Loads PHPExcel from file into PHPExcel instance
*
* @param string $pFilename
* @param PHPExcel\Workbook $objPHPExcel
* @return PHPExcel
* @throws PHPExcel\Reader_Exception
*/
public function loadIntoExisting($pFilename, Workbook $objPHPExcel)
{
$lineEnding = ini_get('auto_detect_line_endings');
ini_set('auto_detect_line_endings', true);
// Open file
$this->_openFile($pFilename);
if (!$this->_isValidFormat()) {
fclose ($this->_fileHandle);
throw new Reader_Exception($pFilename . " is an Invalid Spreadsheet file.");
}
$fileHandle = $this->_fileHandle;
// Open file
$this->_openFile($pFilename);
if (!$this->_isValidFormat()) {
fclose ($this->_fileHandle);
throw new Reader_Exception($pFilename . " is an Invalid Spreadsheet file.");
}
$fileHandle = $this->_fileHandle;
// Skip BOM, if any
$this->_skipBOM();
// Skip BOM, if any
$this->_skipBOM();
// Create new PHPExcel object
while ($objPHPExcel->getSheetCount() <= $this->_sheetIndex) {
$objPHPExcel->createSheet();
}
$sheet = $objPHPExcel->setActiveSheetIndex($this->_sheetIndex);
// Create new PHPExcel object
while ($objPHPExcel->getSheetCount() <= $this->_sheetIndex) {
$objPHPExcel->createSheet();
}
$sheet = $objPHPExcel->setActiveSheetIndex($this->_sheetIndex);
$escapeEnclosures = array( "\\" . $this->_enclosure,
$this->_enclosure . $this->_enclosure
);
$escapeEnclosures = array( "\\" . $this->_enclosure,
$this->_enclosure . $this->_enclosure
);
// Set our starting row based on whether we're in contiguous mode or not
$currentRow = 1;
if ($this->_contiguous) {
$currentRow = ($this->_contiguousRow == -1) ? $sheet->getHighestRow(): $this->_contiguousRow;
}
// Set our starting row based on whether we're in contiguous mode or not
$currentRow = 1;
if ($this->_contiguous) {
$currentRow = ($this->_contiguousRow == -1) ? $sheet->getHighestRow(): $this->_contiguousRow;
}
// Loop through each line of the file in turn
while (($rowData = fgetcsv($fileHandle, 0, $this->_delimiter, $this->_enclosure)) !== FALSE) {
$columnLetter = 'A';
foreach($rowData as $rowDatum) {
if ($rowDatum != '' && $this->_readFilter->readCell($columnLetter, $currentRow)) {
// Unescape enclosures
$rowDatum = str_replace($escapeEnclosures, $this->_enclosure, $rowDatum);
// Loop through each line of the file in turn
while (($rowData = fgetcsv($fileHandle, 0, $this->_delimiter, $this->_enclosure)) !== false) {
$columnLetter = 'A';
foreach($rowData as $rowDatum) {
if ($rowDatum != '' && $this->_readFilter->readCell($columnLetter, $currentRow)) {
// Unescape enclosures
$rowDatum = str_replace($escapeEnclosures, $this->_enclosure, $rowDatum);
// Convert encoding if necessary
if ($this->_inputEncoding !== 'UTF-8') {
$rowDatum = Shared_String::ConvertEncoding($rowDatum, 'UTF-8', $this->_inputEncoding);
}
// Convert encoding if necessary
if ($this->_inputEncoding !== 'UTF-8') {
$rowDatum = Shared_String::ConvertEncoding($rowDatum, 'UTF-8', $this->_inputEncoding);
}
// Set cell value
$sheet->getCell($columnLetter . $currentRow)->setValue($rowDatum);
}
++$columnLetter;
}
++$currentRow;
}
// Set cell value
$sheet->getCell($columnLetter . $currentRow)->setValue($rowDatum);
}
++$columnLetter;
}
++$currentRow;
}
// Close file
fclose($fileHandle);
// Close file
fclose($fileHandle);
if ($this->_contiguous) {
$this->_contiguousRow = $currentRow;
}
if ($this->_contiguous) {
$this->_contiguousRow = $currentRow;
}
ini_set('auto_detect_line_endings', $lineEnding);
ini_set('auto_detect_line_endings', $lineEnding);
// Return
return $objPHPExcel;
}
// Return
return $objPHPExcel;
}
/**
* Get delimiter
*
* @return string
*/
public function getDelimiter() {
return $this->_delimiter;
}
/**
* Get delimiter
*
* @return string
*/
public function getDelimiter() {
return $this->_delimiter;
}
/**
* Set delimiter
*
* @param string $pValue Delimiter, defaults to ,
* @return PHPExcel\Reader_CSV
*/
public function setDelimiter($pValue = ',') {
$this->_delimiter = $pValue;
return $this;
}
/**
* Set delimiter
*
* @param string $pValue Delimiter, defaults to ,
* @return PHPExcel\Reader_CSV
*/
public function setDelimiter($pValue = ',') {
$this->_delimiter = $pValue;
return $this;
}
/**
* Get enclosure
*
* @return string
*/
public function getEnclosure() {
return $this->_enclosure;
}
/**
* Get enclosure
*
* @return string
*/
public function getEnclosure() {
return $this->_enclosure;
}
/**
* Set enclosure
*
* @param string $pValue Enclosure, defaults to "
* @return PHPExcel\Reader_CSV
*/
public function setEnclosure($pValue = '"') {
if ($pValue == '') {
$pValue = '"';
}
$this->_enclosure = $pValue;
return $this;
}
/**
* Set enclosure
*
* @param string $pValue Enclosure, defaults to "
* @return PHPExcel\Reader_CSV
*/
public function setEnclosure($pValue = '"') {
if ($pValue == '') {
$pValue = '"';
}
$this->_enclosure = $pValue;
return $this;
}
/**
* Get line ending
*
* @return string
*/
public function getLineEnding() {
return $this->_lineEnding;
}
/**
* Get line ending
*
* @return string
*/
public function getLineEnding() {
return $this->_lineEnding;
}
/**
* Set line ending
*
* @param string $pValue Line ending, defaults to OS line ending (PHP_EOL)
* @return PHPExcel\Reader_CSV
*/
public function setLineEnding($pValue = PHP_EOL) {
$this->_lineEnding = $pValue;
return $this;
}
/**
* Set line ending
*
* @param string $pValue Line ending, defaults to OS line ending (PHP_EOL)
* @return PHPExcel\Reader_CSV
*/
public function setLineEnding($pValue = PHP_EOL) {
$this->_lineEnding = $pValue;
return $this;
}
/**
* Get sheet index
*
* @return integer
*/
public function getSheetIndex() {
return $this->_sheetIndex;
}
/**
* Get sheet index
*
* @return integer
*/
public function getSheetIndex() {
return $this->_sheetIndex;
}
/**
* Set sheet index
*
* @param integer $pValue Sheet index
* @return PHPExcel\Reader_CSV
*/
public function setSheetIndex($pValue = 0) {
$this->_sheetIndex = $pValue;
return $this;
}
/**
* Set sheet index
*
* @param integer $pValue Sheet index
* @return PHPExcel\Reader_CSV
*/
public function setSheetIndex($pValue = 0) {
$this->_sheetIndex = $pValue;
return $this;
}
/**
* Set Contiguous
*
* @param boolean $contiguous
*/
public function setContiguous($contiguous = FALSE)
{
$this->_contiguous = (bool) $contiguous;
if (!$contiguous) {
$this->_contiguousRow = -1;
}
/**
* Set Contiguous
*
* @param boolean $contiguous
*/
public function setContiguous($contiguous = false)
{
$this->_contiguous = (bool) $contiguous;
if (!$contiguous) {
$this->_contiguousRow = -1;
}
return $this;
}
/**
* Get Contiguous
*
* @return boolean
*/
public function getContiguous() {
return $this->_contiguous;
}
return $this;
}
/**
* Get Contiguous
*
* @return boolean
*/
public function getContiguous() {
return $this->_contiguous;
}
}

View File

@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\Reader
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@ -37,15 +37,15 @@ namespace PHPExcel;
*/
class Reader_DefaultReadFilter implements Reader_IReadFilter
{
/**
* Should this cell be read?
*
* @param $column String column index
* @param $row Row index
* @param $worksheetName Optional worksheet name
* @return boolean
*/
public function readCell($column, $row, $worksheetName = '') {
return true;
}
/**
* Should this cell be read?
*
* @param $column String column index
* @param $row Row index
* @param $worksheetName Optional worksheet name
* @return boolean
*/
public function readCell($column, $row, $worksheetName = '') {
return true;
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -18,11 +18,11 @@
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category PHPExcel
* @package PHPExcel\Reader_Excel2007
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
* @category PHPExcel
* @package PHPExcel\Reader_Excel2007
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@ -31,490 +31,489 @@ namespace PHPExcel;
/**
* PHPExcel\Reader_Excel2007_Chart
*
* @category PHPExcel
* @package PHPExcel\Reader_Excel2007
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @category PHPExcel
* @package PHPExcel\Reader_Excel2007
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
*/
class Reader_Excel2007_Chart
{
private static function _getAttribute($component, $name, $format) {
$attributes = $component->attributes();
if (isset($attributes[$name])) {
if ($format == 'string') {
return (string) $attributes[$name];
} elseif ($format == 'integer') {
return (integer) $attributes[$name];
} elseif ($format == 'boolean') {
return (boolean) ($attributes[$name] === '0' || $attributes[$name] !== 'true') ? false : true;
} else {
return (float) $attributes[$name];
}
}
return null;
} // function _getAttribute()
private static function _getAttribute($component, $name, $format) {
$attributes = $component->attributes();
if (isset($attributes[$name])) {
if ($format == 'string') {
return (string) $attributes[$name];
} elseif ($format == 'integer') {
return (integer) $attributes[$name];
} elseif ($format == 'boolean') {
return (boolean) ($attributes[$name] === '0' || $attributes[$name] !== 'true') ? false : true;
} else {
return (float) $attributes[$name];
}
}
return null;
} // function _getAttribute()
private static function _readColor($color,$background=false) {
if (isset($color["rgb"])) {
return (string)$color["rgb"];
} else if (isset($color["indexed"])) {
return Style_Color::indexedColor($color["indexed"]-7,$background)->getARGB();
}
}
private static function _readColor($color,$background=false) {
if (isset($color["rgb"])) {
return (string)$color["rgb"];
} else if (isset($color["indexed"])) {
return Style_Color::indexedColor($color["indexed"]-7,$background)->getARGB();
}
}
public static function readChart($chartElements,$chartName) {
$namespacesChartMeta = $chartElements->getNamespaces(true);
$chartElementsC = $chartElements->children($namespacesChartMeta['c']);
public static function readChart($chartElements,$chartName) {
$namespacesChartMeta = $chartElements->getNamespaces(true);
$chartElementsC = $chartElements->children($namespacesChartMeta['c']);
$XaxisLabel = $YaxisLabel = $legend = $title = NULL;
$dispBlanksAs = $plotVisOnly = NULL;
$XaxisLabel = $YaxisLabel = $legend = $title = null;
$dispBlanksAs = $plotVisOnly = null;
foreach($chartElementsC as $chartElementKey => $chartElement) {
switch ($chartElementKey) {
case "chart":
foreach($chartElement as $chartDetailsKey => $chartDetails) {
$chartDetailsC = $chartDetails->children($namespacesChartMeta['c']);
switch ($chartDetailsKey) {
case "plotArea":
$plotAreaLayout = $XaxisLable = $YaxisLable = null;
$plotSeries = $plotAttributes = array();
foreach($chartDetails as $chartDetailKey => $chartDetail) {
switch ($chartDetailKey) {
case "layout":
$plotAreaLayout = self::_chartLayoutDetails($chartDetail,$namespacesChartMeta,'plotArea');
break;
case "catAx":
if (isset($chartDetail->title)) {
$XaxisLabel = self::_chartTitle($chartDetail->title->children($namespacesChartMeta['c']),$namespacesChartMeta,'cat');
}
break;
case "dateAx":
if (isset($chartDetail->title)) {
$XaxisLabel = self::_chartTitle($chartDetail->title->children($namespacesChartMeta['c']),$namespacesChartMeta,'cat');
}
break;
case "valAx":
if (isset($chartDetail->title)) {
$YaxisLabel = self::_chartTitle($chartDetail->title->children($namespacesChartMeta['c']),$namespacesChartMeta,'cat');
}
break;
case "barChart":
case "bar3DChart":
$barDirection = self::_getAttribute($chartDetail->barDir, 'val', 'string');
$plotSer = self::_chartDataSeries($chartDetail,$namespacesChartMeta,$chartDetailKey);
$plotSer->setPlotDirection($barDirection);
$plotSeries[] = $plotSer;
$plotAttributes = self::_readChartAttributes($chartDetail);
break;
case "lineChart":
case "line3DChart":
$plotSeries[] = self::_chartDataSeries($chartDetail,$namespacesChartMeta,$chartDetailKey);
$plotAttributes = self::_readChartAttributes($chartDetail);
break;
case "areaChart":
case "area3DChart":
$plotSeries[] = self::_chartDataSeries($chartDetail,$namespacesChartMeta,$chartDetailKey);
$plotAttributes = self::_readChartAttributes($chartDetail);
break;
case "doughnutChart":
case "pieChart":
case "pie3DChart":
$explosion = isset($chartDetail->ser->explosion);
$plotSer = self::_chartDataSeries($chartDetail,$namespacesChartMeta,$chartDetailKey);
$plotSer->setPlotStyle($explosion);
$plotSeries[] = $plotSer;
$plotAttributes = self::_readChartAttributes($chartDetail);
break;
case "scatterChart":
$scatterStyle = self::_getAttribute($chartDetail->scatterStyle, 'val', 'string');
$plotSer = self::_chartDataSeries($chartDetail,$namespacesChartMeta,$chartDetailKey);
$plotSer->setPlotStyle($scatterStyle);
$plotSeries[] = $plotSer;
$plotAttributes = self::_readChartAttributes($chartDetail);
break;
case "bubbleChart":
$bubbleScale = self::_getAttribute($chartDetail->bubbleScale, 'val', 'integer');
$plotSer = self::_chartDataSeries($chartDetail,$namespacesChartMeta,$chartDetailKey);
$plotSer->setPlotStyle($bubbleScale);
$plotSeries[] = $plotSer;
$plotAttributes = self::_readChartAttributes($chartDetail);
break;
case "radarChart":
$radarStyle = self::_getAttribute($chartDetail->radarStyle, 'val', 'string');
$plotSer = self::_chartDataSeries($chartDetail,$namespacesChartMeta,$chartDetailKey);
$plotSer->setPlotStyle($radarStyle);
$plotSeries[] = $plotSer;
$plotAttributes = self::_readChartAttributes($chartDetail);
break;
case "surfaceChart":
case "surface3DChart":
$wireFrame = self::_getAttribute($chartDetail->wireframe, 'val', 'boolean');
$plotSer = self::_chartDataSeries($chartDetail,$namespacesChartMeta,$chartDetailKey);
$plotSer->setPlotStyle($wireFrame);
$plotSeries[] = $plotSer;
$plotAttributes = self::_readChartAttributes($chartDetail);
break;
case "stockChart":
$plotSeries[] = self::_chartDataSeries($chartDetail,$namespacesChartMeta,$chartDetailKey);
$plotAttributes = self::_readChartAttributes($plotAreaLayout);
break;
}
}
if ($plotAreaLayout == NULL) {
$plotAreaLayout = new Chart_Layout();
}
$plotArea = new Chart_PlotArea($plotAreaLayout,$plotSeries);
self::_setChartAttributes($plotAreaLayout,$plotAttributes);
break;
case "plotVisOnly":
$plotVisOnly = self::_getAttribute($chartDetails, 'val', 'string');
break;
case "dispBlanksAs":
$dispBlanksAs = self::_getAttribute($chartDetails, 'val', 'string');
break;
case "title":
$title = self::_chartTitle($chartDetails,$namespacesChartMeta,'title');
break;
case "legend":
$legendPos = 'r';
$legendLayout = null;
$legendOverlay = false;
foreach($chartDetails as $chartDetailKey => $chartDetail) {
switch ($chartDetailKey) {
case "legendPos":
$legendPos = self::_getAttribute($chartDetail, 'val', 'string');
break;
case "overlay":
$legendOverlay = self::_getAttribute($chartDetail, 'val', 'boolean');
break;
case "layout":
$legendLayout = self::_chartLayoutDetails($chartDetail,$namespacesChartMeta,'legend');
break;
}
}
$legend = new Chart_Legend($legendPos, $legendLayout, $legendOverlay);
break;
}
}
}
}
$chart = new Chart($chartName,$title,$legend,$plotArea,$plotVisOnly,$dispBlanksAs,$XaxisLabel,$YaxisLabel);
foreach($chartElementsC as $chartElementKey => $chartElement) {
switch ($chartElementKey) {
case "chart":
foreach($chartElement as $chartDetailsKey => $chartDetails) {
$chartDetailsC = $chartDetails->children($namespacesChartMeta['c']);
switch ($chartDetailsKey) {
case "plotArea":
$plotAreaLayout = $XaxisLable = $YaxisLable = null;
$plotSeries = $plotAttributes = array();
foreach($chartDetails as $chartDetailKey => $chartDetail) {
switch ($chartDetailKey) {
case "layout":
$plotAreaLayout = self::_chartLayoutDetails($chartDetail,$namespacesChartMeta,'plotArea');
break;
case "catAx":
if (isset($chartDetail->title)) {
$XaxisLabel = self::_chartTitle($chartDetail->title->children($namespacesChartMeta['c']),$namespacesChartMeta,'cat');
}
break;
case "dateAx":
if (isset($chartDetail->title)) {
$XaxisLabel = self::_chartTitle($chartDetail->title->children($namespacesChartMeta['c']),$namespacesChartMeta,'cat');
}
break;
case "valAx":
if (isset($chartDetail->title)) {
$YaxisLabel = self::_chartTitle($chartDetail->title->children($namespacesChartMeta['c']),$namespacesChartMeta,'cat');
}
break;
case "barChart":
case "bar3DChart":
$barDirection = self::_getAttribute($chartDetail->barDir, 'val', 'string');
$plotSer = self::_chartDataSeries($chartDetail,$namespacesChartMeta,$chartDetailKey);
$plotSer->setPlotDirection($barDirection);
$plotSeries[] = $plotSer;
$plotAttributes = self::_readChartAttributes($chartDetail);
break;
case "lineChart":
case "line3DChart":
$plotSeries[] = self::_chartDataSeries($chartDetail,$namespacesChartMeta,$chartDetailKey);
$plotAttributes = self::_readChartAttributes($chartDetail);
break;
case "areaChart":
case "area3DChart":
$plotSeries[] = self::_chartDataSeries($chartDetail,$namespacesChartMeta,$chartDetailKey);
$plotAttributes = self::_readChartAttributes($chartDetail);
break;
case "doughnutChart":
case "pieChart":
case "pie3DChart":
$explosion = isset($chartDetail->ser->explosion);
$plotSer = self::_chartDataSeries($chartDetail,$namespacesChartMeta,$chartDetailKey);
$plotSer->setPlotStyle($explosion);
$plotSeries[] = $plotSer;
$plotAttributes = self::_readChartAttributes($chartDetail);
break;
case "scatterChart":
$scatterStyle = self::_getAttribute($chartDetail->scatterStyle, 'val', 'string');
$plotSer = self::_chartDataSeries($chartDetail,$namespacesChartMeta,$chartDetailKey);
$plotSer->setPlotStyle($scatterStyle);
$plotSeries[] = $plotSer;
$plotAttributes = self::_readChartAttributes($chartDetail);
break;
case "bubbleChart":
$bubbleScale = self::_getAttribute($chartDetail->bubbleScale, 'val', 'integer');
$plotSer = self::_chartDataSeries($chartDetail,$namespacesChartMeta,$chartDetailKey);
$plotSer->setPlotStyle($bubbleScale);
$plotSeries[] = $plotSer;
$plotAttributes = self::_readChartAttributes($chartDetail);
break;
case "radarChart":
$radarStyle = self::_getAttribute($chartDetail->radarStyle, 'val', 'string');
$plotSer = self::_chartDataSeries($chartDetail,$namespacesChartMeta,$chartDetailKey);
$plotSer->setPlotStyle($radarStyle);
$plotSeries[] = $plotSer;
$plotAttributes = self::_readChartAttributes($chartDetail);
break;
case "surfaceChart":
case "surface3DChart":
$wireFrame = self::_getAttribute($chartDetail->wireframe, 'val', 'boolean');
$plotSer = self::_chartDataSeries($chartDetail,$namespacesChartMeta,$chartDetailKey);
$plotSer->setPlotStyle($wireFrame);
$plotSeries[] = $plotSer;
$plotAttributes = self::_readChartAttributes($chartDetail);
break;
case "stockChart":
$plotSeries[] = self::_chartDataSeries($chartDetail,$namespacesChartMeta,$chartDetailKey);
$plotAttributes = self::_readChartAttributes($plotAreaLayout);
break;
}
}
if ($plotAreaLayout == null) {
$plotAreaLayout = new Chart_Layout();
}
$plotArea = new Chart_PlotArea($plotAreaLayout,$plotSeries);
self::_setChartAttributes($plotAreaLayout,$plotAttributes);
break;
case "plotVisOnly":
$plotVisOnly = self::_getAttribute($chartDetails, 'val', 'string');
break;
case "dispBlanksAs":
$dispBlanksAs = self::_getAttribute($chartDetails, 'val', 'string');
break;
case "title":
$title = self::_chartTitle($chartDetails,$namespacesChartMeta,'title');
break;
case "legend":
$legendPos = 'r';
$legendLayout = null;
$legendOverlay = false;
foreach($chartDetails as $chartDetailKey => $chartDetail) {
switch ($chartDetailKey) {
case "legendPos":
$legendPos = self::_getAttribute($chartDetail, 'val', 'string');
break;
case "overlay":
$legendOverlay = self::_getAttribute($chartDetail, 'val', 'boolean');
break;
case "layout":
$legendLayout = self::_chartLayoutDetails($chartDetail,$namespacesChartMeta,'legend');
break;
}
}
$legend = new Chart_Legend($legendPos, $legendLayout, $legendOverlay);
break;
}
}
}
}
$chart = new Chart($chartName,$title,$legend,$plotArea,$plotVisOnly,$dispBlanksAs,$XaxisLabel,$YaxisLabel);
return $chart;
} // function readChart()
return $chart;
} // function readChart()
private static function _chartTitle($titleDetails,$namespacesChartMeta,$type) {
$caption = array();
$titleLayout = null;
foreach($titleDetails as $titleDetailKey => $chartDetail) {
switch ($titleDetailKey) {
case "tx":
$titleDetails = $chartDetail->rich->children($namespacesChartMeta['a']);
foreach($titleDetails as $titleKey => $titleDetail) {
switch ($titleKey) {
case "p":
$titleDetailPart = $titleDetail->children($namespacesChartMeta['a']);
$caption[] = self::_parseRichText($titleDetailPart);
}
}
break;
case "layout":
$titleLayout = self::_chartLayoutDetails($chartDetail,$namespacesChartMeta);
break;
}
}
private static function _chartTitle($titleDetails,$namespacesChartMeta,$type) {
$caption = array();
$titleLayout = null;
foreach($titleDetails as $titleDetailKey => $chartDetail) {
switch ($titleDetailKey) {
case "tx":
$titleDetails = $chartDetail->rich->children($namespacesChartMeta['a']);
foreach($titleDetails as $titleKey => $titleDetail) {
switch ($titleKey) {
case "p":
$titleDetailPart = $titleDetail->children($namespacesChartMeta['a']);
$caption[] = self::_parseRichText($titleDetailPart);
}
}
break;
case "layout":
$titleLayout = self::_chartLayoutDetails($chartDetail,$namespacesChartMeta);
break;
}
}
return new Chart_Title($caption, $titleLayout);
} // function _chartTitle()
return new Chart_Title($caption, $titleLayout);
} // function _chartTitle()
private static function _chartLayoutDetails($chartDetail,$namespacesChartMeta) {
if (!isset($chartDetail->manualLayout)) {
return null;
}
$details = $chartDetail->manualLayout->children($namespacesChartMeta['c']);
if (is_null($details)) {
return null;
}
$layout = array();
foreach($details as $detailKey => $detail) {
// echo $detailKey,' => ',self::_getAttribute($detail, 'val', 'string'),PHP_EOL;
$layout[$detailKey] = self::_getAttribute($detail, 'val', 'string');
}
return new Chart_Layout($layout);
} // function _chartLayoutDetails()
private static function _chartLayoutDetails($chartDetail,$namespacesChartMeta) {
if (!isset($chartDetail->manualLayout)) {
return null;
}
$details = $chartDetail->manualLayout->children($namespacesChartMeta['c']);
if (is_null($details)) {
return null;
}
$layout = array();
foreach($details as $detailKey => $detail) {
// echo $detailKey,' => ',self::_getAttribute($detail, 'val', 'string'),PHP_EOL;
$layout[$detailKey] = self::_getAttribute($detail, 'val', 'string');
}
return new Chart_Layout($layout);
} // function _chartLayoutDetails()
private static function _chartDataSeries($chartDetail,$namespacesChartMeta,$plotType) {
$multiSeriesType = NULL;
$smoothLine = false;
$seriesLabel = $seriesCategory = $seriesValues = $plotOrder = array();
private static function _chartDataSeries($chartDetail,$namespacesChartMeta,$plotType) {
$multiSeriesType = null;
$smoothLine = false;
$seriesLabel = $seriesCategory = $seriesValues = $plotOrder = array();
$seriesDetailSet = $chartDetail->children($namespacesChartMeta['c']);
foreach($seriesDetailSet as $seriesDetailKey => $seriesDetails) {
switch ($seriesDetailKey) {
case "grouping":
$multiSeriesType = self::_getAttribute($chartDetail->grouping, 'val', 'string');
break;
case "ser":
$marker = NULL;
foreach($seriesDetails as $seriesKey => $seriesDetail) {
switch ($seriesKey) {
case "idx":
$seriesIndex = self::_getAttribute($seriesDetail, 'val', 'integer');
break;
case "order":
$seriesOrder = self::_getAttribute($seriesDetail, 'val', 'integer');
$plotOrder[$seriesIndex] = $seriesOrder;
break;
case "tx":
$seriesLabel[$seriesIndex] = self::_chartDataSeriesValueSet($seriesDetail,$namespacesChartMeta);
break;
case "marker":
$marker = self::_getAttribute($seriesDetail->symbol, 'val', 'string');
break;
case "smooth":
$smoothLine = self::_getAttribute($seriesDetail, 'val', 'boolean');
break;
case "cat":
$seriesCategory[$seriesIndex] = self::_chartDataSeriesValueSet($seriesDetail,$namespacesChartMeta);
break;
case "val":
$seriesValues[$seriesIndex] = self::_chartDataSeriesValueSet($seriesDetail,$namespacesChartMeta,$marker);
break;
case "xVal":
$seriesCategory[$seriesIndex] = self::_chartDataSeriesValueSet($seriesDetail,$namespacesChartMeta,$marker);
break;
case "yVal":
$seriesValues[$seriesIndex] = self::_chartDataSeriesValueSet($seriesDetail,$namespacesChartMeta,$marker);
break;
}
}
}
}
return new Chart_DataSeries($plotType,$multiSeriesType,$plotOrder,$seriesLabel,$seriesCategory,$seriesValues,$smoothLine);
} // function _chartDataSeries()
$seriesDetailSet = $chartDetail->children($namespacesChartMeta['c']);
foreach($seriesDetailSet as $seriesDetailKey => $seriesDetails) {
switch ($seriesDetailKey) {
case "grouping":
$multiSeriesType = self::_getAttribute($chartDetail->grouping, 'val', 'string');
break;
case "ser":
$marker = null;
foreach($seriesDetails as $seriesKey => $seriesDetail) {
switch ($seriesKey) {
case "idx":
$seriesIndex = self::_getAttribute($seriesDetail, 'val', 'integer');
break;
case "order":
$seriesOrder = self::_getAttribute($seriesDetail, 'val', 'integer');
$plotOrder[$seriesIndex] = $seriesOrder;
break;
case "tx":
$seriesLabel[$seriesIndex] = self::_chartDataSeriesValueSet($seriesDetail,$namespacesChartMeta);
break;
case "marker":
$marker = self::_getAttribute($seriesDetail->symbol, 'val', 'string');
break;
case "smooth":
$smoothLine = self::_getAttribute($seriesDetail, 'val', 'boolean');
break;
case "cat":
$seriesCategory[$seriesIndex] = self::_chartDataSeriesValueSet($seriesDetail,$namespacesChartMeta);
break;
case "val":
$seriesValues[$seriesIndex] = self::_chartDataSeriesValueSet($seriesDetail,$namespacesChartMeta,$marker);
break;
case "xVal":
$seriesCategory[$seriesIndex] = self::_chartDataSeriesValueSet($seriesDetail,$namespacesChartMeta,$marker);
break;
case "yVal":
$seriesValues[$seriesIndex] = self::_chartDataSeriesValueSet($seriesDetail,$namespacesChartMeta,$marker);
break;
}
}
}
}
return new Chart_DataSeries($plotType,$multiSeriesType,$plotOrder,$seriesLabel,$seriesCategory,$seriesValues,$smoothLine);
} // function _chartDataSeries()
private static function _chartDataSeriesValueSet($seriesDetail, $namespacesChartMeta, $marker = null, $smoothLine = false) {
if (isset($seriesDetail->strRef)) {
$seriesSource = (string) $seriesDetail->strRef->f;
$seriesData = self::_chartDataSeriesValues($seriesDetail->strRef->strCache->children($namespacesChartMeta['c']),'s');
private static function _chartDataSeriesValueSet($seriesDetail, $namespacesChartMeta, $marker = null, $smoothLine = false) {
if (isset($seriesDetail->strRef)) {
$seriesSource = (string) $seriesDetail->strRef->f;
$seriesData = self::_chartDataSeriesValues($seriesDetail->strRef->strCache->children($namespacesChartMeta['c']),'s');
return new Chart_DataSeriesValues('String',$seriesSource,$seriesData['formatCode'],$seriesData['pointCount'],$seriesData['dataValues'],$marker,$smoothLine);
} elseif (isset($seriesDetail->numRef)) {
$seriesSource = (string) $seriesDetail->numRef->f;
$seriesData = self::_chartDataSeriesValues($seriesDetail->numRef->numCache->children($namespacesChartMeta['c']));
return new Chart_DataSeriesValues('String',$seriesSource,$seriesData['formatCode'],$seriesData['pointCount'],$seriesData['dataValues'],$marker,$smoothLine);
} elseif (isset($seriesDetail->numRef)) {
$seriesSource = (string) $seriesDetail->numRef->f;
$seriesData = self::_chartDataSeriesValues($seriesDetail->numRef->numCache->children($namespacesChartMeta['c']));
return new Chart_DataSeriesValues('Number',$seriesSource,$seriesData['formatCode'],$seriesData['pointCount'],$seriesData['dataValues'],$marker,$smoothLine);
} elseif (isset($seriesDetail->multiLvlStrRef)) {
$seriesSource = (string) $seriesDetail->multiLvlStrRef->f;
$seriesData = self::_chartDataSeriesValuesMultiLevel($seriesDetail->multiLvlStrRef->multiLvlStrCache->children($namespacesChartMeta['c']),'s');
$seriesData['pointCount'] = count($seriesData['dataValues']);
return new Chart_DataSeriesValues('Number',$seriesSource,$seriesData['formatCode'],$seriesData['pointCount'],$seriesData['dataValues'],$marker,$smoothLine);
} elseif (isset($seriesDetail->multiLvlStrRef)) {
$seriesSource = (string) $seriesDetail->multiLvlStrRef->f;
$seriesData = self::_chartDataSeriesValuesMultiLevel($seriesDetail->multiLvlStrRef->multiLvlStrCache->children($namespacesChartMeta['c']),'s');
$seriesData['pointCount'] = count($seriesData['dataValues']);
return new Chart_DataSeriesValues('String',$seriesSource,$seriesData['formatCode'],$seriesData['pointCount'],$seriesData['dataValues'],$marker,$smoothLine);
} elseif (isset($seriesDetail->multiLvlNumRef)) {
$seriesSource = (string) $seriesDetail->multiLvlNumRef->f;
$seriesData = self::_chartDataSeriesValuesMultiLevel($seriesDetail->multiLvlNumRef->multiLvlNumCache->children($namespacesChartMeta['c']),'s');
$seriesData['pointCount'] = count($seriesData['dataValues']);
return new Chart_DataSeriesValues('String',$seriesSource,$seriesData['formatCode'],$seriesData['pointCount'],$seriesData['dataValues'],$marker,$smoothLine);
} elseif (isset($seriesDetail->multiLvlNumRef)) {
$seriesSource = (string) $seriesDetail->multiLvlNumRef->f;
$seriesData = self::_chartDataSeriesValuesMultiLevel($seriesDetail->multiLvlNumRef->multiLvlNumCache->children($namespacesChartMeta['c']),'s');
$seriesData['pointCount'] = count($seriesData['dataValues']);
return new Chart_DataSeriesValues('String',$seriesSource,$seriesData['formatCode'],$seriesData['pointCount'],$seriesData['dataValues'],$marker,$smoothLine);
}
return null;
} // function _chartDataSeriesValueSet()
return new Chart_DataSeriesValues('String',$seriesSource,$seriesData['formatCode'],$seriesData['pointCount'],$seriesData['dataValues'],$marker,$smoothLine);
}
return null;
} // function _chartDataSeriesValueSet()
private static function _chartDataSeriesValues($seriesValueSet,$dataType='n') {
$seriesVal = array();
$formatCode = '';
$pointCount = 0;
private static function _chartDataSeriesValues($seriesValueSet,$dataType='n') {
$seriesVal = array();
$formatCode = '';
$pointCount = 0;
foreach($seriesValueSet as $seriesValueIdx => $seriesValue) {
switch ($seriesValueIdx) {
case 'ptCount':
$pointCount = self::_getAttribute($seriesValue, 'val', 'integer');
break;
case 'formatCode':
$formatCode = (string) $seriesValue;
break;
case 'pt':
$pointVal = self::_getAttribute($seriesValue, 'idx', 'integer');
if ($dataType == 's') {
$seriesVal[$pointVal] = (string) $seriesValue->v;
} else {
$seriesVal[$pointVal] = (float) $seriesValue->v;
}
break;
}
}
foreach($seriesValueSet as $seriesValueIdx => $seriesValue) {
switch ($seriesValueIdx) {
case 'ptCount':
$pointCount = self::_getAttribute($seriesValue, 'val', 'integer');
break;
case 'formatCode':
$formatCode = (string) $seriesValue;
break;
case 'pt':
$pointVal = self::_getAttribute($seriesValue, 'idx', 'integer');
if ($dataType == 's') {
$seriesVal[$pointVal] = (string) $seriesValue->v;
} else {
$seriesVal[$pointVal] = (float) $seriesValue->v;
}
break;
}
}
if (empty($seriesVal)) {
$seriesVal = NULL;
}
if (empty($seriesVal)) {
$seriesVal = null;
}
return array( 'formatCode' => $formatCode,
'pointCount' => $pointCount,
'dataValues' => $seriesVal
);
} // function _chartDataSeriesValues()
return array( 'formatCode' => $formatCode,
'pointCount' => $pointCount,
'dataValues' => $seriesVal
);
} // function _chartDataSeriesValues()
private static function _chartDataSeriesValuesMultiLevel($seriesValueSet,$dataType='n') {
$seriesVal = array();
$formatCode = '';
$pointCount = 0;
private static function _chartDataSeriesValuesMultiLevel($seriesValueSet,$dataType='n') {
$seriesVal = array();
$formatCode = '';
$pointCount = 0;
foreach($seriesValueSet->lvl as $seriesLevelIdx => $seriesLevel) {
foreach($seriesLevel as $seriesValueIdx => $seriesValue) {
switch ($seriesValueIdx) {
case 'ptCount':
$pointCount = self::_getAttribute($seriesValue, 'val', 'integer');
break;
case 'formatCode':
$formatCode = (string) $seriesValue;
break;
case 'pt':
$pointVal = self::_getAttribute($seriesValue, 'idx', 'integer');
if ($dataType == 's') {
$seriesVal[$pointVal][] = (string) $seriesValue->v;
} else {
$seriesVal[$pointVal][] = (float) $seriesValue->v;
}
break;
}
}
}
foreach($seriesValueSet->lvl as $seriesLevelIdx => $seriesLevel) {
foreach($seriesLevel as $seriesValueIdx => $seriesValue) {
switch ($seriesValueIdx) {
case 'ptCount':
$pointCount = self::_getAttribute($seriesValue, 'val', 'integer');
break;
case 'formatCode':
$formatCode = (string) $seriesValue;
break;
case 'pt':
$pointVal = self::_getAttribute($seriesValue, 'idx', 'integer');
if ($dataType == 's') {
$seriesVal[$pointVal][] = (string) $seriesValue->v;
} else {
$seriesVal[$pointVal][] = (float) $seriesValue->v;
}
break;
}
}
}
return array( 'formatCode' => $formatCode,
'pointCount' => $pointCount,
'dataValues' => $seriesVal
);
} // function _chartDataSeriesValuesMultiLevel()
return array( 'formatCode' => $formatCode,
'pointCount' => $pointCount,
'dataValues' => $seriesVal
);
} // function _chartDataSeriesValuesMultiLevel()
private static function _parseRichText($titleDetailPart = null) {
$value = new RichText();
private static function _parseRichText($titleDetailPart = null) {
$value = new RichText();
foreach($titleDetailPart as $titleDetailElementKey => $titleDetailElement) {
if (isset($titleDetailElement->t)) {
$objText = $value->createTextRun( (string) $titleDetailElement->t );
}
if (isset($titleDetailElement->rPr)) {
if (isset($titleDetailElement->rPr->rFont["val"])) {
$objText->getFont()->setName((string) $titleDetailElement->rPr->rFont["val"]);
}
foreach($titleDetailPart as $titleDetailElementKey => $titleDetailElement) {
if (isset($titleDetailElement->t)) {
$objText = $value->createTextRun( (string) $titleDetailElement->t );
}
if (isset($titleDetailElement->rPr)) {
if (isset($titleDetailElement->rPr->rFont["val"])) {
$objText->getFont()->setName((string) $titleDetailElement->rPr->rFont["val"]);
}
$fontSize = (self::_getAttribute($titleDetailElement->rPr, 'sz', 'integer'));
if (!is_null($fontSize)) {
$objText->getFont()->setSize(floor($fontSize / 100));
}
$fontSize = (self::_getAttribute($titleDetailElement->rPr, 'sz', 'integer'));
if (!is_null($fontSize)) {
$objText->getFont()->setSize(floor($fontSize / 100));
}
$fontColor = (self::_getAttribute($titleDetailElement->rPr, 'color', 'string'));
if (!is_null($fontColor)) {
$objText->getFont()->setColor( new Style_Color( self::_readColor($fontColor) ) );
}
$fontColor = (self::_getAttribute($titleDetailElement->rPr, 'color', 'string'));
if (!is_null($fontColor)) {
$objText->getFont()->setColor( new Style_Color( self::_readColor($fontColor) ) );
}
$bold = self::_getAttribute($titleDetailElement->rPr, 'b', 'boolean');
if (!is_null($bold)) {
$objText->getFont()->setBold($bold);
}
$bold = self::_getAttribute($titleDetailElement->rPr, 'b', 'boolean');
if (!is_null($bold)) {
$objText->getFont()->setBold($bold);
}
$italic = self::_getAttribute($titleDetailElement->rPr, 'i', 'boolean');
if (!is_null($italic)) {
$objText->getFont()->setItalic($italic);
}
$italic = self::_getAttribute($titleDetailElement->rPr, 'i', 'boolean');
if (!is_null($italic)) {
$objText->getFont()->setItalic($italic);
}
$baseline = self::_getAttribute($titleDetailElement->rPr, 'baseline', 'integer');
if (!is_null($baseline)) {
if ($baseline > 0) {
$objText->getFont()->setSuperScript(true);
} elseif($baseline < 0) {
$objText->getFont()->setSubScript(true);
}
}
$baseline = self::_getAttribute($titleDetailElement->rPr, 'baseline', 'integer');
if (!is_null($baseline)) {
if ($baseline > 0) {
$objText->getFont()->setSuperScript(true);
} elseif($baseline < 0) {
$objText->getFont()->setSubScript(true);
}
}
$underscore = (self::_getAttribute($titleDetailElement->rPr, 'u', 'string'));
if (!is_null($underscore)) {
if ($underscore == 'sng') {
$objText->getFont()->setUnderline(Style_Font::UNDERLINE_SINGLE);
} elseif($underscore == 'dbl') {
$objText->getFont()->setUnderline(Style_Font::UNDERLINE_DOUBLE);
} else {
$objText->getFont()->setUnderline(Style_Font::UNDERLINE_NONE);
}
}
$underscore = (self::_getAttribute($titleDetailElement->rPr, 'u', 'string'));
if (!is_null($underscore)) {
if ($underscore == 'sng') {
$objText->getFont()->setUnderline(Style_Font::UNDERLINE_SINGLE);
} elseif($underscore == 'dbl') {
$objText->getFont()->setUnderline(Style_Font::UNDERLINE_DOUBLE);
} else {
$objText->getFont()->setUnderline(Style_Font::UNDERLINE_NONE);
}
}
$strikethrough = (self::_getAttribute($titleDetailElement->rPr, 's', 'string'));
if (!is_null($strikethrough)) {
if ($strikethrough == 'noStrike') {
$objText->getFont()->setStrikethrough(false);
} else {
$objText->getFont()->setStrikethrough(true);
}
}
}
}
$strikethrough = (self::_getAttribute($titleDetailElement->rPr, 's', 'string'));
if (!is_null($strikethrough)) {
if ($strikethrough == 'noStrike') {
$objText->getFont()->setStrikethrough(false);
} else {
$objText->getFont()->setStrikethrough(true);
}
}
}
}
return $value;
}
return $value;
}
private static function _readChartAttributes($chartDetail) {
$plotAttributes = array();
if (isset($chartDetail->dLbls)) {
if (isset($chartDetail->dLbls->howLegendKey)) {
$plotAttributes['showLegendKey'] = self::_getAttribute($chartDetail->dLbls->showLegendKey, 'val', 'string');
}
if (isset($chartDetail->dLbls->showVal)) {
$plotAttributes['showVal'] = self::_getAttribute($chartDetail->dLbls->showVal, 'val', 'string');
}
if (isset($chartDetail->dLbls->showCatName)) {
$plotAttributes['showCatName'] = self::_getAttribute($chartDetail->dLbls->showCatName, 'val', 'string');
}
if (isset($chartDetail->dLbls->showSerName)) {
$plotAttributes['showSerName'] = self::_getAttribute($chartDetail->dLbls->showSerName, 'val', 'string');
}
if (isset($chartDetail->dLbls->showPercent)) {
$plotAttributes['showPercent'] = self::_getAttribute($chartDetail->dLbls->showPercent, 'val', 'string');
}
if (isset($chartDetail->dLbls->showBubbleSize)) {
$plotAttributes['showBubbleSize'] = self::_getAttribute($chartDetail->dLbls->showBubbleSize, 'val', 'string');
}
if (isset($chartDetail->dLbls->showLeaderLines)) {
$plotAttributes['showLeaderLines'] = self::_getAttribute($chartDetail->dLbls->showLeaderLines, 'val', 'string');
}
}
private static function _readChartAttributes($chartDetail) {
$plotAttributes = array();
if (isset($chartDetail->dLbls)) {
if (isset($chartDetail->dLbls->howLegendKey)) {
$plotAttributes['showLegendKey'] = self::_getAttribute($chartDetail->dLbls->showLegendKey, 'val', 'string');
}
if (isset($chartDetail->dLbls->showVal)) {
$plotAttributes['showVal'] = self::_getAttribute($chartDetail->dLbls->showVal, 'val', 'string');
}
if (isset($chartDetail->dLbls->showCatName)) {
$plotAttributes['showCatName'] = self::_getAttribute($chartDetail->dLbls->showCatName, 'val', 'string');
}
if (isset($chartDetail->dLbls->showSerName)) {
$plotAttributes['showSerName'] = self::_getAttribute($chartDetail->dLbls->showSerName, 'val', 'string');
}
if (isset($chartDetail->dLbls->showPercent)) {
$plotAttributes['showPercent'] = self::_getAttribute($chartDetail->dLbls->showPercent, 'val', 'string');
}
if (isset($chartDetail->dLbls->showBubbleSize)) {
$plotAttributes['showBubbleSize'] = self::_getAttribute($chartDetail->dLbls->showBubbleSize, 'val', 'string');
}
if (isset($chartDetail->dLbls->showLeaderLines)) {
$plotAttributes['showLeaderLines'] = self::_getAttribute($chartDetail->dLbls->showLeaderLines, 'val', 'string');
}
}
return $plotAttributes;
}
private static function _setChartAttributes($plotArea,$plotAttributes)
{
foreach($plotAttributes as $plotAttributeKey => $plotAttributeValue) {
switch($plotAttributeKey) {
case 'showLegendKey' :
$plotArea->setShowLegendKey($plotAttributeValue);
break;
case 'showVal' :
$plotArea->setShowVal($plotAttributeValue);
break;
case 'showCatName' :
$plotArea->setShowCatName($plotAttributeValue);
break;
case 'showSerName' :
$plotArea->setShowSerName($plotAttributeValue);
break;
case 'showPercent' :
$plotArea->setShowPercent($plotAttributeValue);
break;
case 'showBubbleSize' :
$plotArea->setShowBubbleSize($plotAttributeValue);
break;
case 'showLeaderLines' :
$plotArea->setShowLeaderLines($plotAttributeValue);
break;
}
}
}
return $plotAttributes;
}
private static function _setChartAttributes($plotArea,$plotAttributes)
{
foreach($plotAttributes as $plotAttributeKey => $plotAttributeValue) {
switch($plotAttributeKey) {
case 'showLegendKey' :
$plotArea->setShowLegendKey($plotAttributeValue);
break;
case 'showVal' :
$plotArea->setShowVal($plotAttributeValue);
break;
case 'showCatName' :
$plotArea->setShowCatName($plotAttributeValue);
break;
case 'showSerName' :
$plotArea->setShowSerName($plotAttributeValue);
break;
case 'showPercent' :
$plotArea->setShowPercent($plotAttributeValue);
break;
case 'showBubbleSize' :
$plotArea->setShowBubbleSize($plotAttributeValue);
break;
case 'showLeaderLines' :
$plotArea->setShowLeaderLines($plotAttributeValue);
break;
}
}
}
}

View File

@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\Reader_Excel2007
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@ -37,57 +37,57 @@ namespace PHPExcel;
*/
class Reader_Excel2007_Theme
{
/**
* Theme Name
*
* @var string
*/
private $_themeName;
/**
* Theme Name
*
* @var string
*/
private $_themeName;
/**
* Colour Scheme Name
*
* @var string
*/
private $_colourSchemeName;
/**
* Colour Scheme Name
*
* @var string
*/
private $_colourSchemeName;
/**
* Colour Map indexed by position
*
* @var array of string
*/
private $_colourMapValues;
/**
* Colour Map indexed by position
*
* @var array of string
*/
private $_colourMapValues;
/**
* Colour Map
*
* @var array of string
*/
private $_colourMap;
/**
* Colour Map
*
* @var array of string
*/
private $_colourMap;
/**
* Create a new PHPExcel\Theme
*
*
*/
public function __construct($themeName,$colourSchemeName,$colourMap)
{
// Initialise values
$this->_themeName = $themeName;
$this->_colourSchemeName = $colourSchemeName;
$this->_colourMap = $colourMap;
// Initialise values
$this->_themeName = $themeName;
$this->_colourSchemeName = $colourSchemeName;
$this->_colourMap = $colourMap;
}
/**
* Get Theme Name
*
* @return string
*/
public function getThemeName()
{
return $this->_themeName;
}
/**
* Get Theme Name
*
* @return string
*/
public function getThemeName()
{
return $this->_themeName;
}
/**
* Get colour Scheme Name
@ -95,7 +95,7 @@ class Reader_Excel2007_Theme
* @return string
*/
public function getColourSchemeName() {
return $this->_colourSchemeName;
return $this->_colourSchemeName;
}
/**
@ -104,23 +104,23 @@ class Reader_Excel2007_Theme
* @return string
*/
public function getColourByIndex($index=0) {
if (isset($this->_colourMap[$index])) {
return $this->_colourMap[$index];
}
return null;
if (isset($this->_colourMap[$index])) {
return $this->_colourMap[$index];
}
return null;
}
/**
* Implement PHP __clone to create a deep clone, not just a shallow copy.
*/
public function __clone() {
$vars = get_object_vars($this);
foreach ($vars as $key => $value) {
if ((is_object($value)) && ($key != '_parent')) {
$this->$key = clone $value;
} else {
$this->$key = $value;
}
}
}
/**
* Implement PHP __clone to create a deep clone, not just a shallow copy.
*/
public function __clone() {
$vars = get_object_vars($this);
foreach ($vars as $key => $value) {
if ((is_object($value)) && ($key != '_parent')) {
$this->$key = clone $value;
} else {
$this->$key = $value;
}
}
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -21,8 +21,8 @@
* @category PHPExcel
* @package PHPExcel\Reader
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@ -36,19 +36,19 @@ namespace PHPExcel;
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
*/
class Reader_Exception extends Exception {
/**
* Error handler callback
*
* @param mixed $code
* @param mixed $string
* @param mixed $file
* @param mixed $line
* @param mixed $context
*/
public static function errorHandlerCallback($code, $string, $file, $line, $context) {
$e = new self($string, $code);
$e->line = $line;
$e->file = $file;
throw $e;
}
/**
* Error handler callback
*
* @param mixed $code
* @param mixed $string
* @param mixed $file
* @param mixed $line
* @param mixed $context
*/
public static function errorHandlerCallback($code, $string, $file, $line, $context) {
$e = new self($string, $code);
$e->line = $line;
$e->file = $file;
throw $e;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\Reader
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@ -37,425 +37,424 @@ namespace PHPExcel;
*/
class Reader_HTML extends Reader_Abstract implements Reader_IReader
{
/**
* Input encoding
*
* @var string
*/
private $_inputEncoding = 'ANSI';
/**
* Input encoding
*
* @var string
*/
private $_inputEncoding = 'ANSI';
/**
* Sheet index to read
*
* @var int
*/
private $_sheetIndex = 0;
/**
* Sheet index to read
*
* @var int
*/
private $_sheetIndex = 0;
/**
* Formats
*
* @var array
*/
private $_formats = array( 'h1' => array( 'font' => array( 'bold' => true,
'size' => 24,
),
), // Bold, 24pt
'h2' => array( 'font' => array( 'bold' => true,
'size' => 18,
),
), // Bold, 18pt
'h3' => array( 'font' => array( 'bold' => true,
'size' => 13.5,
),
), // Bold, 13.5pt
'h4' => array( 'font' => array( 'bold' => true,
'size' => 12,
),
), // Bold, 12pt
'h5' => array( 'font' => array( 'bold' => true,
'size' => 10,
),
), // Bold, 10pt
'h6' => array( 'font' => array( 'bold' => true,
'size' => 7.5,
),
), // Bold, 7.5pt
'a' => array( 'font' => array( 'underline' => true,
'color' => array( 'argb' => Style_Color::COLOR_BLUE,
),
),
), // Blue underlined
'hr' => array( 'borders' => array( 'bottom' => array( 'style' => Style_Border::BORDER_THIN,
'color' => array( Style_Color::COLOR_BLACK,
),
),
),
), // Bottom border
);
/**
* Formats
*
* @var array
*/
private $_formats = array( 'h1' => array( 'font' => array( 'bold' => true,
'size' => 24,
),
), // Bold, 24pt
'h2' => array( 'font' => array( 'bold' => true,
'size' => 18,
),
), // Bold, 18pt
'h3' => array( 'font' => array( 'bold' => true,
'size' => 13.5,
),
), // Bold, 13.5pt
'h4' => array( 'font' => array( 'bold' => true,
'size' => 12,
),
), // Bold, 12pt
'h5' => array( 'font' => array( 'bold' => true,
'size' => 10,
),
), // Bold, 10pt
'h6' => array( 'font' => array( 'bold' => true,
'size' => 7.5,
),
), // Bold, 7.5pt
'a' => array( 'font' => array( 'underline' => true,
'color' => array( 'argb' => Style_Color::COLOR_BLUE,
),
),
), // Blue underlined
'hr' => array( 'borders' => array( 'bottom' => array( 'style' => Style_Border::BORDER_THIN,
'color' => array( Style_Color::COLOR_BLACK,
),
),
),
), // Bottom border
);
/**
* Create a new PHPExcel\Reader_HTML
*/
public function __construct() {
$this->_readFilter = new Reader_DefaultReadFilter();
}
/**
* Create a new PHPExcel\Reader_HTML
*/
public function __construct() {
$this->_readFilter = new Reader_DefaultReadFilter();
}
/**
* Validate that the current file is an HTML file
*
* @return boolean
*/
protected function _isValidFormat()
{
// Reading 2048 bytes should be enough to validate that the format is HTML
$data = fread($this->_fileHandle, 2048);
if ((strpos($data, '<') !== FALSE) &&
(strlen($data) !== strlen(strip_tags($data)))) {
return TRUE;
}
/**
* Validate that the current file is an HTML file
*
* @return boolean
*/
protected function _isValidFormat()
{
// Reading 2048 bytes should be enough to validate that the format is HTML
$data = fread($this->_fileHandle, 2048);
if ((strpos($data, '<') !== false) &&
(strlen($data) !== strlen(strip_tags($data)))) {
return true;
}
return FALSE;
}
return false;
}
/**
* Loads PHPExcel from file
*
* @param string $pFilename
* @return PHPExcel
* @throws PHPExcel\Reader_Exception
*/
public function load($pFilename)
{
// Create new PHPExcel Workbook
$objPHPExcel = new Workbook();
/**
* Loads PHPExcel from file
*
* @param string $pFilename
* @return PHPExcel
* @throws PHPExcel\Reader_Exception
*/
public function load($pFilename)
{
// Create new PHPExcel Workbook
$objPHPExcel = new Workbook();
// Load into this instance
return $this->loadIntoExisting($pFilename, $objPHPExcel);
}
// Load into this instance
return $this->loadIntoExisting($pFilename, $objPHPExcel);
}
/**
* Set input encoding
*
* @param string $pValue Input encoding
*/
public function setInputEncoding($pValue = 'ANSI')
{
$this->_inputEncoding = $pValue;
return $this;
}
/**
* Set input encoding
*
* @param string $pValue Input encoding
*/
public function setInputEncoding($pValue = 'ANSI')
{
$this->_inputEncoding = $pValue;
return $this;
}
/**
* Get input encoding
*
* @return string
*/
public function getInputEncoding()
{
return $this->_inputEncoding;
}
/**
* Get input encoding
*
* @return string
*/
public function getInputEncoding()
{
return $this->_inputEncoding;
}
// Data Array used for testing only, should write to PHPExcel object on completion of tests
private $_dataArray = array();
// Data Array used for testing only, should write to PHPExcel object on completion of tests
private $_dataArray = array();
private $_tableLevel = 0;
private $_nestedColumn = array('A');
private $_tableLevel = 0;
private $_nestedColumn = array('A');
private function _setTableStartColumn($column) {
if ($this->_tableLevel == 0)
$column = 'A';
++$this->_tableLevel;
$this->_nestedColumn[$this->_tableLevel] = $column;
private function _setTableStartColumn($column) {
if ($this->_tableLevel == 0)
$column = 'A';
++$this->_tableLevel;
$this->_nestedColumn[$this->_tableLevel] = $column;
return $this->_nestedColumn[$this->_tableLevel];
}
return $this->_nestedColumn[$this->_tableLevel];
}
private function _getTableStartColumn() {
return $this->_nestedColumn[$this->_tableLevel];
}
private function _getTableStartColumn() {
return $this->_nestedColumn[$this->_tableLevel];
}
private function _releaseTableStartColumn() {
--$this->_tableLevel;
return array_pop($this->_nestedColumn);
}
private function _releaseTableStartColumn() {
--$this->_tableLevel;
return array_pop($this->_nestedColumn);
}
private function _flushCell($sheet,$column,$row,&$cellContent) {
if (is_string($cellContent)) {
// Simple String content
if (trim($cellContent) > '') {
// Only actually write it if there's content in the string
// echo 'FLUSH CELL: ' , $column , $row , ' => ' , $cellContent , '<br />';
// Write to worksheet to be done here...
// ... we return the cell so we can mess about with styles more easily
$cell = $sheet->setCellValue($column.$row,$cellContent,true);
$this->_dataArray[$row][$column] = $cellContent;
}
} else {
// We have a Rich Text run
// TODO
$this->_dataArray[$row][$column] = 'RICH TEXT: ' . $cellContent;
}
$cellContent = (string) '';
}
private function _flushCell($sheet,$column,$row,&$cellContent) {
if (is_string($cellContent)) {
// Simple String content
if (trim($cellContent) > '') {
// Only actually write it if there's content in the string
// echo 'FLUSH CELL: ' , $column , $row , ' => ' , $cellContent , '<br />';
// Write to worksheet to be done here...
// ... we return the cell so we can mess about with styles more easily
$cell = $sheet->setCellValue($column.$row,$cellContent,true);
$this->_dataArray[$row][$column] = $cellContent;
}
} else {
// We have a Rich Text run
// TODO
$this->_dataArray[$row][$column] = 'RICH TEXT: ' . $cellContent;
}
$cellContent = (string) '';
}
private function _processDomElement(DOMNode $element, $sheet, &$row, &$column, &$cellContent){
foreach($element->childNodes as $child){
if ($child instanceof DOMText) {
$domText = preg_replace('/\s+/',' ',trim($child->nodeValue));
if (is_string($cellContent)) {
// simply append the text if the cell content is a plain text string
$cellContent .= $domText;
} else {
// but if we have a rich text run instead, we need to append it correctly
// TODO
}
} elseif($child instanceof DOMElement) {
// echo '<b>DOM ELEMENT: </b>' , strtoupper($child->nodeName) , '<br />';
private function _processDomElement(DOMNode $element, $sheet, &$row, &$column, &$cellContent){
foreach($element->childNodes as $child){
if ($child instanceof DOMText) {
$domText = preg_replace('/\s+/',' ',trim($child->nodeValue));
if (is_string($cellContent)) {
// simply append the text if the cell content is a plain text string
$cellContent .= $domText;
} else {
// but if we have a rich text run instead, we need to append it correctly
// TODO
}
} elseif($child instanceof DOMElement) {
// echo '<b>DOM ELEMENT: </b>' , strtoupper($child->nodeName) , '<br />';
$attributeArray = array();
foreach($child->attributes as $attribute) {
// echo '<b>ATTRIBUTE: </b>' , $attribute->name , ' => ' , $attribute->value , '<br />';
$attributeArray[$attribute->name] = $attribute->value;
}
$attributeArray = array();
foreach($child->attributes as $attribute) {
// echo '<b>ATTRIBUTE: </b>' , $attribute->name , ' => ' , $attribute->value , '<br />';
$attributeArray[$attribute->name] = $attribute->value;
}
switch($child->nodeName) {
case 'meta' :
foreach($attributeArray as $attributeName => $attributeValue) {
switch($attributeName) {
case 'content':
// TODO
// Extract character set, so we can convert to UTF-8 if required
break;
}
}
$this->_processDomElement($child,$sheet,$row,$column,$cellContent);
break;
case 'title' :
$this->_processDomElement($child,$sheet,$row,$column,$cellContent);
$sheet->setTitle($cellContent);
$cellContent = '';
break;
case 'span' :
case 'div' :
case 'font' :
case 'i' :
case 'em' :
case 'strong':
case 'b' :
// echo 'STYLING, SPAN OR DIV<br />';
if ($cellContent > '')
$cellContent .= ' ';
$this->_processDomElement($child,$sheet,$row,$column,$cellContent);
if ($cellContent > '')
$cellContent .= ' ';
// echo 'END OF STYLING, SPAN OR DIV<br />';
break;
case 'hr' :
$this->_flushCell($sheet,$column,$row,$cellContent);
++$row;
if (isset($this->_formats[$child->nodeName])) {
$sheet->getStyle($column.$row)->applyFromArray($this->_formats[$child->nodeName]);
} else {
$cellContent = '----------';
$this->_flushCell($sheet,$column,$row,$cellContent);
}
++$row;
case 'br' :
if ($this->_tableLevel > 0) {
// If we're inside a table, replace with a \n
$cellContent .= "\n";
} else {
// Otherwise flush our existing content and move the row cursor on
$this->_flushCell($sheet,$column,$row,$cellContent);
++$row;
}
// echo 'HARD LINE BREAK: ' , '<br />';
break;
case 'a' :
// echo 'START OF HYPERLINK: ' , '<br />';
foreach($attributeArray as $attributeName => $attributeValue) {
switch($attributeName) {
case 'href':
// echo 'Link to ' , $attributeValue , '<br />';
$sheet->getCell($column.$row)->getHyperlink()->setUrl($attributeValue);
if (isset($this->_formats[$child->nodeName])) {
$sheet->getStyle($column.$row)->applyFromArray($this->_formats[$child->nodeName]);
}
break;
}
}
$cellContent .= ' ';
$this->_processDomElement($child,$sheet,$row,$column,$cellContent);
// echo 'END OF HYPERLINK:' , '<br />';
break;
case 'h1' :
case 'h2' :
case 'h3' :
case 'h4' :
case 'h5' :
case 'h6' :
case 'ol' :
case 'ul' :
case 'p' :
if ($this->_tableLevel > 0) {
// If we're inside a table, replace with a \n
$cellContent .= "\n";
// echo 'LIST ENTRY: ' , '<br />';
$this->_processDomElement($child,$sheet,$row,$column,$cellContent);
// echo 'END OF LIST ENTRY:' , '<br />';
} else {
if ($cellContent > '') {
$this->_flushCell($sheet,$column,$row,$cellContent);
$row += 2;
}
// echo 'START OF PARAGRAPH: ' , '<br />';
$this->_processDomElement($child,$sheet,$row,$column,$cellContent);
// echo 'END OF PARAGRAPH:' , '<br />';
$this->_flushCell($sheet,$column,$row,$cellContent);
switch($child->nodeName) {
case 'meta' :
foreach($attributeArray as $attributeName => $attributeValue) {
switch($attributeName) {
case 'content':
// TODO
// Extract character set, so we can convert to UTF-8 if required
break;
}
}
$this->_processDomElement($child,$sheet,$row,$column,$cellContent);
break;
case 'title' :
$this->_processDomElement($child,$sheet,$row,$column,$cellContent);
$sheet->setTitle($cellContent);
$cellContent = '';
break;
case 'span' :
case 'div' :
case 'font' :
case 'i' :
case 'em' :
case 'strong':
case 'b' :
// echo 'STYLING, SPAN OR DIV<br />';
if ($cellContent > '')
$cellContent .= ' ';
$this->_processDomElement($child,$sheet,$row,$column,$cellContent);
if ($cellContent > '')
$cellContent .= ' ';
// echo 'END OF STYLING, SPAN OR DIV<br />';
break;
case 'hr' :
$this->_flushCell($sheet,$column,$row,$cellContent);
++$row;
if (isset($this->_formats[$child->nodeName])) {
$sheet->getStyle($column.$row)->applyFromArray($this->_formats[$child->nodeName]);
} else {
$cellContent = '----------';
$this->_flushCell($sheet,$column,$row,$cellContent);
}
++$row;
case 'br' :
if ($this->_tableLevel > 0) {
// If we're inside a table, replace with a \n
$cellContent .= "\n";
} else {
// Otherwise flush our existing content and move the row cursor on
$this->_flushCell($sheet,$column,$row,$cellContent);
++$row;
}
// echo 'HARD LINE BREAK: ' , '<br />';
break;
case 'a' :
// echo 'START OF HYPERLINK: ' , '<br />';
foreach($attributeArray as $attributeName => $attributeValue) {
switch($attributeName) {
case 'href':
// echo 'Link to ' , $attributeValue , '<br />';
$sheet->getCell($column.$row)->getHyperlink()->setUrl($attributeValue);
if (isset($this->_formats[$child->nodeName])) {
$sheet->getStyle($column.$row)->applyFromArray($this->_formats[$child->nodeName]);
}
break;
}
}
$cellContent .= ' ';
$this->_processDomElement($child,$sheet,$row,$column,$cellContent);
// echo 'END OF HYPERLINK:' , '<br />';
break;
case 'h1' :
case 'h2' :
case 'h3' :
case 'h4' :
case 'h5' :
case 'h6' :
case 'ol' :
case 'ul' :
case 'p' :
if ($this->_tableLevel > 0) {
// If we're inside a table, replace with a \n
$cellContent .= "\n";
// echo 'LIST ENTRY: ' , '<br />';
$this->_processDomElement($child,$sheet,$row,$column,$cellContent);
// echo 'END OF LIST ENTRY:' , '<br />';
} else {
if ($cellContent > '') {
$this->_flushCell($sheet,$column,$row,$cellContent);
$row += 2;
}
// echo 'START OF PARAGRAPH: ' , '<br />';
$this->_processDomElement($child,$sheet,$row,$column,$cellContent);
// echo 'END OF PARAGRAPH:' , '<br />';
$this->_flushCell($sheet,$column,$row,$cellContent);
if (isset($this->_formats[$child->nodeName])) {
$sheet->getStyle($column.$row)->applyFromArray($this->_formats[$child->nodeName]);
}
if (isset($this->_formats[$child->nodeName])) {
$sheet->getStyle($column.$row)->applyFromArray($this->_formats[$child->nodeName]);
}
$row += 2;
$column = 'A';
}
break;
case 'li' :
if ($this->_tableLevel > 0) {
// If we're inside a table, replace with a \n
$cellContent .= "\n";
// echo 'LIST ENTRY: ' , '<br />';
$this->_processDomElement($child,$sheet,$row,$column,$cellContent);
// echo 'END OF LIST ENTRY:' , '<br />';
} else {
if ($cellContent > '') {
$this->_flushCell($sheet,$column,$row,$cellContent);
}
++$row;
// echo 'LIST ENTRY: ' , '<br />';
$this->_processDomElement($child,$sheet,$row,$column,$cellContent);
// echo 'END OF LIST ENTRY:' , '<br />';
$this->_flushCell($sheet,$column,$row,$cellContent);
$column = 'A';
}
break;
case 'table' :
$this->_flushCell($sheet,$column,$row,$cellContent);
$column = $this->_setTableStartColumn($column);
// echo 'START OF TABLE LEVEL ' , $this->_tableLevel , '<br />';
if ($this->_tableLevel > 1)
--$row;
$this->_processDomElement($child,$sheet,$row,$column,$cellContent);
// echo 'END OF TABLE LEVEL ' , $this->_tableLevel , '<br />';
$column = $this->_releaseTableStartColumn();
if ($this->_tableLevel > 1) {
++$column;
} else {
++$row;
}
break;
case 'thead' :
case 'tbody' :
$this->_processDomElement($child,$sheet,$row,$column,$cellContent);
break;
case 'tr' :
++$row;
$column = $this->_getTableStartColumn();
$cellContent = '';
// echo 'START OF TABLE ' , $this->_tableLevel , ' ROW<br />';
$this->_processDomElement($child,$sheet,$row,$column,$cellContent);
// echo 'END OF TABLE ' , $this->_tableLevel , ' ROW<br />';
break;
case 'th' :
case 'td' :
// echo 'START OF TABLE ' , $this->_tableLevel , ' CELL<br />';
$this->_processDomElement($child,$sheet,$row,$column,$cellContent);
// echo 'END OF TABLE ' , $this->_tableLevel , ' CELL<br />';
$this->_flushCell($sheet,$column,$row,$cellContent);
++$column;
break;
case 'body' :
$row = 1;
$column = 'A';
$content = '';
$this->_tableLevel = 0;
$this->_processDomElement($child,$sheet,$row,$column,$cellContent);
break;
default:
$this->_processDomElement($child,$sheet,$row,$column,$cellContent);
}
}
}
}
$row += 2;
$column = 'A';
}
break;
case 'li' :
if ($this->_tableLevel > 0) {
// If we're inside a table, replace with a \n
$cellContent .= "\n";
// echo 'LIST ENTRY: ' , '<br />';
$this->_processDomElement($child,$sheet,$row,$column,$cellContent);
// echo 'END OF LIST ENTRY:' , '<br />';
} else {
if ($cellContent > '') {
$this->_flushCell($sheet,$column,$row,$cellContent);
}
++$row;
// echo 'LIST ENTRY: ' , '<br />';
$this->_processDomElement($child,$sheet,$row,$column,$cellContent);
// echo 'END OF LIST ENTRY:' , '<br />';
$this->_flushCell($sheet,$column,$row,$cellContent);
$column = 'A';
}
break;
case 'table' :
$this->_flushCell($sheet,$column,$row,$cellContent);
$column = $this->_setTableStartColumn($column);
// echo 'START OF TABLE LEVEL ' , $this->_tableLevel , '<br />';
if ($this->_tableLevel > 1)
--$row;
$this->_processDomElement($child,$sheet,$row,$column,$cellContent);
// echo 'END OF TABLE LEVEL ' , $this->_tableLevel , '<br />';
$column = $this->_releaseTableStartColumn();
if ($this->_tableLevel > 1) {
++$column;
} else {
++$row;
}
break;
case 'thead' :
case 'tbody' :
$this->_processDomElement($child,$sheet,$row,$column,$cellContent);
break;
case 'tr' :
++$row;
$column = $this->_getTableStartColumn();
$cellContent = '';
// echo 'START OF TABLE ' , $this->_tableLevel , ' ROW<br />';
$this->_processDomElement($child,$sheet,$row,$column,$cellContent);
// echo 'END OF TABLE ' , $this->_tableLevel , ' ROW<br />';
break;
case 'th' :
case 'td' :
// echo 'START OF TABLE ' , $this->_tableLevel , ' CELL<br />';
$this->_processDomElement($child,$sheet,$row,$column,$cellContent);
// echo 'END OF TABLE ' , $this->_tableLevel , ' CELL<br />';
$this->_flushCell($sheet,$column,$row,$cellContent);
++$column;
break;
case 'body' :
$row = 1;
$column = 'A';
$content = '';
$this->_tableLevel = 0;
$this->_processDomElement($child,$sheet,$row,$column,$cellContent);
break;
default:
$this->_processDomElement($child,$sheet,$row,$column,$cellContent);
}
}
}
}
/**
* Loads PHPExcel from file into PHPExcel instance
*
* @param string $pFilename
* @param PHPExcel $objPHPExcel
* @return PHPExcel
* @throws PHPExcel\Reader_Exception
*/
public function loadIntoExisting($pFilename, PHPExcel $objPHPExcel)
{
// Open file to validate
$this->_openFile($pFilename);
if (!$this->_isValidFormat()) {
fclose ($this->_fileHandle);
throw new Reader_Exception($pFilename . " is an Invalid HTML file.");
}
// Close after validating
fclose ($this->_fileHandle);
/**
* Loads PHPExcel from file into PHPExcel instance
*
* @param string $pFilename
* @param PHPExcel $objPHPExcel
* @return PHPExcel
* @throws PHPExcel\Reader_Exception
*/
public function loadIntoExisting($pFilename, PHPExcel $objPHPExcel)
{
// Open file to validate
$this->_openFile($pFilename);
if (!$this->_isValidFormat()) {
fclose ($this->_fileHandle);
throw new Reader_Exception($pFilename . " is an Invalid HTML file.");
}
// Close after validating
fclose ($this->_fileHandle);
// Create new PHPExcel
while ($objPHPExcel->getSheetCount() <= $this->_sheetIndex) {
$objPHPExcel->createSheet();
}
$objPHPExcel->setActiveSheetIndex( $this->_sheetIndex );
// Create new PHPExcel
while ($objPHPExcel->getSheetCount() <= $this->_sheetIndex) {
$objPHPExcel->createSheet();
}
$objPHPExcel->setActiveSheetIndex( $this->_sheetIndex );
// Create a new DOM object
$dom = new domDocument;
// Reload the HTML file into the DOM object
$loaded = $dom->loadHTMLFile($pFilename);
if ($loaded === FALSE) {
throw new Reader_Exception('Failed to load ',$pFilename,' as a DOM Document');
}
// Create a new DOM object
$dom = new domDocument;
// Reload the HTML file into the DOM object
$loaded = $dom->loadHTMLFile($pFilename);
if ($loaded === false) {
throw new Reader_Exception('Failed to load ',$pFilename,' as a DOM Document');
}
// Discard white space
$dom->preserveWhiteSpace = false;
// Discard white space
$dom->preserveWhiteSpace = false;
$row = 0;
$column = 'A';
$content = '';
$this->_processDomElement($dom,$objPHPExcel->getActiveSheet(),$row,$column,$content);
$row = 0;
$column = 'A';
$content = '';
$this->_processDomElement($dom,$objPHPExcel->getActiveSheet(),$row,$column,$content);
// echo '<hr />';
// var_dump($this->_dataArray);
// echo '<hr />';
// var_dump($this->_dataArray);
// Return
return $objPHPExcel;
}
// Return
return $objPHPExcel;
}
/**
* Get sheet index
*
* @return int
*/
public function getSheetIndex() {
return $this->_sheetIndex;
}
/**
* Set sheet index
*
* @param int $pValue Sheet index
* @return PHPExcel\Reader_HTML
*/
public function setSheetIndex($pValue = 0) {
$this->_sheetIndex = $pValue;
return $this;
}
/**
* Get sheet index
*
* @return int
*/
public function getSheetIndex() {
return $this->_sheetIndex;
}
/**
* Set sheet index
*
* @param int $pValue Sheet index
* @return PHPExcel\Reader_HTML
*/
public function setSheetIndex($pValue = 0) {
$this->_sheetIndex = $pValue;
return $this;
}
}

View File

@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\Reader
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@ -37,13 +37,13 @@ namespace PHPExcel;
*/
interface Reader_IReadFilter
{
/**
* Should this cell be read?
*
* @param $column String column index
* @param $row Row index
* @param $worksheetName Optional worksheet name
* @return boolean
*/
public function readCell($column, $row, $worksheetName = '');
/**
* Should this cell be read?
*
* @param $column String column index
* @param $row Row index
* @param $worksheetName Optional worksheet name
* @return boolean
*/
public function readCell($column, $row, $worksheetName = '');
}

View File

@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\Reader
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@ -37,19 +37,19 @@ namespace PHPExcel;
*/
interface Reader_IReader
{
/**
* Can the current PHPExcel\Reader_IReader read the file?
*
* @param string $pFilename
* @return boolean
*/
public function canRead($pFilename);
/**
* Can the current PHPExcel\Reader_IReader read the file?
*
* @param string $pFilename
* @return boolean
*/
public function canRead($pFilename);
/**
* Loads PHPExcel from file
*
* @param string $pFilename
* @throws PHPExcel\Reader_Exception
*/
public function load($pFilename);
/**
* Loads PHPExcel from file
*
* @param string $pFilename
* @throws PHPExcel\Reader_Exception
*/
public function load($pFilename);
}

File diff suppressed because it is too large Load Diff

View File

@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\Reader
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@ -37,407 +37,406 @@ namespace PHPExcel;
*/
class Reader_SYLK extends Reader_Abstract implements Reader_IReader
{
/**
* Input encoding
*
* @var string
*/
private $_inputEncoding = 'ANSI';
/**
* Input encoding
*
* @var string
*/
private $_inputEncoding = 'ANSI';
/**
* Sheet index to read
*
* @var int
*/
private $_sheetIndex = 0;
/**
* Sheet index to read
*
* @var int
*/
private $_sheetIndex = 0;
/**
* Formats
*
* @var array
*/
private $_formats = array();
/**
* Formats
*
* @var array
*/
private $_formats = array();
/**
* Format Count
*
* @var int
*/
private $_format = 0;
/**
* Format Count
*
* @var int
*/
private $_format = 0;
/**
* Create a new PHPExcel\Reader_SYLK
*/
public function __construct() {
$this->_readFilter = new Reader_DefaultReadFilter();
}
/**
* Create a new PHPExcel\Reader_SYLK
*/
public function __construct() {
$this->_readFilter = new Reader_DefaultReadFilter();
}
/**
* Validate that the current file is a SYLK file
*
* @return boolean
*/
protected function _isValidFormat()
{
// Read sample data (first 2 KB will do)
$data = fread($this->_fileHandle, 2048);
/**
* Validate that the current file is a SYLK file
*
* @return boolean
*/
protected function _isValidFormat()
{
// Read sample data (first 2 KB will do)
$data = fread($this->_fileHandle, 2048);
// Count delimiters in file
$delimiterCount = substr_count($data, ';');
if ($delimiterCount < 1) {
return FALSE;
}
// Count delimiters in file
$delimiterCount = substr_count($data, ';');
if ($delimiterCount < 1) {
return false;
}
// Analyze first line looking for ID; signature
$lines = explode("\n", $data);
if (substr($lines[0],0,4) != 'ID;P') {
return FALSE;
}
// Analyze first line looking for ID; signature
$lines = explode("\n", $data);
if (substr($lines[0],0,4) != 'ID;P') {
return false;
}
return TRUE;
}
return true;
}
/**
* Set input encoding
*
* @param string $pValue Input encoding
*/
public function setInputEncoding($pValue = 'ANSI')
{
$this->_inputEncoding = $pValue;
return $this;
}
/**
* Set input encoding
*
* @param string $pValue Input encoding
*/
public function setInputEncoding($pValue = 'ANSI')
{
$this->_inputEncoding = $pValue;
return $this;
}
/**
* Get input encoding
*
* @return string
*/
public function getInputEncoding()
{
return $this->_inputEncoding;
}
/**
* Get input encoding
*
* @return string
*/
public function getInputEncoding()
{
return $this->_inputEncoding;
}
/**
* Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns)
*
* @param string $pFilename
* @throws PHPExcel\Reader_Exception
*/
public function listWorksheetInfo($pFilename)
{
// Open file
$this->_openFile($pFilename);
if (!$this->_isValidFormat()) {
fclose ($this->_fileHandle);
throw new Reader_Exception($pFilename . " is an Invalid Spreadsheet file.");
}
$fileHandle = $this->_fileHandle;
rewind($fileHandle);
/**
* Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns)
*
* @param string $pFilename
* @throws PHPExcel\Reader_Exception
*/
public function listWorksheetInfo($pFilename)
{
// Open file
$this->_openFile($pFilename);
if (!$this->_isValidFormat()) {
fclose ($this->_fileHandle);
throw new Reader_Exception($pFilename . " is an Invalid Spreadsheet file.");
}
$fileHandle = $this->_fileHandle;
rewind($fileHandle);
$worksheetInfo = array();
$worksheetInfo[0]['worksheetName'] = 'Worksheet';
$worksheetInfo[0]['lastColumnLetter'] = 'A';
$worksheetInfo[0]['lastColumnIndex'] = 0;
$worksheetInfo[0]['totalRows'] = 0;
$worksheetInfo[0]['totalColumns'] = 0;
$worksheetInfo = array();
$worksheetInfo[0]['worksheetName'] = 'Worksheet';
$worksheetInfo[0]['lastColumnLetter'] = 'A';
$worksheetInfo[0]['lastColumnIndex'] = 0;
$worksheetInfo[0]['totalRows'] = 0;
$worksheetInfo[0]['totalColumns'] = 0;
// Loop through file
$rowData = array();
// Loop through file
$rowData = array();
// loop through one row (line) at a time in the file
$rowIndex = 0;
while (($rowData = fgets($fileHandle)) !== FALSE) {
$columnIndex = 0;
// loop through one row (line) at a time in the file
$rowIndex = 0;
while (($rowData = fgets($fileHandle)) !== false) {
$columnIndex = 0;
// convert SYLK encoded $rowData to UTF-8
$rowData = Shared_String::SYLKtoUTF8($rowData);
// convert SYLK encoded $rowData to UTF-8
$rowData = Shared_String::SYLKtoUTF8($rowData);
// explode each row at semicolons while taking into account that literal semicolon (;)
// is escaped like this (;;)
$rowData = explode("\t",str_replace('¤',';',str_replace(';',"\t",str_replace(';;','¤',rtrim($rowData)))));
// explode each row at semicolons while taking into account that literal semicolon (;)
// is escaped like this (;;)
$rowData = explode("\t",str_replace('¤',';',str_replace(';',"\t",str_replace(';;','¤',rtrim($rowData)))));
$dataType = array_shift($rowData);
if ($dataType == 'C') {
// Read cell value data
foreach($rowData as $rowDatum) {
switch($rowDatum{0}) {
case 'C' :
case 'X' :
$columnIndex = substr($rowDatum,1) - 1;
break;
case 'R' :
case 'Y' :
$rowIndex = substr($rowDatum,1);
break;
}
$dataType = array_shift($rowData);
if ($dataType == 'C') {
// Read cell value data
foreach($rowData as $rowDatum) {
switch($rowDatum{0}) {
case 'C' :
case 'X' :
$columnIndex = substr($rowDatum,1) - 1;
break;
case 'R' :
case 'Y' :
$rowIndex = substr($rowDatum,1);
break;
}
$worksheetInfo[0]['totalRows'] = max($worksheetInfo[0]['totalRows'], $rowIndex);
$worksheetInfo[0]['lastColumnIndex'] = max($worksheetInfo[0]['lastColumnIndex'], $columnIndex);
}
}
}
$worksheetInfo[0]['totalRows'] = max($worksheetInfo[0]['totalRows'], $rowIndex);
$worksheetInfo[0]['lastColumnIndex'] = max($worksheetInfo[0]['lastColumnIndex'], $columnIndex);
}
}
}
$worksheetInfo[0]['lastColumnLetter'] = Cell::stringFromColumnIndex($worksheetInfo[0]['lastColumnIndex']);
$worksheetInfo[0]['totalColumns'] = $worksheetInfo[0]['lastColumnIndex'] + 1;
$worksheetInfo[0]['lastColumnLetter'] = Cell::stringFromColumnIndex($worksheetInfo[0]['lastColumnIndex']);
$worksheetInfo[0]['totalColumns'] = $worksheetInfo[0]['lastColumnIndex'] + 1;
// Close file
fclose($fileHandle);
// Close file
fclose($fileHandle);
return $worksheetInfo;
}
return $worksheetInfo;
}
/**
* Loads PHPExcel from file
*
* @param string $pFilename
* @return PHPExcel
* @throws PHPExcel\Reader_Exception
*/
public function load($pFilename)
{
// Create new PHPExcel Workbook
$objPHPExcel = new Workbook();
/**
* Loads PHPExcel from file
*
* @param string $pFilename
* @return PHPExcel
* @throws PHPExcel\Reader_Exception
*/
public function load($pFilename)
{
// Create new PHPExcel Workbook
$objPHPExcel = new Workbook();
// Load into this instance
return $this->loadIntoExisting($pFilename, $objPHPExcel);
}
// Load into this instance
return $this->loadIntoExisting($pFilename, $objPHPExcel);
}
/**
* Loads PHPExcel from file into PHPExcel instance
*
* @param string $pFilename
* @param PHPExcel $objPHPExcel
* @return PHPExcel
* @throws PHPExcel\Reader_Exception
*/
public function loadIntoExisting($pFilename, PHPExcel $objPHPExcel)
{
// Open file
$this->_openFile($pFilename);
if (!$this->_isValidFormat()) {
fclose ($this->_fileHandle);
throw new Reader_Exception($pFilename . " is an Invalid Spreadsheet file.");
}
$fileHandle = $this->_fileHandle;
rewind($fileHandle);
/**
* Loads PHPExcel from file into PHPExcel instance
*
* @param string $pFilename
* @param PHPExcel $objPHPExcel
* @return PHPExcel
* @throws PHPExcel\Reader_Exception
*/
public function loadIntoExisting($pFilename, PHPExcel $objPHPExcel)
{
// Open file
$this->_openFile($pFilename);
if (!$this->_isValidFormat()) {
fclose ($this->_fileHandle);
throw new Reader_Exception($pFilename . " is an Invalid Spreadsheet file.");
}
$fileHandle = $this->_fileHandle;
rewind($fileHandle);
// Create new PHPExcel
while ($objPHPExcel->getSheetCount() <= $this->_sheetIndex) {
$objPHPExcel->createSheet();
}
$objPHPExcel->setActiveSheetIndex( $this->_sheetIndex );
// Create new PHPExcel
while ($objPHPExcel->getSheetCount() <= $this->_sheetIndex) {
$objPHPExcel->createSheet();
}
$objPHPExcel->setActiveSheetIndex( $this->_sheetIndex );
$fromFormats = array('\-', '\ ');
$toFormats = array('-', ' ');
$fromFormats = array('\-', '\ ');
$toFormats = array('-', ' ');
// Loop through file
$rowData = array();
$column = $row = '';
// Loop through file
$rowData = array();
$column = $row = '';
// loop through one row (line) at a time in the file
while (($rowData = fgets($fileHandle)) !== FALSE) {
// loop through one row (line) at a time in the file
while (($rowData = fgets($fileHandle)) !== false) {
// convert SYLK encoded $rowData to UTF-8
$rowData = Shared_String::SYLKtoUTF8($rowData);
// convert SYLK encoded $rowData to UTF-8
$rowData = Shared_String::SYLKtoUTF8($rowData);
// explode each row at semicolons while taking into account that literal semicolon (;)
// is escaped like this (;;)
$rowData = explode("\t",str_replace('¤',';',str_replace(';',"\t",str_replace(';;','¤',rtrim($rowData)))));
// explode each row at semicolons while taking into account that literal semicolon (;)
// is escaped like this (;;)
$rowData = explode("\t",str_replace('¤',';',str_replace(';',"\t",str_replace(';;','¤',rtrim($rowData)))));
$dataType = array_shift($rowData);
// Read shared styles
if ($dataType == 'P') {
$formatArray = array();
foreach($rowData as $rowDatum) {
switch($rowDatum{0}) {
case 'P' : $formatArray['numberformat']['code'] = str_replace($fromFormats,$toFormats,substr($rowDatum,1));
break;
case 'E' :
case 'F' : $formatArray['font']['name'] = substr($rowDatum,1);
break;
case 'L' : $formatArray['font']['size'] = substr($rowDatum,1);
break;
case 'S' : $styleSettings = substr($rowDatum,1);
for ($i=0;$i<strlen($styleSettings);++$i) {
switch ($styleSettings{$i}) {
case 'I' : $formatArray['font']['italic'] = true;
break;
case 'D' : $formatArray['font']['bold'] = true;
break;
case 'T' : $formatArray['borders']['top']['style'] = Style_Border::BORDER_THIN;
break;
case 'B' : $formatArray['borders']['bottom']['style'] = Style_Border::BORDER_THIN;
break;
case 'L' : $formatArray['borders']['left']['style'] = Style_Border::BORDER_THIN;
break;
case 'R' : $formatArray['borders']['right']['style'] = Style_Border::BORDER_THIN;
break;
}
}
break;
}
}
$this->_formats['P'.$this->_format++] = $formatArray;
// Read cell value data
} elseif ($dataType == 'C') {
$hasCalculatedValue = false;
$cellData = $cellDataFormula = '';
foreach($rowData as $rowDatum) {
switch($rowDatum{0}) {
case 'C' :
case 'X' : $column = substr($rowDatum,1);
break;
case 'R' :
case 'Y' : $row = substr($rowDatum,1);
break;
case 'K' : $cellData = substr($rowDatum,1);
break;
case 'E' : $cellDataFormula = '='.substr($rowDatum,1);
// Convert R1C1 style references to A1 style references (but only when not quoted)
$temp = explode('"',$cellDataFormula);
$key = false;
foreach($temp as &$value) {
// Only count/replace in alternate array entries
if ($key = !$key) {
preg_match_all('/(R(\[?-?\d*\]?))(C(\[?-?\d*\]?))/',$value, $cellReferences,PREG_SET_ORDER+PREG_OFFSET_CAPTURE);
// Reverse the matches array, otherwise all our offsets will become incorrect if we modify our way
// through the formula from left to right. Reversing means that we work right to left.through
// the formula
$cellReferences = array_reverse($cellReferences);
// Loop through each R1C1 style reference in turn, converting it to its A1 style equivalent,
// then modify the formula to use that new reference
foreach($cellReferences as $cellReference) {
$rowReference = $cellReference[2][0];
// Empty R reference is the current row
if ($rowReference == '') $rowReference = $row;
// Bracketed R references are relative to the current row
if ($rowReference{0} == '[') $rowReference = $row + trim($rowReference,'[]');
$columnReference = $cellReference[4][0];
// Empty C reference is the current column
if ($columnReference == '') $columnReference = $column;
// Bracketed C references are relative to the current column
if ($columnReference{0} == '[') $columnReference = $column + trim($columnReference,'[]');
$A1CellReference = Cell::stringFromColumnIndex($columnReference-1).$rowReference;
$dataType = array_shift($rowData);
// Read shared styles
if ($dataType == 'P') {
$formatArray = array();
foreach($rowData as $rowDatum) {
switch($rowDatum{0}) {
case 'P' : $formatArray['numberformat']['code'] = str_replace($fromFormats,$toFormats,substr($rowDatum,1));
break;
case 'E' :
case 'F' : $formatArray['font']['name'] = substr($rowDatum,1);
break;
case 'L' : $formatArray['font']['size'] = substr($rowDatum,1);
break;
case 'S' : $styleSettings = substr($rowDatum,1);
for ($i=0;$i<strlen($styleSettings);++$i) {
switch ($styleSettings{$i}) {
case 'I' : $formatArray['font']['italic'] = true;
break;
case 'D' : $formatArray['font']['bold'] = true;
break;
case 'T' : $formatArray['borders']['top']['style'] = Style_Border::BORDER_THIN;
break;
case 'B' : $formatArray['borders']['bottom']['style'] = Style_Border::BORDER_THIN;
break;
case 'L' : $formatArray['borders']['left']['style'] = Style_Border::BORDER_THIN;
break;
case 'R' : $formatArray['borders']['right']['style'] = Style_Border::BORDER_THIN;
break;
}
}
break;
}
}
$this->_formats['P'.$this->_format++] = $formatArray;
// Read cell value data
} elseif ($dataType == 'C') {
$hasCalculatedValue = false;
$cellData = $cellDataFormula = '';
foreach($rowData as $rowDatum) {
switch($rowDatum{0}) {
case 'C' :
case 'X' : $column = substr($rowDatum,1);
break;
case 'R' :
case 'Y' : $row = substr($rowDatum,1);
break;
case 'K' : $cellData = substr($rowDatum,1);
break;
case 'E' : $cellDataFormula = '='.substr($rowDatum,1);
// Convert R1C1 style references to A1 style references (but only when not quoted)
$temp = explode('"',$cellDataFormula);
$key = false;
foreach($temp as &$value) {
// Only count/replace in alternate array entries
if ($key = !$key) {
preg_match_all('/(R(\[?-?\d*\]?))(C(\[?-?\d*\]?))/',$value, $cellReferences,PREG_SET_ORDER+PREG_OFFSET_CAPTURE);
// Reverse the matches array, otherwise all our offsets will become incorrect if we modify our way
// through the formula from left to right. Reversing means that we work right to left.through
// the formula
$cellReferences = array_reverse($cellReferences);
// Loop through each R1C1 style reference in turn, converting it to its A1 style equivalent,
// then modify the formula to use that new reference
foreach($cellReferences as $cellReference) {
$rowReference = $cellReference[2][0];
// Empty R reference is the current row
if ($rowReference == '') $rowReference = $row;
// Bracketed R references are relative to the current row
if ($rowReference{0} == '[') $rowReference = $row + trim($rowReference,'[]');
$columnReference = $cellReference[4][0];
// Empty C reference is the current column
if ($columnReference == '') $columnReference = $column;
// Bracketed C references are relative to the current column
if ($columnReference{0} == '[') $columnReference = $column + trim($columnReference,'[]');
$A1CellReference = Cell::stringFromColumnIndex($columnReference-1).$rowReference;
$value = substr_replace($value,$A1CellReference,$cellReference[0][1],strlen($cellReference[0][0]));
}
}
}
unset($value);
// Then rebuild the formula string
$cellDataFormula = implode('"',$temp);
$hasCalculatedValue = true;
break;
}
}
$columnLetter = Cell::stringFromColumnIndex($column-1);
$cellData = Calculation::_unwrapResult($cellData);
$value = substr_replace($value,$A1CellReference,$cellReference[0][1],strlen($cellReference[0][0]));
}
}
}
unset($value);
// Then rebuild the formula string
$cellDataFormula = implode('"',$temp);
$hasCalculatedValue = true;
break;
}
}
$columnLetter = Cell::stringFromColumnIndex($column-1);
$cellData = Calculation::_unwrapResult($cellData);
// Set cell value
$objPHPExcel->getActiveSheet()->getCell($columnLetter.$row)->setValue(($hasCalculatedValue) ? $cellDataFormula : $cellData);
if ($hasCalculatedValue) {
$cellData = Calculation::_unwrapResult($cellData);
$objPHPExcel->getActiveSheet()->getCell($columnLetter.$row)->setCalculatedValue($cellData);
}
// Read cell formatting
} elseif ($dataType == 'F') {
$formatStyle = $columnWidth = $styleSettings = '';
$styleData = array();
foreach($rowData as $rowDatum) {
switch($rowDatum{0}) {
case 'C' :
case 'X' : $column = substr($rowDatum,1);
break;
case 'R' :
case 'Y' : $row = substr($rowDatum,1);
break;
case 'P' : $formatStyle = $rowDatum;
break;
case 'W' : list($startCol,$endCol,$columnWidth) = explode(' ',substr($rowDatum,1));
break;
case 'S' : $styleSettings = substr($rowDatum,1);
for ($i=0;$i<strlen($styleSettings);++$i) {
switch ($styleSettings{$i}) {
case 'I' : $styleData['font']['italic'] = true;
break;
case 'D' : $styleData['font']['bold'] = true;
break;
case 'T' : $styleData['borders']['top']['style'] = Style_Border::BORDER_THIN;
break;
case 'B' : $styleData['borders']['bottom']['style'] = Style_Border::BORDER_THIN;
break;
case 'L' : $styleData['borders']['left']['style'] = Style_Border::BORDER_THIN;
break;
case 'R' : $styleData['borders']['right']['style'] = Style_Border::BORDER_THIN;
break;
}
}
break;
}
}
if (($formatStyle > '') && ($column > '') && ($row > '')) {
$columnLetter = Cell::stringFromColumnIndex($column-1);
if (isset($this->_formats[$formatStyle])) {
$objPHPExcel->getActiveSheet()->getStyle($columnLetter.$row)->applyFromArray($this->_formats[$formatStyle]);
}
}
if ((!empty($styleData)) && ($column > '') && ($row > '')) {
$columnLetter = Cell::stringFromColumnIndex($column-1);
$objPHPExcel->getActiveSheet()->getStyle($columnLetter.$row)->applyFromArray($styleData);
}
if ($columnWidth > '') {
if ($startCol == $endCol) {
$startCol = Cell::stringFromColumnIndex($startCol-1);
$objPHPExcel->getActiveSheet()->getColumnDimension($startCol)->setWidth($columnWidth);
} else {
$startCol = Cell::stringFromColumnIndex($startCol-1);
$endCol = Cell::stringFromColumnIndex($endCol-1);
$objPHPExcel->getActiveSheet()->getColumnDimension($startCol)->setWidth($columnWidth);
do {
$objPHPExcel->getActiveSheet()->getColumnDimension(++$startCol)->setWidth($columnWidth);
} while ($startCol != $endCol);
}
}
} else {
foreach($rowData as $rowDatum) {
switch($rowDatum{0}) {
case 'C' :
case 'X' : $column = substr($rowDatum,1);
break;
case 'R' :
case 'Y' : $row = substr($rowDatum,1);
break;
}
}
}
}
// Set cell value
$objPHPExcel->getActiveSheet()->getCell($columnLetter.$row)->setValue(($hasCalculatedValue) ? $cellDataFormula : $cellData);
if ($hasCalculatedValue) {
$cellData = Calculation::_unwrapResult($cellData);
$objPHPExcel->getActiveSheet()->getCell($columnLetter.$row)->setCalculatedValue($cellData);
}
// Read cell formatting
} elseif ($dataType == 'F') {
$formatStyle = $columnWidth = $styleSettings = '';
$styleData = array();
foreach($rowData as $rowDatum) {
switch($rowDatum{0}) {
case 'C' :
case 'X' : $column = substr($rowDatum,1);
break;
case 'R' :
case 'Y' : $row = substr($rowDatum,1);
break;
case 'P' : $formatStyle = $rowDatum;
break;
case 'W' : list($startCol,$endCol,$columnWidth) = explode(' ',substr($rowDatum,1));
break;
case 'S' : $styleSettings = substr($rowDatum,1);
for ($i=0;$i<strlen($styleSettings);++$i) {
switch ($styleSettings{$i}) {
case 'I' : $styleData['font']['italic'] = true;
break;
case 'D' : $styleData['font']['bold'] = true;
break;
case 'T' : $styleData['borders']['top']['style'] = Style_Border::BORDER_THIN;
break;
case 'B' : $styleData['borders']['bottom']['style'] = Style_Border::BORDER_THIN;
break;
case 'L' : $styleData['borders']['left']['style'] = Style_Border::BORDER_THIN;
break;
case 'R' : $styleData['borders']['right']['style'] = Style_Border::BORDER_THIN;
break;
}
}
break;
}
}
if (($formatStyle > '') && ($column > '') && ($row > '')) {
$columnLetter = Cell::stringFromColumnIndex($column-1);
if (isset($this->_formats[$formatStyle])) {
$objPHPExcel->getActiveSheet()->getStyle($columnLetter.$row)->applyFromArray($this->_formats[$formatStyle]);
}
}
if ((!empty($styleData)) && ($column > '') && ($row > '')) {
$columnLetter = Cell::stringFromColumnIndex($column-1);
$objPHPExcel->getActiveSheet()->getStyle($columnLetter.$row)->applyFromArray($styleData);
}
if ($columnWidth > '') {
if ($startCol == $endCol) {
$startCol = Cell::stringFromColumnIndex($startCol-1);
$objPHPExcel->getActiveSheet()->getColumnDimension($startCol)->setWidth($columnWidth);
} else {
$startCol = Cell::stringFromColumnIndex($startCol-1);
$endCol = Cell::stringFromColumnIndex($endCol-1);
$objPHPExcel->getActiveSheet()->getColumnDimension($startCol)->setWidth($columnWidth);
do {
$objPHPExcel->getActiveSheet()->getColumnDimension(++$startCol)->setWidth($columnWidth);
} while ($startCol != $endCol);
}
}
} else {
foreach($rowData as $rowDatum) {
switch($rowDatum{0}) {
case 'C' :
case 'X' : $column = substr($rowDatum,1);
break;
case 'R' :
case 'Y' : $row = substr($rowDatum,1);
break;
}
}
}
}
// Close file
fclose($fileHandle);
// Close file
fclose($fileHandle);
// Return
return $objPHPExcel;
}
// Return
return $objPHPExcel;
}
/**
* Get sheet index
*
* @return int
*/
public function getSheetIndex() {
return $this->_sheetIndex;
}
/**
* Set sheet index
*
* @param int $pValue Sheet index
* @return PHPExcel\Reader_SYLK
*/
public function setSheetIndex($pValue = 0) {
$this->_sheetIndex = $pValue;
return $this;
}
/**
* Get sheet index
*
* @return int
*/
public function getSheetIndex() {
return $this->_sheetIndex;
}
/**
* Set sheet index
*
* @param int $pValue Sheet index
* @return PHPExcel\Reader_SYLK
*/
public function setSheetIndex($pValue = 0) {
$this->_sheetIndex = $pValue;
return $this;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -56,7 +56,7 @@ class RichText implements IComparable
$this->_richTextElements = array();
// Rich-Text string attached to cell?
if ($pCell !== NULL) {
if ($pCell !== null) {
// Add cell text and style
if ($pCell->getValue() != "") {
$objRun = new RichText_Run($pCell->getValue());

View File

@ -19,7 +19,7 @@
* @category PHPExcel
* @package PHPExcel\RichText
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@ -35,32 +35,32 @@ namespace PHPExcel;
*/
interface RichText_ITextElement
{
/**
* Get text
*
* @return string Text
*/
public function getText();
/**
* Get text
*
* @return string Text
*/
public function getText();
/**
* Set text
*
* @param $pText string Text
* @return PHPExcel\RichText_ITextElement
*/
public function setText($pText = '');
/**
* Set text
*
* @param $pText string Text
* @return PHPExcel\RichText_ITextElement
*/
public function setText($pText = '');
/**
* Get font
*
* @return PHPExcel\Style_Font
*/
public function getFont();
/**
* Get font
*
* @return PHPExcel\Style_Font
*/
public function getFont();
/**
* Get hash code
*
* @return string Hash code
*/
public function getHashCode();
/**
* Get hash code
*
* @return string Hash code
*/
public function getHashCode();
}

View File

@ -19,7 +19,7 @@
* @category PHPExcel
* @package PHPExcel\RichText
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@ -35,70 +35,70 @@ namespace PHPExcel;
*/
class RichText_Run extends RichText_TextElement implements RichText_ITextElement
{
/**
* Font
*
* @var PHPExcel\Style_Font
*/
protected $_font;
/**
* Font
*
* @var PHPExcel\Style_Font
*/
protected $_font;
/**
* Create a new PHPExcel\RichText_Run instance
*
* @param string $pText Text
* @param string $pText Text
*/
public function __construct($pText = '')
{
// Initialise variables
$this->setText($pText);
$this->_font = new Style_Font();
// Initialise variables
$this->setText($pText);
$this->_font = new Style_Font();
}
/**
* Get font
*
* @return PHPExcel\Style_Font
*/
public function getFont() {
return $this->_font;
}
/**
* Set font
*
* @param PHPExcel\Style_Font $pFont Font
* @throws PHPExcel\Exception
* @return PHPExcel\RichText_ITextElement
*/
public function setFont(Style_Font $pFont = null) {
$this->_font = $pFont;
return $this;
}
/**
* Get hash code
*
* @return string Hash code
*/
public function getHashCode() {
return md5(
$this->getText()
. $this->_font->getHashCode()
. __CLASS__
);
/**
* Get font
*
* @return PHPExcel\Style_Font
*/
public function getFont() {
return $this->_font;
}
/**
* Implement PHP __clone to create a deep clone, not just a shallow copy.
*/
public function __clone() {
$vars = get_object_vars($this);
foreach ($vars as $key => $value) {
if (is_object($value)) {
$this->$key = clone $value;
} else {
$this->$key = $value;
}
}
}
/**
* Set font
*
* @param PHPExcel\Style_Font $pFont Font
* @throws PHPExcel\Exception
* @return PHPExcel\RichText_ITextElement
*/
public function setFont(Style_Font $pFont = null) {
$this->_font = $pFont;
return $this;
}
/**
* Get hash code
*
* @return string Hash code
*/
public function getHashCode() {
return md5(
$this->getText()
. $this->_font->getHashCode()
. __CLASS__
);
}
/**
* Implement PHP __clone to create a deep clone, not just a shallow copy.
*/
public function __clone() {
$vars = get_object_vars($this);
foreach ($vars as $key => $value) {
if (is_object($value)) {
$this->$key = clone $value;
} else {
$this->$key = $value;
}
}
}
}

View File

@ -19,7 +19,7 @@
* @category PHPExcel
* @package PHPExcel\RichText
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@ -35,76 +35,76 @@ namespace PHPExcel;
*/
class RichText_TextElement implements RichText_ITextElement
{
/**
* Text
*
* @var string
*/
protected $_text;
/**
* Text
*
* @var string
*/
protected $_text;
/**
* Create a new PHPExcel\RichText_TextElement instance
*
* @param string $pText Text
* @param string $pText Text
*/
public function __construct($pText = '')
{
// Initialise variables
$this->_text = $pText;
// Initialise variables
$this->_text = $pText;
}
/**
* Get text
*
* @return string Text
*/
public function getText() {
return $this->_text;
}
/**
* Set text
*
* @param $pText string Text
* @return PHPExcel\RichText_ITextElement
*/
public function setText($pText = '') {
$this->_text = $pText;
return $this;
}
/**
* Get font
*
* @return PHPExcel\Style_Font
*/
public function getFont() {
return null;
}
/**
* Get hash code
*
* @return string Hash code
*/
public function getHashCode() {
return md5(
$this->_text
. __CLASS__
);
/**
* Get text
*
* @return string Text
*/
public function getText() {
return $this->_text;
}
/**
* Implement PHP __clone to create a deep clone, not just a shallow copy.
*/
public function __clone() {
$vars = get_object_vars($this);
foreach ($vars as $key => $value) {
if (is_object($value)) {
$this->$key = clone $value;
} else {
$this->$key = $value;
}
}
}
/**
* Set text
*
* @param $pText string Text
* @return PHPExcel\RichText_ITextElement
*/
public function setText($pText = '') {
$this->_text = $pText;
return $this;
}
/**
* Get font
*
* @return PHPExcel\Style_Font
*/
public function getFont() {
return null;
}
/**
* Get hash code
*
* @return string Hash code
*/
public function getHashCode() {
return md5(
$this->_text
. __CLASS__
);
}
/**
* Implement PHP __clone to create a deep clone, not just a shallow copy.
*/
public function __clone() {
$vars = get_object_vars($this);
foreach ($vars as $key => $value) {
if (is_object($value)) {
$this->$key = clone $value;
} else {
$this->$key = $value;
}
}
}
}

View File

@ -39,9 +39,9 @@ class Settings
const CHART_RENDERER_JPGRAPH = 'jpgraph';
/** Optional PDF Rendering libraries */
const PDF_RENDERER_TCPDF = 'tcPDF';
const PDF_RENDERER_DOMPDF = 'DomPDF';
const PDF_RENDERER_MPDF = 'mPDF';
const PDF_RENDERER_TCPDF = 'tcPDF';
const PDF_RENDERER_DOMPDF = 'DomPDF';
const PDF_RENDERER_MPDF = 'mPDF';
protected static $_chartRenderers = array(
@ -57,8 +57,8 @@ class Settings
/**
* Name of the class used for Zip file management
* e.g.
* ZipArchive
* e.g.
* ZipArchive
*
* @var string
*/
@ -67,68 +67,68 @@ class Settings
/**
* Name of the external Library used for rendering charts
* e.g.
* jpgraph
* e.g.
* jpgraph
*
* @var string
*/
protected static $_chartRendererName = NULL;
protected static $_chartRendererName = null;
/**
* Directory Path to the external Library used for rendering charts
*
* @var string
*/
protected static $_chartRendererPath = NULL;
protected static $_chartRendererPath = null;
/**
* Name of the external Library used for rendering PDF files
* e.g.
* mPDF
* e.g.
* mPDF
*
* @var string
*/
protected static $_pdfRendererName = NULL;
protected static $_pdfRendererName = null;
/**
* Directory Path to the external Library used for rendering PDF files
*
* @var string
*/
protected static $_pdfRendererPath = NULL;
protected static $_pdfRendererPath = null;
/**
* Set the Zip handler Class that PHPExcel should use for Zip file management (PCLZip or ZipArchive)
*
* @param string $zipClass The Zip handler class that PHPExcel should use for Zip file management
* e.g. PHPExcel\Settings::PCLZip or PHPExcel\Settings::ZipArchive
* @return boolean Success or failure
* @param string $zipClass The Zip handler class that PHPExcel should use for Zip file management
* e.g. PHPExcel\Settings::PCLZip or PHPExcel\Settings::ZipArchive
* @return boolean Success or failure
*/
public static function setZipClass($zipClass)
{
if (($zipClass === self::PCLZIP) ||
($zipClass === self::ZIPARCHIVE)) {
self::$_zipClass = $zipClass;
return TRUE;
return true;
}
return FALSE;
} // function setZipClass()
return false;
}
/**
* Return the name of the Zip handler Class that PHPExcel is configured to use (PCLZip or ZipArchive)
* or Zip file management
* or Zip file management
*
* @return string Name of the Zip handler Class that PHPExcel is configured to use
* for Zip file management
* e.g. PHPExcel\Settings::PCLZip or PHPExcel\Settings::ZipArchive
* for Zip file management
* e.g. PHPExcel\Settings::PCLZip or PHPExcel\Settings::ZipArchive
*/
public static function getZipClass()
{
return self::$_zipClass;
} // function getZipClass()
}
/**
@ -139,7 +139,7 @@ class Settings
public static function getCacheStorageMethod()
{
return CachedObjectStorageFactory::getCacheStorageMethod();
} // function getCacheStorageMethod()
}
/**
@ -150,7 +150,7 @@ class Settings
public static function getCacheStorageClass()
{
return CachedObjectStorageFactory::getCacheStorageClass();
} // function getCacheStorageClass()
}
/**
@ -161,12 +161,12 @@ class Settings
* @return boolean Success or failure
*/
public static function setCacheStorageMethod(
$method = CachedObjectStorageFactory::cache_in_memory,
$method = CachedObjectStorageFactory::cache_in_memory,
$arguments = array()
)
{
return CachedObjectStorageFactory::initialize($method, $arguments);
} // function setCacheStorageMethod()
}
/**
@ -178,94 +178,94 @@ class Settings
public static function setLocale($locale='en_us')
{
return Calculation::getInstance()->setLocale($locale);
} // function setLocale()
}
/**
* Set details of the external library that PHPExcel should use for rendering charts
*
* @param string $libraryName Internal reference name of the library
* e.g. PHPExcel\Settings::CHART_RENDERER_JPGRAPH
* @param string $libraryName Internal reference name of the library
* e.g. PHPExcel\Settings::CHART_RENDERER_JPGRAPH
* @param string $libraryBaseDir Directory path to the library's base folder
*
* @return boolean Success or failure
* @return boolean Success or failure
*/
public static function setChartRenderer($libraryName, $libraryBaseDir)
{
if (!self::setChartRendererName($libraryName))
return FALSE;
return false;
return self::setChartRendererPath($libraryBaseDir);
} // function setChartRenderer()
}
/**
* Identify to PHPExcel the external library to use for rendering charts
*
* @param string $libraryName Internal reference name of the library
* e.g. PHPExcel\Settings::CHART_RENDERER_JPGRAPH
* @param string $libraryName Internal reference name of the library
* e.g. PHPExcel\Settings::CHART_RENDERER_JPGRAPH
*
* @return boolean Success or failure
* @return boolean Success or failure
*/
public static function setChartRendererName($libraryName)
{
if (!in_array($libraryName,self::$_chartRenderers)) {
return FALSE;
return false;
}
self::$_chartRendererName = $libraryName;
return TRUE;
} // function setChartRendererName()
return true;
}
/**
* Tell PHPExcel where to find the external library to use for rendering charts
*
* @param string $libraryBaseDir Directory path to the library's base folder
* @return boolean Success or failure
* @param string $libraryBaseDir Directory path to the library's base folder
* @return boolean Success or failure
*/
public static function setChartRendererPath($libraryBaseDir)
{
if ((file_exists($libraryBaseDir) === false) || (is_readable($libraryBaseDir) === false)) {
return FALSE;
return false;
}
self::$_chartRendererPath = $libraryBaseDir;
return TRUE;
} // function setChartRendererPath()
return true;
}
/**
* Return the Chart Rendering Library that PHPExcel is currently configured to use (e.g. jpgraph)
*
* @return string|NULL Internal reference name of the Chart Rendering Library that PHPExcel is
* currently configured to use
* e.g. PHPExcel\Settings::CHART_RENDERER_JPGRAPH
* @return string|null Internal reference name of the Chart Rendering Library that PHPExcel is
* currently configured to use
* e.g. PHPExcel\Settings::CHART_RENDERER_JPGRAPH
*/
public static function getChartRendererName()
{
return self::$_chartRendererName;
} // function getChartRendererName()
}
/**
* Return the directory path to the Chart Rendering Library that PHPExcel is currently configured to use
*
* @return string|NULL Directory Path to the Chart Rendering Library that PHPExcel is
* currently configured to use
* @return string|null Directory Path to the Chart Rendering Library that PHPExcel is
* currently configured to use
*/
public static function getChartRendererPath()
{
return self::$_chartRendererPath;
} // function getChartRendererPath()
}
/**
* Set details of the external library that PHPExcel should use for rendering PDF files
*
* @param string $libraryName Internal reference name of the library
* e.g. PHPExcel\Settings::PDF_RENDERER_TCPDF,
* PHPExcel\Settings::PDF_RENDERER_DOMPDF
* e.g. PHPExcel\Settings::PDF_RENDERER_TCPDF,
* PHPExcel\Settings::PDF_RENDERER_DOMPDF
* or PHPExcel\Settings::PDF_RENDERER_MPDF
* @param string $libraryBaseDir Directory path to the library's base folder
*
@ -274,31 +274,31 @@ class Settings
public static function setPdfRenderer($libraryName, $libraryBaseDir)
{
if (!self::setPdfRendererName($libraryName))
return FALSE;
return false;
return self::setPdfRendererPath($libraryBaseDir);
} // function setPdfRenderer()
}
/**
* Identify to PHPExcel the external library to use for rendering PDF files
*
* @param string $libraryName Internal reference name of the library
* e.g. PHPExcel\Settings::PDF_RENDERER_TCPDF,
* PHPExcel\Settings::PDF_RENDERER_DOMPDF
* or PHPExcel\Settings::PDF_RENDERER_MPDF
* e.g. PHPExcel\Settings::PDF_RENDERER_TCPDF,
* PHPExcel\Settings::PDF_RENDERER_DOMPDF
* or PHPExcel\Settings::PDF_RENDERER_MPDF
*
* @return boolean Success or failure
*/
public static function setPdfRendererName($libraryName)
{
if (!in_array($libraryName,self::$_pdfRenderers)) {
return FALSE;
return false;
}
self::$_pdfRendererName = $libraryName;
return TRUE;
} // function setPdfRendererName()
return true;
}
/**
@ -310,19 +310,19 @@ class Settings
public static function setPdfRendererPath($libraryBaseDir)
{
if ((file_exists($libraryBaseDir) === false) || (is_readable($libraryBaseDir) === false)) {
return FALSE;
return false;
}
self::$_pdfRendererPath = $libraryBaseDir;
return TRUE;
} // function setPdfRendererPath()
return true;
}
/**
* Return the PDF Rendering Library that PHPExcel is currently configured to use (e.g. dompdf)
*
* @return string|NULL Internal reference name of the PDF Rendering Library that PHPExcel is
* currently configured to use
* @return string|null Internal reference name of the PDF Rendering Library that PHPExcel is
* currently configured to use
* e.g. PHPExcel\Settings::PDF_RENDERER_TCPDF,
* PHPExcel\Settings::PDF_RENDERER_DOMPDF
* or PHPExcel\Settings::PDF_RENDERER_MPDF
@ -330,18 +330,17 @@ class Settings
public static function getPdfRendererName()
{
return self::$_pdfRendererName;
} // function getPdfRendererName()
}
/**
* Return the directory path to the PDF Rendering Library that PHPExcel is currently configured to use
*
* @return string|NULL Directory Path to the PDF Rendering Library that PHPExcel is
* currently configured to use
* @return string|null Directory Path to the PDF Rendering Library that PHPExcel is
* currently configured to use
*/
public static function getPdfRendererPath()
{
return self::$_pdfRendererPath;
} // function getPdfRendererPath()
}
}

View File

@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\Shared
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@ -38,71 +38,74 @@ namespace PHPExcel;
class Shared_CodePage
{
protected static $_codepages = array(
case 367 => 'ASCII'; // ASCII
case 437 => 'CP437'; // OEM US
case 737 => 'CP737'; // OEM Greek
case 775 => 'CP775'; // OEM Baltic
case 850 => 'CP850'; // OEM Latin I
case 852 => 'CP852'; // OEM Latin II (Central European)
case 855 => 'CP855'; // OEM Cyrillic
case 857 => 'CP857'; // OEM Turkish
case 858 => 'CP858'; // OEM Multilingual Latin I with Euro
case 860 => 'CP860'; // OEM Portugese
case 861 => 'CP861'; // OEM Icelandic
case 862 => 'CP862'; // OEM Hebrew
case 863 => 'CP863'; // OEM Canadian (French)
case 864 => 'CP864'; // OEM Arabic
case 865 => 'CP865'; // OEM Nordic
case 866 => 'CP866'; // OEM Cyrillic (Russian)
case 869 => 'CP869'; // OEM Greek (Modern)
case 874 => 'CP874'; // ANSI Thai
case 932 => 'CP932'; // ANSI Japanese Shift-JIS
case 936 => 'CP936'; // ANSI Chinese Simplified GBK
case 949 => 'CP949'; // ANSI Korean (Wansung)
case 950 => 'CP950'; // ANSI Chinese Traditional BIG5
case 1200 => 'UTF-16LE'; // UTF-16 (BIFF8)
case 1250 => 'CP1250'; // ANSI Latin II (Central European)
case 1251 => 'CP1251'; // ANSI Cyrillic
case 0 => 'CP1252'; // CodePage is not always correctly set when the xls file was saved by Apple's Numbers program, so default it
case 1252 => 'CP1252'; // ANSI Latin I (BIFF4-BIFF7)
case 1253 => 'CP1253'; // ANSI Greek
case 1254 => 'CP1254'; // ANSI Turkish
case 1255 => 'CP1255'; // ANSI Hebrew
case 1256 => 'CP1256'; // ANSI Arabic
case 1257 => 'CP1257'; // ANSI Baltic
case 1258 => 'CP1258'; // ANSI Vietnamese
case 1361 => 'CP1361'; // ANSI Korean (Johab)
case 10000 => 'MAC'; // Apple Roman
case 10006 => 'MACGREEK'; // Macintosh Greek
case 10007 => 'MACCYRILLIC'; // Macintosh Cyrillic
case 10029 => 'MACCENTRALEUROPE'; // Macintosh Central Europe
case 10079 => 'MACICELAND'; // Macintosh Icelandic
case 10081 => 'MACTURKISH'; // Macintosh Turkish
case 32768 => 'MAC'; // Apple Roman
case 65000 => 'UTF-7'; // Unicode (UTF-7)
case 65001 => 'UTF-8'; // Unicode (UTF-8)
0 => 'CP1252', // CodePage is not always correctly set when the xls file was saved by Apple's Numbers program, so default it
367 => 'ASCII', // ASCII
437 => 'CP437', // OEM US
737 => 'CP737', // OEM Greek
775 => 'CP775', // OEM Baltic
850 => 'CP850', // OEM Latin I
852 => 'CP852', // OEM Latin II (Central European)
855 => 'CP855', // OEM Cyrillic
857 => 'CP857', // OEM Turkish
858 => 'CP858', // OEM Multilingual Latin I with Euro
860 => 'CP860', // OEM Portugese
861 => 'CP861', // OEM Icelandic
862 => 'CP862', // OEM Hebrew
863 => 'CP863', // OEM Canadian (French)
864 => 'CP864', // OEM Arabic
865 => 'CP865', // OEM Nordic
866 => 'CP866', // OEM Cyrillic (Russian)
869 => 'CP869', // OEM Greek (Modern)
874 => 'CP874', // ANSI Thai
932 => 'CP932', // ANSI Japanese Shift-JIS
936 => 'CP936', // ANSI Chinese Simplified GBK
949 => 'CP949', // ANSI Korean (Wansung)
950 => 'CP950', // ANSI Chinese Traditional BIG5
1200 => 'UTF-16LE', // UTF-16 (BIFF8)
1250 => 'CP1250', // ANSI Latin II (Central European)
1251 => 'CP1251', // ANSI Cyrillic
1252 => 'CP1252', // ANSI Latin I (BIFF4-BIFF7)
1253 => 'CP1253', // ANSI Greek
1254 => 'CP1254', // ANSI Turkish
1255 => 'CP1255', // ANSI Hebrew
1256 => 'CP1256', // ANSI Arabic
1257 => 'CP1257', // ANSI Baltic
1258 => 'CP1258', // ANSI Vietnamese
1361 => 'CP1361', // ANSI Korean (Johab)
10000 => 'MAC', // Apple Roman
10006 => 'MACGREEK', // Macintosh Greek
10007 => 'MACCYRILLIC', // Macintosh Cyrillic
10029 => 'MACCENTRALEUROPE', // Macintosh Central Europe
10079 => 'MACICELAND', // Macintosh Icelandic
10081 => 'MACTURKISH', // Macintosh Turkish
32768 => 'MAC', // Apple Roman
65000 => 'UTF-7', // Unicode (UTF-7)
65001 => 'UTF-8', // Unicode (UTF-8)
);
/**
* Convert Microsoft Code Page Identifier to Code Page Name which iconv
* and mbstring understands
*
* @param integer $codePage Microsoft Code Page Indentifier
* @return string Code Page Name
* @throws PHPExcel\Exception
*/
public static function NumberToName($codePage = 1252)
{
switch ($codePage) {
case 720: throw new Exception('Code page 720 not supported.'); break; // OEM Arabic
case 32769: throw new Exception('Code page 32769 not supported.'); break; // ANSI Latin I (BIFF2-BIFF3)
/**
* Convert Microsoft Code Page Identifier to Code Page Name which iconv
* and mbstring understands
*
* @param integer $codePage Microsoft Code Page Indentifier
* @return string Code Page Name
* @throws PHPExcel\Exception
*/
public static function NumberToName($codePage = 1252)
{
switch ($codePage) {
case 720: // OEM Arabic
throw new Exception('Code page 720 not supported.');
break;
case 32769: // ANSI Latin I (BIFF2-BIFF3)
throw new Exception('Code page 32769 not supported.');
break;
default:
if isset(self::$_codepages[$codePage]) {
if (isset(self::$_codepages[$codePage])) {
return self::$_codepages[$codePage];
}
}
throw new Exception('Unknown codepage: ' . $codePage);
}
}
throw new Exception('Unknown codepage: ' . $codePage);
}
}

View File

@ -20,10 +20,10 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category PHPExcel
* @package PHPExcel\Shared
* @package PHPExcel\Shared
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@ -33,342 +33,340 @@ namespace PHPExcel;
* PHPExcel\Shared_Date
*
* @category PHPExcel
* @package PHPExcel\Shared
* @package PHPExcel\Shared
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
*/
class Shared_Date
{
/** constants */
const CALENDAR_WINDOWS_1900 = 1900; // Base date of 1st Jan 1900 = 1.0
const CALENDAR_MAC_1904 = 1904; // Base date of 2nd Jan 1904 = 1.0
/** constants */
const CALENDAR_WINDOWS_1900 = 1900; // Base date of 1st Jan 1900 = 1.0
const CALENDAR_MAC_1904 = 1904; // Base date of 2nd Jan 1904 = 1.0
/*
* Names of the months of the year, indexed by shortname
* Planned usage for locale settings
*
* @public
* @var string[]
*/
public static $_monthNames = array( 'Jan' => 'January',
'Feb' => 'February',
'Mar' => 'March',
'Apr' => 'April',
'May' => 'May',
'Jun' => 'June',
'Jul' => 'July',
'Aug' => 'August',
'Sep' => 'September',
'Oct' => 'October',
'Nov' => 'November',
'Dec' => 'December',
);
/*
* Names of the months of the year, indexed by shortname
* Planned usage for locale settings
*
* @public
* @var string[]
*/
public static $_monthNames = array( 'Jan' => 'January',
'Feb' => 'February',
'Mar' => 'March',
'Apr' => 'April',
'May' => 'May',
'Jun' => 'June',
'Jul' => 'July',
'Aug' => 'August',
'Sep' => 'September',
'Oct' => 'October',
'Nov' => 'November',
'Dec' => 'December',
);
/*
* Names of the months of the year, indexed by shortname
* Planned usage for locale settings
*
* @public
* @var string[]
*/
public static $_numberSuffixes = array( 'st',
'nd',
'rd',
'th',
);
/*
* Names of the months of the year, indexed by shortname
* Planned usage for locale settings
*
* @public
* @var string[]
*/
public static $_numberSuffixes = array( 'st',
'nd',
'rd',
'th',
);
/*
* Base calendar year to use for calculations
*
* @private
* @var int
*/
protected static $_excelBaseDate = self::CALENDAR_WINDOWS_1900;
/*
* Base calendar year to use for calculations
*
* @private
* @var int
*/
protected static $_excelBaseDate = self::CALENDAR_WINDOWS_1900;
/**
* Set the Excel calendar (Windows 1900 or Mac 1904)
*
* @param integer $baseDate Excel base date (1900 or 1904)
* @return boolean Success or failure
*/
public static function setExcelCalendar($baseDate) {
if (($baseDate == self::CALENDAR_WINDOWS_1900) ||
($baseDate == self::CALENDAR_MAC_1904)) {
self::$_excelBaseDate = $baseDate;
return TRUE;
}
return FALSE;
} // function setExcelCalendar()
/**
* Set the Excel calendar (Windows 1900 or Mac 1904)
*
* @param integer $baseDate Excel base date (1900 or 1904)
* @return boolean Success or failure
*/
public static function setExcelCalendar($baseDate) {
if (($baseDate == self::CALENDAR_WINDOWS_1900) ||
($baseDate == self::CALENDAR_MAC_1904)) {
self::$_excelBaseDate = $baseDate;
return TRUE;
}
return false;
} // function setExcelCalendar()
/**
* Return the Excel calendar (Windows 1900 or Mac 1904)
*
* @return integer Excel base date (1900 or 1904)
*/
public static function getExcelCalendar() {
return self::$_excelBaseDate;
} // function getExcelCalendar()
/**
* Return the Excel calendar (Windows 1900 or Mac 1904)
*
* @return integer Excel base date (1900 or 1904)
*/
public static function getExcelCalendar() {
return self::$_excelBaseDate;
} // function getExcelCalendar()
/**
* Convert a date from Excel to PHP
*
* @param long $dateValue Excel date/time value
* @param boolean $adjustToTimezone Flag indicating whether $dateValue should be treated as
* a UST timestamp, or adjusted to UST
* @param string $timezone The timezone for finding the adjustment from UST
* @return long PHP serialized date/time
*/
public static function ExcelToPHP($dateValue = 0, $adjustToTimezone = FALSE, $timezone = NULL) {
if (self::$_excelBaseDate == self::CALENDAR_WINDOWS_1900) {
$my_excelBaseDate = 25569;
// Adjust for the spurious 29-Feb-1900 (Day 60)
if ($dateValue < 60) {
--$my_excelBaseDate;
}
} else {
$my_excelBaseDate = 24107;
}
/**
* Convert a date from Excel to PHP
*
* @param long $dateValue Excel date/time value
* @param boolean $adjustToTimezone Flag indicating whether $dateValue should be treated as
* a UST timestamp, or adjusted to UST
* @param string $timezone The timezone for finding the adjustment from UST
* @return long PHP serialized date/time
*/
public static function ExcelToPHP($dateValue = 0, $adjustToTimezone = false, $timezone = null) {
if (self::$_excelBaseDate == self::CALENDAR_WINDOWS_1900) {
$my_excelBaseDate = 25569;
// Adjust for the spurious 29-Feb-1900 (Day 60)
if ($dateValue < 60) {
--$my_excelBaseDate;
}
} else {
$my_excelBaseDate = 24107;
}
// Perform conversion
if ($dateValue >= 1) {
$utcDays = $dateValue - $my_excelBaseDate;
$returnValue = round($utcDays * 86400);
if (($returnValue <= PHP_INT_MAX) && ($returnValue >= -PHP_INT_MAX)) {
$returnValue = (integer) $returnValue;
}
} else {
$hours = round($dateValue * 24);
$mins = round($dateValue * 1440) - round($hours * 60);
$secs = round($dateValue * 86400) - round($hours * 3600) - round($mins * 60);
$returnValue = (integer) gmmktime($hours, $mins, $secs);
}
// Perform conversion
if ($dateValue >= 1) {
$utcDays = $dateValue - $my_excelBaseDate;
$returnValue = round($utcDays * 86400);
if (($returnValue <= PHP_INT_MAX) && ($returnValue >= -PHP_INT_MAX)) {
$returnValue = (integer) $returnValue;
}
} else {
$hours = round($dateValue * 24);
$mins = round($dateValue * 1440) - round($hours * 60);
$secs = round($dateValue * 86400) - round($hours * 3600) - round($mins * 60);
$returnValue = (integer) gmmktime($hours, $mins, $secs);
}
$timezoneAdjustment = ($adjustToTimezone) ?
Shared_TimeZone::getTimezoneAdjustment($timezone, $returnValue) :
0;
$timezoneAdjustment = ($adjustToTimezone) ?
Shared_TimeZone::getTimezoneAdjustment($timezone, $returnValue) :
0;
// Return
return $returnValue + $timezoneAdjustment;
} // function ExcelToPHP()
// Return
return $returnValue + $timezoneAdjustment;
} // function ExcelToPHP()
/**
* Convert a date from Excel to a PHP Date/Time object
*
* @param integer $dateValue Excel date/time value
* @return integer PHP date/time object
*/
public static function ExcelToPHPObject($dateValue = 0) {
$dateTime = self::ExcelToPHP($dateValue);
$days = floor($dateTime / 86400);
$time = round((($dateTime / 86400) - $days) * 86400);
$hours = round($time / 3600);
$minutes = round($time / 60) - ($hours * 60);
$seconds = round($time) - ($hours * 3600) - ($minutes * 60);
/**
* Convert a date from Excel to a PHP Date/Time object
*
* @param integer $dateValue Excel date/time value
* @return integer PHP date/time object
*/
public static function ExcelToPHPObject($dateValue = 0) {
$dateTime = self::ExcelToPHP($dateValue);
$days = floor($dateTime / 86400);
$time = round((($dateTime / 86400) - $days) * 86400);
$hours = round($time / 3600);
$minutes = round($time / 60) - ($hours * 60);
$seconds = round($time) - ($hours * 3600) - ($minutes * 60);
$dateObj = date_create('1-Jan-1970+'.$days.' days');
$dateObj->setTime($hours,$minutes,$seconds);
$dateObj = date_create('1-Jan-1970+'.$days.' days');
$dateObj->setTime($hours,$minutes,$seconds);
return $dateObj;
} // function ExcelToPHPObject()
return $dateObj;
} // function ExcelToPHPObject()
/**
* Convert a date from PHP to Excel
*
* @param mixed $dateValue PHP serialized date/time or date object
* @param boolean $adjustToTimezone Flag indicating whether $dateValue should be treated as
* a UST timestamp, or adjusted to UST
* @param string $timezone The timezone for finding the adjustment from UST
* @return mixed Excel date/time value
* or boolean FALSE on failure
*/
public static function PHPToExcel($dateValue = 0, $adjustToTimezone = FALSE, $timezone = NULL) {
$saveTimeZone = date_default_timezone_get();
date_default_timezone_set('UTC');
$retValue = FALSE;
if ((is_object($dateValue)) && ($dateValue instanceof DateTime)) {
$retValue = self::FormattedPHPToExcel( $dateValue->format('Y'), $dateValue->format('m'), $dateValue->format('d'),
$dateValue->format('H'), $dateValue->format('i'), $dateValue->format('s')
);
} elseif (is_numeric($dateValue)) {
$retValue = self::FormattedPHPToExcel( date('Y',$dateValue), date('m',$dateValue), date('d',$dateValue),
date('H',$dateValue), date('i',$dateValue), date('s',$dateValue)
);
}
date_default_timezone_set($saveTimeZone);
/**
* Convert a date from PHP to Excel
*
* @param mixed $dateValue PHP serialized date/time or date object
* @param boolean $adjustToTimezone Flag indicating whether $dateValue should be treated as
* a UST timestamp, or adjusted to UST
* @param string $timezone The timezone for finding the adjustment from UST
* @return mixed Excel date/time value
* or boolean FALSE on failure
*/
public static function PHPToExcel($dateValue = 0, $adjustToTimezone = false, $timezone = null) {
$saveTimeZone = date_default_timezone_get();
date_default_timezone_set('UTC');
$retValue = false;
if ((is_object($dateValue)) && ($dateValue instanceof DateTime)) {
$retValue = self::FormattedPHPToExcel( $dateValue->format('Y'), $dateValue->format('m'), $dateValue->format('d'),
$dateValue->format('H'), $dateValue->format('i'), $dateValue->format('s')
);
} elseif (is_numeric($dateValue)) {
$retValue = self::FormattedPHPToExcel( date('Y',$dateValue), date('m',$dateValue), date('d',$dateValue),
date('H',$dateValue), date('i',$dateValue), date('s',$dateValue)
);
}
date_default_timezone_set($saveTimeZone);
return $retValue;
} // function PHPToExcel()
return $retValue;
} // function PHPToExcel()
/**
* FormattedPHPToExcel
*
* @param long $year
* @param long $month
* @param long $day
* @param long $hours
* @param long $minutes
* @param long $seconds
* @return long Excel date/time value
*/
public static function FormattedPHPToExcel($year, $month, $day, $hours=0, $minutes=0, $seconds=0) {
if (self::$_excelBaseDate == self::CALENDAR_WINDOWS_1900) {
//
// Fudge factor for the erroneous fact that the year 1900 is treated as a Leap Year in MS Excel
// This affects every date following 28th February 1900
//
$excel1900isLeapYear = TRUE;
if (($year == 1900) && ($month <= 2)) { $excel1900isLeapYear = FALSE; }
$my_excelBaseDate = 2415020;
} else {
$my_excelBaseDate = 2416481;
$excel1900isLeapYear = FALSE;
}
/**
* FormattedPHPToExcel
*
* @param long $year
* @param long $month
* @param long $day
* @param long $hours
* @param long $minutes
* @param long $seconds
* @return long Excel date/time value
*/
public static function FormattedPHPToExcel($year, $month, $day, $hours=0, $minutes=0, $seconds=0) {
if (self::$_excelBaseDate == self::CALENDAR_WINDOWS_1900) {
//
// Fudge factor for the erroneous fact that the year 1900 is treated as a Leap Year in MS Excel
// This affects every date following 28th February 1900
//
$excel1900isLeapYear = TRUE;
if (($year == 1900) && ($month <= 2)) { $excel1900isLeapYear = false; }
$my_excelBaseDate = 2415020;
} else {
$my_excelBaseDate = 2416481;
$excel1900isLeapYear = false;
}
// Julian base date Adjustment
if ($month > 2) {
$month -= 3;
} else {
$month += 9;
--$year;
}
// Julian base date Adjustment
if ($month > 2) {
$month -= 3;
} else {
$month += 9;
--$year;
}
// Calculate the Julian Date, then subtract the Excel base date (JD 2415020 = 31-Dec-1899 Giving Excel Date of 0)
$century = substr($year,0,2);
$decade = substr($year,2,2);
$excelDate = floor((146097 * $century) / 4) + floor((1461 * $decade) / 4) + floor((153 * $month + 2) / 5) + $day + 1721119 - $my_excelBaseDate + $excel1900isLeapYear;
// Calculate the Julian Date, then subtract the Excel base date (JD 2415020 = 31-Dec-1899 Giving Excel Date of 0)
$century = substr($year,0,2);
$decade = substr($year,2,2);
$excelDate = floor((146097 * $century) / 4) + floor((1461 * $decade) / 4) + floor((153 * $month + 2) / 5) + $day + 1721119 - $my_excelBaseDate + $excel1900isLeapYear;
$excelTime = (($hours * 3600) + ($minutes * 60) + $seconds) / 86400;
$excelTime = (($hours * 3600) + ($minutes * 60) + $seconds) / 86400;
return (float) $excelDate + $excelTime;
} // function FormattedPHPToExcel()
return (float) $excelDate + $excelTime;
} // function FormattedPHPToExcel()
/**
* Is a given cell a date/time?
*
* @param PHPExcel\Cell $pCell
* @return boolean
*/
public static function isDateTime(Cell $pCell) {
return self::isDateTimeFormat(
$pCell->getWorksheet()->getStyle(
$pCell->getCoordinate()
)->getNumberFormat()
);
} // function isDateTime()
/**
* Is a given cell a date/time?
*
* @param PHPExcel\Cell $pCell
* @return boolean
*/
public static function isDateTime(Cell $pCell) {
return self::isDateTimeFormat(
$pCell->getWorksheet()->getStyle(
$pCell->getCoordinate()
)->getNumberFormat()
);
} // function isDateTime()
/**
* Is a given number format a date/time?
*
* @param Style_NumberFormat $pFormat
* @return boolean
*/
public static function isDateTimeFormat(Style_NumberFormat $pFormat) {
return self::isDateTimeFormatCode($pFormat->getFormatCode());
} // function isDateTimeFormat()
/**
* Is a given number format a date/time?
*
* @param Style_NumberFormat $pFormat
* @return boolean
*/
public static function isDateTimeFormat(Style_NumberFormat $pFormat) {
return self::isDateTimeFormatCode($pFormat->getFormatCode());
} // function isDateTimeFormat()
private static $possibleDateFormatCharacters = 'eymdHs';
private static $possibleDateFormatCharacters = 'eymdHs';
/**
* Is a given number format code a date/time?
*
* @param string $pFormatCode
* @return boolean
*/
public static function isDateTimeFormatCode($pFormatCode = '') {
// Switch on formatcode
switch ($pFormatCode) {
// General contains an epoch letter 'e', so we trap for it explicitly here
case Style_NumberFormat::FORMAT_GENERAL:
return FALSE;
// Explicitly defined date formats
case Style_NumberFormat::FORMAT_DATE_YYYYMMDD:
case Style_NumberFormat::FORMAT_DATE_YYYYMMDD2:
case Style_NumberFormat::FORMAT_DATE_DDMMYYYY:
case Style_NumberFormat::FORMAT_DATE_DMYSLASH:
case Style_NumberFormat::FORMAT_DATE_DMYMINUS:
case Style_NumberFormat::FORMAT_DATE_DMMINUS:
case Style_NumberFormat::FORMAT_DATE_MYMINUS:
case Style_NumberFormat::FORMAT_DATE_DATETIME:
case Style_NumberFormat::FORMAT_DATE_TIME1:
case Style_NumberFormat::FORMAT_DATE_TIME2:
case Style_NumberFormat::FORMAT_DATE_TIME3:
case Style_NumberFormat::FORMAT_DATE_TIME4:
case Style_NumberFormat::FORMAT_DATE_TIME5:
case Style_NumberFormat::FORMAT_DATE_TIME6:
case Style_NumberFormat::FORMAT_DATE_TIME7:
case Style_NumberFormat::FORMAT_DATE_TIME8:
case Style_NumberFormat::FORMAT_DATE_YYYYMMDDSLASH:
case Style_NumberFormat::FORMAT_DATE_XLSX14:
case Style_NumberFormat::FORMAT_DATE_XLSX15:
case Style_NumberFormat::FORMAT_DATE_XLSX16:
case Style_NumberFormat::FORMAT_DATE_XLSX17:
case Style_NumberFormat::FORMAT_DATE_XLSX22:
return TRUE;
}
/**
* Is a given number format code a date/time?
*
* @param string $pFormatCode
* @return boolean
*/
public static function isDateTimeFormatCode($pFormatCode = '') {
// Switch on formatcode
switch ($pFormatCode) {
// General contains an epoch letter 'e', so we trap for it explicitly here
case Style_NumberFormat::FORMAT_GENERAL:
return false;
// Explicitly defined date formats
case Style_NumberFormat::FORMAT_DATE_YYYYMMDD:
case Style_NumberFormat::FORMAT_DATE_YYYYMMDD2:
case Style_NumberFormat::FORMAT_DATE_DDMMYYYY:
case Style_NumberFormat::FORMAT_DATE_DMYSLASH:
case Style_NumberFormat::FORMAT_DATE_DMYMINUS:
case Style_NumberFormat::FORMAT_DATE_DMMINUS:
case Style_NumberFormat::FORMAT_DATE_MYMINUS:
case Style_NumberFormat::FORMAT_DATE_DATETIME:
case Style_NumberFormat::FORMAT_DATE_TIME1:
case Style_NumberFormat::FORMAT_DATE_TIME2:
case Style_NumberFormat::FORMAT_DATE_TIME3:
case Style_NumberFormat::FORMAT_DATE_TIME4:
case Style_NumberFormat::FORMAT_DATE_TIME5:
case Style_NumberFormat::FORMAT_DATE_TIME6:
case Style_NumberFormat::FORMAT_DATE_TIME7:
case Style_NumberFormat::FORMAT_DATE_TIME8:
case Style_NumberFormat::FORMAT_DATE_YYYYMMDDSLASH:
case Style_NumberFormat::FORMAT_DATE_XLSX14:
case Style_NumberFormat::FORMAT_DATE_XLSX15:
case Style_NumberFormat::FORMAT_DATE_XLSX16:
case Style_NumberFormat::FORMAT_DATE_XLSX17:
case Style_NumberFormat::FORMAT_DATE_XLSX22:
return TRUE;
}
// Typically number, currency or accounting (or occasionally fraction) formats
if ((substr($pFormatCode,0,1) == '_') || (substr($pFormatCode,0,2) == '0 ')) {
return FALSE;
}
// Try checking for any of the date formatting characters that don't appear within square braces
if (preg_match('/(^|\])[^\[]*['.self::$possibleDateFormatCharacters.']/i',$pFormatCode)) {
// We might also have a format mask containing quoted strings...
// we don't want to test for any of our characters within the quoted blocks
if (strpos($pFormatCode,'"') !== FALSE) {
$segMatcher = FALSE;
foreach(explode('"',$pFormatCode) as $subVal) {
// Only test in alternate array entries (the non-quoted blocks)
if (($segMatcher = !$segMatcher) &&
(preg_match('/(^|\])[^\[]*['.self::$possibleDateFormatCharacters.']/i',$subVal))) {
return TRUE;
}
}
return FALSE;
}
return TRUE;
}
// Typically number, currency or accounting (or occasionally fraction) formats
if ((substr($pFormatCode,0,1) == '_') || (substr($pFormatCode,0,2) == '0 ')) {
return false;
}
// Try checking for any of the date formatting characters that don't appear within square braces
if (preg_match('/(^|\])[^\[]*['.self::$possibleDateFormatCharacters.']/i',$pFormatCode)) {
// We might also have a format mask containing quoted strings...
// we don't want to test for any of our characters within the quoted blocks
if (strpos($pFormatCode,'"') !== false) {
$segMatcher = false;
foreach(explode('"',$pFormatCode) as $subVal) {
// Only test in alternate array entries (the non-quoted blocks)
if (($segMatcher = !$segMatcher) &&
(preg_match('/(^|\])[^\[]*['.self::$possibleDateFormatCharacters.']/i',$subVal))) {
return true;
}
}
return false;
}
return true;
}
// No date...
return FALSE;
} // function isDateTimeFormatCode()
// No date...
return false;
} // function isDateTimeFormatCode()
/**
* Convert a date/time string to Excel time
*
* @param string $dateValue Examples: '2009-12-31', '2009-12-31 15:59', '2009-12-31 15:59:10'
* @return float|FALSE Excel date/time serial value
*/
public static function stringToExcel($dateValue = '') {
if (strlen($dateValue) < 2)
return FALSE;
if (!preg_match('/^(\d{1,4}[ \.\/\-][A-Z]{3,9}([ \.\/\-]\d{1,4})?|[A-Z]{3,9}[ \.\/\-]\d{1,4}([ \.\/\-]\d{1,4})?|\d{1,4}[ \.\/\-]\d{1,4}([ \.\/\-]\d{1,4})?)( \d{1,2}:\d{1,2}(:\d{1,2})?)?$/iu', $dateValue))
return FALSE;
/**
* Convert a date/time string to Excel time
*
* @param string $dateValue Examples: '2009-12-31', '2009-12-31 15:59', '2009-12-31 15:59:10'
* @return float|false Excel date/time serial value
*/
public static function stringToExcel($dateValue = '') {
if (strlen($dateValue) < 2)
return false;
if (!preg_match('/^(\d{1,4}[ \.\/\-][A-Z]{3,9}([ \.\/\-]\d{1,4})?|[A-Z]{3,9}[ \.\/\-]\d{1,4}([ \.\/\-]\d{1,4})?|\d{1,4}[ \.\/\-]\d{1,4}([ \.\/\-]\d{1,4})?)( \d{1,2}:\d{1,2}(:\d{1,2})?)?$/iu', $dateValue))
return false;
$dateValueNew = Calculation_DateTime::DATEVALUE($dateValue);
$dateValueNew = Calculation_DateTime::DATEVALUE($dateValue);
if ($dateValueNew === Calculation_Functions::VALUE()) {
return FALSE;
} else {
if (strpos($dateValue, ':') !== FALSE) {
$timeValue = Calculation_DateTime::TIMEVALUE($dateValue);
if ($timeValue === Calculation_Functions::VALUE()) {
return FALSE;
}
$dateValueNew += $timeValue;
}
return $dateValueNew;
}
}
if ($dateValueNew === Calculation_Functions::VALUE()) {
return false;
} else {
if (strpos($dateValue, ':') !== false) {
$timeValue = Calculation_DateTime::TIMEVALUE($dateValue);
if ($timeValue === Calculation_Functions::VALUE()) {
return false;
}
$dateValueNew += $timeValue;
}
return $dateValueNew;
}
}
public static function monthStringToNumber($month) {
$monthIndex = 1;
@ -382,11 +380,10 @@ class Shared_Date
}
public static function dayStringToNumber($day) {
$strippedDayValue = (str_replace(self::$_numberSuffixes,'',$day));
if (is_numeric($strippedDayValue)) {
return $strippedDayValue;
}
return $day;
$strippedDayValue = (str_replace(self::$_numberSuffixes,'',$day));
if (is_numeric($strippedDayValue)) {
return $strippedDayValue;
}
return $day;
}
}

View File

@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\Shared
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@ -37,149 +37,149 @@ namespace PHPExcel;
*/
class Shared_Drawing
{
/**
* Convert pixels to EMU
*
* @param int $pValue Value in pixels
* @return int Value in EMU
*/
public static function pixelsToEMU($pValue = 0) {
return round($pValue * 9525);
}
/**
* Convert pixels to EMU
*
* @param int $pValue Value in pixels
* @return int Value in EMU
*/
public static function pixelsToEMU($pValue = 0) {
return round($pValue * 9525);
}
/**
* Convert EMU to pixels
*
* @param int $pValue Value in EMU
* @return int Value in pixels
*/
public static function EMUToPixels($pValue = 0) {
if ($pValue != 0) {
return round($pValue / 9525);
} else {
return 0;
}
}
/**
* Convert EMU to pixels
*
* @param int $pValue Value in EMU
* @return int Value in pixels
*/
public static function EMUToPixels($pValue = 0) {
if ($pValue != 0) {
return round($pValue / 9525);
} else {
return 0;
}
}
/**
* Convert pixels to column width. Exact algorithm not known.
* By inspection of a real Excel file using Calibri 11, one finds 1000px ~ 142.85546875
* This gives a conversion factor of 7. Also, we assume that pixels and font size are proportional.
*
* @param int $pValue Value in pixels
* @param PHPExcel\Style_Font $pDefaultFont Default font of the workbook
* @return int Value in cell dimension
*/
public static function pixelsToCellDimension($pValue = 0, Style_Font $pDefaultFont) {
// Font name and size
$name = $pDefaultFont->getName();
$size = $pDefaultFont->getSize();
/**
* Convert pixels to column width. Exact algorithm not known.
* By inspection of a real Excel file using Calibri 11, one finds 1000px ~ 142.85546875
* This gives a conversion factor of 7. Also, we assume that pixels and font size are proportional.
*
* @param int $pValue Value in pixels
* @param PHPExcel\Style_Font $pDefaultFont Default font of the workbook
* @return int Value in cell dimension
*/
public static function pixelsToCellDimension($pValue = 0, Style_Font $pDefaultFont) {
// Font name and size
$name = $pDefaultFont->getName();
$size = $pDefaultFont->getSize();
if (isset(Shared_Font::$defaultColumnWidths[$name][$size])) {
// Exact width can be determined
$colWidth = $pValue
* Shared_Font::$defaultColumnWidths[$name][$size]['width']
/ Shared_Font::$defaultColumnWidths[$name][$size]['px'];
} else {
// We don't have data for this particular font and size, use approximation by
// extrapolating from Calibri 11
$colWidth = $pValue * 11
* Shared_Font::$defaultColumnWidths['Calibri'][11]['width']
/ Shared_Font::$defaultColumnWidths['Calibri'][11]['px'] / $size;
}
if (isset(Shared_Font::$defaultColumnWidths[$name][$size])) {
// Exact width can be determined
$colWidth = $pValue
* Shared_Font::$defaultColumnWidths[$name][$size]['width']
/ Shared_Font::$defaultColumnWidths[$name][$size]['px'];
} else {
// We don't have data for this particular font and size, use approximation by
// extrapolating from Calibri 11
$colWidth = $pValue * 11
* Shared_Font::$defaultColumnWidths['Calibri'][11]['width']
/ Shared_Font::$defaultColumnWidths['Calibri'][11]['px'] / $size;
}
return $colWidth;
}
return $colWidth;
}
/**
* Convert column width from (intrinsic) Excel units to pixels
*
* @param float $pValue Value in cell dimension
* @param PHPExcel\Style_Font $pDefaultFont Default font of the workbook
* @return int Value in pixels
*/
public static function cellDimensionToPixels($pValue = 0, Style_Font $pDefaultFont) {
// Font name and size
$name = $pDefaultFont->getName();
$size = $pDefaultFont->getSize();
/**
* Convert column width from (intrinsic) Excel units to pixels
*
* @param float $pValue Value in cell dimension
* @param PHPExcel\Style_Font $pDefaultFont Default font of the workbook
* @return int Value in pixels
*/
public static function cellDimensionToPixels($pValue = 0, Style_Font $pDefaultFont) {
// Font name and size
$name = $pDefaultFont->getName();
$size = $pDefaultFont->getSize();
if (isset(Shared_Font::$defaultColumnWidths[$name][$size])) {
// Exact width can be determined
$colWidth = $pValue
* Shared_Font::$defaultColumnWidths[$name][$size]['px']
/ Shared_Font::$defaultColumnWidths[$name][$size]['width'];
if (isset(Shared_Font::$defaultColumnWidths[$name][$size])) {
// Exact width can be determined
$colWidth = $pValue
* Shared_Font::$defaultColumnWidths[$name][$size]['px']
/ Shared_Font::$defaultColumnWidths[$name][$size]['width'];
} else {
// We don't have data for this particular font and size, use approximation by
// extrapolating from Calibri 11
$colWidth = $pValue * $size
* Shared_Font::$defaultColumnWidths['Calibri'][11]['px']
/ Shared_Font::$defaultColumnWidths['Calibri'][11]['width'] / 11;
}
} else {
// We don't have data for this particular font and size, use approximation by
// extrapolating from Calibri 11
$colWidth = $pValue * $size
* Shared_Font::$defaultColumnWidths['Calibri'][11]['px']
/ Shared_Font::$defaultColumnWidths['Calibri'][11]['width'] / 11;
}
// Round pixels to closest integer
$colWidth = (int) round($colWidth);
// Round pixels to closest integer
$colWidth = (int) round($colWidth);
return $colWidth;
}
return $colWidth;
}
/**
* Convert pixels to points
*
* @param int $pValue Value in pixels
* @return int Value in points
*/
public static function pixelsToPoints($pValue = 0) {
return $pValue * 0.67777777;
}
/**
* Convert pixels to points
*
* @param int $pValue Value in pixels
* @return int Value in points
*/
public static function pixelsToPoints($pValue = 0) {
return $pValue * 0.67777777;
}
/**
* Convert points to pixels
*
* @param int $pValue Value in points
* @return int Value in pixels
*/
public static function pointsToPixels($pValue = 0) {
if ($pValue != 0) {
return (int) ceil($pValue * 1.333333333);
} else {
return 0;
}
}
/**
* Convert points to pixels
*
* @param int $pValue Value in points
* @return int Value in pixels
*/
public static function pointsToPixels($pValue = 0) {
if ($pValue != 0) {
return (int) ceil($pValue * 1.333333333);
} else {
return 0;
}
}
/**
* Convert degrees to angle
*
* @param int $pValue Degrees
* @return int Angle
*/
public static function degreesToAngle($pValue = 0) {
return (int)round($pValue * 60000);
}
/**
* Convert degrees to angle
*
* @param int $pValue Degrees
* @return int Angle
*/
public static function degreesToAngle($pValue = 0) {
return (int)round($pValue * 60000);
}
/**
* Convert angle to degrees
*
* @param int $pValue Angle
* @return int Degrees
*/
public static function angleToDegrees($pValue = 0) {
if ($pValue != 0) {
return round($pValue / 60000);
} else {
return 0;
}
}
/**
* Convert angle to degrees
*
* @param int $pValue Angle
* @return int Degrees
*/
public static function angleToDegrees($pValue = 0) {
if ($pValue != 0) {
return round($pValue / 60000);
} else {
return 0;
}
}
/**
* Create a new image from file. By alexander at alexauto dot nl
*
* @link http://www.php.net/manual/en/function.imagecreatefromwbmp.php#86214
* @param string $filename Path to Windows DIB (BMP) image
* @return resource
*/
public static function imagecreatefrombmp($p_sFile)
{
/**
* Create a new image from file. By alexander at alexauto dot nl
*
* @link http://www.php.net/manual/en/function.imagecreatefromwbmp.php#86214
* @param string $filename Path to Windows DIB (BMP) image
* @return resource
*/
public static function imagecreatefrombmp($p_sFile)
{
// Load the image into a string
$file = fopen($p_sFile,"rb");
$read = fread($file,10);
@ -269,6 +269,6 @@ class Shared_Drawing
// Return image-object
return $image;
}
}
}

View File

@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\Shared_Escher
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@ -37,58 +37,58 @@ namespace PHPExcel;
*/
class Shared_Escher
{
/**
* Drawing Group Container
*
* @var PHPExcel\Shared_Escher_DggContainer
*/
private $_dggContainer;
/**
* Drawing Group Container
*
* @var PHPExcel\Shared_Escher_DggContainer
*/
private $_dggContainer;
/**
* Drawing Container
*
* @var PHPExcel\Shared_Escher_DgContainer
*/
private $_dgContainer;
/**
* Drawing Container
*
* @var PHPExcel\Shared_Escher_DgContainer
*/
private $_dgContainer;
/**
* Get Drawing Group Container
*
* @return PHPExcel\Shared_Escher_DgContainer
*/
public function getDggContainer()
{
return $this->_dggContainer;
}
/**
* Get Drawing Group Container
*
* @return PHPExcel\Shared_Escher_DgContainer
*/
public function getDggContainer()
{
return $this->_dggContainer;
}
/**
* Set Drawing Group Container
*
* @param PHPExcel\Shared_Escher_DggContainer $dggContainer
*/
public function setDggContainer($dggContainer)
{
return $this->_dggContainer = $dggContainer;
}
/**
* Set Drawing Group Container
*
* @param PHPExcel\Shared_Escher_DggContainer $dggContainer
*/
public function setDggContainer($dggContainer)
{
return $this->_dggContainer = $dggContainer;
}
/**
* Get Drawing Container
*
* @return PHPExcel\Shared_Escher_DgContainer
*/
public function getDgContainer()
{
return $this->_dgContainer;
}
/**
* Get Drawing Container
*
* @return PHPExcel\Shared_Escher_DgContainer
*/
public function getDgContainer()
{
return $this->_dgContainer;
}
/**
* Set Drawing Container
*
* @param PHPExcel\Shared_Escher_DgContainer $dgContainer
*/
public function setDgContainer($dgContainer)
{
return $this->_dgContainer = $dgContainer;
}
/**
* Set Drawing Container
*
* @param PHPExcel\Shared_Escher_DgContainer $dgContainer
*/
public function setDgContainer($dgContainer)
{
return $this->_dgContainer = $dgContainer;
}
}

View File

@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\Shared_Escher
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@ -37,50 +37,50 @@ namespace PHPExcel;
*/
class Shared_Escher_DgContainer
{
/**
* Drawing index, 1-based.
*
* @var int
*/
private $_dgId;
/**
* Drawing index, 1-based.
*
* @var int
*/
private $_dgId;
/**
* Last shape index in this drawing
*
* @var int
*/
private $_lastSpId;
/**
* Last shape index in this drawing
*
* @var int
*/
private $_lastSpId;
private $_spgrContainer = null;
private $_spgrContainer = null;
public function getDgId()
{
return $this->_dgId;
}
public function getDgId()
{
return $this->_dgId;
}
public function setDgId($value)
{
$this->_dgId = $value;
}
public function setDgId($value)
{
$this->_dgId = $value;
}
public function getLastSpId()
{
return $this->_lastSpId;
}
public function getLastSpId()
{
return $this->_lastSpId;
}
public function setLastSpId($value)
{
$this->_lastSpId = $value;
}
public function setLastSpId($value)
{
$this->_lastSpId = $value;
}
public function getSpgrContainer()
{
return $this->_spgrContainer;
}
public function getSpgrContainer()
{
return $this->_spgrContainer;
}
public function setSpgrContainer($spgrContainer)
{
return $this->_spgrContainer = $spgrContainer;
}
public function setSpgrContainer($spgrContainer)
{
return $this->_spgrContainer = $spgrContainer;
}
}

View File

@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\Shared_Escher
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@ -37,76 +37,76 @@ namespace PHPExcel;
*/
class Shared_Escher_DgContainer_SpgrContainer
{
/**
* Parent Shape Group Container
*
* @var PHPExcel\Shared_Escher_DgContainer_SpgrContainer
*/
private $_parent;
/**
* Parent Shape Group Container
*
* @var PHPExcel\Shared_Escher_DgContainer_SpgrContainer
*/
private $_parent;
/**
* Shape Container collection
*
* @var array
*/
private $_children = array();
/**
* Shape Container collection
*
* @var array
*/
private $_children = array();
/**
* Set parent Shape Group Container
*
* @param PHPExcel\Shared_Escher_DgContainer_SpgrContainer $parent
*/
public function setParent($parent)
{
$this->_parent = $parent;
}
/**
* Set parent Shape Group Container
*
* @param PHPExcel\Shared_Escher_DgContainer_SpgrContainer $parent
*/
public function setParent($parent)
{
$this->_parent = $parent;
}
/**
* Get the parent Shape Group Container if any
*
* @return PHPExcel\Shared_Escher_DgContainer_SpgrContainer|null
*/
public function getParent()
{
return $this->_parent;
}
/**
* Get the parent Shape Group Container if any
*
* @return PHPExcel\Shared_Escher_DgContainer_SpgrContainer|null
*/
public function getParent()
{
return $this->_parent;
}
/**
* Add a child. This will be either spgrContainer or spContainer
*
* @param mixed $child
*/
public function addChild($child)
{
$this->_children[] = $child;
$child->setParent($this);
}
/**
* Add a child. This will be either spgrContainer or spContainer
*
* @param mixed $child
*/
public function addChild($child)
{
$this->_children[] = $child;
$child->setParent($this);
}
/**
* Get collection of Shape Containers
*/
public function getChildren()
{
return $this->_children;
}
/**
* Get collection of Shape Containers
*/
public function getChildren()
{
return $this->_children;
}
/**
* Recursively get all spContainers within this spgrContainer
*
* @return PHPExcel\Shared_Escher_DgContainer_SpgrContainer_SpContainer[]
*/
public function getAllSpContainers()
{
$allSpContainers = array();
/**
* Recursively get all spContainers within this spgrContainer
*
* @return PHPExcel\Shared_Escher_DgContainer_SpgrContainer_SpContainer[]
*/
public function getAllSpContainers()
{
$allSpContainers = array();
foreach ($this->_children as $child) {
if ($child instanceof Shared_Escher_DgContainer_SpgrContainer) {
$allSpContainers = array_merge($allSpContainers, $child->getAllSpContainers());
} else {
$allSpContainers[] = $child;
}
}
foreach ($this->_children as $child) {
if ($child instanceof Shared_Escher_DgContainer_SpgrContainer) {
$allSpContainers = array_merge($allSpContainers, $child->getAllSpContainers());
} else {
$allSpContainers[] = $child;
}
}
return $allSpContainers;
}
return $allSpContainers;
}
}

View File

@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\Shared_Escher
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@ -37,362 +37,362 @@ namespace PHPExcel;
*/
class Shared_Escher_DgContainer_SpgrContainer_SpContainer
{
/**
* Parent Shape Group Container
*
* @var PHPExcel\Shared_Escher_DgContainer_SpgrContainer
*/
private $_parent;
/**
* Parent Shape Group Container
*
* @var PHPExcel\Shared_Escher_DgContainer_SpgrContainer
*/
private $_parent;
/**
* Is this a group shape?
*
* @var boolean
*/
private $_spgr = false;
/**
* Is this a group shape?
*
* @var boolean
*/
private $_spgr = false;
/**
* Shape type
*
* @var int
*/
private $_spType;
/**
* Shape type
*
* @var int
*/
private $_spType;
/**
* Shape flag
*
* @var int
*/
private $_spFlag;
/**
* Shape flag
*
* @var int
*/
private $_spFlag;
/**
* Shape index (usually group shape has index 0, and the rest: 1,2,3...)
*
* @var boolean
*/
private $_spId;
/**
* Shape index (usually group shape has index 0, and the rest: 1,2,3...)
*
* @var boolean
*/
private $_spId;
/**
* Array of options
*
* @var array
*/
private $_OPT;
/**
* Array of options
*
* @var array
*/
private $_OPT;
/**
* Cell coordinates of upper-left corner of shape, e.g. 'A1'
*
* @var string
*/
private $_startCoordinates;
/**
* Cell coordinates of upper-left corner of shape, e.g. 'A1'
*
* @var string
*/
private $_startCoordinates;
/**
* Horizontal offset of upper-left corner of shape measured in 1/1024 of column width
*
* @var int
*/
private $_startOffsetX;
/**
* Horizontal offset of upper-left corner of shape measured in 1/1024 of column width
*
* @var int
*/
private $_startOffsetX;
/**
* Vertical offset of upper-left corner of shape measured in 1/256 of row height
*
* @var int
*/
private $_startOffsetY;
/**
* Vertical offset of upper-left corner of shape measured in 1/256 of row height
*
* @var int
*/
private $_startOffsetY;
/**
* Cell coordinates of bottom-right corner of shape, e.g. 'B2'
*
* @var string
*/
private $_endCoordinates;
/**
* Cell coordinates of bottom-right corner of shape, e.g. 'B2'
*
* @var string
*/
private $_endCoordinates;
/**
* Horizontal offset of bottom-right corner of shape measured in 1/1024 of column width
*
* @var int
*/
private $_endOffsetX;
/**
* Horizontal offset of bottom-right corner of shape measured in 1/1024 of column width
*
* @var int
*/
private $_endOffsetX;
/**
* Vertical offset of bottom-right corner of shape measured in 1/256 of row height
*
* @var int
*/
private $_endOffsetY;
/**
* Vertical offset of bottom-right corner of shape measured in 1/256 of row height
*
* @var int
*/
private $_endOffsetY;
/**
* Set parent Shape Group Container
*
* @param PHPExcel\Shared_Escher_DgContainer_SpgrContainer $parent
*/
public function setParent($parent)
{
$this->_parent = $parent;
}
/**
* Set parent Shape Group Container
*
* @param PHPExcel\Shared_Escher_DgContainer_SpgrContainer $parent
*/
public function setParent($parent)
{
$this->_parent = $parent;
}
/**
* Get the parent Shape Group Container
*
* @return PHPExcel\Shared_Escher_DgContainer_SpgrContainer
*/
public function getParent()
{
return $this->_parent;
}
/**
* Get the parent Shape Group Container
*
* @return PHPExcel\Shared_Escher_DgContainer_SpgrContainer
*/
public function getParent()
{
return $this->_parent;
}
/**
* Set whether this is a group shape
*
* @param boolean $value
*/
public function setSpgr($value = false)
{
$this->_spgr = $value;
}
/**
* Set whether this is a group shape
*
* @param boolean $value
*/
public function setSpgr($value = false)
{
$this->_spgr = $value;
}
/**
* Get whether this is a group shape
*
* @return boolean
*/
public function getSpgr()
{
return $this->_spgr;
}
/**
* Get whether this is a group shape
*
* @return boolean
*/
public function getSpgr()
{
return $this->_spgr;
}
/**
* Set the shape type
*
* @param int $value
*/
public function setSpType($value)
{
$this->_spType = $value;
}
/**
* Set the shape type
*
* @param int $value
*/
public function setSpType($value)
{
$this->_spType = $value;
}
/**
* Get the shape type
*
* @return int
*/
public function getSpType()
{
return $this->_spType;
}
/**
* Get the shape type
*
* @return int
*/
public function getSpType()
{
return $this->_spType;
}
/**
* Set the shape flag
*
* @param int $value
*/
public function setSpFlag($value)
{
$this->_spFlag = $value;
}
/**
* Set the shape flag
*
* @param int $value
*/
public function setSpFlag($value)
{
$this->_spFlag = $value;
}
/**
* Get the shape flag
*
* @return int
*/
public function getSpFlag()
{
return $this->_spFlag;
}
/**
* Get the shape flag
*
* @return int
*/
public function getSpFlag()
{
return $this->_spFlag;
}
/**
* Set the shape index
*
* @param int $value
*/
public function setSpId($value)
{
$this->_spId = $value;
}
/**
* Set the shape index
*
* @param int $value
*/
public function setSpId($value)
{
$this->_spId = $value;
}
/**
* Get the shape index
*
* @return int
*/
public function getSpId()
{
return $this->_spId;
}
/**
* Get the shape index
*
* @return int
*/
public function getSpId()
{
return $this->_spId;
}
/**
* Set an option for the Shape Group Container
*
* @param int $property The number specifies the option
* @param mixed $value
*/
public function setOPT($property, $value)
{
$this->_OPT[$property] = $value;
}
/**
* Set an option for the Shape Group Container
*
* @param int $property The number specifies the option
* @param mixed $value
*/
public function setOPT($property, $value)
{
$this->_OPT[$property] = $value;
}
/**
* Get an option for the Shape Group Container
*
* @param int $property The number specifies the option
* @return mixed
*/
public function getOPT($property)
{
if (isset($this->_OPT[$property])) {
return $this->_OPT[$property];
}
return null;
}
/**
* Get an option for the Shape Group Container
*
* @param int $property The number specifies the option
* @return mixed
*/
public function getOPT($property)
{
if (isset($this->_OPT[$property])) {
return $this->_OPT[$property];
}
return null;
}
/**
* Get the collection of options
*
* @return array
*/
public function getOPTCollection()
{
return $this->_OPT;
}
/**
* Get the collection of options
*
* @return array
*/
public function getOPTCollection()
{
return $this->_OPT;
}
/**
* Set cell coordinates of upper-left corner of shape
*
* @param string $value
*/
public function setStartCoordinates($value = 'A1')
{
$this->_startCoordinates = $value;
}
/**
* Set cell coordinates of upper-left corner of shape
*
* @param string $value
*/
public function setStartCoordinates($value = 'A1')
{
$this->_startCoordinates = $value;
}
/**
* Get cell coordinates of upper-left corner of shape
*
* @return string
*/
public function getStartCoordinates()
{
return $this->_startCoordinates;
}
/**
* Get cell coordinates of upper-left corner of shape
*
* @return string
*/
public function getStartCoordinates()
{
return $this->_startCoordinates;
}
/**
* Set offset in x-direction of upper-left corner of shape measured in 1/1024 of column width
*
* @param int $startOffsetX
*/
public function setStartOffsetX($startOffsetX = 0)
{
$this->_startOffsetX = $startOffsetX;
}
/**
* Set offset in x-direction of upper-left corner of shape measured in 1/1024 of column width
*
* @param int $startOffsetX
*/
public function setStartOffsetX($startOffsetX = 0)
{
$this->_startOffsetX = $startOffsetX;
}
/**
* Get offset in x-direction of upper-left corner of shape measured in 1/1024 of column width
*
* @return int
*/
public function getStartOffsetX()
{
return $this->_startOffsetX;
}
/**
* Get offset in x-direction of upper-left corner of shape measured in 1/1024 of column width
*
* @return int
*/
public function getStartOffsetX()
{
return $this->_startOffsetX;
}
/**
* Set offset in y-direction of upper-left corner of shape measured in 1/256 of row height
*
* @param int $startOffsetY
*/
public function setStartOffsetY($startOffsetY = 0)
{
$this->_startOffsetY = $startOffsetY;
}
/**
* Set offset in y-direction of upper-left corner of shape measured in 1/256 of row height
*
* @param int $startOffsetY
*/
public function setStartOffsetY($startOffsetY = 0)
{
$this->_startOffsetY = $startOffsetY;
}
/**
* Get offset in y-direction of upper-left corner of shape measured in 1/256 of row height
*
* @return int
*/
public function getStartOffsetY()
{
return $this->_startOffsetY;
}
/**
* Get offset in y-direction of upper-left corner of shape measured in 1/256 of row height
*
* @return int
*/
public function getStartOffsetY()
{
return $this->_startOffsetY;
}
/**
* Set cell coordinates of bottom-right corner of shape
*
* @param string $value
*/
public function setEndCoordinates($value = 'A1')
{
$this->_endCoordinates = $value;
}
/**
* Set cell coordinates of bottom-right corner of shape
*
* @param string $value
*/
public function setEndCoordinates($value = 'A1')
{
$this->_endCoordinates = $value;
}
/**
* Get cell coordinates of bottom-right corner of shape
*
* @return string
*/
public function getEndCoordinates()
{
return $this->_endCoordinates;
}
/**
* Get cell coordinates of bottom-right corner of shape
*
* @return string
*/
public function getEndCoordinates()
{
return $this->_endCoordinates;
}
/**
* Set offset in x-direction of bottom-right corner of shape measured in 1/1024 of column width
*
* @param int $startOffsetX
*/
public function setEndOffsetX($endOffsetX = 0)
{
$this->_endOffsetX = $endOffsetX;
}
/**
* Set offset in x-direction of bottom-right corner of shape measured in 1/1024 of column width
*
* @param int $startOffsetX
*/
public function setEndOffsetX($endOffsetX = 0)
{
$this->_endOffsetX = $endOffsetX;
}
/**
* Get offset in x-direction of bottom-right corner of shape measured in 1/1024 of column width
*
* @return int
*/
public function getEndOffsetX()
{
return $this->_endOffsetX;
}
/**
* Get offset in x-direction of bottom-right corner of shape measured in 1/1024 of column width
*
* @return int
*/
public function getEndOffsetX()
{
return $this->_endOffsetX;
}
/**
* Set offset in y-direction of bottom-right corner of shape measured in 1/256 of row height
*
* @param int $endOffsetY
*/
public function setEndOffsetY($endOffsetY = 0)
{
$this->_endOffsetY = $endOffsetY;
}
/**
* Set offset in y-direction of bottom-right corner of shape measured in 1/256 of row height
*
* @param int $endOffsetY
*/
public function setEndOffsetY($endOffsetY = 0)
{
$this->_endOffsetY = $endOffsetY;
}
/**
* Get offset in y-direction of bottom-right corner of shape measured in 1/256 of row height
*
* @return int
*/
public function getEndOffsetY()
{
return $this->_endOffsetY;
}
/**
* Get offset in y-direction of bottom-right corner of shape measured in 1/256 of row height
*
* @return int
*/
public function getEndOffsetY()
{
return $this->_endOffsetY;
}
/**
* Get the nesting level of this spContainer. This is the number of spgrContainers between this spContainer and
* the dgContainer. A value of 1 = immediately within first spgrContainer
* Higher nesting level occurs if and only if spContainer is part of a shape group
*
* @return int Nesting level
*/
public function getNestingLevel()
{
$nestingLevel = 0;
/**
* Get the nesting level of this spContainer. This is the number of spgrContainers between this spContainer and
* the dgContainer. A value of 1 = immediately within first spgrContainer
* Higher nesting level occurs if and only if spContainer is part of a shape group
*
* @return int Nesting level
*/
public function getNestingLevel()
{
$nestingLevel = 0;
$parent = $this->getParent();
while ($parent instanceof Shared_Escher_DgContainer_SpgrContainer) {
++$nestingLevel;
$parent = $parent->getParent();
}
$parent = $this->getParent();
while ($parent instanceof Shared_Escher_DgContainer_SpgrContainer) {
++$nestingLevel;
$parent = $parent->getParent();
}
return $nestingLevel;
}
return $nestingLevel;
}
}

View File

@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\Shared_Escher
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@ -37,170 +37,170 @@ namespace PHPExcel;
*/
class Shared_Escher_DggContainer
{
/**
* Maximum shape index of all shapes in all drawings increased by one
*
* @var int
*/
private $_spIdMax;
/**
* Maximum shape index of all shapes in all drawings increased by one
*
* @var int
*/
private $_spIdMax;
/**
* Total number of drawings saved
*
* @var int
*/
private $_cDgSaved;
/**
* Total number of drawings saved
*
* @var int
*/
private $_cDgSaved;
/**
* Total number of shapes saved (including group shapes)
*
* @var int
*/
private $_cSpSaved;
/**
* Total number of shapes saved (including group shapes)
*
* @var int
*/
private $_cSpSaved;
/**
* BLIP Store Container
*
* @var PHPExcel\Shared_Escher_DggContainer_BstoreContainer
*/
private $_bstoreContainer;
/**
* BLIP Store Container
*
* @var PHPExcel\Shared_Escher_DggContainer_BstoreContainer
*/
private $_bstoreContainer;
/**
* Array of options for the drawing group
*
* @var array
*/
private $_OPT = array();
/**
* Array of options for the drawing group
*
* @var array
*/
private $_OPT = array();
/**
* Array of identifier clusters containg information about the maximum shape identifiers
*
* @var array
*/
private $_IDCLs = array();
/**
* Array of identifier clusters containg information about the maximum shape identifiers
*
* @var array
*/
private $_IDCLs = array();
/**
* Get maximum shape index of all shapes in all drawings (plus one)
*
* @return int
*/
public function getSpIdMax()
{
return $this->_spIdMax;
}
/**
* Get maximum shape index of all shapes in all drawings (plus one)
*
* @return int
*/
public function getSpIdMax()
{
return $this->_spIdMax;
}
/**
* Set maximum shape index of all shapes in all drawings (plus one)
*
* @param int
*/
public function setSpIdMax($value)
{
$this->_spIdMax = $value;
}
/**
* Set maximum shape index of all shapes in all drawings (plus one)
*
* @param int
*/
public function setSpIdMax($value)
{
$this->_spIdMax = $value;
}
/**
* Get total number of drawings saved
*
* @return int
*/
public function getCDgSaved()
{
return $this->_cDgSaved;
}
/**
* Get total number of drawings saved
*
* @return int
*/
public function getCDgSaved()
{
return $this->_cDgSaved;
}
/**
* Set total number of drawings saved
*
* @param int
*/
public function setCDgSaved($value)
{
$this->_cDgSaved = $value;
}
/**
* Set total number of drawings saved
*
* @param int
*/
public function setCDgSaved($value)
{
$this->_cDgSaved = $value;
}
/**
* Get total number of shapes saved (including group shapes)
*
* @return int
*/
public function getCSpSaved()
{
return $this->_cSpSaved;
}
/**
* Get total number of shapes saved (including group shapes)
*
* @return int
*/
public function getCSpSaved()
{
return $this->_cSpSaved;
}
/**
* Set total number of shapes saved (including group shapes)
*
* @param int
*/
public function setCSpSaved($value)
{
$this->_cSpSaved = $value;
}
/**
* Set total number of shapes saved (including group shapes)
*
* @param int
*/
public function setCSpSaved($value)
{
$this->_cSpSaved = $value;
}
/**
* Get BLIP Store Container
*
* @return PHPExcel\Shared_Escher_DggContainer_BstoreContainer
*/
public function getBstoreContainer()
{
return $this->_bstoreContainer;
}
/**
* Get BLIP Store Container
*
* @return PHPExcel\Shared_Escher_DggContainer_BstoreContainer
*/
public function getBstoreContainer()
{
return $this->_bstoreContainer;
}
/**
* Set BLIP Store Container
*
* @param PHPExcel\Shared_Escher_DggContainer_BstoreContainer $bstoreContainer
*/
public function setBstoreContainer($bstoreContainer)
{
$this->_bstoreContainer = $bstoreContainer;
}
/**
* Set BLIP Store Container
*
* @param PHPExcel\Shared_Escher_DggContainer_BstoreContainer $bstoreContainer
*/
public function setBstoreContainer($bstoreContainer)
{
$this->_bstoreContainer = $bstoreContainer;
}
/**
* Set an option for the drawing group
*
* @param int $property The number specifies the option
* @param mixed $value
*/
public function setOPT($property, $value)
{
$this->_OPT[$property] = $value;
}
/**
* Set an option for the drawing group
*
* @param int $property The number specifies the option
* @param mixed $value
*/
public function setOPT($property, $value)
{
$this->_OPT[$property] = $value;
}
/**
* Get an option for the drawing group
*
* @param int $property The number specifies the option
* @return mixed
*/
public function getOPT($property)
{
if (isset($this->_OPT[$property])) {
return $this->_OPT[$property];
}
return null;
}
/**
* Get an option for the drawing group
*
* @param int $property The number specifies the option
* @return mixed
*/
public function getOPT($property)
{
if (isset($this->_OPT[$property])) {
return $this->_OPT[$property];
}
return null;
}
/**
* Get identifier clusters
*
* @return array
*/
public function getIDCLs()
{
return $this->_IDCLs;
}
/**
* Get identifier clusters
*
* @return array
*/
public function getIDCLs()
{
return $this->_IDCLs;
}
/**
* Set identifier clusters. array(<drawingId> => <max shape id>, ...)
*
* @param array $pValue
*/
public function setIDCLs($pValue)
{
$this->_IDCLs = $pValue;
}
/**
* Set identifier clusters. array(<drawingId> => <max shape id>, ...)
*
* @param array $pValue
*/
public function setIDCLs($pValue)
{
$this->_IDCLs = $pValue;
}
}

View File

@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\Shared_Escher
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@ -37,32 +37,32 @@ namespace PHPExcel;
*/
class Shared_Escher_DggContainer_BstoreContainer
{
/**
* BLIP Store Entries. Each of them holds one BLIP (Big Large Image or Picture)
*
* @var array
*/
private $_BSECollection = array();
/**
* BLIP Store Entries. Each of them holds one BLIP (Big Large Image or Picture)
*
* @var array
*/
private $_BSECollection = array();
/**
* Add a BLIP Store Entry
*
* @param PHPExcel\Shared_Escher_DggContainer_BstoreContainer_BSE $BSE
*/
public function addBSE($BSE)
{
$this->_BSECollection[] = $BSE;
$BSE->setParent($this);
}
/**
* Add a BLIP Store Entry
*
* @param PHPExcel\Shared_Escher_DggContainer_BstoreContainer_BSE $BSE
*/
public function addBSE($BSE)
{
$this->_BSECollection[] = $BSE;
$BSE->setParent($this);
}
/**
* Get the collection of BLIP Store Entries
*
* @return PHPExcel\Shared_Escher_DggContainer_BstoreContainer_BSE[]
*/
public function getBSECollection()
{
return $this->_BSECollection;
}
/**
* Get the collection of BLIP Store Entries
*
* @return PHPExcel\Shared_Escher_DggContainer_BstoreContainer_BSE[]
*/
public function getBSECollection()
{
return $this->_BSECollection;
}
}

View File

@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\Shared_Escher
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@ -37,87 +37,87 @@ namespace PHPExcel;
*/
class Shared_Escher_DggContainer_BstoreContainer_BSE
{
const BLIPTYPE_ERROR = 0x00;
const BLIPTYPE_UNKNOWN = 0x01;
const BLIPTYPE_EMF = 0x02;
const BLIPTYPE_WMF = 0x03;
const BLIPTYPE_PICT = 0x04;
const BLIPTYPE_JPEG = 0x05;
const BLIPTYPE_PNG = 0x06;
const BLIPTYPE_DIB = 0x07;
const BLIPTYPE_TIFF = 0x11;
const BLIPTYPE_CMYKJPEG = 0x12;
const BLIPTYPE_ERROR = 0x00;
const BLIPTYPE_UNKNOWN = 0x01;
const BLIPTYPE_EMF = 0x02;
const BLIPTYPE_WMF = 0x03;
const BLIPTYPE_PICT = 0x04;
const BLIPTYPE_JPEG = 0x05;
const BLIPTYPE_PNG = 0x06;
const BLIPTYPE_DIB = 0x07;
const BLIPTYPE_TIFF = 0x11;
const BLIPTYPE_CMYKJPEG = 0x12;
/**
* The parent BLIP Store Entry Container
*
* @var PHPExcel\Shared_Escher_DggContainer_BstoreContainer
*/
private $_parent;
/**
* The parent BLIP Store Entry Container
*
* @var PHPExcel\Shared_Escher_DggContainer_BstoreContainer
*/
private $_parent;
/**
* The BLIP (Big Large Image or Picture)
*
* @var PHPExcel\Shared_Escher_DggContainer_BstoreContainer_BSE_Blip
*/
private $_blip;
/**
* The BLIP (Big Large Image or Picture)
*
* @var PHPExcel\Shared_Escher_DggContainer_BstoreContainer_BSE_Blip
*/
private $_blip;
/**
* The BLIP type
*
* @var int
*/
private $_blipType;
/**
* The BLIP type
*
* @var int
*/
private $_blipType;
/**
* Set parent BLIP Store Entry Container
*
* @param PHPExcel\Shared_Escher_DggContainer_BstoreContainer $parent
*/
public function setParent($parent)
{
$this->_parent = $parent;
}
/**
* Set parent BLIP Store Entry Container
*
* @param PHPExcel\Shared_Escher_DggContainer_BstoreContainer $parent
*/
public function setParent($parent)
{
$this->_parent = $parent;
}
/**
* Get the BLIP
*
* @return PHPExcel\Shared_Escher_DggContainer_BstoreContainer_BSE_Blip
*/
public function getBlip()
{
return $this->_blip;
}
/**
* Get the BLIP
*
* @return PHPExcel\Shared_Escher_DggContainer_BstoreContainer_BSE_Blip
*/
public function getBlip()
{
return $this->_blip;
}
/**
* Set the BLIP
*
* @param PHPExcel\Shared_Escher_DggContainer_BstoreContainer_BSE_Blip $blip
*/
public function setBlip($blip)
{
$this->_blip = $blip;
$blip->setParent($this);
}
/**
* Set the BLIP
*
* @param PHPExcel\Shared_Escher_DggContainer_BstoreContainer_BSE_Blip $blip
*/
public function setBlip($blip)
{
$this->_blip = $blip;
$blip->setParent($this);
}
/**
* Get the BLIP type
*
* @return int
*/
public function getBlipType()
{
return $this->_blipType;
}
/**
* Get the BLIP type
*
* @return int
*/
public function getBlipType()
{
return $this->_blipType;
}
/**
* Set the BLIP type
*
* @param int
*/
public function setBlipType($blipType)
{
$this->_blipType = $blipType;
}
/**
* Set the BLIP type
*
* @param int
*/
public function setBlipType($blipType)
{
$this->_blipType = $blipType;
}
}

View File

@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\Shared_Escher
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@ -37,58 +37,58 @@ namespace PHPExcel;
*/
class Shared_Escher_DggContainer_BstoreContainer_BSE_Blip
{
/**
* The parent BSE
*
* @var PHPExcel\Shared_Escher_DggContainer_BstoreContainer_BSE
*/
private $_parent;
/**
* The parent BSE
*
* @var PHPExcel\Shared_Escher_DggContainer_BstoreContainer_BSE
*/
private $_parent;
/**
* Raw image data
*
* @var string
*/
private $_data;
/**
* Raw image data
*
* @var string
*/
private $_data;
/**
* Get the raw image data
*
* @return string
*/
public function getData()
{
return $this->_data;
}
/**
* Get the raw image data
*
* @return string
*/
public function getData()
{
return $this->_data;
}
/**
* Set the raw image data
*
* @param string
*/
public function setData($data)
{
$this->_data = $data;
}
/**
* Set the raw image data
*
* @param string
*/
public function setData($data)
{
$this->_data = $data;
}
/**
* Set parent BSE
*
* @param PHPExcel\Shared_Escher_DggContainer_BstoreContainer_BSE $parent
*/
public function setParent($parent)
{
$this->_parent = $parent;
}
/**
* Set parent BSE
*
* @param PHPExcel\Shared_Escher_DggContainer_BstoreContainer_BSE $parent
*/
public function setParent($parent)
{
$this->_parent = $parent;
}
/**
* Get parent BSE
*
* @return PHPExcel\Shared_Escher_DggContainer_BstoreContainer_BSE $parent
*/
public function getParent()
{
return $this->_parent;
}
/**
* Get parent BSE
*
* @return PHPExcel\Shared_Escher_DggContainer_BstoreContainer_BSE $parent
*/
public function getParent()
{
return $this->_parent;
}
}

View File

@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\Shared
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@ -37,284 +37,284 @@ namespace PHPExcel;
*/
class Shared_Excel5
{
/**
* Get the width of a column in pixels. We use the relationship y = ceil(7x) where
* x is the width in intrinsic Excel units (measuring width in number of normal characters)
* This holds for Arial 10
*
* @param PHPExcel\Worksheet $sheet The sheet
* @param string $col The column
* @return integer The width in pixels
*/
public static function sizeCol($sheet, $col = 'A')
{
// default font of the workbook
$font = $sheet->getParent()->getDefaultStyle()->getFont();
/**
* Get the width of a column in pixels. We use the relationship y = ceil(7x) where
* x is the width in intrinsic Excel units (measuring width in number of normal characters)
* This holds for Arial 10
*
* @param PHPExcel\Worksheet $sheet The sheet
* @param string $col The column
* @return integer The width in pixels
*/
public static function sizeCol($sheet, $col = 'A')
{
// default font of the workbook
$font = $sheet->getParent()->getDefaultStyle()->getFont();
$columnDimensions = $sheet->getColumnDimensions();
$columnDimensions = $sheet->getColumnDimensions();
// first find the true column width in pixels (uncollapsed and unhidden)
if ( isset($columnDimensions[$col]) and $columnDimensions[$col]->getWidth() != -1 ) {
// first find the true column width in pixels (uncollapsed and unhidden)
if ( isset($columnDimensions[$col]) and $columnDimensions[$col]->getWidth() != -1 ) {
// then we have column dimension with explicit width
$columnDimension = $columnDimensions[$col];
$width = $columnDimension->getWidth();
$pixelWidth = Shared_Drawing::cellDimensionToPixels($width, $font);
// then we have column dimension with explicit width
$columnDimension = $columnDimensions[$col];
$width = $columnDimension->getWidth();
$pixelWidth = Shared_Drawing::cellDimensionToPixels($width, $font);
} else if ($sheet->getDefaultColumnDimension()->getWidth() != -1) {
} else if ($sheet->getDefaultColumnDimension()->getWidth() != -1) {
// then we have default column dimension with explicit width
$defaultColumnDimension = $sheet->getDefaultColumnDimension();
$width = $defaultColumnDimension->getWidth();
$pixelWidth = Shared_Drawing::cellDimensionToPixels($width, $font);
// then we have default column dimension with explicit width
$defaultColumnDimension = $sheet->getDefaultColumnDimension();
$width = $defaultColumnDimension->getWidth();
$pixelWidth = Shared_Drawing::cellDimensionToPixels($width, $font);
} else {
} else {
// we don't even have any default column dimension. Width depends on default font
$pixelWidth = Shared_Font::getDefaultColumnWidthByFont($font, true);
}
// we don't even have any default column dimension. Width depends on default font
$pixelWidth = Shared_Font::getDefaultColumnWidthByFont($font, true);
}
// now find the effective column width in pixels
if (isset($columnDimensions[$col]) and !$columnDimensions[$col]->getVisible()) {
$effectivePixelWidth = 0;
} else {
$effectivePixelWidth = $pixelWidth;
}
// now find the effective column width in pixels
if (isset($columnDimensions[$col]) and !$columnDimensions[$col]->getVisible()) {
$effectivePixelWidth = 0;
} else {
$effectivePixelWidth = $pixelWidth;
}
return $effectivePixelWidth;
}
return $effectivePixelWidth;
}
/**
* Convert the height of a cell from user's units to pixels. By interpolation
* the relationship is: y = 4/3x. If the height hasn't been set by the user we
* use the default value. If the row is hidden we use a value of zero.
*
* @param PHPExcel\Worksheet $sheet The sheet
* @param integer $row The row index (1-based)
* @return integer The width in pixels
*/
public static function sizeRow($sheet, $row = 1)
{
// default font of the workbook
$font = $sheet->getParent()->getDefaultStyle()->getFont();
/**
* Convert the height of a cell from user's units to pixels. By interpolation
* the relationship is: y = 4/3x. If the height hasn't been set by the user we
* use the default value. If the row is hidden we use a value of zero.
*
* @param PHPExcel\Worksheet $sheet The sheet
* @param integer $row The row index (1-based)
* @return integer The width in pixels
*/
public static function sizeRow($sheet, $row = 1)
{
// default font of the workbook
$font = $sheet->getParent()->getDefaultStyle()->getFont();
$rowDimensions = $sheet->getRowDimensions();
$rowDimensions = $sheet->getRowDimensions();
// first find the true row height in pixels (uncollapsed and unhidden)
if ( isset($rowDimensions[$row]) and $rowDimensions[$row]->getRowHeight() != -1) {
// first find the true row height in pixels (uncollapsed and unhidden)
if ( isset($rowDimensions[$row]) and $rowDimensions[$row]->getRowHeight() != -1) {
// then we have a row dimension
$rowDimension = $rowDimensions[$row];
$rowHeight = $rowDimension->getRowHeight();
$pixelRowHeight = (int) ceil(4 * $rowHeight / 3); // here we assume Arial 10
// then we have a row dimension
$rowDimension = $rowDimensions[$row];
$rowHeight = $rowDimension->getRowHeight();
$pixelRowHeight = (int) ceil(4 * $rowHeight / 3); // here we assume Arial 10
} else if ($sheet->getDefaultRowDimension()->getRowHeight() != -1) {
} else if ($sheet->getDefaultRowDimension()->getRowHeight() != -1) {
// then we have a default row dimension with explicit height
$defaultRowDimension = $sheet->getDefaultRowDimension();
$rowHeight = $defaultRowDimension->getRowHeight();
$pixelRowHeight = Shared_Drawing::pointsToPixels($rowHeight);
// then we have a default row dimension with explicit height
$defaultRowDimension = $sheet->getDefaultRowDimension();
$rowHeight = $defaultRowDimension->getRowHeight();
$pixelRowHeight = Shared_Drawing::pointsToPixels($rowHeight);
} else {
} else {
// we don't even have any default row dimension. Height depends on default font
$pointRowHeight = Shared_Font::getDefaultRowHeightByFont($font);
$pixelRowHeight = Shared_Font::fontSizeToPixels($pointRowHeight);
// we don't even have any default row dimension. Height depends on default font
$pointRowHeight = Shared_Font::getDefaultRowHeightByFont($font);
$pixelRowHeight = Shared_Font::fontSizeToPixels($pointRowHeight);
}
}
// now find the effective row height in pixels
if ( isset($rowDimensions[$row]) and !$rowDimensions[$row]->getVisible() ) {
$effectivePixelRowHeight = 0;
} else {
$effectivePixelRowHeight = $pixelRowHeight;
}
// now find the effective row height in pixels
if ( isset($rowDimensions[$row]) and !$rowDimensions[$row]->getVisible() ) {
$effectivePixelRowHeight = 0;
} else {
$effectivePixelRowHeight = $pixelRowHeight;
}
return $effectivePixelRowHeight;
}
return $effectivePixelRowHeight;
}
/**
* Get the horizontal distance in pixels between two anchors
* The distanceX is found as sum of all the spanning columns widths minus correction for the two offsets
*
* @param PHPExcel\Worksheet $sheet
* @param string $startColumn
* @param integer $startOffsetX Offset within start cell measured in 1/1024 of the cell width
* @param string $endColumn
* @param integer $endOffsetX Offset within end cell measured in 1/1024 of the cell width
* @return integer Horizontal measured in pixels
*/
public static function getDistanceX(Worksheet $sheet, $startColumn = 'A', $startOffsetX = 0, $endColumn = 'A', $endOffsetX = 0)
{
$distanceX = 0;
/**
* Get the horizontal distance in pixels between two anchors
* The distanceX is found as sum of all the spanning columns widths minus correction for the two offsets
*
* @param PHPExcel\Worksheet $sheet
* @param string $startColumn
* @param integer $startOffsetX Offset within start cell measured in 1/1024 of the cell width
* @param string $endColumn
* @param integer $endOffsetX Offset within end cell measured in 1/1024 of the cell width
* @return integer Horizontal measured in pixels
*/
public static function getDistanceX(Worksheet $sheet, $startColumn = 'A', $startOffsetX = 0, $endColumn = 'A', $endOffsetX = 0)
{
$distanceX = 0;
// add the widths of the spanning columns
$startColumnIndex = Cell::columnIndexFromString($startColumn) - 1; // 1-based
$endColumnIndex = Cell::columnIndexFromString($endColumn) - 1; // 1-based
for ($i = $startColumnIndex; $i <= $endColumnIndex; ++$i) {
$distanceX += self::sizeCol($sheet, Cell::stringFromColumnIndex($i));
}
// add the widths of the spanning columns
$startColumnIndex = Cell::columnIndexFromString($startColumn) - 1; // 1-based
$endColumnIndex = Cell::columnIndexFromString($endColumn) - 1; // 1-based
for ($i = $startColumnIndex; $i <= $endColumnIndex; ++$i) {
$distanceX += self::sizeCol($sheet, Cell::stringFromColumnIndex($i));
}
// correct for offsetX in startcell
$distanceX -= (int) floor(self::sizeCol($sheet, $startColumn) * $startOffsetX / 1024);
// correct for offsetX in startcell
$distanceX -= (int) floor(self::sizeCol($sheet, $startColumn) * $startOffsetX / 1024);
// correct for offsetX in endcell
$distanceX -= (int) floor(self::sizeCol($sheet, $endColumn) * (1 - $endOffsetX / 1024));
// correct for offsetX in endcell
$distanceX -= (int) floor(self::sizeCol($sheet, $endColumn) * (1 - $endOffsetX / 1024));
return $distanceX;
}
return $distanceX;
}
/**
* Get the vertical distance in pixels between two anchors
* The distanceY is found as sum of all the spanning rows minus two offsets
*
* @param PHPExcel\Worksheet $sheet
* @param integer $startRow (1-based)
* @param integer $startOffsetY Offset within start cell measured in 1/256 of the cell height
* @param integer $endRow (1-based)
* @param integer $endOffsetY Offset within end cell measured in 1/256 of the cell height
* @return integer Vertical distance measured in pixels
*/
public static function getDistanceY(Worksheet $sheet, $startRow = 1, $startOffsetY = 0, $endRow = 1, $endOffsetY = 0)
{
$distanceY = 0;
/**
* Get the vertical distance in pixels between two anchors
* The distanceY is found as sum of all the spanning rows minus two offsets
*
* @param PHPExcel\Worksheet $sheet
* @param integer $startRow (1-based)
* @param integer $startOffsetY Offset within start cell measured in 1/256 of the cell height
* @param integer $endRow (1-based)
* @param integer $endOffsetY Offset within end cell measured in 1/256 of the cell height
* @return integer Vertical distance measured in pixels
*/
public static function getDistanceY(Worksheet $sheet, $startRow = 1, $startOffsetY = 0, $endRow = 1, $endOffsetY = 0)
{
$distanceY = 0;
// add the widths of the spanning rows
for ($row = $startRow; $row <= $endRow; ++$row) {
$distanceY += self::sizeRow($sheet, $row);
}
// add the widths of the spanning rows
for ($row = $startRow; $row <= $endRow; ++$row) {
$distanceY += self::sizeRow($sheet, $row);
}
// correct for offsetX in startcell
$distanceY -= (int) floor(self::sizeRow($sheet, $startRow) * $startOffsetY / 256);
// correct for offsetX in startcell
$distanceY -= (int) floor(self::sizeRow($sheet, $startRow) * $startOffsetY / 256);
// correct for offsetX in endcell
$distanceY -= (int) floor(self::sizeRow($sheet, $endRow) * (1 - $endOffsetY / 256));
// correct for offsetX in endcell
$distanceY -= (int) floor(self::sizeRow($sheet, $endRow) * (1 - $endOffsetY / 256));
return $distanceY;
}
return $distanceY;
}
/**
* Convert 1-cell anchor coordinates to 2-cell anchor coordinates
* This function is ported from PEAR Spreadsheet_Writer_Excel with small modifications
*
* Calculate the vertices that define the position of the image as required by
* the OBJ record.
*
* +------------+------------+
* | A | B |
* +-----+------------+------------+
* | |(x1,y1) | |
* | 1 |(A1)._______|______ |
* | | | | |
* | | | | |
* +-----+----| BITMAP |-----+
* | | | | |
* | 2 | |______________. |
* | | | (B2)|
* | | | (x2,y2)|
* +---- +------------+------------+
*
* Example of a bitmap that covers some of the area from cell A1 to cell B2.
*
* Based on the width and height of the bitmap we need to calculate 8 vars:
* $col_start, $row_start, $col_end, $row_end, $x1, $y1, $x2, $y2.
* The width and height of the cells are also variable and have to be taken into
* account.
* The values of $col_start and $row_start are passed in from the calling
* function. The values of $col_end and $row_end are calculated by subtracting
* the width and height of the bitmap from the width and height of the
* underlying cells.
* The vertices are expressed as a percentage of the underlying cell width as
* follows (rhs values are in pixels):
*
* x1 = X / W *1024
* y1 = Y / H *256
* x2 = (X-1) / W *1024
* y2 = (Y-1) / H *256
*
* Where: X is distance from the left side of the underlying cell
* Y is distance from the top of the underlying cell
* W is the width of the cell
* H is the height of the cell
*
* @param PHPExcel\Worksheet $sheet
* @param string $coordinates E.g. 'A1'
* @param integer $offsetX Horizontal offset in pixels
* @param integer $offsetY Vertical offset in pixels
* @param integer $width Width in pixels
* @param integer $height Height in pixels
* @return array
*/
public static function oneAnchor2twoAnchor($sheet, $coordinates, $offsetX, $offsetY, $width, $height)
{
list($column, $row) = Cell::coordinateFromString($coordinates);
$col_start = Cell::columnIndexFromString($column) - 1;
$row_start = $row - 1;
/**
* Convert 1-cell anchor coordinates to 2-cell anchor coordinates
* This function is ported from PEAR Spreadsheet_Writer_Excel with small modifications
*
* Calculate the vertices that define the position of the image as required by
* the OBJ record.
*
* +------------+------------+
* | A | B |
* +-----+------------+------------+
* | |(x1,y1) | |
* | 1 |(A1)._______|______ |
* | | | | |
* | | | | |
* +-----+----| BITMAP |-----+
* | | | | |
* | 2 | |______________. |
* | | | (B2)|
* | | | (x2,y2)|
* +---- +------------+------------+
*
* Example of a bitmap that covers some of the area from cell A1 to cell B2.
*
* Based on the width and height of the bitmap we need to calculate 8 vars:
* $col_start, $row_start, $col_end, $row_end, $x1, $y1, $x2, $y2.
* The width and height of the cells are also variable and have to be taken into
* account.
* The values of $col_start and $row_start are passed in from the calling
* function. The values of $col_end and $row_end are calculated by subtracting
* the width and height of the bitmap from the width and height of the
* underlying cells.
* The vertices are expressed as a percentage of the underlying cell width as
* follows (rhs values are in pixels):
*
* x1 = X / W *1024
* y1 = Y / H *256
* x2 = (X-1) / W *1024
* y2 = (Y-1) / H *256
*
* Where: X is distance from the left side of the underlying cell
* Y is distance from the top of the underlying cell
* W is the width of the cell
* H is the height of the cell
*
* @param PHPExcel\Worksheet $sheet
* @param string $coordinates E.g. 'A1'
* @param integer $offsetX Horizontal offset in pixels
* @param integer $offsetY Vertical offset in pixels
* @param integer $width Width in pixels
* @param integer $height Height in pixels
* @return array
*/
public static function oneAnchor2twoAnchor($sheet, $coordinates, $offsetX, $offsetY, $width, $height)
{
list($column, $row) = Cell::coordinateFromString($coordinates);
$col_start = Cell::columnIndexFromString($column) - 1;
$row_start = $row - 1;
$x1 = $offsetX;
$y1 = $offsetY;
$x1 = $offsetX;
$y1 = $offsetY;
// Initialise end cell to the same as the start cell
$col_end = $col_start; // Col containing lower right corner of object
$row_end = $row_start; // Row containing bottom right corner of object
// Initialise end cell to the same as the start cell
$col_end = $col_start; // Col containing lower right corner of object
$row_end = $row_start; // Row containing bottom right corner of object
// Zero the specified offset if greater than the cell dimensions
if ($x1 >= self::sizeCol($sheet, Cell::stringFromColumnIndex($col_start))) {
$x1 = 0;
}
if ($y1 >= self::sizeRow($sheet, $row_start + 1)) {
$y1 = 0;
}
// Zero the specified offset if greater than the cell dimensions
if ($x1 >= self::sizeCol($sheet, Cell::stringFromColumnIndex($col_start))) {
$x1 = 0;
}
if ($y1 >= self::sizeRow($sheet, $row_start + 1)) {
$y1 = 0;
}
$width = $width + $x1 -1;
$height = $height + $y1 -1;
$width = $width + $x1 -1;
$height = $height + $y1 -1;
// Subtract the underlying cell widths to find the end cell of the image
while ($width >= self::sizeCol($sheet, Cell::stringFromColumnIndex($col_end))) {
$width -= self::sizeCol($sheet, Cell::stringFromColumnIndex($col_end));
++$col_end;
}
// Subtract the underlying cell widths to find the end cell of the image
while ($width >= self::sizeCol($sheet, Cell::stringFromColumnIndex($col_end))) {
$width -= self::sizeCol($sheet, Cell::stringFromColumnIndex($col_end));
++$col_end;
}
// Subtract the underlying cell heights to find the end cell of the image
while ($height >= self::sizeRow($sheet, $row_end + 1)) {
$height -= self::sizeRow($sheet, $row_end + 1);
++$row_end;
}
// Subtract the underlying cell heights to find the end cell of the image
while ($height >= self::sizeRow($sheet, $row_end + 1)) {
$height -= self::sizeRow($sheet, $row_end + 1);
++$row_end;
}
// Bitmap isn't allowed to start or finish in a hidden cell, i.e. a cell
// with zero height or width.
if (self::sizeCol($sheet, Cell::stringFromColumnIndex($col_start)) == 0) {
return;
}
if (self::sizeCol($sheet, Cell::stringFromColumnIndex($col_end)) == 0) {
return;
}
if (self::sizeRow($sheet, $row_start + 1) == 0) {
return;
}
if (self::sizeRow($sheet, $row_end + 1) == 0) {
return;
}
// Bitmap isn't allowed to start or finish in a hidden cell, i.e. a cell
// with zero height or width.
if (self::sizeCol($sheet, Cell::stringFromColumnIndex($col_start)) == 0) {
return;
}
if (self::sizeCol($sheet, Cell::stringFromColumnIndex($col_end)) == 0) {
return;
}
if (self::sizeRow($sheet, $row_start + 1) == 0) {
return;
}
if (self::sizeRow($sheet, $row_end + 1) == 0) {
return;
}
// Convert the pixel values to the percentage value expected by Excel
$x1 = $x1 / self::sizeCol($sheet, Cell::stringFromColumnIndex($col_start)) * 1024;
$y1 = $y1 / self::sizeRow($sheet, $row_start + 1) * 256;
$x2 = ($width + 1) / self::sizeCol($sheet, Cell::stringFromColumnIndex($col_end)) * 1024; // Distance to right side of object
$y2 = ($height + 1) / self::sizeRow($sheet, $row_end + 1) * 256; // Distance to bottom of object
// Convert the pixel values to the percentage value expected by Excel
$x1 = $x1 / self::sizeCol($sheet, Cell::stringFromColumnIndex($col_start)) * 1024;
$y1 = $y1 / self::sizeRow($sheet, $row_start + 1) * 256;
$x2 = ($width + 1) / self::sizeCol($sheet, Cell::stringFromColumnIndex($col_end)) * 1024; // Distance to right side of object
$y2 = ($height + 1) / self::sizeRow($sheet, $row_end + 1) * 256; // Distance to bottom of object
$startCoordinates = Cell::stringFromColumnIndex($col_start) . ($row_start + 1);
$endCoordinates = Cell::stringFromColumnIndex($col_end) . ($row_end + 1);
$startCoordinates = Cell::stringFromColumnIndex($col_start) . ($row_start + 1);
$endCoordinates = Cell::stringFromColumnIndex($col_end) . ($row_end + 1);
$twoAnchor = array(
'startCoordinates' => $startCoordinates,
'startOffsetX' => $x1,
'startOffsetY' => $y1,
'endCoordinates' => $endCoordinates,
'endOffsetX' => $x2,
'endOffsetY' => $y2,
);
$twoAnchor = array(
'startCoordinates' => $startCoordinates,
'startOffsetX' => $x1,
'startOffsetY' => $y1,
'endCoordinates' => $endCoordinates,
'endOffsetX' => $x2,
'endOffsetY' => $y2,
);
return $twoAnchor;
}
return $twoAnchor;
}
}

View File

@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\Shared
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@ -37,144 +37,143 @@ namespace PHPExcel;
*/
class Shared_File
{
/*
* Use Temp or File Upload Temp for temporary files
*
* @protected
* @var boolean
*/
protected static $_useUploadTempDirectory = FALSE;
/*
* Use Temp or File Upload Temp for temporary files
*
* @protected
* @var boolean
*/
protected static $_useUploadTempDirectory = false;
/**
* Set the flag indicating whether the File Upload Temp directory should be used for temporary files
*
* @param boolean $useUploadTempDir Use File Upload Temporary directory (true or false)
*/
public static function setUseUploadTempDirectory($useUploadTempDir = FALSE) {
self::$_useUploadTempDirectory = (boolean) $useUploadTempDir;
} // function setUseUploadTempDirectory()
/**
* Set the flag indicating whether the File Upload Temp directory should be used for temporary files
*
* @param boolean $useUploadTempDir Use File Upload Temporary directory (true or false)
*/
public static function setUseUploadTempDirectory($useUploadTempDir = false) {
self::$_useUploadTempDirectory = (boolean) $useUploadTempDir;
} // function setUseUploadTempDirectory()
/**
* Get the flag indicating whether the File Upload Temp directory should be used for temporary files
*
* @return boolean Use File Upload Temporary directory (true or false)
*/
public static function getUseUploadTempDirectory() {
return self::$_useUploadTempDirectory;
} // function getUseUploadTempDirectory()
/**
* Get the flag indicating whether the File Upload Temp directory should be used for temporary files
*
* @return boolean Use File Upload Temporary directory (true or false)
*/
public static function getUseUploadTempDirectory() {
return self::$_useUploadTempDirectory;
} // function getUseUploadTempDirectory()
/**
* Verify if a file exists
*
* @param string $pFilename Filename
* @return bool
*/
public static function file_exists($pFilename) {
// Sick construction, but it seems that
// file_exists returns strange values when
// doing the original file_exists on ZIP archives...
if ( strtolower(substr($pFilename, 0, 3)) == 'zip' ) {
// Open ZIP file and verify if the file exists
$zipFile = substr($pFilename, 6, strpos($pFilename, '#') - 6);
$archiveFile = substr($pFilename, strpos($pFilename, '#') + 1);
/**
* Verify if a file exists
*
* @param string $pFilename Filename
* @return bool
*/
public static function file_exists($pFilename) {
// Sick construction, but it seems that
// file_exists returns strange values when
// doing the original file_exists on ZIP archives...
if ( strtolower(substr($pFilename, 0, 3)) == 'zip' ) {
// Open ZIP file and verify if the file exists
$zipFile = substr($pFilename, 6, strpos($pFilename, '#') - 6);
$archiveFile = substr($pFilename, strpos($pFilename, '#') + 1);
$zip = new \ZipArchive();
if ($zip->open($zipFile) === true) {
$returnValue = ($zip->getFromName($archiveFile) !== false);
$zip->close();
return $returnValue;
} else {
return false;
}
} else {
// Regular file_exists
return file_exists($pFilename);
}
}
$zip = new \ZipArchive();
if ($zip->open($zipFile) === true) {
$returnValue = ($zip->getFromName($archiveFile) !== false);
$zip->close();
return $returnValue;
} else {
return false;
}
} else {
// Regular file_exists
return file_exists($pFilename);
}
}
/**
* Returns canonicalized absolute pathname, also for ZIP archives
*
* @param string $pFilename
* @return string
*/
public static function realpath($pFilename) {
// Returnvalue
$returnValue = '';
/**
* Returns canonicalized absolute pathname, also for ZIP archives
*
* @param string $pFilename
* @return string
*/
public static function realpath($pFilename) {
// Returnvalue
$returnValue = '';
// Try using realpath()
if (file_exists($pFilename)) {
$returnValue = realpath($pFilename);
}
// Try using realpath()
if (file_exists($pFilename)) {
$returnValue = realpath($pFilename);
}
// Found something?
if ($returnValue == '' || ($returnValue === NULL)) {
$pathArray = explode('/' , $pFilename);
while(in_array('..', $pathArray) && $pathArray[0] != '..') {
for ($i = 0; $i < count($pathArray); ++$i) {
if ($pathArray[$i] == '..' && $i > 0) {
unset($pathArray[$i]);
unset($pathArray[$i - 1]);
break;
}
}
}
$returnValue = implode('/', $pathArray);
}
// Found something?
if ($returnValue == '' || ($returnValue === null)) {
$pathArray = explode('/' , $pFilename);
while(in_array('..', $pathArray) && $pathArray[0] != '..') {
for ($i = 0; $i < count($pathArray); ++$i) {
if ($pathArray[$i] == '..' && $i > 0) {
unset($pathArray[$i]);
unset($pathArray[$i - 1]);
break;
}
}
}
$returnValue = implode('/', $pathArray);
}
// Return
return $returnValue;
}
// Return
return $returnValue;
}
/**
* Get the systems temporary directory.
*
* @return string
*/
public static function sys_get_temp_dir()
{
if (self::$_useUploadTempDirectory) {
// use upload-directory when defined to allow running on environments having very restricted
// open_basedir configs
if (ini_get('upload_tmp_dir') !== FALSE) {
if ($temp = ini_get('upload_tmp_dir')) {
if (file_exists($temp))
return realpath($temp);
}
}
}
/**
* Get the systems temporary directory.
*
* @return string
*/
public static function sys_get_temp_dir()
{
if (self::$_useUploadTempDirectory) {
// use upload-directory when defined to allow running on environments having very restricted
// open_basedir configs
if (ini_get('upload_tmp_dir') !== false) {
if ($temp = ini_get('upload_tmp_dir')) {
if (file_exists($temp))
return realpath($temp);
}
}
}
// sys_get_temp_dir is only available since PHP 5.2.1
// http://php.net/manual/en/function.sys-get-temp-dir.php#94119
if ( !function_exists('sys_get_temp_dir')) {
if ($temp = getenv('TMP') ) {
if ((!empty($temp)) && (file_exists($temp))) { return realpath($temp); }
}
if ($temp = getenv('TEMP') ) {
if ((!empty($temp)) && (file_exists($temp))) { return realpath($temp); }
}
if ($temp = getenv('TMPDIR') ) {
if ((!empty($temp)) && (file_exists($temp))) { return realpath($temp); }
}
// sys_get_temp_dir is only available since PHP 5.2.1
// http://php.net/manual/en/function.sys-get-temp-dir.php#94119
if ( !function_exists('sys_get_temp_dir')) {
if ($temp = getenv('TMP') ) {
if ((!empty($temp)) && (file_exists($temp))) { return realpath($temp); }
}
if ($temp = getenv('TEMP') ) {
if ((!empty($temp)) && (file_exists($temp))) { return realpath($temp); }
}
if ($temp = getenv('TMPDIR') ) {
if ((!empty($temp)) && (file_exists($temp))) { return realpath($temp); }
}
// trick for creating a file in system's temporary dir
// without knowing the path of the system's temporary dir
$temp = tempnam(__FILE__, '');
if (file_exists($temp)) {
unlink($temp);
return realpath(dirname($temp));
}
// trick for creating a file in system's temporary dir
// without knowing the path of the system's temporary dir
$temp = tempnam(__FILE__, '');
if (file_exists($temp)) {
unlink($temp);
return realpath(dirname($temp));
}
return null;
}
// use ordinary built-in PHP function
// There should be no problem with the 5.2.4 Suhosin realpath() bug, because this line should only
// be called if we're running 5.2.1 or earlier
return realpath(sys_get_temp_dir());
}
return null;
}
// use ordinary built-in PHP function
// There should be no problem with the 5.2.4 Suhosin realpath() bug, because this line should only
// be called if we're running 5.2.1 or earlier
return realpath(sys_get_temp_dir());
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,149 +1,149 @@
<?php
/**
* @package JAMA
* @package JAMA
*
* Cholesky decomposition class
* Cholesky decomposition class
*
* For a symmetric, positive definite matrix A, the Cholesky decomposition
* is an lower triangular matrix L so that A = L*L'.
* For a symmetric, positive definite matrix A, the Cholesky decomposition
* is an lower triangular matrix L so that A = L*L'.
*
* If the matrix is not symmetric or positive definite, the constructor
* returns a partial decomposition and sets an internal flag that may
* be queried by the isSPD() method.
* If the matrix is not symmetric or positive definite, the constructor
* returns a partial decomposition and sets an internal flag that may
* be queried by the isSPD() method.
*
* @author Paul Meagher
* @author Michael Bommarito
* @version 1.2
* @author Paul Meagher
* @author Michael Bommarito
* @version 1.2
*/
class CholeskyDecomposition {
/**
* Decomposition storage
* @var array
* @access private
*/
private $L = array();
/**
* Decomposition storage
* @var array
* @access private
*/
private $L = array();
/**
* Matrix row and column dimension
* @var int
* @access private
*/
private $m;
/**
* Matrix row and column dimension
* @var int
* @access private
*/
private $m;
/**
* Symmetric positive definite flag
* @var boolean
* @access private
*/
private $isspd = true;
/**
* Symmetric positive definite flag
* @var boolean
* @access private
*/
private $isspd = true;
/**
* CholeskyDecomposition
*
* Class constructor - decomposes symmetric positive definite matrix
* @param mixed Matrix square symmetric positive definite matrix
*/
public function __construct($A = null) {
if ($A instanceof Matrix) {
$this->L = $A->getArray();
$this->m = $A->getRowDimension();
/**
* CholeskyDecomposition
*
* Class constructor - decomposes symmetric positive definite matrix
* @param mixed Matrix square symmetric positive definite matrix
*/
public function __construct($A = null) {
if ($A instanceof Matrix) {
$this->L = $A->getArray();
$this->m = $A->getRowDimension();
for($i = 0; $i < $this->m; ++$i) {
for($j = $i; $j < $this->m; ++$j) {
for($sum = $this->L[$i][$j], $k = $i - 1; $k >= 0; --$k) {
$sum -= $this->L[$i][$k] * $this->L[$j][$k];
}
if ($i == $j) {
if ($sum >= 0) {
$this->L[$i][$i] = sqrt($sum);
} else {
$this->isspd = false;
}
} else {
if ($this->L[$i][$i] != 0) {
$this->L[$j][$i] = $sum / $this->L[$i][$i];
}
}
}
for($i = 0; $i < $this->m; ++$i) {
for($j = $i; $j < $this->m; ++$j) {
for($sum = $this->L[$i][$j], $k = $i - 1; $k >= 0; --$k) {
$sum -= $this->L[$i][$k] * $this->L[$j][$k];
}
if ($i == $j) {
if ($sum >= 0) {
$this->L[$i][$i] = sqrt($sum);
} else {
$this->isspd = false;
}
} else {
if ($this->L[$i][$i] != 0) {
$this->L[$j][$i] = $sum / $this->L[$i][$i];
}
}
}
for ($k = $i+1; $k < $this->m; ++$k) {
$this->L[$i][$k] = 0.0;
}
}
} else {
throw new PHPExcel\Calculation_Exception(JAMAError(ArgumentTypeException));
}
} // function __construct()
for ($k = $i+1; $k < $this->m; ++$k) {
$this->L[$i][$k] = 0.0;
}
}
} else {
throw new PHPExcel\Calculation_Exception(JAMAError(ArgumentTypeException));
}
} // function __construct()
/**
* Is the matrix symmetric and positive definite?
*
* @return boolean
*/
public function isSPD() {
return $this->isspd;
} // function isSPD()
/**
* Is the matrix symmetric and positive definite?
*
* @return boolean
*/
public function isSPD() {
return $this->isspd;
} // function isSPD()
/**
* getL
*
* Return triangular factor.
* @return Matrix Lower triangular matrix
*/
public function getL() {
return new Matrix($this->L);
} // function getL()
/**
* getL
*
* Return triangular factor.
* @return Matrix Lower triangular matrix
*/
public function getL() {
return new Matrix($this->L);
} // function getL()
/**
* Solve A*X = B
*
* @param $B Row-equal matrix
* @return Matrix L * L' * X = B
*/
public function solve($B = null) {
if ($B instanceof Matrix) {
if ($B->getRowDimension() == $this->m) {
if ($this->isspd) {
$X = $B->getArrayCopy();
$nx = $B->getColumnDimension();
/**
* Solve A*X = B
*
* @param $B Row-equal matrix
* @return Matrix L * L' * X = B
*/
public function solve($B = null) {
if ($B instanceof Matrix) {
if ($B->getRowDimension() == $this->m) {
if ($this->isspd) {
$X = $B->getArrayCopy();
$nx = $B->getColumnDimension();
for ($k = 0; $k < $this->m; ++$k) {
for ($i = $k + 1; $i < $this->m; ++$i) {
for ($j = 0; $j < $nx; ++$j) {
$X[$i][$j] -= $X[$k][$j] * $this->L[$i][$k];
}
}
for ($j = 0; $j < $nx; ++$j) {
$X[$k][$j] /= $this->L[$k][$k];
}
}
for ($k = 0; $k < $this->m; ++$k) {
for ($i = $k + 1; $i < $this->m; ++$i) {
for ($j = 0; $j < $nx; ++$j) {
$X[$i][$j] -= $X[$k][$j] * $this->L[$i][$k];
}
}
for ($j = 0; $j < $nx; ++$j) {
$X[$k][$j] /= $this->L[$k][$k];
}
}
for ($k = $this->m - 1; $k >= 0; --$k) {
for ($j = 0; $j < $nx; ++$j) {
$X[$k][$j] /= $this->L[$k][$k];
}
for ($i = 0; $i < $k; ++$i) {
for ($j = 0; $j < $nx; ++$j) {
$X[$i][$j] -= $X[$k][$j] * $this->L[$k][$i];
}
}
}
for ($k = $this->m - 1; $k >= 0; --$k) {
for ($j = 0; $j < $nx; ++$j) {
$X[$k][$j] /= $this->L[$k][$k];
}
for ($i = 0; $i < $k; ++$i) {
for ($j = 0; $j < $nx; ++$j) {
$X[$i][$j] -= $X[$k][$j] * $this->L[$k][$i];
}
}
}
return new Matrix($X, $this->m, $nx);
} else {
throw new PHPExcel\Calculation_Exception(JAMAError(MatrixSPDException));
}
} else {
throw new PHPExcel\Calculation_Exception(JAMAError(MatrixDimensionException));
}
} else {
throw new PHPExcel\Calculation_Exception(JAMAError(ArgumentTypeException));
}
} // function solve()
return new Matrix($X, $this->m, $nx);
} else {
throw new PHPExcel\Calculation_Exception(JAMAError(MatrixSPDException));
}
} else {
throw new PHPExcel\Calculation_Exception(JAMAError(MatrixDimensionException));
}
} else {
throw new PHPExcel\Calculation_Exception(JAMAError(ArgumentTypeException));
}
} // function solve()
} // class CholeskyDecomposition
} // class CholeskyDecomposition

File diff suppressed because it is too large Load Diff

View File

@ -1,258 +1,258 @@
<?php
/**
* @package JAMA
* @package JAMA
*
* For an m-by-n matrix A with m >= n, the LU decomposition is an m-by-n
* unit lower triangular matrix L, an n-by-n upper triangular matrix U,
* and a permutation vector piv of length m so that A(piv,:) = L*U.
* If m < n, then L is m-by-m and U is m-by-n.
* For an m-by-n matrix A with m >= n, the LU decomposition is an m-by-n
* unit lower triangular matrix L, an n-by-n upper triangular matrix U,
* and a permutation vector piv of length m so that A(piv,:) = L*U.
* If m < n, then L is m-by-m and U is m-by-n.
*
* The LU decompostion with pivoting always exists, even if the matrix is
* singular, so the constructor will never fail. The primary use of the
* LU decomposition is in the solution of square systems of simultaneous
* linear equations. This will fail if isNonsingular() returns false.
* The LU decompostion with pivoting always exists, even if the matrix is
* singular, so the constructor will never fail. The primary use of the
* LU decomposition is in the solution of square systems of simultaneous
* linear equations. This will fail if isNonsingular() returns false.
*
* @author Paul Meagher
* @author Bartosz Matosiuk
* @author Michael Bommarito
* @version 1.1
* @license PHP v3.0
* @author Paul Meagher
* @author Bartosz Matosiuk
* @author Michael Bommarito
* @version 1.1
* @license PHP v3.0
*/
class PHPExcel_Shared_JAMA_LUDecomposition {
const MatrixSingularException = "Can only perform operation on singular matrix.";
const MatrixSquareException = "Mismatched Row dimension";
const MatrixSingularException = "Can only perform operation on singular matrix.";
const MatrixSquareException = "Mismatched Row dimension";
/**
* Decomposition storage
* @var array
*/
private $LU = array();
/**
* Decomposition storage
* @var array
*/
private $LU = array();
/**
* Row dimension.
* @var int
*/
private $m;
/**
* Row dimension.
* @var int
*/
private $m;
/**
* Column dimension.
* @var int
*/
private $n;
/**
* Column dimension.
* @var int
*/
private $n;
/**
* Pivot sign.
* @var int
*/
private $pivsign;
/**
* Pivot sign.
* @var int
*/
private $pivsign;
/**
* Internal storage of pivot vector.
* @var array
*/
private $piv = array();
/**
* Internal storage of pivot vector.
* @var array
*/
private $piv = array();
/**
* LU Decomposition constructor.
*
* @param $A Rectangular matrix
* @return Structure to access L, U and piv.
*/
public function __construct($A) {
if ($A instanceof PHPExcel_Shared_JAMA_Matrix) {
// Use a "left-looking", dot-product, Crout/Doolittle algorithm.
$this->LU = $A->getArray();
$this->m = $A->getRowDimension();
$this->n = $A->getColumnDimension();
for ($i = 0; $i < $this->m; ++$i) {
$this->piv[$i] = $i;
}
$this->pivsign = 1;
$LUrowi = $LUcolj = array();
/**
* LU Decomposition constructor.
*
* @param $A Rectangular matrix
* @return Structure to access L, U and piv.
*/
public function __construct($A) {
if ($A instanceof PHPExcel_Shared_JAMA_Matrix) {
// Use a "left-looking", dot-product, Crout/Doolittle algorithm.
$this->LU = $A->getArray();
$this->m = $A->getRowDimension();
$this->n = $A->getColumnDimension();
for ($i = 0; $i < $this->m; ++$i) {
$this->piv[$i] = $i;
}
$this->pivsign = 1;
$LUrowi = $LUcolj = array();
// Outer loop.
for ($j = 0; $j < $this->n; ++$j) {
// Make a copy of the j-th column to localize references.
for ($i = 0; $i < $this->m; ++$i) {
$LUcolj[$i] = &$this->LU[$i][$j];
}
// Apply previous transformations.
for ($i = 0; $i < $this->m; ++$i) {
$LUrowi = $this->LU[$i];
// Most of the time is spent in the following dot product.
$kmax = min($i,$j);
$s = 0.0;
for ($k = 0; $k < $kmax; ++$k) {
$s += $LUrowi[$k] * $LUcolj[$k];
}
$LUrowi[$j] = $LUcolj[$i] -= $s;
}
// Find pivot and exchange if necessary.
$p = $j;
for ($i = $j+1; $i < $this->m; ++$i) {
if (abs($LUcolj[$i]) > abs($LUcolj[$p])) {
$p = $i;
}
}
if ($p != $j) {
for ($k = 0; $k < $this->n; ++$k) {
$t = $this->LU[$p][$k];
$this->LU[$p][$k] = $this->LU[$j][$k];
$this->LU[$j][$k] = $t;
}
$k = $this->piv[$p];
$this->piv[$p] = $this->piv[$j];
$this->piv[$j] = $k;
$this->pivsign = $this->pivsign * -1;
}
// Compute multipliers.
if (($j < $this->m) && ($this->LU[$j][$j] != 0.0)) {
for ($i = $j+1; $i < $this->m; ++$i) {
$this->LU[$i][$j] /= $this->LU[$j][$j];
}
}
}
} else {
throw new PHPExcel_Calculation_Exception(PHPExcel_Shared_JAMA_Matrix::ArgumentTypeException);
}
} // function __construct()
// Outer loop.
for ($j = 0; $j < $this->n; ++$j) {
// Make a copy of the j-th column to localize references.
for ($i = 0; $i < $this->m; ++$i) {
$LUcolj[$i] = &$this->LU[$i][$j];
}
// Apply previous transformations.
for ($i = 0; $i < $this->m; ++$i) {
$LUrowi = $this->LU[$i];
// Most of the time is spent in the following dot product.
$kmax = min($i,$j);
$s = 0.0;
for ($k = 0; $k < $kmax; ++$k) {
$s += $LUrowi[$k] * $LUcolj[$k];
}
$LUrowi[$j] = $LUcolj[$i] -= $s;
}
// Find pivot and exchange if necessary.
$p = $j;
for ($i = $j+1; $i < $this->m; ++$i) {
if (abs($LUcolj[$i]) > abs($LUcolj[$p])) {
$p = $i;
}
}
if ($p != $j) {
for ($k = 0; $k < $this->n; ++$k) {
$t = $this->LU[$p][$k];
$this->LU[$p][$k] = $this->LU[$j][$k];
$this->LU[$j][$k] = $t;
}
$k = $this->piv[$p];
$this->piv[$p] = $this->piv[$j];
$this->piv[$j] = $k;
$this->pivsign = $this->pivsign * -1;
}
// Compute multipliers.
if (($j < $this->m) && ($this->LU[$j][$j] != 0.0)) {
for ($i = $j+1; $i < $this->m; ++$i) {
$this->LU[$i][$j] /= $this->LU[$j][$j];
}
}
}
} else {
throw new PHPExcel_Calculation_Exception(PHPExcel_Shared_JAMA_Matrix::ArgumentTypeException);
}
} // function __construct()
/**
* Get lower triangular factor.
*
* @return array Lower triangular factor
*/
public function getL() {
for ($i = 0; $i < $this->m; ++$i) {
for ($j = 0; $j < $this->n; ++$j) {
if ($i > $j) {
$L[$i][$j] = $this->LU[$i][$j];
} elseif ($i == $j) {
$L[$i][$j] = 1.0;
} else {
$L[$i][$j] = 0.0;
}
}
}
return new PHPExcel_Shared_JAMA_Matrix($L);
} // function getL()
/**
* Get lower triangular factor.
*
* @return array Lower triangular factor
*/
public function getL() {
for ($i = 0; $i < $this->m; ++$i) {
for ($j = 0; $j < $this->n; ++$j) {
if ($i > $j) {
$L[$i][$j] = $this->LU[$i][$j];
} elseif ($i == $j) {
$L[$i][$j] = 1.0;
} else {
$L[$i][$j] = 0.0;
}
}
}
return new PHPExcel_Shared_JAMA_Matrix($L);
} // function getL()
/**
* Get upper triangular factor.
*
* @return array Upper triangular factor
*/
public function getU() {
for ($i = 0; $i < $this->n; ++$i) {
for ($j = 0; $j < $this->n; ++$j) {
if ($i <= $j) {
$U[$i][$j] = $this->LU[$i][$j];
} else {
$U[$i][$j] = 0.0;
}
}
}
return new PHPExcel_Shared_JAMA_Matrix($U);
} // function getU()
/**
* Get upper triangular factor.
*
* @return array Upper triangular factor
*/
public function getU() {
for ($i = 0; $i < $this->n; ++$i) {
for ($j = 0; $j < $this->n; ++$j) {
if ($i <= $j) {
$U[$i][$j] = $this->LU[$i][$j];
} else {
$U[$i][$j] = 0.0;
}
}
}
return new PHPExcel_Shared_JAMA_Matrix($U);
} // function getU()
/**
* Return pivot permutation vector.
*
* @return array Pivot vector
*/
public function getPivot() {
return $this->piv;
} // function getPivot()
/**
* Return pivot permutation vector.
*
* @return array Pivot vector
*/
public function getPivot() {
return $this->piv;
} // function getPivot()
/**
* Alias for getPivot
*
* @see getPivot
*/
public function getDoublePivot() {
return $this->getPivot();
} // function getDoublePivot()
/**
* Alias for getPivot
*
* @see getPivot
*/
public function getDoublePivot() {
return $this->getPivot();
} // function getDoublePivot()
/**
* Is the matrix nonsingular?
*
* @return true if U, and hence A, is nonsingular.
*/
public function isNonsingular() {
for ($j = 0; $j < $this->n; ++$j) {
if ($this->LU[$j][$j] == 0) {
return false;
}
}
return true;
} // function isNonsingular()
/**
* Is the matrix nonsingular?
*
* @return true if U, and hence A, is nonsingular.
*/
public function isNonsingular() {
for ($j = 0; $j < $this->n; ++$j) {
if ($this->LU[$j][$j] == 0) {
return false;
}
}
return true;
} // function isNonsingular()
/**
* Count determinants
*
* @return array d matrix deterninat
*/
public function det() {
if ($this->m == $this->n) {
$d = $this->pivsign;
for ($j = 0; $j < $this->n; ++$j) {
$d *= $this->LU[$j][$j];
}
return $d;
} else {
throw new PHPExcel_Calculation_Exception(PHPExcel_Shared_JAMA_Matrix::MatrixDimensionException);
}
} // function det()
/**
* Count determinants
*
* @return array d matrix deterninat
*/
public function det() {
if ($this->m == $this->n) {
$d = $this->pivsign;
for ($j = 0; $j < $this->n; ++$j) {
$d *= $this->LU[$j][$j];
}
return $d;
} else {
throw new PHPExcel_Calculation_Exception(PHPExcel_Shared_JAMA_Matrix::MatrixDimensionException);
}
} // function det()
/**
* Solve A*X = B
*
* @param $B A Matrix with as many rows as A and any number of columns.
* @return X so that L*U*X = B(piv,:)
* @PHPExcel_Calculation_Exception IllegalArgumentException Matrix row dimensions must agree.
* @PHPExcel_Calculation_Exception RuntimeException Matrix is singular.
*/
public function solve($B) {
if ($B->getRowDimension() == $this->m) {
if ($this->isNonsingular()) {
// Copy right hand side with pivoting
$nx = $B->getColumnDimension();
$X = $B->getMatrix($this->piv, 0, $nx-1);
// Solve L*Y = B(piv,:)
for ($k = 0; $k < $this->n; ++$k) {
for ($i = $k+1; $i < $this->n; ++$i) {
for ($j = 0; $j < $nx; ++$j) {
$X->A[$i][$j] -= $X->A[$k][$j] * $this->LU[$i][$k];
}
}
}
// Solve U*X = Y;
for ($k = $this->n-1; $k >= 0; --$k) {
for ($j = 0; $j < $nx; ++$j) {
$X->A[$k][$j] /= $this->LU[$k][$k];
}
for ($i = 0; $i < $k; ++$i) {
for ($j = 0; $j < $nx; ++$j) {
$X->A[$i][$j] -= $X->A[$k][$j] * $this->LU[$i][$k];
}
}
}
return $X;
} else {
throw new PHPExcel_Calculation_Exception(self::MatrixSingularException);
}
} else {
throw new PHPExcel_Calculation_Exception(self::MatrixSquareException);
}
} // function solve()
/**
* Solve A*X = B
*
* @param $B A Matrix with as many rows as A and any number of columns.
* @return X so that L*U*X = B(piv,:)
* @PHPExcel_Calculation_Exception IllegalArgumentException Matrix row dimensions must agree.
* @PHPExcel_Calculation_Exception RuntimeException Matrix is singular.
*/
public function solve($B) {
if ($B->getRowDimension() == $this->m) {
if ($this->isNonsingular()) {
// Copy right hand side with pivoting
$nx = $B->getColumnDimension();
$X = $B->getMatrix($this->piv, 0, $nx-1);
// Solve L*Y = B(piv,:)
for ($k = 0; $k < $this->n; ++$k) {
for ($i = $k+1; $i < $this->n; ++$i) {
for ($j = 0; $j < $nx; ++$j) {
$X->A[$i][$j] -= $X->A[$k][$j] * $this->LU[$i][$k];
}
}
}
// Solve U*X = Y;
for ($k = $this->n-1; $k >= 0; --$k) {
for ($j = 0; $j < $nx; ++$j) {
$X->A[$k][$j] /= $this->LU[$k][$k];
}
for ($i = 0; $i < $k; ++$i) {
for ($j = 0; $j < $nx; ++$j) {
$X->A[$i][$j] -= $X->A[$k][$j] * $this->LU[$i][$k];
}
}
}
return $X;
} else {
throw new PHPExcel_Calculation_Exception(self::MatrixSingularException);
}
} else {
throw new PHPExcel_Calculation_Exception(self::MatrixSquareException);
}
} // function solve()
} // class PHPExcel_Shared_JAMA_LUDecomposition
} // class PHPExcel_Shared_JAMA_LUDecomposition

File diff suppressed because it is too large Load Diff

View File

@ -1,234 +1,234 @@
<?php
/**
* @package JAMA
* @package JAMA
*
* For an m-by-n matrix A with m >= n, the QR decomposition is an m-by-n
* orthogonal matrix Q and an n-by-n upper triangular matrix R so that
* A = Q*R.
* For an m-by-n matrix A with m >= n, the QR decomposition is an m-by-n
* orthogonal matrix Q and an n-by-n upper triangular matrix R so that
* A = Q*R.
*
* The QR decompostion always exists, even if the matrix does not have
* full rank, so the constructor will never fail. The primary use of the
* QR decomposition is in the least squares solution of nonsquare systems
* of simultaneous linear equations. This will fail if isFullRank()
* returns false.
* The QR decompostion always exists, even if the matrix does not have
* full rank, so the constructor will never fail. The primary use of the
* QR decomposition is in the least squares solution of nonsquare systems
* of simultaneous linear equations. This will fail if isFullRank()
* returns false.
*
* @author Paul Meagher
* @license PHP v3.0
* @version 1.1
* @author Paul Meagher
* @license PHP v3.0
* @version 1.1
*/
class PHPExcel_Shared_JAMA_QRDecomposition {
const MatrixRankException = "Can only perform operation on full-rank matrix.";
const MatrixRankException = "Can only perform operation on full-rank matrix.";
/**
* Array for internal storage of decomposition.
* @var array
*/
private $QR = array();
/**
* Array for internal storage of decomposition.
* @var array
*/
private $QR = array();
/**
* Row dimension.
* @var integer
*/
private $m;
/**
* Row dimension.
* @var integer
*/
private $m;
/**
* Column dimension.
* @var integer
*/
private $n;
/**
* Column dimension.
* @var integer
*/
private $n;
/**
* Array for internal storage of diagonal of R.
* @var array
*/
private $Rdiag = array();
/**
* Array for internal storage of diagonal of R.
* @var array
*/
private $Rdiag = array();
/**
* QR Decomposition computed by Householder reflections.
*
* @param matrix $A Rectangular matrix
* @return Structure to access R and the Householder vectors and compute Q.
*/
public function __construct($A) {
if($A instanceof PHPExcel_Shared_JAMA_Matrix) {
// Initialize.
$this->QR = $A->getArrayCopy();
$this->m = $A->getRowDimension();
$this->n = $A->getColumnDimension();
// Main loop.
for ($k = 0; $k < $this->n; ++$k) {
// Compute 2-norm of k-th column without under/overflow.
$nrm = 0.0;
for ($i = $k; $i < $this->m; ++$i) {
$nrm = hypo($nrm, $this->QR[$i][$k]);
}
if ($nrm != 0.0) {
// Form k-th Householder vector.
if ($this->QR[$k][$k] < 0) {
$nrm = -$nrm;
}
for ($i = $k; $i < $this->m; ++$i) {
$this->QR[$i][$k] /= $nrm;
}
$this->QR[$k][$k] += 1.0;
// Apply transformation to remaining columns.
for ($j = $k+1; $j < $this->n; ++$j) {
$s = 0.0;
for ($i = $k; $i < $this->m; ++$i) {
$s += $this->QR[$i][$k] * $this->QR[$i][$j];
}
$s = -$s/$this->QR[$k][$k];
for ($i = $k; $i < $this->m; ++$i) {
$this->QR[$i][$j] += $s * $this->QR[$i][$k];
}
}
}
$this->Rdiag[$k] = -$nrm;
}
} else {
throw new PHPExcel_Calculation_Exception(PHPExcel_Shared_JAMA_Matrix::ArgumentTypeException);
}
} // function __construct()
/**
* QR Decomposition computed by Householder reflections.
*
* @param matrix $A Rectangular matrix
* @return Structure to access R and the Householder vectors and compute Q.
*/
public function __construct($A) {
if($A instanceof PHPExcel_Shared_JAMA_Matrix) {
// Initialize.
$this->QR = $A->getArrayCopy();
$this->m = $A->getRowDimension();
$this->n = $A->getColumnDimension();
// Main loop.
for ($k = 0; $k < $this->n; ++$k) {
// Compute 2-norm of k-th column without under/overflow.
$nrm = 0.0;
for ($i = $k; $i < $this->m; ++$i) {
$nrm = hypo($nrm, $this->QR[$i][$k]);
}
if ($nrm != 0.0) {
// Form k-th Householder vector.
if ($this->QR[$k][$k] < 0) {
$nrm = -$nrm;
}
for ($i = $k; $i < $this->m; ++$i) {
$this->QR[$i][$k] /= $nrm;
}
$this->QR[$k][$k] += 1.0;
// Apply transformation to remaining columns.
for ($j = $k+1; $j < $this->n; ++$j) {
$s = 0.0;
for ($i = $k; $i < $this->m; ++$i) {
$s += $this->QR[$i][$k] * $this->QR[$i][$j];
}
$s = -$s/$this->QR[$k][$k];
for ($i = $k; $i < $this->m; ++$i) {
$this->QR[$i][$j] += $s * $this->QR[$i][$k];
}
}
}
$this->Rdiag[$k] = -$nrm;
}
} else {
throw new PHPExcel_Calculation_Exception(PHPExcel_Shared_JAMA_Matrix::ArgumentTypeException);
}
} // function __construct()
/**
* Is the matrix full rank?
*
* @return boolean true if R, and hence A, has full rank, else false.
*/
public function isFullRank() {
for ($j = 0; $j < $this->n; ++$j) {
if ($this->Rdiag[$j] == 0) {
return false;
}
}
return true;
} // function isFullRank()
/**
* Is the matrix full rank?
*
* @return boolean true if R, and hence A, has full rank, else false.
*/
public function isFullRank() {
for ($j = 0; $j < $this->n; ++$j) {
if ($this->Rdiag[$j] == 0) {
return false;
}
}
return true;
} // function isFullRank()
/**
* Return the Householder vectors
*
* @return Matrix Lower trapezoidal matrix whose columns define the reflections
*/
public function getH() {
for ($i = 0; $i < $this->m; ++$i) {
for ($j = 0; $j < $this->n; ++$j) {
if ($i >= $j) {
$H[$i][$j] = $this->QR[$i][$j];
} else {
$H[$i][$j] = 0.0;
}
}
}
return new PHPExcel_Shared_JAMA_Matrix($H);
} // function getH()
/**
* Return the Householder vectors
*
* @return Matrix Lower trapezoidal matrix whose columns define the reflections
*/
public function getH() {
for ($i = 0; $i < $this->m; ++$i) {
for ($j = 0; $j < $this->n; ++$j) {
if ($i >= $j) {
$H[$i][$j] = $this->QR[$i][$j];
} else {
$H[$i][$j] = 0.0;
}
}
}
return new PHPExcel_Shared_JAMA_Matrix($H);
} // function getH()
/**
* Return the upper triangular factor
*
* @return Matrix upper triangular factor
*/
public function getR() {
for ($i = 0; $i < $this->n; ++$i) {
for ($j = 0; $j < $this->n; ++$j) {
if ($i < $j) {
$R[$i][$j] = $this->QR[$i][$j];
} elseif ($i == $j) {
$R[$i][$j] = $this->Rdiag[$i];
} else {
$R[$i][$j] = 0.0;
}
}
}
return new PHPExcel_Shared_JAMA_Matrix($R);
} // function getR()
/**
* Return the upper triangular factor
*
* @return Matrix upper triangular factor
*/
public function getR() {
for ($i = 0; $i < $this->n; ++$i) {
for ($j = 0; $j < $this->n; ++$j) {
if ($i < $j) {
$R[$i][$j] = $this->QR[$i][$j];
} elseif ($i == $j) {
$R[$i][$j] = $this->Rdiag[$i];
} else {
$R[$i][$j] = 0.0;
}
}
}
return new PHPExcel_Shared_JAMA_Matrix($R);
} // function getR()
/**
* Generate and return the (economy-sized) orthogonal factor
*
* @return Matrix orthogonal factor
*/
public function getQ() {
for ($k = $this->n-1; $k >= 0; --$k) {
for ($i = 0; $i < $this->m; ++$i) {
$Q[$i][$k] = 0.0;
}
$Q[$k][$k] = 1.0;
for ($j = $k; $j < $this->n; ++$j) {
if ($this->QR[$k][$k] != 0) {
$s = 0.0;
for ($i = $k; $i < $this->m; ++$i) {
$s += $this->QR[$i][$k] * $Q[$i][$j];
}
$s = -$s/$this->QR[$k][$k];
for ($i = $k; $i < $this->m; ++$i) {
$Q[$i][$j] += $s * $this->QR[$i][$k];
}
}
}
}
/*
for($i = 0; $i < count($Q); ++$i) {
for($j = 0; $j < count($Q); ++$j) {
if(! isset($Q[$i][$j]) ) {
$Q[$i][$j] = 0;
}
}
}
*/
return new PHPExcel_Shared_JAMA_Matrix($Q);
} // function getQ()
/**
* Generate and return the (economy-sized) orthogonal factor
*
* @return Matrix orthogonal factor
*/
public function getQ() {
for ($k = $this->n-1; $k >= 0; --$k) {
for ($i = 0; $i < $this->m; ++$i) {
$Q[$i][$k] = 0.0;
}
$Q[$k][$k] = 1.0;
for ($j = $k; $j < $this->n; ++$j) {
if ($this->QR[$k][$k] != 0) {
$s = 0.0;
for ($i = $k; $i < $this->m; ++$i) {
$s += $this->QR[$i][$k] * $Q[$i][$j];
}
$s = -$s/$this->QR[$k][$k];
for ($i = $k; $i < $this->m; ++$i) {
$Q[$i][$j] += $s * $this->QR[$i][$k];
}
}
}
}
/*
for($i = 0; $i < count($Q); ++$i) {
for($j = 0; $j < count($Q); ++$j) {
if(! isset($Q[$i][$j]) ) {
$Q[$i][$j] = 0;
}
}
}
*/
return new PHPExcel_Shared_JAMA_Matrix($Q);
} // function getQ()
/**
* Least squares solution of A*X = B
*
* @param Matrix $B A Matrix with as many rows as A and any number of columns.
* @return Matrix Matrix that minimizes the two norm of Q*R*X-B.
*/
public function solve($B) {
if ($B->getRowDimension() == $this->m) {
if ($this->isFullRank()) {
// Copy right hand side
$nx = $B->getColumnDimension();
$X = $B->getArrayCopy();
// Compute Y = transpose(Q)*B
for ($k = 0; $k < $this->n; ++$k) {
for ($j = 0; $j < $nx; ++$j) {
$s = 0.0;
for ($i = $k; $i < $this->m; ++$i) {
$s += $this->QR[$i][$k] * $X[$i][$j];
}
$s = -$s/$this->QR[$k][$k];
for ($i = $k; $i < $this->m; ++$i) {
$X[$i][$j] += $s * $this->QR[$i][$k];
}
}
}
// Solve R*X = Y;
for ($k = $this->n-1; $k >= 0; --$k) {
for ($j = 0; $j < $nx; ++$j) {
$X[$k][$j] /= $this->Rdiag[$k];
}
for ($i = 0; $i < $k; ++$i) {
for ($j = 0; $j < $nx; ++$j) {
$X[$i][$j] -= $X[$k][$j]* $this->QR[$i][$k];
}
}
}
$X = new PHPExcel_Shared_JAMA_Matrix($X);
return ($X->getMatrix(0, $this->n-1, 0, $nx));
} else {
throw new PHPExcel_Calculation_Exception(self::MatrixRankException);
}
} else {
throw new PHPExcel_Calculation_Exception(PHPExcel_Shared_JAMA_Matrix::MatrixDimensionException);
}
} // function solve()
/**
* Least squares solution of A*X = B
*
* @param Matrix $B A Matrix with as many rows as A and any number of columns.
* @return Matrix Matrix that minimizes the two norm of Q*R*X-B.
*/
public function solve($B) {
if ($B->getRowDimension() == $this->m) {
if ($this->isFullRank()) {
// Copy right hand side
$nx = $B->getColumnDimension();
$X = $B->getArrayCopy();
// Compute Y = transpose(Q)*B
for ($k = 0; $k < $this->n; ++$k) {
for ($j = 0; $j < $nx; ++$j) {
$s = 0.0;
for ($i = $k; $i < $this->m; ++$i) {
$s += $this->QR[$i][$k] * $X[$i][$j];
}
$s = -$s/$this->QR[$k][$k];
for ($i = $k; $i < $this->m; ++$i) {
$X[$i][$j] += $s * $this->QR[$i][$k];
}
}
}
// Solve R*X = Y;
for ($k = $this->n-1; $k >= 0; --$k) {
for ($j = 0; $j < $nx; ++$j) {
$X[$k][$j] /= $this->Rdiag[$k];
}
for ($i = 0; $i < $k; ++$i) {
for ($j = 0; $j < $nx; ++$j) {
$X[$i][$j] -= $X[$k][$j]* $this->QR[$i][$k];
}
}
}
$X = new PHPExcel_Shared_JAMA_Matrix($X);
return ($X->getMatrix(0, $this->n-1, 0, $nx));
} else {
throw new PHPExcel_Calculation_Exception(self::MatrixRankException);
}
} else {
throw new PHPExcel_Calculation_Exception(PHPExcel_Shared_JAMA_Matrix::MatrixDimensionException);
}
} // function solve()
} // PHPExcel_Shared_JAMA_class QRDecomposition
} // PHPExcel_Shared_JAMA_class QRDecomposition

File diff suppressed because it is too large Load Diff

View File

@ -1,10 +1,10 @@
<?php
/**
* @package JAMA
* @package JAMA
*
* Error handling
* @author Michael Bommarito
* @version 01292005
* Error handling
* @author Michael Bommarito
* @version 01292005
*/
//Language constant
@ -64,19 +64,19 @@ define('RowLengthException', -10);
$error['EN'][RowLengthException] = "All rows must have the same length.";
/**
* Custom error handler
* @param int $num Error number
* Custom error handler
* @param int $num Error number
*/
function JAMAError($errorNumber = null) {
global $error;
global $error;
if (isset($errorNumber)) {
if (isset($error[JAMALANG][$errorNumber])) {
return $error[JAMALANG][$errorNumber];
} else {
return $error['EN'][$errorNumber];
}
} else {
return ("Invalid argument to JAMAError()");
}
if (isset($errorNumber)) {
if (isset($error[JAMALANG][$errorNumber])) {
return $error[JAMALANG][$errorNumber];
} else {
return $error['EN'][$errorNumber];
}
} else {
return ("Invalid argument to JAMAError()");
}
}

View File

@ -1,43 +1,43 @@
<?php
/**
* @package JAMA
* @package JAMA
*
* Pythagorean Theorem:
* Pythagorean Theorem:
*
* a = 3
* b = 4
* r = sqrt(square(a) + square(b))
* r = 5
* a = 3
* b = 4
* r = sqrt(square(a) + square(b))
* r = 5
*
* r = sqrt(a^2 + b^2) without under/overflow.
* r = sqrt(a^2 + b^2) without under/overflow.
*/
function hypo($a, $b) {
if (abs($a) > abs($b)) {
$r = $b / $a;
$r = abs($a) * sqrt(1 + $r * $r);
} elseif ($b != 0) {
$r = $a / $b;
$r = abs($b) * sqrt(1 + $r * $r);
} else {
$r = 0.0;
}
return $r;
} // function hypo()
if (abs($a) > abs($b)) {
$r = $b / $a;
$r = abs($a) * sqrt(1 + $r * $r);
} elseif ($b != 0) {
$r = $a / $b;
$r = abs($b) * sqrt(1 + $r * $r);
} else {
$r = 0.0;
}
return $r;
} // function hypo()
/**
* Mike Bommarito's version.
* Compute n-dimensional hyotheneuse.
* Mike Bommarito's version.
* Compute n-dimensional hyotheneuse.
*
function hypot() {
$s = 0;
foreach (func_get_args() as $d) {
if (is_numeric($d)) {
$s += pow($d, 2);
} else {
throw new PHPExcel_Calculation_Exception(JAMAError(ArgumentTypeException));
}
}
return sqrt($s);
$s = 0;
foreach (func_get_args() as $d) {
if (is_numeric($d)) {
$s += pow($d, 2);
} else {
throw new PHPExcel_Calculation_Exception(JAMAError(ArgumentTypeException));
}
}
return sqrt($s);
}
*/

View File

@ -39,495 +39,495 @@ $GLOBALS['_OLE_INSTANCES'] = array();
*/
class Shared_OLE
{
const OLE_PPS_TYPE_ROOT = 5;
const OLE_PPS_TYPE_DIR = 1;
const OLE_PPS_TYPE_FILE = 2;
const OLE_DATA_SIZE_SMALL = 0x1000;
const OLE_LONG_INT_SIZE = 4;
const OLE_PPS_SIZE = 0x80;
const OLE_PPS_TYPE_ROOT = 5;
const OLE_PPS_TYPE_DIR = 1;
const OLE_PPS_TYPE_FILE = 2;
const OLE_DATA_SIZE_SMALL = 0x1000;
const OLE_LONG_INT_SIZE = 4;
const OLE_PPS_SIZE = 0x80;
/**
* The file handle for reading an OLE container
* @var resource
*/
public $_file_handle;
/**
* The file handle for reading an OLE container
* @var resource
*/
public $_file_handle;
/**
* Array of PPS's found on the OLE container
* @var array
*/
public $_list = array();
/**
* Array of PPS's found on the OLE container
* @var array
*/
public $_list = array();
/**
* Root directory of OLE container
* @var OLE_PPS_Root
*/
public $root;
/**
* Root directory of OLE container
* @var OLE_PPS_Root
*/
public $root;
/**
* Big Block Allocation Table
* @var array (blockId => nextBlockId)
*/
public $bbat;
/**
* Big Block Allocation Table
* @var array (blockId => nextBlockId)
*/
public $bbat;
/**
* Short Block Allocation Table
* @var array (blockId => nextBlockId)
*/
public $sbat;
/**
* Short Block Allocation Table
* @var array (blockId => nextBlockId)
*/
public $sbat;
/**
* Size of big blocks. This is usually 512.
* @var int number of octets per block.
*/
public $bigBlockSize;
/**
* Size of big blocks. This is usually 512.
* @var int number of octets per block.
*/
public $bigBlockSize;
/**
* Size of small blocks. This is usually 64.
* @var int number of octets per block
*/
public $smallBlockSize;
/**
* Size of small blocks. This is usually 64.
* @var int number of octets per block
*/
public $smallBlockSize;
/**
* Reads an OLE container from the contents of the file given.
*
* @acces public
* @param string $file
* @return mixed true on success, PEAR_Error on failure
*/
public function read($file)
{
$fh = fopen($file, "r");
if (!$fh) {
throw new Reader_Exception("Can't open file $file");
}
$this->_file_handle = $fh;
/**
* Reads an OLE container from the contents of the file given.
*
* @acces public
* @param string $file
* @return mixed true on success, PEAR_Error on failure
*/
public function read($file)
{
$fh = fopen($file, "r");
if (!$fh) {
throw new Reader_Exception("Can't open file $file");
}
$this->_file_handle = $fh;
$signature = fread($fh, 8);
if ("\xD0\xCF\x11\xE0\xA1\xB1\x1A\xE1" != $signature) {
throw new Reader_Exception("File doesn't seem to be an OLE container.");
}
fseek($fh, 28);
if (fread($fh, 2) != "\xFE\xFF") {
// This shouldn't be a problem in practice
throw new Reader_Exception("Only Little-Endian encoding is supported.");
}
// Size of blocks and short blocks in bytes
$this->bigBlockSize = pow(2, self::_readInt2($fh));
$this->smallBlockSize = pow(2, self::_readInt2($fh));
$signature = fread($fh, 8);
if ("\xD0\xCF\x11\xE0\xA1\xB1\x1A\xE1" != $signature) {
throw new Reader_Exception("File doesn't seem to be an OLE container.");
}
fseek($fh, 28);
if (fread($fh, 2) != "\xFE\xFF") {
// This shouldn't be a problem in practice
throw new Reader_Exception("Only Little-Endian encoding is supported.");
}
// Size of blocks and short blocks in bytes
$this->bigBlockSize = pow(2, self::_readInt2($fh));
$this->smallBlockSize = pow(2, self::_readInt2($fh));
// Skip UID, revision number and version number
fseek($fh, 44);
// Number of blocks in Big Block Allocation Table
$bbatBlockCount = self::_readInt4($fh);
// Skip UID, revision number and version number
fseek($fh, 44);
// Number of blocks in Big Block Allocation Table
$bbatBlockCount = self::_readInt4($fh);
// Root chain 1st block
$directoryFirstBlockId = self::_readInt4($fh);
// Root chain 1st block
$directoryFirstBlockId = self::_readInt4($fh);
// Skip unused bytes
fseek($fh, 56);
// Streams shorter than this are stored using small blocks
$this->bigBlockThreshold = self::_readInt4($fh);
// Block id of first sector in Short Block Allocation Table
$sbatFirstBlockId = self::_readInt4($fh);
// Number of blocks in Short Block Allocation Table
$sbbatBlockCount = self::_readInt4($fh);
// Block id of first sector in Master Block Allocation Table
$mbatFirstBlockId = self::_readInt4($fh);
// Number of blocks in Master Block Allocation Table
$mbbatBlockCount = self::_readInt4($fh);
$this->bbat = array();
// Skip unused bytes
fseek($fh, 56);
// Streams shorter than this are stored using small blocks
$this->bigBlockThreshold = self::_readInt4($fh);
// Block id of first sector in Short Block Allocation Table
$sbatFirstBlockId = self::_readInt4($fh);
// Number of blocks in Short Block Allocation Table
$sbbatBlockCount = self::_readInt4($fh);
// Block id of first sector in Master Block Allocation Table
$mbatFirstBlockId = self::_readInt4($fh);
// Number of blocks in Master Block Allocation Table
$mbbatBlockCount = self::_readInt4($fh);
$this->bbat = array();
// Remaining 4 * 109 bytes of current block is beginning of Master
// Block Allocation Table
$mbatBlocks = array();
for ($i = 0; $i < 109; ++$i) {
$mbatBlocks[] = self::_readInt4($fh);
}
// Remaining 4 * 109 bytes of current block is beginning of Master
// Block Allocation Table
$mbatBlocks = array();
for ($i = 0; $i < 109; ++$i) {
$mbatBlocks[] = self::_readInt4($fh);
}
// Read rest of Master Block Allocation Table (if any is left)
$pos = $this->_getBlockOffset($mbatFirstBlockId);
for ($i = 0; $i < $mbbatBlockCount; ++$i) {
fseek($fh, $pos);
for ($j = 0; $j < $this->bigBlockSize / 4 - 1; ++$j) {
$mbatBlocks[] = self::_readInt4($fh);
}
// Last block id in each block points to next block
$pos = $this->_getBlockOffset(self::_readInt4($fh));
}
// Read rest of Master Block Allocation Table (if any is left)
$pos = $this->_getBlockOffset($mbatFirstBlockId);
for ($i = 0; $i < $mbbatBlockCount; ++$i) {
fseek($fh, $pos);
for ($j = 0; $j < $this->bigBlockSize / 4 - 1; ++$j) {
$mbatBlocks[] = self::_readInt4($fh);
}
// Last block id in each block points to next block
$pos = $this->_getBlockOffset(self::_readInt4($fh));
}
// Read Big Block Allocation Table according to chain specified by
// $mbatBlocks
for ($i = 0; $i < $bbatBlockCount; ++$i) {
$pos = $this->_getBlockOffset($mbatBlocks[$i]);
fseek($fh, $pos);
for ($j = 0 ; $j < $this->bigBlockSize / 4; ++$j) {
$this->bbat[] = self::_readInt4($fh);
}
}
// Read Big Block Allocation Table according to chain specified by
// $mbatBlocks
for ($i = 0; $i < $bbatBlockCount; ++$i) {
$pos = $this->_getBlockOffset($mbatBlocks[$i]);
fseek($fh, $pos);
for ($j = 0 ; $j < $this->bigBlockSize / 4; ++$j) {
$this->bbat[] = self::_readInt4($fh);
}
}
// Read short block allocation table (SBAT)
$this->sbat = array();
$shortBlockCount = $sbbatBlockCount * $this->bigBlockSize / 4;
$sbatFh = $this->getStream($sbatFirstBlockId);
for ($blockId = 0; $blockId < $shortBlockCount; ++$blockId) {
$this->sbat[$blockId] = self::_readInt4($sbatFh);
}
fclose($sbatFh);
// Read short block allocation table (SBAT)
$this->sbat = array();
$shortBlockCount = $sbbatBlockCount * $this->bigBlockSize / 4;
$sbatFh = $this->getStream($sbatFirstBlockId);
for ($blockId = 0; $blockId < $shortBlockCount; ++$blockId) {
$this->sbat[$blockId] = self::_readInt4($sbatFh);
}
fclose($sbatFh);
$this->_readPpsWks($directoryFirstBlockId);
$this->_readPpsWks($directoryFirstBlockId);
return true;
}
return true;
}
/**
* @param int block id
* @param int byte offset from beginning of file
* @access public
*/
public function _getBlockOffset($blockId)
{
return 512 + $blockId * $this->bigBlockSize;
}
/**
* @param int block id
* @param int byte offset from beginning of file
* @access public
*/
public function _getBlockOffset($blockId)
{
return 512 + $blockId * $this->bigBlockSize;
}
/**
* Returns a stream for use with fread() etc. External callers should
* use PHPExcel\Shared_OLE_PPS_File::getStream().
* @param int|PPS block id or PPS
* @return resource read-only stream
*/
public function getStream($blockIdOrPps)
{
static $isRegistered = false;
if (!$isRegistered) {
stream_wrapper_register('ole-chainedblockstream',
__NAMESPACE__ . '\Shared_OLE_ChainedBlockStream');
$isRegistered = true;
}
/**
* Returns a stream for use with fread() etc. External callers should
* use PHPExcel\Shared_OLE_PPS_File::getStream().
* @param int|PPS block id or PPS
* @return resource read-only stream
*/
public function getStream($blockIdOrPps)
{
static $isRegistered = false;
if (!$isRegistered) {
stream_wrapper_register('ole-chainedblockstream',
__NAMESPACE__ . '\Shared_OLE_ChainedBlockStream');
$isRegistered = true;
}
// Store current instance in global array, so that it can be accessed
// in OLE_ChainedBlockStream::stream_open().
// Object is removed from self::$instances in OLE_Stream::close().
$GLOBALS['_OLE_INSTANCES'][] = $this;
$instanceId = end(array_keys($GLOBALS['_OLE_INSTANCES']));
// Store current instance in global array, so that it can be accessed
// in OLE_ChainedBlockStream::stream_open().
// Object is removed from self::$instances in OLE_Stream::close().
$GLOBALS['_OLE_INSTANCES'][] = $this;
$instanceId = end(array_keys($GLOBALS['_OLE_INSTANCES']));
$path = 'ole-chainedblockstream://oleInstanceId=' . $instanceId;
if ($blockIdOrPps instanceof Shared_OLE_PPS) {
$path .= '&blockId=' . $blockIdOrPps->_StartBlock;
$path .= '&size=' . $blockIdOrPps->Size;
} else {
$path .= '&blockId=' . $blockIdOrPps;
}
return fopen($path, 'r');
}
$path = 'ole-chainedblockstream://oleInstanceId=' . $instanceId;
if ($blockIdOrPps instanceof Shared_OLE_PPS) {
$path .= '&blockId=' . $blockIdOrPps->_StartBlock;
$path .= '&size=' . $blockIdOrPps->Size;
} else {
$path .= '&blockId=' . $blockIdOrPps;
}
return fopen($path, 'r');
}
/**
* Reads a signed char.
* @param resource file handle
* @return int
* @access public
*/
private static function _readInt1($fh)
{
list(, $tmp) = unpack("c", fread($fh, 1));
return $tmp;
}
/**
* Reads a signed char.
* @param resource file handle
* @return int
* @access public
*/
private static function _readInt1($fh)
{
list(, $tmp) = unpack("c", fread($fh, 1));
return $tmp;
}
/**
* Reads an unsigned short (2 octets).
* @param resource file handle
* @return int
* @access public
*/
private static function _readInt2($fh)
{
list(, $tmp) = unpack("v", fread($fh, 2));
return $tmp;
}
/**
* Reads an unsigned short (2 octets).
* @param resource file handle
* @return int
* @access public
*/
private static function _readInt2($fh)
{
list(, $tmp) = unpack("v", fread($fh, 2));
return $tmp;
}
/**
* Reads an unsigned long (4 octets).
* @param resource file handle
* @return int
* @access public
*/
private static function _readInt4($fh)
{
list(, $tmp) = unpack("V", fread($fh, 4));
return $tmp;
}
/**
* Reads an unsigned long (4 octets).
* @param resource file handle
* @return int
* @access public
*/
private static function _readInt4($fh)
{
list(, $tmp) = unpack("V", fread($fh, 4));
return $tmp;
}
/**
* Gets information about all PPS's on the OLE container from the PPS WK's
* creates an OLE_PPS object for each one.
*
* @access public
* @param integer the block id of the first block
* @return mixed true on success, PEAR_Error on failure
*/
public function _readPpsWks($blockId)
{
$fh = $this->getStream($blockId);
for ($pos = 0; ; $pos += 128) {
fseek($fh, $pos, SEEK_SET);
$nameUtf16 = fread($fh, 64);
$nameLength = self::_readInt2($fh);
$nameUtf16 = substr($nameUtf16, 0, $nameLength - 2);
// Simple conversion from UTF-16LE to ISO-8859-1
$name = str_replace("\x00", "", $nameUtf16);
$type = self::_readInt1($fh);
switch ($type) {
case self::OLE_PPS_TYPE_ROOT:
$pps = new Shared_OLE_PPS_Root(null, null, array());
$this->root = $pps;
break;
case self::OLE_PPS_TYPE_DIR:
$pps = new Shared_OLE_PPS(null, null, null, null, null,
null, null, null, null, array());
break;
case self::OLE_PPS_TYPE_FILE:
$pps = new Shared_OLE_PPS_File($name);
break;
default:
continue;
}
fseek($fh, 1, SEEK_CUR);
$pps->Type = $type;
$pps->Name = $name;
$pps->PrevPps = self::_readInt4($fh);
$pps->NextPps = self::_readInt4($fh);
$pps->DirPps = self::_readInt4($fh);
fseek($fh, 20, SEEK_CUR);
$pps->Time1st = self::OLE2LocalDate(fread($fh, 8));
$pps->Time2nd = self::OLE2LocalDate(fread($fh, 8));
$pps->_StartBlock = self::_readInt4($fh);
$pps->Size = self::_readInt4($fh);
$pps->No = count($this->_list);
$this->_list[] = $pps;
/**
* Gets information about all PPS's on the OLE container from the PPS WK's
* creates an OLE_PPS object for each one.
*
* @access public
* @param integer the block id of the first block
* @return mixed true on success, PEAR_Error on failure
*/
public function _readPpsWks($blockId)
{
$fh = $this->getStream($blockId);
for ($pos = 0; ; $pos += 128) {
fseek($fh, $pos, SEEK_SET);
$nameUtf16 = fread($fh, 64);
$nameLength = self::_readInt2($fh);
$nameUtf16 = substr($nameUtf16, 0, $nameLength - 2);
// Simple conversion from UTF-16LE to ISO-8859-1
$name = str_replace("\x00", "", $nameUtf16);
$type = self::_readInt1($fh);
switch ($type) {
case self::OLE_PPS_TYPE_ROOT:
$pps = new Shared_OLE_PPS_Root(null, null, array());
$this->root = $pps;
break;
case self::OLE_PPS_TYPE_DIR:
$pps = new Shared_OLE_PPS(null, null, null, null, null,
null, null, null, null, array());
break;
case self::OLE_PPS_TYPE_FILE:
$pps = new Shared_OLE_PPS_File($name);
break;
default:
continue;
}
fseek($fh, 1, SEEK_CUR);
$pps->Type = $type;
$pps->Name = $name;
$pps->PrevPps = self::_readInt4($fh);
$pps->NextPps = self::_readInt4($fh);
$pps->DirPps = self::_readInt4($fh);
fseek($fh, 20, SEEK_CUR);
$pps->Time1st = self::OLE2LocalDate(fread($fh, 8));
$pps->Time2nd = self::OLE2LocalDate(fread($fh, 8));
$pps->_StartBlock = self::_readInt4($fh);
$pps->Size = self::_readInt4($fh);
$pps->No = count($this->_list);
$this->_list[] = $pps;
// check if the PPS tree (starting from root) is complete
if (isset($this->root) &&
$this->_ppsTreeComplete($this->root->No)) {
// check if the PPS tree (starting from root) is complete
if (isset($this->root) &&
$this->_ppsTreeComplete($this->root->No)) {
break;
}
}
fclose($fh);
break;
}
}
fclose($fh);
// Initialize $pps->children on directories
foreach ($this->_list as $pps) {
if ($pps->Type == self::OLE_PPS_TYPE_DIR || $pps->Type == self::OLE_PPS_TYPE_ROOT) {
$nos = array($pps->DirPps);
$pps->children = array();
while ($nos) {
$no = array_pop($nos);
if ($no != -1) {
$childPps = $this->_list[$no];
$nos[] = $childPps->PrevPps;
$nos[] = $childPps->NextPps;
$pps->children[] = $childPps;
}
}
}
}
// Initialize $pps->children on directories
foreach ($this->_list as $pps) {
if ($pps->Type == self::OLE_PPS_TYPE_DIR || $pps->Type == self::OLE_PPS_TYPE_ROOT) {
$nos = array($pps->DirPps);
$pps->children = array();
while ($nos) {
$no = array_pop($nos);
if ($no != -1) {
$childPps = $this->_list[$no];
$nos[] = $childPps->PrevPps;
$nos[] = $childPps->NextPps;
$pps->children[] = $childPps;
}
}
}
}
return true;
}
return true;
}
/**
* It checks whether the PPS tree is complete (all PPS's read)
* starting with the given PPS (not necessarily root)
*
* @access public
* @param integer $index The index of the PPS from which we are checking
* @return boolean Whether the PPS tree for the given PPS is complete
*/
public function _ppsTreeComplete($index)
{
return isset($this->_list[$index]) &&
($pps = $this->_list[$index]) &&
($pps->PrevPps == -1 ||
$this->_ppsTreeComplete($pps->PrevPps)) &&
($pps->NextPps == -1 ||
$this->_ppsTreeComplete($pps->NextPps)) &&
($pps->DirPps == -1 ||
$this->_ppsTreeComplete($pps->DirPps));
}
/**
* It checks whether the PPS tree is complete (all PPS's read)
* starting with the given PPS (not necessarily root)
*
* @access public
* @param integer $index The index of the PPS from which we are checking
* @return boolean Whether the PPS tree for the given PPS is complete
*/
public function _ppsTreeComplete($index)
{
return isset($this->_list[$index]) &&
($pps = $this->_list[$index]) &&
($pps->PrevPps == -1 ||
$this->_ppsTreeComplete($pps->PrevPps)) &&
($pps->NextPps == -1 ||
$this->_ppsTreeComplete($pps->NextPps)) &&
($pps->DirPps == -1 ||
$this->_ppsTreeComplete($pps->DirPps));
}
/**
* Checks whether a PPS is a File PPS or not.
* If there is no PPS for the index given, it will return false.
*
* @access public
* @param integer $index The index for the PPS
* @return bool true if it's a File PPS, false otherwise
*/
public function isFile($index)
{
if (isset($this->_list[$index])) {
return ($this->_list[$index]->Type == self::OLE_PPS_TYPE_FILE);
}
return false;
}
/**
* Checks whether a PPS is a File PPS or not.
* If there is no PPS for the index given, it will return false.
*
* @access public
* @param integer $index The index for the PPS
* @return bool true if it's a File PPS, false otherwise
*/
public function isFile($index)
{
if (isset($this->_list[$index])) {
return ($this->_list[$index]->Type == self::OLE_PPS_TYPE_FILE);
}
return false;
}
/**
* Checks whether a PPS is a Root PPS or not.
* If there is no PPS for the index given, it will return false.
*
* @access public
* @param integer $index The index for the PPS.
* @return bool true if it's a Root PPS, false otherwise
*/
public function isRoot($index)
{
if (isset($this->_list[$index])) {
return ($this->_list[$index]->Type == self::OLE_PPS_TYPE_ROOT);
}
return false;
}
/**
* Checks whether a PPS is a Root PPS or not.
* If there is no PPS for the index given, it will return false.
*
* @access public
* @param integer $index The index for the PPS.
* @return bool true if it's a Root PPS, false otherwise
*/
public function isRoot($index)
{
if (isset($this->_list[$index])) {
return ($this->_list[$index]->Type == self::OLE_PPS_TYPE_ROOT);
}
return false;
}
/**
* Gives the total number of PPS's found in the OLE container.
*
* @access public
* @return integer The total number of PPS's found in the OLE container
*/
public function ppsTotal()
{
return count($this->_list);
}
/**
* Gives the total number of PPS's found in the OLE container.
*
* @access public
* @return integer The total number of PPS's found in the OLE container
*/
public function ppsTotal()
{
return count($this->_list);
}
/**
* Gets data from a PPS
* If there is no PPS for the index given, it will return an empty string.
*
* @access public
* @param integer $index The index for the PPS
* @param integer $position The position from which to start reading
* (relative to the PPS)
* @param integer $length The amount of bytes to read (at most)
* @return string The binary string containing the data requested
* @see OLE_PPS_File::getStream()
*/
public function getData($index, $position, $length)
{
// if position is not valid return empty string
if (!isset($this->_list[$index]) || ($position >= $this->_list[$index]->Size) || ($position < 0)) {
return '';
}
$fh = $this->getStream($this->_list[$index]);
$data = stream_get_contents($fh, $length, $position);
fclose($fh);
return $data;
}
/**
* Gets data from a PPS
* If there is no PPS for the index given, it will return an empty string.
*
* @access public
* @param integer $index The index for the PPS
* @param integer $position The position from which to start reading
* (relative to the PPS)
* @param integer $length The amount of bytes to read (at most)
* @return string The binary string containing the data requested
* @see OLE_PPS_File::getStream()
*/
public function getData($index, $position, $length)
{
// if position is not valid return empty string
if (!isset($this->_list[$index]) || ($position >= $this->_list[$index]->Size) || ($position < 0)) {
return '';
}
$fh = $this->getStream($this->_list[$index]);
$data = stream_get_contents($fh, $length, $position);
fclose($fh);
return $data;
}
/**
* Gets the data length from a PPS
* If there is no PPS for the index given, it will return 0.
*
* @access public
* @param integer $index The index for the PPS
* @return integer The amount of bytes in data the PPS has
*/
public function getDataLength($index)
{
if (isset($this->_list[$index])) {
return $this->_list[$index]->Size;
}
return 0;
}
/**
* Gets the data length from a PPS
* If there is no PPS for the index given, it will return 0.
*
* @access public
* @param integer $index The index for the PPS
* @return integer The amount of bytes in data the PPS has
*/
public function getDataLength($index)
{
if (isset($this->_list[$index])) {
return $this->_list[$index]->Size;
}
return 0;
}
/**
* Utility function to transform ASCII text to Unicode
*
* @access public
* @static
* @param string $ascii The ASCII string to transform
* @return string The string in Unicode
*/
public static function Asc2Ucs($ascii)
{
$rawname = '';
for ($i = 0; $i < strlen($ascii); ++$i) {
$rawname .= $ascii{$i} . "\x00";
}
return $rawname;
}
/**
* Utility function to transform ASCII text to Unicode
*
* @access public
* @static
* @param string $ascii The ASCII string to transform
* @return string The string in Unicode
*/
public static function Asc2Ucs($ascii)
{
$rawname = '';
for ($i = 0; $i < strlen($ascii); ++$i) {
$rawname .= $ascii{$i} . "\x00";
}
return $rawname;
}
/**
* Utility function
* Returns a string for the OLE container with the date given
*
* @access public
* @static
* @param integer $date A timestamp
* @return string The string for the OLE container
*/
public static function LocalDate2OLE($date = null)
{
if (!isset($date)) {
return "\x00\x00\x00\x00\x00\x00\x00\x00";
}
/**
* Utility function
* Returns a string for the OLE container with the date given
*
* @access public
* @static
* @param integer $date A timestamp
* @return string The string for the OLE container
*/
public static function LocalDate2OLE($date = null)
{
if (!isset($date)) {
return "\x00\x00\x00\x00\x00\x00\x00\x00";
}
// factor used for separating numbers into 4 bytes parts
$factor = pow(2, 32);
// factor used for separating numbers into 4 bytes parts
$factor = pow(2, 32);
// days from 1-1-1601 until the beggining of UNIX era
$days = 134774;
// calculate seconds
$big_date = $days*24*3600 + gmmktime(date("H",$date),date("i",$date),date("s",$date),
date("m",$date),date("d",$date),date("Y",$date));
// multiply just to make MS happy
$big_date *= 10000000;
// days from 1-1-1601 until the beggining of UNIX era
$days = 134774;
// calculate seconds
$big_date = $days*24*3600 + gmmktime(date("H",$date),date("i",$date),date("s",$date),
date("m",$date),date("d",$date),date("Y",$date));
// multiply just to make MS happy
$big_date *= 10000000;
$high_part = floor($big_date / $factor);
// lower 4 bytes
$low_part = floor((($big_date / $factor) - $high_part) * $factor);
$high_part = floor($big_date / $factor);
// lower 4 bytes
$low_part = floor((($big_date / $factor) - $high_part) * $factor);
// Make HEX string
$res = '';
// Make HEX string
$res = '';
for ($i = 0; $i < 4; ++$i) {
$hex = $low_part % 0x100;
$res .= pack('c', $hex);
$low_part /= 0x100;
}
for ($i = 0; $i < 4; ++$i) {
$hex = $high_part % 0x100;
$res .= pack('c', $hex);
$high_part /= 0x100;
}
return $res;
}
for ($i = 0; $i < 4; ++$i) {
$hex = $low_part % 0x100;
$res .= pack('c', $hex);
$low_part /= 0x100;
}
for ($i = 0; $i < 4; ++$i) {
$hex = $high_part % 0x100;
$res .= pack('c', $hex);
$high_part /= 0x100;
}
return $res;
}
/**
* Returns a timestamp from an OLE container's date
*
* @access public
* @static
* @param integer $string A binary string with the encoded date
* @return string The timestamp corresponding to the string
*/
public static function OLE2LocalDate($string)
{
if (strlen($string) != 8) {
return new PEAR_Error("Expecting 8 byte string");
}
/**
* Returns a timestamp from an OLE container's date
*
* @access public
* @static
* @param integer $string A binary string with the encoded date
* @return string The timestamp corresponding to the string
*/
public static function OLE2LocalDate($string)
{
if (strlen($string) != 8) {
return new PEAR_Error("Expecting 8 byte string");
}
// factor used for separating numbers into 4 bytes parts
$factor = pow(2,32);
list(, $high_part) = unpack('V', substr($string, 4, 4));
list(, $low_part) = unpack('V', substr($string, 0, 4));
// factor used for separating numbers into 4 bytes parts
$factor = pow(2,32);
list(, $high_part) = unpack('V', substr($string, 4, 4));
list(, $low_part) = unpack('V', substr($string, 0, 4));
$big_date = ($high_part * $factor) + $low_part;
// translate to seconds
$big_date /= 10000000;
$big_date = ($high_part * $factor) + $low_part;
// translate to seconds
$big_date /= 10000000;
// days from 1-1-1601 until the beggining of UNIX era
$days = 134774;
// days from 1-1-1601 until the beggining of UNIX era
$days = 134774;
// translate to seconds from beggining of UNIX era
$big_date -= $days * 24 * 3600;
return floor($big_date);
}
// translate to seconds from beggining of UNIX era
$big_date -= $days * 24 * 3600;
return floor($big_date);
}
}

View File

@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\Shared_OLE
* @copyright Copyright (c) 2006 - 2007 Christian Schmidt
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@ -40,194 +40,194 @@ namespace PHPExcel;
*/
class Shared_OLE_ChainedBlockStream
{
/**
* The OLE container of the file that is being read.
* @var OLE
*/
public $ole;
/**
* The OLE container of the file that is being read.
* @var OLE
*/
public $ole;
/**
* Parameters specified by fopen().
* @var array
*/
public $params;
/**
* Parameters specified by fopen().
* @var array
*/
public $params;
/**
* The binary data of the file.
* @var string
*/
public $data;
/**
* The binary data of the file.
* @var string
*/
public $data;
/**
* The file pointer.
* @var int byte offset
*/
public $pos;
/**
* The file pointer.
* @var int byte offset
*/
public $pos;
/**
* Implements support for fopen().
* For creating streams using this wrapper, use OLE_PPS_File::getStream().
*
* @param string $path resource name including scheme, e.g.
* ole-chainedblockstream://oleInstanceId=1
* @param string $mode only "r" is supported
* @param int $options mask of STREAM_REPORT_ERRORS and STREAM_USE_PATH
* @param string &$openedPath absolute path of the opened stream (out parameter)
* @return bool true on success
*/
public function stream_open($path, $mode, $options, &$openedPath)
{
if ($mode != 'r') {
if ($options & STREAM_REPORT_ERRORS) {
trigger_error('Only reading is supported', E_USER_WARNING);
}
return false;
}
/**
* Implements support for fopen().
* For creating streams using this wrapper, use OLE_PPS_File::getStream().
*
* @param string $path resource name including scheme, e.g.
* ole-chainedblockstream://oleInstanceId=1
* @param string $mode only "r" is supported
* @param int $options mask of STREAM_REPORT_ERRORS and STREAM_USE_PATH
* @param string &$openedPath absolute path of the opened stream (out parameter)
* @return bool true on success
*/
public function stream_open($path, $mode, $options, &$openedPath)
{
if ($mode != 'r') {
if ($options & STREAM_REPORT_ERRORS) {
trigger_error('Only reading is supported', E_USER_WARNING);
}
return false;
}
// 25 is length of "ole-chainedblockstream://"
parse_str(substr($path, 25), $this->params);
if (!isset($this->params['oleInstanceId'],
$this->params['blockId'],
$GLOBALS['_OLE_INSTANCES'][$this->params['oleInstanceId']])) {
// 25 is length of "ole-chainedblockstream://"
parse_str(substr($path, 25), $this->params);
if (!isset($this->params['oleInstanceId'],
$this->params['blockId'],
$GLOBALS['_OLE_INSTANCES'][$this->params['oleInstanceId']])) {
if ($options & STREAM_REPORT_ERRORS) {
trigger_error('OLE stream not found', E_USER_WARNING);
}
return false;
}
$this->ole = $GLOBALS['_OLE_INSTANCES'][$this->params['oleInstanceId']];
if ($options & STREAM_REPORT_ERRORS) {
trigger_error('OLE stream not found', E_USER_WARNING);
}
return false;
}
$this->ole = $GLOBALS['_OLE_INSTANCES'][$this->params['oleInstanceId']];
$blockId = $this->params['blockId'];
$this->data = '';
if (isset($this->params['size']) &&
$this->params['size'] < $this->ole->bigBlockThreshold &&
$blockId != $this->ole->root->_StartBlock) {
$blockId = $this->params['blockId'];
$this->data = '';
if (isset($this->params['size']) &&
$this->params['size'] < $this->ole->bigBlockThreshold &&
$blockId != $this->ole->root->_StartBlock) {
// Block id refers to small blocks
$rootPos = $this->ole->_getBlockOffset($this->ole->root->_StartBlock);
while ($blockId != -2) {
$pos = $rootPos + $blockId * $this->ole->bigBlockSize;
$blockId = $this->ole->sbat[$blockId];
fseek($this->ole->_file_handle, $pos);
$this->data .= fread($this->ole->_file_handle, $this->ole->bigBlockSize);
}
} else {
// Block id refers to big blocks
while ($blockId != -2) {
$pos = $this->ole->_getBlockOffset($blockId);
fseek($this->ole->_file_handle, $pos);
$this->data .= fread($this->ole->_file_handle, $this->ole->bigBlockSize);
$blockId = $this->ole->bbat[$blockId];
}
}
if (isset($this->params['size'])) {
$this->data = substr($this->data, 0, $this->params['size']);
}
// Block id refers to small blocks
$rootPos = $this->ole->_getBlockOffset($this->ole->root->_StartBlock);
while ($blockId != -2) {
$pos = $rootPos + $blockId * $this->ole->bigBlockSize;
$blockId = $this->ole->sbat[$blockId];
fseek($this->ole->_file_handle, $pos);
$this->data .= fread($this->ole->_file_handle, $this->ole->bigBlockSize);
}
} else {
// Block id refers to big blocks
while ($blockId != -2) {
$pos = $this->ole->_getBlockOffset($blockId);
fseek($this->ole->_file_handle, $pos);
$this->data .= fread($this->ole->_file_handle, $this->ole->bigBlockSize);
$blockId = $this->ole->bbat[$blockId];
}
}
if (isset($this->params['size'])) {
$this->data = substr($this->data, 0, $this->params['size']);
}
if ($options & STREAM_USE_PATH) {
$openedPath = $path;
}
if ($options & STREAM_USE_PATH) {
$openedPath = $path;
}
return true;
}
return true;
}
/**
* Implements support for fclose().
*
*/
public function stream_close()
{
$this->ole = null;
unset($GLOBALS['_OLE_INSTANCES']);
}
/**
* Implements support for fclose().
*
*/
public function stream_close()
{
$this->ole = null;
unset($GLOBALS['_OLE_INSTANCES']);
}
/**
* Implements support for fread(), fgets() etc.
*
* @param int $count maximum number of bytes to read
* @return string
*/
public function stream_read($count)
{
if ($this->stream_eof()) {
return false;
}
$s = substr($this->data, $this->pos, $count);
$this->pos += $count;
return $s;
}
/**
* Implements support for fread(), fgets() etc.
*
* @param int $count maximum number of bytes to read
* @return string
*/
public function stream_read($count)
{
if ($this->stream_eof()) {
return false;
}
$s = substr($this->data, $this->pos, $count);
$this->pos += $count;
return $s;
}
/**
* Implements support for feof().
*
* @return bool TRUE if the file pointer is at EOF; otherwise FALSE
*/
public function stream_eof()
{
// As we don't support below 5.2 anymore, this is simply redundancy and overhead
// $eof = $this->pos >= strlen($this->data);
// // Workaround for bug in PHP 5.0.x: http://bugs.php.net/27508
// if (version_compare(PHP_VERSION, '5.0', '>=') &&
// version_compare(PHP_VERSION, '5.1', '<')) {
// $eof = !$eof;
// }
// return $eof;
return $this->pos >= strlen($this->data);
}
/**
* Implements support for feof().
*
* @return bool TRUE if the file pointer is at EOF; otherwise FALSE
*/
public function stream_eof()
{
// As we don't support below 5.2 anymore, this is simply redundancy and overhead
// $eof = $this->pos >= strlen($this->data);
// // Workaround for bug in PHP 5.0.x: http://bugs.php.net/27508
// if (version_compare(PHP_VERSION, '5.0', '>=') &&
// version_compare(PHP_VERSION, '5.1', '<')) {
// $eof = !$eof;
// }
// return $eof;
return $this->pos >= strlen($this->data);
}
/**
* Returns the position of the file pointer, i.e. its offset into the file
* stream. Implements support for ftell().
*
* @return int
*/
public function stream_tell()
{
return $this->pos;
}
/**
* Returns the position of the file pointer, i.e. its offset into the file
* stream. Implements support for ftell().
*
* @return int
*/
public function stream_tell()
{
return $this->pos;
}
/**
* Implements support for fseek().
*
* @param int $offset byte offset
* @param int $whence SEEK_SET, SEEK_CUR or SEEK_END
* @return bool
*/
public function stream_seek($offset, $whence)
{
if ($whence == SEEK_SET && $offset >= 0) {
$this->pos = $offset;
} elseif ($whence == SEEK_CUR && -$offset <= $this->pos) {
$this->pos += $offset;
} elseif ($whence == SEEK_END && -$offset <= sizeof($this->data)) {
$this->pos = strlen($this->data) + $offset;
} else {
return false;
}
return true;
}
/**
* Implements support for fseek().
*
* @param int $offset byte offset
* @param int $whence SEEK_SET, SEEK_CUR or SEEK_END
* @return bool
*/
public function stream_seek($offset, $whence)
{
if ($whence == SEEK_SET && $offset >= 0) {
$this->pos = $offset;
} elseif ($whence == SEEK_CUR && -$offset <= $this->pos) {
$this->pos += $offset;
} elseif ($whence == SEEK_END && -$offset <= sizeof($this->data)) {
$this->pos = strlen($this->data) + $offset;
} else {
return false;
}
return true;
}
/**
* Implements support for fstat(). Currently the only supported field is
* "size".
* @return array
*/
public function stream_stat()
{
return array(
'size' => strlen($this->data),
);
}
/**
* Implements support for fstat(). Currently the only supported field is
* "size".
* @return array
*/
public function stream_stat()
{
return array(
'size' => strlen($this->data),
);
}
// Methods used by stream_wrapper_register() that are not implemented:
// bool stream_flush ( void )
// int stream_write ( string data )
// bool rename ( string path_from, string path_to )
// bool mkdir ( string path, int mode, int options )
// bool rmdir ( string path, int options )
// bool dir_opendir ( string path, int options )
// array url_stat ( string path, int flags )
// string dir_readdir ( void )
// bool dir_rewinddir ( void )
// bool dir_closedir ( void )
// Methods used by stream_wrapper_register() that are not implemented:
// bool stream_flush ( void )
// int stream_write ( string data )
// bool rename ( string path_from, string path_to )
// bool mkdir ( string path, int mode, int options )
// bool rmdir ( string path, int options )
// bool dir_opendir ( string path, int options )
// array url_stat ( string path, int flags )
// string dir_readdir ( void )
// bool dir_rewinddir ( void )
// bool dir_closedir ( void )
}

View File

@ -31,202 +31,202 @@ namespace PHPExcel;
*/
class Shared_OLE_PPS
{
/**
* The PPS index
* @var integer
*/
public $No;
/**
* The PPS index
* @var integer
*/
public $No;
/**
* The PPS name (in Unicode)
* @var string
*/
public $Name;
/**
* The PPS name (in Unicode)
* @var string
*/
public $Name;
/**
* The PPS type. Dir, Root or File
* @var integer
*/
public $Type;
/**
* The PPS type. Dir, Root or File
* @var integer
*/
public $Type;
/**
* The index of the previous PPS
* @var integer
*/
public $PrevPps;
/**
* The index of the previous PPS
* @var integer
*/
public $PrevPps;
/**
* The index of the next PPS
* @var integer
*/
public $NextPps;
/**
* The index of the next PPS
* @var integer
*/
public $NextPps;
/**
* The index of it's first child if this is a Dir or Root PPS
* @var integer
*/
public $DirPps;
/**
* The index of it's first child if this is a Dir or Root PPS
* @var integer
*/
public $DirPps;
/**
* A timestamp
* @var integer
*/
public $Time1st;
/**
* A timestamp
* @var integer
*/
public $Time1st;
/**
* A timestamp
* @var integer
*/
public $Time2nd;
/**
* A timestamp
* @var integer
*/
public $Time2nd;
/**
* Starting block (small or big) for this PPS's data inside the container
* @var integer
*/
public $_StartBlock;
/**
* Starting block (small or big) for this PPS's data inside the container
* @var integer
*/
public $_StartBlock;
/**
* The size of the PPS's data (in bytes)
* @var integer
*/
public $Size;
/**
* The size of the PPS's data (in bytes)
* @var integer
*/
public $Size;
/**
* The PPS's data (only used if it's not using a temporary file)
* @var string
*/
public $_data;
/**
* The PPS's data (only used if it's not using a temporary file)
* @var string
*/
public $_data;
/**
* Array of child PPS's (only used by Root and Dir PPS's)
* @var array
*/
public $children = array();
/**
* Array of child PPS's (only used by Root and Dir PPS's)
* @var array
*/
public $children = array();
/**
* Pointer to OLE container
* @var OLE
*/
public $ole;
/**
* Pointer to OLE container
* @var OLE
*/
public $ole;
/**
* The constructor
*
* @access public
* @param integer $No The PPS index
* @param string $name The PPS name
* @param integer $type The PPS type. Dir, Root or File
* @param integer $prev The index of the previous PPS
* @param integer $next The index of the next PPS
* @param integer $dir The index of it's first child if this is a Dir or Root PPS
* @param integer $time_1st A timestamp
* @param integer $time_2nd A timestamp
* @param string $data The (usually binary) source data of the PPS
* @param array $children Array containing children PPS for this PPS
*/
public function __construct($No, $name, $type, $prev, $next, $dir, $time_1st, $time_2nd, $data, $children)
{
$this->No = $No;
$this->Name = $name;
$this->Type = $type;
$this->PrevPps = $prev;
$this->NextPps = $next;
$this->DirPps = $dir;
$this->Time1st = $time_1st;
$this->Time2nd = $time_2nd;
$this->_data = $data;
$this->children = $children;
if ($data != '') {
$this->Size = strlen($data);
} else {
$this->Size = 0;
}
}
/**
* The constructor
*
* @access public
* @param integer $No The PPS index
* @param string $name The PPS name
* @param integer $type The PPS type. Dir, Root or File
* @param integer $prev The index of the previous PPS
* @param integer $next The index of the next PPS
* @param integer $dir The index of it's first child if this is a Dir or Root PPS
* @param integer $time_1st A timestamp
* @param integer $time_2nd A timestamp
* @param string $data The (usually binary) source data of the PPS
* @param array $children Array containing children PPS for this PPS
*/
public function __construct($No, $name, $type, $prev, $next, $dir, $time_1st, $time_2nd, $data, $children)
{
$this->No = $No;
$this->Name = $name;
$this->Type = $type;
$this->PrevPps = $prev;
$this->NextPps = $next;
$this->DirPps = $dir;
$this->Time1st = $time_1st;
$this->Time2nd = $time_2nd;
$this->_data = $data;
$this->children = $children;
if ($data != '') {
$this->Size = strlen($data);
} else {
$this->Size = 0;
}
}
/**
* Returns the amount of data saved for this PPS
*
* @access public
* @return integer The amount of data (in bytes)
*/
public function _DataLen()
{
if (!isset($this->_data)) {
return 0;
}
//if (isset($this->_PPS_FILE)) {
// fseek($this->_PPS_FILE, 0);
// $stats = fstat($this->_PPS_FILE);
// return $stats[7];
//} else {
return strlen($this->_data);
//}
}
/**
* Returns the amount of data saved for this PPS
*
* @access public
* @return integer The amount of data (in bytes)
*/
public function _DataLen()
{
if (!isset($this->_data)) {
return 0;
}
//if (isset($this->_PPS_FILE)) {
// fseek($this->_PPS_FILE, 0);
// $stats = fstat($this->_PPS_FILE);
// return $stats[7];
//} else {
return strlen($this->_data);
//}
}
/**
* Returns a string with the PPS's WK (What is a WK?)
*
* @access public
* @return string The binary string
*/
public function _getPpsWk()
{
$ret = str_pad($this->Name,64,"\x00");
/**
* Returns a string with the PPS's WK (What is a WK?)
*
* @access public
* @return string The binary string
*/
public function _getPpsWk()
{
$ret = str_pad($this->Name,64,"\x00");
$ret .= pack("v", strlen($this->Name) + 2) // 66
. pack("c", $this->Type) // 67
. pack("c", 0x00) //UK // 68
. pack("V", $this->PrevPps) //Prev // 72
. pack("V", $this->NextPps) //Next // 76
. pack("V", $this->DirPps) //Dir // 80
. "\x00\x09\x02\x00" // 84
. "\x00\x00\x00\x00" // 88
. "\xc0\x00\x00\x00" // 92
. "\x00\x00\x00\x46" // 96 // Seems to be ok only for Root
. "\x00\x00\x00\x00" // 100
. Shared_OLE::LocalDate2OLE($this->Time1st) // 108
. Shared_OLE::LocalDate2OLE($this->Time2nd) // 116
. pack("V", isset($this->_StartBlock)?
$this->_StartBlock:0) // 120
. pack("V", $this->Size) // 124
. pack("V", 0); // 128
return $ret;
}
$ret .= pack("v", strlen($this->Name) + 2) // 66
. pack("c", $this->Type) // 67
. pack("c", 0x00) //UK // 68
. pack("V", $this->PrevPps) //Prev // 72
. pack("V", $this->NextPps) //Next // 76
. pack("V", $this->DirPps) //Dir // 80
. "\x00\x09\x02\x00" // 84
. "\x00\x00\x00\x00" // 88
. "\xc0\x00\x00\x00" // 92
. "\x00\x00\x00\x46" // 96 // Seems to be ok only for Root
. "\x00\x00\x00\x00" // 100
. Shared_OLE::LocalDate2OLE($this->Time1st) // 108
. Shared_OLE::LocalDate2OLE($this->Time2nd) // 116
. pack("V", isset($this->_StartBlock)?
$this->_StartBlock:0) // 120
. pack("V", $this->Size) // 124
. pack("V", 0); // 128
return $ret;
}
/**
* Updates index and pointers to previous, next and children PPS's for this
* PPS. I don't think it'll work with Dir PPS's.
*
* @access public
* @param array &$raList Reference to the array of PPS's for the whole OLE
* container
* @return integer The index for this PPS
*/
public static function _savePpsSetPnt(&$raList, $to_save, $depth = 0)
{
if ( !is_array($to_save) || (empty($to_save)) ) {
return 0xFFFFFFFF;
} elseif( count($to_save) == 1 ) {
$cnt = count($raList);
// If the first entry, it's the root... Don't clone it!
$raList[$cnt] = ( $depth == 0 ) ? $to_save[0] : clone $to_save[0];
$raList[$cnt]->No = $cnt;
$raList[$cnt]->PrevPps = 0xFFFFFFFF;
$raList[$cnt]->NextPps = 0xFFFFFFFF;
$raList[$cnt]->DirPps = self::_savePpsSetPnt($raList, @$raList[$cnt]->children, $depth++);
} else {
$iPos = floor(count($to_save) / 2);
$aPrev = array_slice($to_save, 0, $iPos);
$aNext = array_slice($to_save, $iPos + 1);
$cnt = count($raList);
// If the first entry, it's the root... Don't clone it!
$raList[$cnt] = ( $depth == 0 ) ? $to_save[$iPos] : clone $to_save[$iPos];
$raList[$cnt]->No = $cnt;
$raList[$cnt]->PrevPps = self::_savePpsSetPnt($raList, $aPrev, $depth++);
$raList[$cnt]->NextPps = self::_savePpsSetPnt($raList, $aNext, $depth++);
$raList[$cnt]->DirPps = self::_savePpsSetPnt($raList, @$raList[$cnt]->children, $depth++);
/**
* Updates index and pointers to previous, next and children PPS's for this
* PPS. I don't think it'll work with Dir PPS's.
*
* @access public
* @param array &$raList Reference to the array of PPS's for the whole OLE
* container
* @return integer The index for this PPS
*/
public static function _savePpsSetPnt(&$raList, $to_save, $depth = 0)
{
if ( !is_array($to_save) || (empty($to_save)) ) {
return 0xFFFFFFFF;
} elseif( count($to_save) == 1 ) {
$cnt = count($raList);
// If the first entry, it's the root... Don't clone it!
$raList[$cnt] = ( $depth == 0 ) ? $to_save[0] : clone $to_save[0];
$raList[$cnt]->No = $cnt;
$raList[$cnt]->PrevPps = 0xFFFFFFFF;
$raList[$cnt]->NextPps = 0xFFFFFFFF;
$raList[$cnt]->DirPps = self::_savePpsSetPnt($raList, @$raList[$cnt]->children, $depth++);
} else {
$iPos = floor(count($to_save) / 2);
$aPrev = array_slice($to_save, 0, $iPos);
$aNext = array_slice($to_save, $iPos + 1);
$cnt = count($raList);
// If the first entry, it's the root... Don't clone it!
$raList[$cnt] = ( $depth == 0 ) ? $to_save[$iPos] : clone $to_save[$iPos];
$raList[$cnt]->No = $cnt;
$raList[$cnt]->PrevPps = self::_savePpsSetPnt($raList, $aPrev, $depth++);
$raList[$cnt]->NextPps = self::_savePpsSetPnt($raList, $aNext, $depth++);
$raList[$cnt]->DirPps = self::_savePpsSetPnt($raList, @$raList[$cnt]->children, $depth++);
}
return $cnt;
}
}
return $cnt;
}
}

Some files were not shown because too many files have changed in this diff Show More