From 1549cc42ca5bd101d813cd873860662132c2111a Mon Sep 17 00:00:00 2001
From: Mark Baker
Date: Sun, 23 Jun 2013 16:30:50 +0100
Subject: [PATCH] Initial work on adapting code to PSR-2 standards
---
Classes/Autoloader.php | 55 +-
Classes/PHPExcel/CachedObjectStorage/APC.php | 41 +-
.../CachedObjectStorage/CacheBase.php | 465 +-
.../PHPExcel/CachedObjectStorage/DiscISAM.php | 277 +-
.../PHPExcel/CachedObjectStorage/ICache.php | 101 +-
.../PHPExcel/CachedObjectStorage/Igbinary.php | 160 +-
.../PHPExcel/CachedObjectStorage/Memcache.php | 434 +-
.../PHPExcel/CachedObjectStorage/Memory.php | 120 +-
.../CachedObjectStorage/MemoryGZip.php | 136 +-
.../CachedObjectStorage/MemorySerialized.php | 136 +-
.../PHPExcel/CachedObjectStorage/PHPTemp.php | 254 +-
.../PHPExcel/CachedObjectStorage/SQLite.php | 407 +-
.../PHPExcel/CachedObjectStorage/SQLite3.php | 485 +-
.../PHPExcel/CachedObjectStorage/Wincache.php | 428 +-
.../PHPExcel/CachedObjectStorageFactory.php | 47 +-
.../CalcEngine/CyclicReferenceStack.php | 115 +-
Classes/PHPExcel/CalcEngine/Logger.php | 218 +-
Classes/PHPExcel/Calculation.php | 7321 ++++-----
Classes/PHPExcel/Calculation/Database.php | 1258 +-
Classes/PHPExcel/Calculation/DateTime.php | 2822 ++--
Classes/PHPExcel/Calculation/Engineering.php | 4921 +++---
Classes/PHPExcel/Calculation/Exception.php | 34 +-
.../PHPExcel/Calculation/ExceptionHandler.php | 28 +-
Classes/PHPExcel/Calculation/Financial.php | 4421 +++--
.../PHPExcel/Calculation/FormulaParser.php | 916 +-
Classes/PHPExcel/Calculation/FormulaToken.php | 148 +-
Classes/PHPExcel/Calculation/Function.php | 116 +-
Classes/PHPExcel/Calculation/Functions.php | 1296 +-
Classes/PHPExcel/Calculation/Logical.php | 459 +-
Classes/PHPExcel/Calculation/LookupRef.php | 1545 +-
Classes/PHPExcel/Calculation/MathTrig.php | 2657 ++-
Classes/PHPExcel/Calculation/Statistical.php | 7187 ++++----
Classes/PHPExcel/Calculation/TextData.php | 1099 +-
Classes/PHPExcel/Calculation/Token/Stack.php | 150 +-
Classes/PHPExcel/Cell.php | 1836 ++-
Classes/PHPExcel/Cell/AdvancedValueBinder.php | 6 +-
Classes/PHPExcel/Cell/IValueBinder.php | 2 +-
Classes/PHPExcel/Chart.php | 1041 +-
Classes/PHPExcel/Chart/DataSeries.php | 577 +-
Classes/PHPExcel/Chart/DataSeriesValues.php | 523 +-
Classes/PHPExcel/Chart/Exception.php | 34 +-
Classes/PHPExcel/Chart/Layout.php | 685 +-
Classes/PHPExcel/Chart/Legend.php | 247 +-
Classes/PHPExcel/Chart/PlotArea.php | 170 +-
Classes/PHPExcel/Chart/Renderer/jpgraph.php | 1407 +-
Classes/PHPExcel/Chart/Title.php | 104 +-
Classes/PHPExcel/Comment.php | 9 +-
Classes/PHPExcel/DocumentProperties.php | 17 +-
Classes/PHPExcel/DocumentSecurity.php | 144 +-
Classes/PHPExcel/HashTable.php | 302 +-
Classes/PHPExcel/IComparable.php | 15 +-
Classes/PHPExcel/IOFactory.php | 416 +-
Classes/PHPExcel/NamedRange.php | 188 +-
Classes/PHPExcel/Reader/Abstract.php | 349 +-
Classes/PHPExcel/Reader/CSV.php | 643 +-
Classes/PHPExcel/Reader/DefaultReadFilter.php | 24 +-
Classes/PHPExcel/Reader/Excel2003XML.php | 1417 +-
Classes/PHPExcel/Reader/Excel2007.php | 3388 ++--
Classes/PHPExcel/Reader/Excel2007/Chart.php | 889 +-
Classes/PHPExcel/Reader/Excel2007/Theme.php | 114 +-
Classes/PHPExcel/Reader/Excel5.php | 13479 ++++++++--------
Classes/PHPExcel/Reader/Excel5/Escher.php | 1110 +-
Classes/PHPExcel/Reader/Exception.php | 34 +-
Classes/PHPExcel/Reader/Gnumeric.php | 1501 +-
Classes/PHPExcel/Reader/HTML.php | 779 +-
Classes/PHPExcel/Reader/IReadFilter.php | 20 +-
Classes/PHPExcel/Reader/IReader.php | 30 +-
Classes/PHPExcel/Reader/OOCalc.php | 1177 +-
Classes/PHPExcel/Reader/SYLK.php | 733 +-
Classes/PHPExcel/ReferenceHelper.php | 1768 +-
Classes/PHPExcel/RichText.php | 2 +-
Classes/PHPExcel/RichText/ITextElement.php | 52 +-
Classes/PHPExcel/RichText/Run.php | 112 +-
Classes/PHPExcel/RichText/TextElement.php | 124 +-
Classes/PHPExcel/Settings.php | 141 +-
Classes/PHPExcel/Shared/CodePage.php | 129 +-
Classes/PHPExcel/Shared/Date.php | 605 +-
Classes/PHPExcel/Shared/Drawing.php | 262 +-
Classes/PHPExcel/Shared/Escher.php | 98 +-
.../PHPExcel/Shared/Escher/DgContainer.php | 76 +-
.../Escher/DgContainer/SpgrContainer.php | 130 +-
.../DgContainer/SpgrContainer/SpContainer.php | 640 +-
.../PHPExcel/Shared/Escher/DggContainer.php | 300 +-
.../Escher/DggContainer/BstoreContainer.php | 52 +-
.../DggContainer/BstoreContainer/BSE.php | 150 +-
.../DggContainer/BstoreContainer/BSE/Blip.php | 98 +-
Classes/PHPExcel/Shared/Excel5.php | 476 +-
Classes/PHPExcel/Shared/File.php | 249 +-
Classes/PHPExcel/Shared/Font.php | 1475 +-
.../Shared/JAMA/CholeskyDecomposition.php | 248 +-
.../Shared/JAMA/EigenvalueDecomposition.php | 1624 +-
.../PHPExcel/Shared/JAMA/LUDecomposition.php | 454 +-
Classes/PHPExcel/Shared/JAMA/Matrix.php | 2086 +--
.../PHPExcel/Shared/JAMA/QRDecomposition.php | 418 +-
.../JAMA/SingularValueDecomposition.php | 968 +-
Classes/PHPExcel/Shared/JAMA/utils/Error.php | 32 +-
Classes/PHPExcel/Shared/JAMA/utils/Maths.php | 58 +-
Classes/PHPExcel/Shared/OLE.php | 886 +-
.../Shared/OLE/ChainedBlockStream.php | 348 +-
Classes/PHPExcel/Shared/OLE/PPS.php | 360 +-
Classes/PHPExcel/Shared/OLE/PPS/File.php | 100 +-
Classes/PHPExcel/Shared/OLE/PPS/Root.php | 814 +-
Classes/PHPExcel/Shared/OLERead.php | 445 +-
Classes/PHPExcel/Shared/PCLZip/pclzip.lib.php | 318 +-
Classes/PHPExcel/Shared/PasswordHasher.php | 38 +-
Classes/PHPExcel/Shared/String.php | 1360 +-
Classes/PHPExcel/Shared/TimeZone.php | 187 +-
Classes/PHPExcel/Shared/XMLWriter.php | 146 +-
Classes/PHPExcel/Shared/ZipArchive.php | 110 +-
Classes/PHPExcel/Shared/ZipStreamWrapper.php | 82 +-
.../PHPExcel/Shared/trend/bestFitClass.php | 782 +-
.../Shared/trend/exponentialBestFitClass.php | 184 +-
.../Shared/trend/linearBestFitClass.php | 120 +-
.../Shared/trend/logarithmicBestFitClass.php | 136 +-
.../Shared/trend/polynomialBestFitClass.php | 324 +-
.../Shared/trend/powerBestFitClass.php | 176 +-
Classes/PHPExcel/Shared/trend/trendClass.php | 212 +-
Classes/PHPExcel/Style.php | 6 +-
Classes/PHPExcel/Style/Alignment.php | 691 +-
Classes/PHPExcel/Style/Border.php | 483 +-
Classes/PHPExcel/Style/Borders.php | 517 +-
Classes/PHPExcel/Style/Color.php | 731 +-
Classes/PHPExcel/Style/Conditional.php | 214 +-
Classes/PHPExcel/Style/Fill.php | 531 +-
Classes/PHPExcel/Style/Font.php | 927 +-
Classes/PHPExcel/Style/NumberFormat.php | 1353 +-
Classes/PHPExcel/Style/Protection.php | 233 +-
Classes/PHPExcel/Style/Supervisor.php | 180 +-
Classes/PHPExcel/Workbook.php | 65 +-
Classes/PHPExcel/Worksheet.php | 190 +-
Classes/PHPExcel/Worksheet/AutoFilter.php | 1495 +-
.../PHPExcel/Worksheet/AutoFilter/Column.php | 631 +-
.../Worksheet/AutoFilter/Column/Rule.php | 783 +-
Classes/PHPExcel/Worksheet/BaseDrawing.php | 416 +-
Classes/PHPExcel/Worksheet/CellIterator.php | 116 +-
.../PHPExcel/Worksheet/ColumnDimension.php | 202 +-
Classes/PHPExcel/Worksheet/Drawing.php | 114 +-
Classes/PHPExcel/Worksheet/Drawing/Shadow.php | 232 +-
Classes/PHPExcel/Worksheet/HeaderFooter.php | 278 +-
.../Worksheet/HeaderFooterDrawing.php | 276 +-
Classes/PHPExcel/Worksheet/MemoryDrawing.php | 168 +-
Classes/PHPExcel/Worksheet/PageMargins.php | 136 +-
Classes/PHPExcel/Worksheet/PageSetup.php | 1152 +-
Classes/PHPExcel/Worksheet/Protection.php | 376 +-
Classes/PHPExcel/Worksheet/Row.php | 92 +-
Classes/PHPExcel/Worksheet/RowDimension.php | 236 +-
Classes/PHPExcel/Worksheet/RowIterator.php | 198 +-
Classes/PHPExcel/Worksheet/SheetView.php | 262 +-
Classes/PHPExcel/Writer/Abstract.php | 196 +-
Classes/PHPExcel/Writer/CSV.php | 490 +-
Classes/PHPExcel/Writer/Excel2007.php | 609 +-
Classes/PHPExcel/Writer/Excel2007/Chart.php | 2293 ++-
.../PHPExcel/Writer/Excel2007/Comments.php | 378 +-
.../Writer/Excel2007/ContentTypes.php | 390 +-
.../PHPExcel/Writer/Excel2007/DocProps.php | 366 +-
Classes/PHPExcel/Writer/Excel2007/Drawing.php | 894 +-
Classes/PHPExcel/Writer/Excel2007/Rels.php | 666 +-
.../PHPExcel/Writer/Excel2007/StringTable.php | 488 +-
Classes/PHPExcel/Writer/Excel2007/Style.php | 1328 +-
Classes/PHPExcel/Writer/Excel2007/Theme.php | 1352 +-
.../PHPExcel/Writer/Excel2007/Workbook.php | 706 +-
.../PHPExcel/Writer/Excel2007/Worksheet.php | 2360 +--
.../PHPExcel/Writer/Excel2007/WriterPart.php | 80 +-
Classes/PHPExcel/Writer/Excel5.php | 1750 +-
Classes/PHPExcel/Writer/Excel5/BIFFwriter.php | 320 +-
Classes/PHPExcel/Writer/Excel5/Escher.php | 824 +-
Classes/PHPExcel/Writer/Excel5/Font.php | 232 +-
Classes/PHPExcel/Writer/Excel5/Parser.php | 2826 ++--
Classes/PHPExcel/Writer/Excel5/Workbook.php | 2756 ++--
Classes/PHPExcel/Writer/Excel5/Worksheet.php | 7218 ++++-----
Classes/PHPExcel/Writer/Excel5/Xf.php | 842 +-
Classes/PHPExcel/Writer/Exception.php | 34 +-
Classes/PHPExcel/Writer/HTML.php | 2989 ++--
Classes/PHPExcel/Writer/IWriter.php | 3 +-
Classes/PHPExcel/Writer/PDF.php | 5 +-
Classes/PHPExcel/Writer/PDF/Core.php | 41 +-
Classes/PHPExcel/Writer/PDF/DomPDF.php | 7 +-
Classes/PHPExcel/Writer/PDF/mPDF.php | 7 +-
Classes/PHPExcel/Writer/PDF/tcPDF.php | 13 +-
179 files changed, 69651 insertions(+), 69718 deletions(-)
diff --git a/Classes/Autoloader.php b/Classes/Autoloader.php
index 896364e..1df3bea 100644
--- a/Classes/Autoloader.php
+++ b/Classes/Autoloader.php
@@ -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;
+ }
}
-
}
diff --git a/Classes/PHPExcel/CachedObjectStorage/APC.php b/Classes/PHPExcel/CachedObjectStorage/APC.php
index af6871e..c7613c0 100644
--- a/Classes/PHPExcel/CachedObjectStorage/APC.php
+++ b/Classes/PHPExcel/CachedObjectStorage/APC.php
@@ -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;
}
-
}
diff --git a/Classes/PHPExcel/CachedObjectStorage/CacheBase.php b/Classes/PHPExcel/CachedObjectStorage/CacheBase.php
index 9d9a10b..338498c 100644
--- a/Classes/PHPExcel/CachedObjectStorage/CacheBase.php
+++ b/Classes/PHPExcel/CachedObjectStorage/CacheBase.php
@@ -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;
+ }
}
diff --git a/Classes/PHPExcel/CachedObjectStorage/DiscISAM.php b/Classes/PHPExcel/CachedObjectStorage/DiscISAM.php
index f9182cf..108f52f 100644
--- a/Classes/PHPExcel/CachedObjectStorage/DiscISAM.php
+++ b/Classes/PHPExcel/CachedObjectStorage/DiscISAM.php
@@ -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()
}
diff --git a/Classes/PHPExcel/CachedObjectStorage/ICache.php b/Classes/PHPExcel/CachedObjectStorage/ICache.php
index b909739..aeb8077 100644
--- a/Classes/PHPExcel/CachedObjectStorage/ICache.php
+++ b/Classes/PHPExcel/CachedObjectStorage/ICache.php
@@ -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();
}
diff --git a/Classes/PHPExcel/CachedObjectStorage/Igbinary.php b/Classes/PHPExcel/CachedObjectStorage/Igbinary.php
index 3866ec8..0b4a657 100644
--- a/Classes/PHPExcel/CachedObjectStorage/Igbinary.php
+++ b/Classes/PHPExcel/CachedObjectStorage/Igbinary.php
@@ -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;
+ }
}
diff --git a/Classes/PHPExcel/CachedObjectStorage/Memcache.php b/Classes/PHPExcel/CachedObjectStorage/Memcache.php
index 11f7779..d3cd609 100644
--- a/Classes/PHPExcel/CachedObjectStorage/Memcache.php
+++ b/Classes/PHPExcel/CachedObjectStorage/Memcache.php
@@ -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;
+ }
}
diff --git a/Classes/PHPExcel/CachedObjectStorage/Memory.php b/Classes/PHPExcel/CachedObjectStorage/Memory.php
index df5e0e3..49f7a51 100644
--- a/Classes/PHPExcel/CachedObjectStorage/Memory.php
+++ b/Classes/PHPExcel/CachedObjectStorage/Memory.php
@@ -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()
}
diff --git a/Classes/PHPExcel/CachedObjectStorage/MemoryGZip.php b/Classes/PHPExcel/CachedObjectStorage/MemoryGZip.php
index 501df5c..7572e7d 100644
--- a/Classes/PHPExcel/CachedObjectStorage/MemoryGZip.php
+++ b/Classes/PHPExcel/CachedObjectStorage/MemoryGZip.php
@@ -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()
}
diff --git a/Classes/PHPExcel/CachedObjectStorage/MemorySerialized.php b/Classes/PHPExcel/CachedObjectStorage/MemorySerialized.php
index d812de7..4fbf0d0 100644
--- a/Classes/PHPExcel/CachedObjectStorage/MemorySerialized.php
+++ b/Classes/PHPExcel/CachedObjectStorage/MemorySerialized.php
@@ -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()
}
diff --git a/Classes/PHPExcel/CachedObjectStorage/PHPTemp.php b/Classes/PHPExcel/CachedObjectStorage/PHPTemp.php
index be385bb..e767131 100644
--- a/Classes/PHPExcel/CachedObjectStorage/PHPTemp.php
+++ b/Classes/PHPExcel/CachedObjectStorage/PHPTemp.php
@@ -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()
}
diff --git a/Classes/PHPExcel/CachedObjectStorage/SQLite.php b/Classes/PHPExcel/CachedObjectStorage/SQLite.php
index b9850b6..eb22783 100644
--- a/Classes/PHPExcel/CachedObjectStorage/SQLite.php
+++ b/Classes/PHPExcel/CachedObjectStorage/SQLite.php
@@ -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;
+ }
}
diff --git a/Classes/PHPExcel/CachedObjectStorage/SQLite3.php b/Classes/PHPExcel/CachedObjectStorage/SQLite3.php
index 1c98b67..f5d93a4 100644
--- a/Classes/PHPExcel/CachedObjectStorage/SQLite3.php
+++ b/Classes/PHPExcel/CachedObjectStorage/SQLite3.php
@@ -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;
+ }
}
diff --git a/Classes/PHPExcel/CachedObjectStorage/Wincache.php b/Classes/PHPExcel/CachedObjectStorage/Wincache.php
index 77cb455..2864b39 100644
--- a/Classes/PHPExcel/CachedObjectStorage/Wincache.php
+++ b/Classes/PHPExcel/CachedObjectStorage/Wincache.php
@@ -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;
+ }
}
diff --git a/Classes/PHPExcel/CachedObjectStorageFactory.php b/Classes/PHPExcel/CachedObjectStorageFactory.php
index 4d1596c..f82ad43 100644
--- a/Classes/PHPExcel/CachedObjectStorageFactory.php
+++ b/Classes/PHPExcel/CachedObjectStorageFactory.php
@@ -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();
+ }
}
diff --git a/Classes/PHPExcel/CalcEngine/CyclicReferenceStack.php b/Classes/PHPExcel/CalcEngine/CyclicReferenceStack.php
index d720359..95d495e 100644
--- a/Classes/PHPExcel/CalcEngine/CyclicReferenceStack.php
+++ b/Classes/PHPExcel/CalcEngine/CyclicReferenceStack.php
@@ -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;
+ }
}
diff --git a/Classes/PHPExcel/CalcEngine/Logger.php b/Classes/PHPExcel/CalcEngine/Logger.php
index beb1598..e98f06f 100644
--- a/Classes/PHPExcel/CalcEngine/Logger.php
+++ b/Classes/PHPExcel/CalcEngine/Logger.php
@@ -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;
+ }
}
-
diff --git a/Classes/PHPExcel/Calculation.php b/Classes/PHPExcel/Calculation.php
index bbbd2cf..07bd8af 100644
--- a/Classes/PHPExcel/Calculation.php
+++ b/Classes/PHPExcel/Calculation.php
@@ -21,3857 +21,3858 @@
* @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;
if (!defined('CALCULATION_REGEXP_CELLREF')) {
- // Test for support of \P (multibyte options) in PCRE
- if(defined('PREG_BAD_UTF8_ERROR')) {
- // Cell reference (cell or range of cells, with or without a sheet reference)
- define('CALCULATION_REGEXP_CELLREF','((([^\s,!&%^\/\*\+<>=-]*)|(\'[^\']*\')|(\"[^\"]*\"))!)?\$?([a-z]{1,3})\$?(\d{1,7})');
- // Named Range of cells
- define('CALCULATION_REGEXP_NAMEDRANGE','((([^\s,!&%^\/\*\+<>=-]*)|(\'[^\']*\')|(\"[^\"]*\"))!)?([_A-Z][_A-Z0-9\.]*)');
- } else {
- // Cell reference (cell or range of cells, with or without a sheet reference)
- define('CALCULATION_REGEXP_CELLREF','(((\w*)|(\'[^\']*\')|(\"[^\"]*\"))!)?\$?([a-z]{1,3})\$?(\d+)');
- // Named Range of cells
- define('CALCULATION_REGEXP_NAMEDRANGE','(((\w*)|(\'.*\')|(\".*\"))!)?([_A-Z][_A-Z0-9\.]*)');
- }
+ // Test for support of \P (multibyte options) in PCRE
+ if(defined('PREG_BAD_UTF8_ERROR')) {
+ // Cell reference (cell or range of cells, with or without a sheet reference)
+ define('CALCULATION_REGEXP_CELLREF','((([^\s,!&%^\/\*\+<>=-]*)|(\'[^\']*\')|(\"[^\"]*\"))!)?\$?([a-z]{1,3})\$?(\d{1,7})');
+ // Named Range of cells
+ define('CALCULATION_REGEXP_NAMEDRANGE','((([^\s,!&%^\/\*\+<>=-]*)|(\'[^\']*\')|(\"[^\"]*\"))!)?([_A-Z][_A-Z0-9\.]*)');
+ } else {
+ // Cell reference (cell or range of cells, with or without a sheet reference)
+ define('CALCULATION_REGEXP_CELLREF','(((\w*)|(\'[^\']*\')|(\"[^\"]*\"))!)?\$?([a-z]{1,3})\$?(\d+)');
+ // Named Range of cells
+ define('CALCULATION_REGEXP_NAMEDRANGE','(((\w*)|(\'.*\')|(\".*\"))!)?([_A-Z][_A-Z0-9\.]*)');
+ }
}
/**
* PHPExcel\Calculation (Multiton)
*
- * @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 {
- /** Constants */
- /** Regular Expressions */
- // Numeric operand
- const CALCULATION_REGEXP_NUMBER = '[-+]?\d*\.?\d+(e[-+]?\d+)?';
- // String operand
- const CALCULATION_REGEXP_STRING = '"(?:[^"]|"")*"';
- // Opening bracket
- const CALCULATION_REGEXP_OPENBRACE = '\(';
- // Function (allow for the old @ symbol that could be used to prefix a function, but we'll ignore it)
- const CALCULATION_REGEXP_FUNCTION = '@?([A-Z][A-Z0-9\.]*)[\s]*\(';
- // Cell reference (cell or range of cells, with or without a sheet reference)
- const CALCULATION_REGEXP_CELLREF = CALCULATION_REGEXP_CELLREF;
- // Named Range of cells
- const CALCULATION_REGEXP_NAMEDRANGE = CALCULATION_REGEXP_NAMEDRANGE;
- // Error
- const CALCULATION_REGEXP_ERROR = '\#[A-Z][A-Z0_\/]*[!\?]?';
+ /** Constants */
+ /** Regular Expressions */
+ // Numeric operand
+ const CALCULATION_REGEXP_NUMBER = '[-+]?\d*\.?\d+(e[-+]?\d+)?';
+ // String operand
+ const CALCULATION_REGEXP_STRING = '"(?:[^"]|"")*"';
+ // Opening bracket
+ const CALCULATION_REGEXP_OPENBRACE = '\(';
+ // Function (allow for the old @ symbol that could be used to prefix a function, but we'll ignore it)
+ const CALCULATION_REGEXP_FUNCTION = '@?([A-Z][A-Z0-9\.]*)[\s]*\(';
+ // Cell reference (cell or range of cells, with or without a sheet reference)
+ const CALCULATION_REGEXP_CELLREF = CALCULATION_REGEXP_CELLREF;
+ // Named Range of cells
+ const CALCULATION_REGEXP_NAMEDRANGE = CALCULATION_REGEXP_NAMEDRANGE;
+ // Error
+ const CALCULATION_REGEXP_ERROR = '\#[A-Z][A-Z0_\/]*[!\?]?';
- /** constants */
- const RETURN_ARRAY_AS_ERROR = 'error';
- const RETURN_ARRAY_AS_VALUE = 'value';
- const RETURN_ARRAY_AS_ARRAY = 'array';
+ /** constants */
+ const RETURN_ARRAY_AS_ERROR = 'error';
+ const RETURN_ARRAY_AS_VALUE = 'value';
+ const RETURN_ARRAY_AS_ARRAY = 'array';
- private static $returnArrayAsType = self::RETURN_ARRAY_AS_VALUE;
+ private static $returnArrayAsType = self::RETURN_ARRAY_AS_VALUE;
- /**
- * Instance of this class
- *
- * @access private
- * @var PHPExcel\Calculation
- */
- private static $_instance;
+ /**
+ * Instance of this class
+ *
+ * @access private
+ * @var PHPExcel\Calculation
+ */
+ private static $_instance;
- /**
- * Instance of the workbook this Calculation Engine is using
- *
- * @access private
- * @var PHPExcel
- */
+ /**
+ * Instance of the workbook this Calculation Engine is using
+ *
+ * @access private
+ * @var PHPExcel
+ */
private $_workbook;
- /**
- * List of instances of the calculation engine that we've instantiated for individual workbooks
- *
- * @access private
- * @var PHPExcel\Calculation[]
- */
+ /**
+ * List of instances of the calculation engine that we've instantiated for individual workbooks
+ *
+ * @access private
+ * @var PHPExcel\Calculation[]
+ */
private static $_workbookSets;
- /**
- * Calculation cache
- *
- * @access private
- * @var array
- */
- private $_calculationCache = array ();
+ /**
+ * Calculation cache
+ *
+ * @access private
+ * @var array
+ */
+ private $_calculationCache = array ();
- /**
- * Calculation cache enabled
- *
- * @access private
- * @var boolean
- */
- private $_calculationCacheEnabled = TRUE;
+ /**
+ * Calculation cache enabled
+ *
+ * @access private
+ * @var boolean
+ */
+ private $_calculationCacheEnabled = TRUE;
- /**
- * List of operators that can be used within formulae
- * The true/false value indicates whether it is a binary operator or a unary operator
- *
- * @access private
- * @var array
- */
- private static $_operators = array('+' => TRUE, '-' => TRUE, '*' => TRUE, '/' => TRUE,
- '^' => TRUE, '&' => TRUE, '%' => FALSE, '~' => FALSE,
- '>' => TRUE, '<' => TRUE, '=' => TRUE, '>=' => TRUE,
- '<=' => TRUE, '<>' => TRUE, '|' => TRUE, ':' => TRUE
- );
+ /**
+ * List of operators that can be used within formulae
+ * The true/false value indicates whether it is a binary operator or a unary operator
+ *
+ * @access private
+ * @var array
+ */
+ private static $_operators = array('+' => TRUE, '-' => TRUE, '*' => TRUE, '/' => TRUE,
+ '^' => TRUE, '&' => TRUE, '%' => false, '~' => false,
+ '>' => TRUE, '<' => TRUE, '=' => TRUE, '>=' => TRUE,
+ '<=' => TRUE, '<>' => TRUE, '|' => TRUE, ':' => TRUE
+ );
- /**
- * List of binary operators (those that expect two operands)
- *
- * @access private
- * @var array
- */
- private static $_binaryOperators = array('+' => TRUE, '-' => TRUE, '*' => TRUE, '/' => TRUE,
- '^' => TRUE, '&' => TRUE, '>' => TRUE, '<' => TRUE,
- '=' => TRUE, '>=' => TRUE, '<=' => TRUE, '<>' => TRUE,
- '|' => TRUE, ':' => TRUE
- );
+ /**
+ * List of binary operators (those that expect two operands)
+ *
+ * @access private
+ * @var array
+ */
+ private static $_binaryOperators = array('+' => TRUE, '-' => TRUE, '*' => TRUE, '/' => TRUE,
+ '^' => TRUE, '&' => TRUE, '>' => TRUE, '<' => TRUE,
+ '=' => TRUE, '>=' => TRUE, '<=' => TRUE, '<>' => TRUE,
+ '|' => TRUE, ':' => TRUE
+ );
- /**
- * The debug log generated by the calculation engine
- *
- * @access private
- * @var PHPExcel\CalcEngine_Logger
- *
- */
- private $debugLog;
+ /**
+ * The debug log generated by the calculation engine
+ *
+ * @access private
+ * @var PHPExcel\CalcEngine_Logger
+ *
+ */
+ private $debugLog;
- /**
- * Flag to determine how formula errors should be handled
- * If true, then a user error will be triggered
- * If false, then an exception will be thrown
- *
- * @access public
- * @var boolean
- *
- */
- public $suppressFormulaErrors = FALSE;
+ /**
+ * Flag to determine how formula errors should be handled
+ * If true, then a user error will be triggered
+ * If false, then an exception will be thrown
+ *
+ * @access public
+ * @var boolean
+ *
+ */
+ public $suppressFormulaErrors = false;
- /**
- * Error message for any error that was raised/thrown by the calculation engine
- *
- * @access public
- * @var string
- *
- */
- public $formulaError = NULL;
+ /**
+ * Error message for any error that was raised/thrown by the calculation engine
+ *
+ * @access public
+ * @var string
+ *
+ */
+ public $formulaError = null;
- /**
- * An array of the nested cell references accessed by the calculation engine, used for the debug log
- *
- * @access private
- * @var array of string
- *
- */
- private $_cyclicReferenceStack;
+ /**
+ * An array of the nested cell references accessed by the calculation engine, used for the debug log
+ *
+ * @access private
+ * @var array of string
+ *
+ */
+ private $_cyclicReferenceStack;
- /**
- * Current iteration counter for cyclic formulae
- * If the value is 0 (or less) then cyclic formulae will throw an exception,
- * otherwise they will iterate to the limit defined here before returning a result
- *
- * @var integer
- *
- */
- private $_cyclicFormulaCount = 0;
+ /**
+ * Current iteration counter for cyclic formulae
+ * If the value is 0 (or less) then cyclic formulae will throw an exception,
+ * otherwise they will iterate to the limit defined here before returning a result
+ *
+ * @var integer
+ *
+ */
+ private $_cyclicFormulaCount = 0;
- private $_cyclicFormulaCell = '';
+ private $_cyclicFormulaCell = '';
- /**
- * Number of iterations for cyclic formulae
- *
- * @var integer
- *
- */
- public $cyclicFormulaCount = 0;
+ /**
+ * Number of iterations for cyclic formulae
+ *
+ * @var integer
+ *
+ */
+ public $cyclicFormulaCount = 0;
- /**
- * Precision used for calculations
- *
- * @var integer
- *
- */
- private $_savedPrecision = 14;
+ /**
+ * Precision used for calculations
+ *
+ * @var integer
+ *
+ */
+ private $_savedPrecision = 14;
- /**
- * The current locale setting
- *
- * @var string
- *
- */
- private static $_localeLanguage = 'en_us'; // US English (default locale)
+ /**
+ * The current locale setting
+ *
+ * @var string
+ *
+ */
+ private static $_localeLanguage = 'en_us'; // US English (default locale)
- /**
- * List of available locale settings
- * Note that this is read for the locale subdirectory only when requested
- *
- * @var string[]
- *
- */
- private static $_validLocaleLanguages = array( 'en' // English (default language)
- );
- /**
- * Locale-specific argument separator for function arguments
- *
- * @var string
- *
- */
- private static $_localeArgumentSeparator = ',';
- private static $_localeFunctions = array();
+ /**
+ * List of available locale settings
+ * Note that this is read for the locale subdirectory only when requested
+ *
+ * @var string[]
+ *
+ */
+ private static $_validLocaleLanguages = array( 'en' // English (default language)
+ );
+ /**
+ * Locale-specific argument separator for function arguments
+ *
+ * @var string
+ *
+ */
+ private static $_localeArgumentSeparator = ',';
+ private static $_localeFunctions = array();
- /**
- * Locale-specific translations for Excel constants (True, False and Null)
- *
- * @var string[]
- *
- */
- public static $_localeBoolean = array( 'TRUE' => 'TRUE',
- 'FALSE' => 'FALSE',
- 'NULL' => 'NULL'
- );
+ /**
+ * Locale-specific translations for Excel constants (True, False and Null)
+ *
+ * @var string[]
+ *
+ */
+ public static $_localeBoolean = array(
+ 'TRUE' => 'TRUE',
+ 'FALSE' => 'FALSE',
+ 'NULL' => 'NULL'
+ );
- /**
- * Excel constant string translations to their PHP equivalents
- * Constant conversion from text name/value to actual (datatyped) value
- *
- * @var string[]
- *
- */
- private static $_ExcelConstants = array('TRUE' => TRUE,
- 'FALSE' => FALSE,
- 'NULL' => NULL
- );
+ /**
+ * Excel constant string translations to their PHP equivalents
+ * Constant conversion from text name/value to actual (datatyped) value
+ *
+ * @var string[]
+ *
+ */
+ private static $_ExcelConstants = array(
+ 'TRUE' => TRUE,
+ 'FALSE' => FALSE,
+ 'NULL' => NULL
+ );
- // PHPExcel functions
- private static $_PHPExcelFunctions = array( // PHPExcel functions
- 'ABS' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'abs',
- 'argumentCount' => '1'
- ),
- 'ACCRINT' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'Calculation_Financial::ACCRINT',
- 'argumentCount' => '4-7'
- ),
- 'ACCRINTM' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'Calculation_Financial::ACCRINTM',
- 'argumentCount' => '3-5'
- ),
- 'ACOS' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'acos',
- 'argumentCount' => '1'
- ),
- 'ACOSH' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'acosh',
- 'argumentCount' => '1'
- ),
- 'ADDRESS' => array('category' => Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
- 'functionCall' => 'Calculation_LookupRef::CELL_ADDRESS',
- 'argumentCount' => '2-5'
- ),
- 'AMORDEGRC' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'Calculation_Financial::AMORDEGRC',
- 'argumentCount' => '6,7'
- ),
- 'AMORLINC' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'Calculation_Financial::AMORLINC',
- 'argumentCount' => '6,7'
- ),
- 'AND' => array('category' => Calculation_Function::CATEGORY_LOGICAL,
- 'functionCall' => 'Calculation_Logical::LOGICAL_AND',
- 'argumentCount' => '1+'
- ),
- 'AREAS' => array('category' => Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
- 'functionCall' => 'Calculation_Functions::DUMMY',
- 'argumentCount' => '1'
- ),
- 'ASC' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'Calculation_Functions::DUMMY',
- 'argumentCount' => '1'
- ),
- 'ASIN' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'asin',
- 'argumentCount' => '1'
- ),
- 'ASINH' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'asinh',
- 'argumentCount' => '1'
- ),
- 'ATAN' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'atan',
- 'argumentCount' => '1'
- ),
- 'ATAN2' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'Calculation_MathTrig::ATAN2',
- 'argumentCount' => '2'
- ),
- 'ATANH' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'atanh',
- 'argumentCount' => '1'
- ),
- 'AVEDEV' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::AVEDEV',
- 'argumentCount' => '1+'
- ),
- 'AVERAGE' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::AVERAGE',
- 'argumentCount' => '1+'
- ),
- 'AVERAGEA' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::AVERAGEA',
- 'argumentCount' => '1+'
- ),
- 'AVERAGEIF' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::AVERAGEIF',
- 'argumentCount' => '2,3'
- ),
- 'AVERAGEIFS' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Functions::DUMMY',
- 'argumentCount' => '3+'
- ),
- 'BAHTTEXT' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'Calculation_Functions::DUMMY',
- 'argumentCount' => '1'
- ),
- 'BESSELI' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'Calculation_Engineering::BESSELI',
- 'argumentCount' => '2'
- ),
- 'BESSELJ' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'Calculation_Engineering::BESSELJ',
- 'argumentCount' => '2'
- ),
- 'BESSELK' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'Calculation_Engineering::BESSELK',
- 'argumentCount' => '2'
- ),
- 'BESSELY' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'Calculation_Engineering::BESSELY',
- 'argumentCount' => '2'
- ),
- 'BETADIST' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::BETADIST',
- 'argumentCount' => '3-5'
- ),
- 'BETAINV' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::BETAINV',
- 'argumentCount' => '3-5'
- ),
- 'BIN2DEC' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'Calculation_Engineering::BINTODEC',
- 'argumentCount' => '1'
- ),
- 'BIN2HEX' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'Calculation_Engineering::BINTOHEX',
- 'argumentCount' => '1,2'
- ),
- 'BIN2OCT' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'Calculation_Engineering::BINTOOCT',
- 'argumentCount' => '1,2'
- ),
- 'BINOMDIST' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::BINOMDIST',
- 'argumentCount' => '4'
- ),
- 'CEILING' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'Calculation_MathTrig::CEILING',
- 'argumentCount' => '2'
- ),
- 'CELL' => array('category' => Calculation_Function::CATEGORY_INFORMATION,
- 'functionCall' => 'Calculation_Functions::DUMMY',
- 'argumentCount' => '1,2'
- ),
- 'CHAR' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'Calculation_TextData::CHARACTER',
- 'argumentCount' => '1'
- ),
- 'CHIDIST' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::CHIDIST',
- 'argumentCount' => '2'
- ),
- 'CHIINV' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::CHIINV',
- 'argumentCount' => '2'
- ),
- 'CHITEST' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Functions::DUMMY',
- 'argumentCount' => '2'
- ),
- 'CHOOSE' => array('category' => Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
- 'functionCall' => 'Calculation_LookupRef::CHOOSE',
- 'argumentCount' => '2+'
- ),
- 'CLEAN' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'Calculation_TextData::TRIMNONPRINTABLE',
- 'argumentCount' => '1'
- ),
- 'CODE' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'Calculation_TextData::ASCIICODE',
- 'argumentCount' => '1'
- ),
- 'COLUMN' => array('category' => Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
- 'functionCall' => 'Calculation_LookupRef::COLUMN',
- 'argumentCount' => '-1',
- 'passByReference' => array(TRUE)
- ),
- 'COLUMNS' => array('category' => Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
- 'functionCall' => 'Calculation_LookupRef::COLUMNS',
- 'argumentCount' => '1'
- ),
- 'COMBIN' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'Calculation_MathTrig::COMBIN',
- 'argumentCount' => '2'
- ),
- 'COMPLEX' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'Calculation_Engineering::COMPLEX',
- 'argumentCount' => '2,3'
- ),
- 'CONCATENATE' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'Calculation_TextData::CONCATENATE',
- 'argumentCount' => '1+'
- ),
- 'CONFIDENCE' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::CONFIDENCE',
- 'argumentCount' => '3'
- ),
- 'CONVERT' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'Calculation_Engineering::CONVERTUOM',
- 'argumentCount' => '3'
- ),
- 'CORREL' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::CORREL',
- 'argumentCount' => '2'
- ),
- 'COS' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'cos',
- 'argumentCount' => '1'
- ),
- 'COSH' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'cosh',
- 'argumentCount' => '1'
- ),
- 'COUNT' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::COUNT',
- 'argumentCount' => '1+'
- ),
- 'COUNTA' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::COUNTA',
- 'argumentCount' => '1+'
- ),
- 'COUNTBLANK' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::COUNTBLANK',
- 'argumentCount' => '1'
- ),
- 'COUNTIF' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::COUNTIF',
- 'argumentCount' => '2'
- ),
- 'COUNTIFS' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Functions::DUMMY',
- 'argumentCount' => '2'
- ),
- 'COUPDAYBS' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'Calculation_Financial::COUPDAYBS',
- 'argumentCount' => '3,4'
- ),
- 'COUPDAYS' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'Calculation_Financial::COUPDAYS',
- 'argumentCount' => '3,4'
- ),
- 'COUPDAYSNC' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'Calculation_Financial::COUPDAYSNC',
- 'argumentCount' => '3,4'
- ),
- 'COUPNCD' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'Calculation_Financial::COUPNCD',
- 'argumentCount' => '3,4'
- ),
- 'COUPNUM' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'Calculation_Financial::COUPNUM',
- 'argumentCount' => '3,4'
- ),
- 'COUPPCD' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'Calculation_Financial::COUPPCD',
- 'argumentCount' => '3,4'
- ),
- 'COVAR' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::COVAR',
- 'argumentCount' => '2'
- ),
- 'CRITBINOM' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::CRITBINOM',
- 'argumentCount' => '3'
- ),
- 'CUBEKPIMEMBER' => array('category' => Calculation_Function::CATEGORY_CUBE,
- 'functionCall' => 'Calculation_Functions::DUMMY',
- 'argumentCount' => '?'
- ),
- 'CUBEMEMBER' => array('category' => Calculation_Function::CATEGORY_CUBE,
- 'functionCall' => 'Calculation_Functions::DUMMY',
- 'argumentCount' => '?'
- ),
- 'CUBEMEMBERPROPERTY' => array('category' => Calculation_Function::CATEGORY_CUBE,
- 'functionCall' => 'Calculation_Functions::DUMMY',
- 'argumentCount' => '?'
- ),
- 'CUBERANKEDMEMBER' => array('category' => Calculation_Function::CATEGORY_CUBE,
- 'functionCall' => 'Calculation_Functions::DUMMY',
- 'argumentCount' => '?'
- ),
- 'CUBESET' => array('category' => Calculation_Function::CATEGORY_CUBE,
- 'functionCall' => 'Calculation_Functions::DUMMY',
- 'argumentCount' => '?'
- ),
- 'CUBESETCOUNT' => array('category' => Calculation_Function::CATEGORY_CUBE,
- 'functionCall' => 'Calculation_Functions::DUMMY',
- 'argumentCount' => '?'
- ),
- 'CUBEVALUE' => array('category' => Calculation_Function::CATEGORY_CUBE,
- 'functionCall' => 'Calculation_Functions::DUMMY',
- 'argumentCount' => '?'
- ),
- 'CUMIPMT' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'Calculation_Financial::CUMIPMT',
- 'argumentCount' => '6'
- ),
- 'CUMPRINC' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'Calculation_Financial::CUMPRINC',
- 'argumentCount' => '6'
- ),
- 'DATE' => array('category' => Calculation_Function::CATEGORY_DATE_AND_TIME,
- 'functionCall' => 'Calculation_DateTime::DATE',
- 'argumentCount' => '3'
- ),
- 'DATEDIF' => array('category' => Calculation_Function::CATEGORY_DATE_AND_TIME,
- 'functionCall' => 'Calculation_DateTime::DATEDIF',
- 'argumentCount' => '2,3'
- ),
- 'DATEVALUE' => array('category' => Calculation_Function::CATEGORY_DATE_AND_TIME,
- 'functionCall' => 'Calculation_DateTime::DATEVALUE',
- 'argumentCount' => '1'
- ),
- 'DAVERAGE' => array('category' => Calculation_Function::CATEGORY_DATABASE,
- 'functionCall' => 'Calculation_Database::DAVERAGE',
- 'argumentCount' => '3'
- ),
- 'DAY' => array('category' => Calculation_Function::CATEGORY_DATE_AND_TIME,
- 'functionCall' => 'Calculation_DateTime::DAYOFMONTH',
- 'argumentCount' => '1'
- ),
- 'DAYS360' => array('category' => Calculation_Function::CATEGORY_DATE_AND_TIME,
- 'functionCall' => 'Calculation_DateTime::DAYS360',
- 'argumentCount' => '2,3'
- ),
- 'DB' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'Calculation_Financial::DB',
- 'argumentCount' => '4,5'
- ),
- 'DCOUNT' => array('category' => Calculation_Function::CATEGORY_DATABASE,
- 'functionCall' => 'Calculation_Database::DCOUNT',
- 'argumentCount' => '3'
- ),
- 'DCOUNTA' => array('category' => Calculation_Function::CATEGORY_DATABASE,
- 'functionCall' => 'Calculation_Database::DCOUNTA',
- 'argumentCount' => '3'
- ),
- 'DDB' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'Calculation_Financial::DDB',
- 'argumentCount' => '4,5'
- ),
- 'DEC2BIN' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'Calculation_Engineering::DECTOBIN',
- 'argumentCount' => '1,2'
- ),
- 'DEC2HEX' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'Calculation_Engineering::DECTOHEX',
- 'argumentCount' => '1,2'
- ),
- 'DEC2OCT' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'Calculation_Engineering::DECTOOCT',
- 'argumentCount' => '1,2'
- ),
- 'DEGREES' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'rad2deg',
- 'argumentCount' => '1'
- ),
- 'DELTA' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'Calculation_Engineering::DELTA',
- 'argumentCount' => '1,2'
- ),
- 'DEVSQ' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::DEVSQ',
- 'argumentCount' => '1+'
- ),
- 'DGET' => array('category' => Calculation_Function::CATEGORY_DATABASE,
- 'functionCall' => 'Calculation_Database::DGET',
- 'argumentCount' => '3'
- ),
- 'DISC' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'Calculation_Financial::DISC',
- 'argumentCount' => '4,5'
- ),
- 'DMAX' => array('category' => Calculation_Function::CATEGORY_DATABASE,
- 'functionCall' => 'Calculation_Database::DMAX',
- 'argumentCount' => '3'
- ),
- 'DMIN' => array('category' => Calculation_Function::CATEGORY_DATABASE,
- 'functionCall' => 'Calculation_Database::DMIN',
- 'argumentCount' => '3'
- ),
- 'DOLLAR' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'Calculation_TextData::DOLLAR',
- 'argumentCount' => '1,2'
- ),
- 'DOLLARDE' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'Calculation_Financial::DOLLARDE',
- 'argumentCount' => '2'
- ),
- 'DOLLARFR' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'Calculation_Financial::DOLLARFR',
- 'argumentCount' => '2'
- ),
- 'DPRODUCT' => array('category' => Calculation_Function::CATEGORY_DATABASE,
- 'functionCall' => 'Calculation_Database::DPRODUCT',
- 'argumentCount' => '3'
- ),
- 'DSTDEV' => array('category' => Calculation_Function::CATEGORY_DATABASE,
- 'functionCall' => 'Calculation_Database::DSTDEV',
- 'argumentCount' => '3'
- ),
- 'DSTDEVP' => array('category' => Calculation_Function::CATEGORY_DATABASE,
- 'functionCall' => 'Calculation_Database::DSTDEVP',
- 'argumentCount' => '3'
- ),
- 'DSUM' => array('category' => Calculation_Function::CATEGORY_DATABASE,
- 'functionCall' => 'Calculation_Database::DSUM',
- 'argumentCount' => '3'
- ),
- 'DURATION' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'Calculation_Functions::DUMMY',
- 'argumentCount' => '5,6'
- ),
- 'DVAR' => array('category' => Calculation_Function::CATEGORY_DATABASE,
- 'functionCall' => 'Calculation_Database::DVAR',
- 'argumentCount' => '3'
- ),
- 'DVARP' => array('category' => Calculation_Function::CATEGORY_DATABASE,
- 'functionCall' => 'Calculation_Database::DVARP',
- 'argumentCount' => '3'
- ),
- 'EDATE' => array('category' => Calculation_Function::CATEGORY_DATE_AND_TIME,
- 'functionCall' => 'Calculation_DateTime::EDATE',
- 'argumentCount' => '2'
- ),
- 'EFFECT' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'Calculation_Financial::EFFECT',
- 'argumentCount' => '2'
- ),
- 'EOMONTH' => array('category' => Calculation_Function::CATEGORY_DATE_AND_TIME,
- 'functionCall' => 'Calculation_DateTime::EOMONTH',
- 'argumentCount' => '2'
- ),
- 'ERF' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'Calculation_Engineering::ERF',
- 'argumentCount' => '1,2'
- ),
- 'ERFC' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'Calculation_Engineering::ERFC',
- 'argumentCount' => '1'
- ),
- 'ERROR.TYPE' => array('category' => Calculation_Function::CATEGORY_INFORMATION,
- 'functionCall' => 'Calculation_Functions::ERROR_TYPE',
- 'argumentCount' => '1'
- ),
- 'EVEN' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'Calculation_MathTrig::EVEN',
- 'argumentCount' => '1'
- ),
- 'EXACT' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'Calculation_Functions::DUMMY',
- 'argumentCount' => '2'
- ),
- 'EXP' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'exp',
- 'argumentCount' => '1'
- ),
- 'EXPONDIST' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::EXPONDIST',
- 'argumentCount' => '3'
- ),
- 'FACT' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'Calculation_MathTrig::FACT',
- 'argumentCount' => '1'
- ),
- 'FACTDOUBLE' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'Calculation_MathTrig::FACTDOUBLE',
- 'argumentCount' => '1'
- ),
- 'FALSE' => array('category' => Calculation_Function::CATEGORY_LOGICAL,
- 'functionCall' => 'Calculation_Logical::FALSE',
- 'argumentCount' => '0'
- ),
- 'FDIST' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Functions::DUMMY',
- 'argumentCount' => '3'
- ),
- 'FIND' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'Calculation_TextData::SEARCHSENSITIVE',
- 'argumentCount' => '2,3'
- ),
- 'FINDB' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'Calculation_TextData::SEARCHSENSITIVE',
- 'argumentCount' => '2,3'
- ),
- 'FINV' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Functions::DUMMY',
- 'argumentCount' => '3'
- ),
- 'FISHER' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::FISHER',
- 'argumentCount' => '1'
- ),
- 'FISHERINV' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::FISHERINV',
- 'argumentCount' => '1'
- ),
- 'FIXED' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'Calculation_TextData::FIXEDFORMAT',
- 'argumentCount' => '1-3'
- ),
- 'FLOOR' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'Calculation_MathTrig::FLOOR',
- 'argumentCount' => '2'
- ),
- 'FORECAST' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::FORECAST',
- 'argumentCount' => '3'
- ),
- 'FREQUENCY' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Functions::DUMMY',
- 'argumentCount' => '2'
- ),
- 'FTEST' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Functions::DUMMY',
- 'argumentCount' => '2'
- ),
- 'FV' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'Calculation_Financial::FV',
- 'argumentCount' => '3-5'
- ),
- 'FVSCHEDULE' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'Calculation_Financial::FVSCHEDULE',
- 'argumentCount' => '2'
- ),
- 'GAMMADIST' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::GAMMADIST',
- 'argumentCount' => '4'
- ),
- 'GAMMAINV' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::GAMMAINV',
- 'argumentCount' => '3'
- ),
- 'GAMMALN' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::GAMMALN',
- 'argumentCount' => '1'
- ),
- 'GCD' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'Calculation_MathTrig::GCD',
- 'argumentCount' => '1+'
- ),
- 'GEOMEAN' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::GEOMEAN',
- 'argumentCount' => '1+'
- ),
- 'GESTEP' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'Calculation_Engineering::GESTEP',
- 'argumentCount' => '1,2'
- ),
- 'GETPIVOTDATA' => array('category' => Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
- 'functionCall' => 'Calculation_Functions::DUMMY',
- 'argumentCount' => '2+'
- ),
- 'GROWTH' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::GROWTH',
- 'argumentCount' => '1-4'
- ),
- 'HARMEAN' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::HARMEAN',
- 'argumentCount' => '1+'
- ),
- 'HEX2BIN' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'Calculation_Engineering::HEXTOBIN',
- 'argumentCount' => '1,2'
- ),
- 'HEX2DEC' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'Calculation_Engineering::HEXTODEC',
- 'argumentCount' => '1'
- ),
- 'HEX2OCT' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'Calculation_Engineering::HEXTOOCT',
- 'argumentCount' => '1,2'
- ),
- 'HLOOKUP' => array('category' => Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
- 'functionCall' => 'Calculation_LookupRef::HLOOKUP',
- 'argumentCount' => '3,4'
- ),
- 'HOUR' => array('category' => Calculation_Function::CATEGORY_DATE_AND_TIME,
- 'functionCall' => 'Calculation_DateTime::HOUROFDAY',
- 'argumentCount' => '1'
- ),
- 'HYPERLINK' => array('category' => Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
- 'functionCall' => 'Calculation_LookupRef::HYPERLINK',
- 'argumentCount' => '1,2',
- 'passCellReference'=> TRUE
- ),
- 'HYPGEOMDIST' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::HYPGEOMDIST',
- 'argumentCount' => '4'
- ),
- 'IF' => array('category' => Calculation_Function::CATEGORY_LOGICAL,
- 'functionCall' => 'Calculation_Logical::STATEMENT_IF',
- 'argumentCount' => '1-3'
- ),
- 'IFERROR' => array('category' => Calculation_Function::CATEGORY_LOGICAL,
- 'functionCall' => 'Calculation_Logical::IFERROR',
- 'argumentCount' => '2'
- ),
- 'IMABS' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'Calculation_Engineering::IMABS',
- 'argumentCount' => '1'
- ),
- 'IMAGINARY' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'Calculation_Engineering::IMAGINARY',
- 'argumentCount' => '1'
- ),
- 'IMARGUMENT' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'Calculation_Engineering::IMARGUMENT',
- 'argumentCount' => '1'
- ),
- 'IMCONJUGATE' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'Calculation_Engineering::IMCONJUGATE',
- 'argumentCount' => '1'
- ),
- 'IMCOS' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'Calculation_Engineering::IMCOS',
- 'argumentCount' => '1'
- ),
- 'IMDIV' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'Calculation_Engineering::IMDIV',
- 'argumentCount' => '2'
- ),
- 'IMEXP' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'Calculation_Engineering::IMEXP',
- 'argumentCount' => '1'
- ),
- 'IMLN' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'Calculation_Engineering::IMLN',
- 'argumentCount' => '1'
- ),
- 'IMLOG10' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'Calculation_Engineering::IMLOG10',
- 'argumentCount' => '1'
- ),
- 'IMLOG2' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'Calculation_Engineering::IMLOG2',
- 'argumentCount' => '1'
- ),
- 'IMPOWER' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'Calculation_Engineering::IMPOWER',
- 'argumentCount' => '2'
- ),
- 'IMPRODUCT' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'Calculation_Engineering::IMPRODUCT',
- 'argumentCount' => '1+'
- ),
- 'IMREAL' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'Calculation_Engineering::IMREAL',
- 'argumentCount' => '1'
- ),
- 'IMSIN' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'Calculation_Engineering::IMSIN',
- 'argumentCount' => '1'
- ),
- 'IMSQRT' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'Calculation_Engineering::IMSQRT',
- 'argumentCount' => '1'
- ),
- 'IMSUB' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'Calculation_Engineering::IMSUB',
- 'argumentCount' => '2'
- ),
- 'IMSUM' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'Calculation_Engineering::IMSUM',
- 'argumentCount' => '1+'
- ),
- 'INDEX' => array('category' => Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
- 'functionCall' => 'Calculation_LookupRef::INDEX',
- 'argumentCount' => '1-4'
- ),
- 'INDIRECT' => array('category' => Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
- 'functionCall' => 'Calculation_LookupRef::INDIRECT',
- 'argumentCount' => '1,2',
- 'passCellReference'=> TRUE
- ),
- 'INFO' => array('category' => Calculation_Function::CATEGORY_INFORMATION,
- 'functionCall' => 'Calculation_Functions::DUMMY',
- 'argumentCount' => '1'
- ),
- 'INT' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'Calculation_MathTrig::INT',
- 'argumentCount' => '1'
- ),
- 'INTERCEPT' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::INTERCEPT',
- 'argumentCount' => '2'
- ),
- 'INTRATE' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'Calculation_Financial::INTRATE',
- 'argumentCount' => '4,5'
- ),
- 'IPMT' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'Calculation_Financial::IPMT',
- 'argumentCount' => '4-6'
- ),
- 'IRR' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'Calculation_Financial::IRR',
- 'argumentCount' => '1,2'
- ),
- 'ISBLANK' => array('category' => Calculation_Function::CATEGORY_INFORMATION,
- 'functionCall' => 'Calculation_Functions::IS_BLANK',
- 'argumentCount' => '1'
- ),
- 'ISERR' => array('category' => Calculation_Function::CATEGORY_INFORMATION,
- 'functionCall' => 'Calculation_Functions::IS_ERR',
- 'argumentCount' => '1'
- ),
- 'ISERROR' => array('category' => Calculation_Function::CATEGORY_INFORMATION,
- 'functionCall' => 'Calculation_Functions::IS_ERROR',
- 'argumentCount' => '1'
- ),
- 'ISEVEN' => array('category' => Calculation_Function::CATEGORY_INFORMATION,
- 'functionCall' => 'Calculation_Functions::IS_EVEN',
- 'argumentCount' => '1'
- ),
- 'ISLOGICAL' => array('category' => Calculation_Function::CATEGORY_INFORMATION,
- 'functionCall' => 'Calculation_Functions::IS_LOGICAL',
- 'argumentCount' => '1'
- ),
- 'ISNA' => array('category' => Calculation_Function::CATEGORY_INFORMATION,
- 'functionCall' => 'Calculation_Functions::IS_NA',
- 'argumentCount' => '1'
- ),
- 'ISNONTEXT' => array('category' => Calculation_Function::CATEGORY_INFORMATION,
- 'functionCall' => 'Calculation_Functions::IS_NONTEXT',
- 'argumentCount' => '1'
- ),
- 'ISNUMBER' => array('category' => Calculation_Function::CATEGORY_INFORMATION,
- 'functionCall' => 'Calculation_Functions::IS_NUMBER',
- 'argumentCount' => '1'
- ),
- 'ISODD' => array('category' => Calculation_Function::CATEGORY_INFORMATION,
- 'functionCall' => 'Calculation_Functions::IS_ODD',
- 'argumentCount' => '1'
- ),
- 'ISPMT' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'Calculation_Financial::ISPMT',
- 'argumentCount' => '4'
- ),
- 'ISREF' => array('category' => Calculation_Function::CATEGORY_INFORMATION,
- 'functionCall' => 'Calculation_Functions::DUMMY',
- 'argumentCount' => '1'
- ),
- 'ISTEXT' => array('category' => Calculation_Function::CATEGORY_INFORMATION,
- 'functionCall' => 'Calculation_Functions::IS_TEXT',
- 'argumentCount' => '1'
- ),
- 'JIS' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'Calculation_Functions::DUMMY',
- 'argumentCount' => '1'
- ),
- 'KURT' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::KURT',
- 'argumentCount' => '1+'
- ),
- 'LARGE' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::LARGE',
- 'argumentCount' => '2'
- ),
- 'LCM' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'Calculation_MathTrig::LCM',
- 'argumentCount' => '1+'
- ),
- 'LEFT' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'Calculation_TextData::LEFT',
- 'argumentCount' => '1,2'
- ),
- 'LEFTB' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'Calculation_TextData::LEFT',
- 'argumentCount' => '1,2'
- ),
- 'LEN' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'Calculation_TextData::STRINGLENGTH',
- 'argumentCount' => '1'
- ),
- 'LENB' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'Calculation_TextData::STRINGLENGTH',
- 'argumentCount' => '1'
- ),
- 'LINEST' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::LINEST',
- 'argumentCount' => '1-4'
- ),
- 'LN' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'log',
- 'argumentCount' => '1'
- ),
- 'LOG' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'Calculation_MathTrig::LOG_BASE',
- 'argumentCount' => '1,2'
- ),
- 'LOG10' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'log10',
- 'argumentCount' => '1'
- ),
- 'LOGEST' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::LOGEST',
- 'argumentCount' => '1-4'
- ),
- 'LOGINV' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::LOGINV',
- 'argumentCount' => '3'
- ),
- 'LOGNORMDIST' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::LOGNORMDIST',
- 'argumentCount' => '3'
- ),
- 'LOOKUP' => array('category' => Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
- 'functionCall' => 'Calculation_LookupRef::LOOKUP',
- 'argumentCount' => '2,3'
- ),
- 'LOWER' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'Calculation_TextData::LOWERCASE',
- 'argumentCount' => '1'
- ),
- 'MATCH' => array('category' => Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
- 'functionCall' => 'Calculation_LookupRef::MATCH',
- 'argumentCount' => '2,3'
- ),
- 'MAX' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::MAX',
- 'argumentCount' => '1+'
- ),
- 'MAXA' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::MAXA',
- 'argumentCount' => '1+'
- ),
- 'MAXIF' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::MAXIF',
- 'argumentCount' => '2+'
- ),
- 'MDETERM' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'Calculation_MathTrig::MDETERM',
- 'argumentCount' => '1'
- ),
- 'MDURATION' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'Calculation_Functions::DUMMY',
- 'argumentCount' => '5,6'
- ),
- 'MEDIAN' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::MEDIAN',
- 'argumentCount' => '1+'
- ),
- 'MEDIANIF' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Functions::DUMMY',
- 'argumentCount' => '2+'
- ),
- 'MID' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'Calculation_TextData::MID',
- 'argumentCount' => '3'
- ),
- 'MIDB' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'Calculation_TextData::MID',
- 'argumentCount' => '3'
- ),
- 'MIN' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::MIN',
- 'argumentCount' => '1+'
- ),
- 'MINA' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::MINA',
- 'argumentCount' => '1+'
- ),
- 'MINIF' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::MINIF',
- 'argumentCount' => '2+'
- ),
- 'MINUTE' => array('category' => Calculation_Function::CATEGORY_DATE_AND_TIME,
- 'functionCall' => 'Calculation_DateTime::MINUTEOFHOUR',
- 'argumentCount' => '1'
- ),
- 'MINVERSE' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'Calculation_MathTrig::MINVERSE',
- 'argumentCount' => '1'
- ),
- 'MIRR' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'Calculation_Financial::MIRR',
- 'argumentCount' => '3'
- ),
- 'MMULT' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'Calculation_MathTrig::MMULT',
- 'argumentCount' => '2'
- ),
- 'MOD' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'Calculation_MathTrig::MOD',
- 'argumentCount' => '2'
- ),
- 'MODE' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::MODE',
- 'argumentCount' => '1+'
- ),
- 'MONTH' => array('category' => Calculation_Function::CATEGORY_DATE_AND_TIME,
- 'functionCall' => 'Calculation_DateTime::MONTHOFYEAR',
- 'argumentCount' => '1'
- ),
- 'MROUND' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'Calculation_MathTrig::MROUND',
- 'argumentCount' => '2'
- ),
- 'MULTINOMIAL' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'Calculation_MathTrig::MULTINOMIAL',
- 'argumentCount' => '1+'
- ),
- 'N' => array('category' => Calculation_Function::CATEGORY_INFORMATION,
- 'functionCall' => 'Calculation_Functions::N',
- 'argumentCount' => '1'
- ),
- 'NA' => array('category' => Calculation_Function::CATEGORY_INFORMATION,
- 'functionCall' => 'Calculation_Functions::NA',
- 'argumentCount' => '0'
- ),
- 'NEGBINOMDIST' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::NEGBINOMDIST',
- 'argumentCount' => '3'
- ),
- 'NETWORKDAYS' => array('category' => Calculation_Function::CATEGORY_DATE_AND_TIME,
- 'functionCall' => 'Calculation_DateTime::NETWORKDAYS',
- 'argumentCount' => '2+'
- ),
- 'NOMINAL' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'Calculation_Financial::NOMINAL',
- 'argumentCount' => '2'
- ),
- 'NORMDIST' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::NORMDIST',
- 'argumentCount' => '4'
- ),
- 'NORMINV' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::NORMINV',
- 'argumentCount' => '3'
- ),
- 'NORMSDIST' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::NORMSDIST',
- 'argumentCount' => '1'
- ),
- 'NORMSINV' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::NORMSINV',
- 'argumentCount' => '1'
- ),
- 'NOT' => array('category' => Calculation_Function::CATEGORY_LOGICAL,
- 'functionCall' => 'Calculation_Logical::NOT',
- 'argumentCount' => '1'
- ),
- 'NOW' => array('category' => Calculation_Function::CATEGORY_DATE_AND_TIME,
- 'functionCall' => 'Calculation_DateTime::DATETIMENOW',
- 'argumentCount' => '0'
- ),
- 'NPER' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'Calculation_Financial::NPER',
- 'argumentCount' => '3-5'
- ),
- 'NPV' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'Calculation_Financial::NPV',
- 'argumentCount' => '2+'
- ),
- 'OCT2BIN' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'Calculation_Engineering::OCTTOBIN',
- 'argumentCount' => '1,2'
- ),
- 'OCT2DEC' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'Calculation_Engineering::OCTTODEC',
- 'argumentCount' => '1'
- ),
- 'OCT2HEX' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'Calculation_Engineering::OCTTOHEX',
- 'argumentCount' => '1,2'
- ),
- 'ODD' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'Calculation_MathTrig::ODD',
- 'argumentCount' => '1'
- ),
- 'ODDFPRICE' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'Calculation_Functions::DUMMY',
- 'argumentCount' => '8,9'
- ),
- 'ODDFYIELD' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'Calculation_Functions::DUMMY',
- 'argumentCount' => '8,9'
- ),
- 'ODDLPRICE' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'Calculation_Functions::DUMMY',
- 'argumentCount' => '7,8'
- ),
- 'ODDLYIELD' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'Calculation_Functions::DUMMY',
- 'argumentCount' => '7,8'
- ),
- 'OFFSET' => array('category' => Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
- 'functionCall' => 'Calculation_LookupRef::OFFSET',
- 'argumentCount' => '3,5',
- 'passCellReference'=> TRUE,
- 'passByReference' => array(TRUE)
- ),
- 'OR' => array('category' => Calculation_Function::CATEGORY_LOGICAL,
- 'functionCall' => 'Calculation_Logical::LOGICAL_OR',
- 'argumentCount' => '1+'
- ),
- 'PEARSON' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::CORREL',
- 'argumentCount' => '2'
- ),
- 'PERCENTILE' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::PERCENTILE',
- 'argumentCount' => '2'
- ),
- 'PERCENTRANK' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::PERCENTRANK',
- 'argumentCount' => '2,3'
- ),
- 'PERMUT' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::PERMUT',
- 'argumentCount' => '2'
- ),
- 'PHONETIC' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'Calculation_Functions::DUMMY',
- 'argumentCount' => '1'
- ),
- 'PI' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'pi',
- 'argumentCount' => '0'
- ),
- 'PMT' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'Calculation_Financial::PMT',
- 'argumentCount' => '3-5'
- ),
- 'POISSON' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::POISSON',
- 'argumentCount' => '3'
- ),
- 'POWER' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'Calculation_MathTrig::POWER',
- 'argumentCount' => '2'
- ),
- 'PPMT' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'Calculation_Financial::PPMT',
- 'argumentCount' => '4-6'
- ),
- 'PRICE' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'Calculation_Financial::PRICE',
- 'argumentCount' => '6,7'
- ),
- 'PRICEDISC' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'Calculation_Financial::PRICEDISC',
- 'argumentCount' => '4,5'
- ),
- 'PRICEMAT' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'Calculation_Financial::PRICEMAT',
- 'argumentCount' => '5,6'
- ),
- 'PROB' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Functions::DUMMY',
- 'argumentCount' => '3,4'
- ),
- 'PRODUCT' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'Calculation_MathTrig::PRODUCT',
- 'argumentCount' => '1+'
- ),
- 'PROPER' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'Calculation_TextData::PROPERCASE',
- 'argumentCount' => '1'
- ),
- 'PV' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'Calculation_Financial::PV',
- 'argumentCount' => '3-5'
- ),
- 'QUARTILE' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::QUARTILE',
- 'argumentCount' => '2'
- ),
- 'QUOTIENT' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'Calculation_MathTrig::QUOTIENT',
- 'argumentCount' => '2'
- ),
- 'RADIANS' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'deg2rad',
- 'argumentCount' => '1'
- ),
- 'RAND' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'Calculation_MathTrig::RAND',
- 'argumentCount' => '0'
- ),
- 'RANDBETWEEN' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'Calculation_MathTrig::RAND',
- 'argumentCount' => '2'
- ),
- 'RANK' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::RANK',
- 'argumentCount' => '2,3'
- ),
- 'RATE' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'Calculation_Financial::RATE',
- 'argumentCount' => '3-6'
- ),
- 'RECEIVED' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'Calculation_Financial::RECEIVED',
- 'argumentCount' => '4-5'
- ),
- 'REPLACE' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'Calculation_TextData::REPLACE',
- 'argumentCount' => '4'
- ),
- 'REPLACEB' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'Calculation_TextData::REPLACE',
- 'argumentCount' => '4'
- ),
- 'REPT' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'str_repeat',
- 'argumentCount' => '2'
- ),
- 'RIGHT' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'Calculation_TextData::RIGHT',
- 'argumentCount' => '1,2'
- ),
- 'RIGHTB' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'Calculation_TextData::RIGHT',
- 'argumentCount' => '1,2'
- ),
- 'ROMAN' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'Calculation_MathTrig::ROMAN',
- 'argumentCount' => '1,2'
- ),
- 'ROUND' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'round',
- 'argumentCount' => '2'
- ),
- 'ROUNDDOWN' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'Calculation_MathTrig::ROUNDDOWN',
- 'argumentCount' => '2'
- ),
- 'ROUNDUP' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'Calculation_MathTrig::ROUNDUP',
- 'argumentCount' => '2'
- ),
- 'ROW' => array('category' => Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
- 'functionCall' => 'Calculation_LookupRef::ROW',
- 'argumentCount' => '-1',
- 'passByReference' => array(TRUE)
- ),
- 'ROWS' => array('category' => Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
- 'functionCall' => 'Calculation_LookupRef::ROWS',
- 'argumentCount' => '1'
- ),
- 'RSQ' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::RSQ',
- 'argumentCount' => '2'
- ),
- 'RTD' => array('category' => Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
- 'functionCall' => 'Calculation_Functions::DUMMY',
- 'argumentCount' => '1+'
- ),
- 'SEARCH' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'Calculation_TextData::SEARCHINSENSITIVE',
- 'argumentCount' => '2,3'
- ),
- 'SEARCHB' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'Calculation_TextData::SEARCHINSENSITIVE',
- 'argumentCount' => '2,3'
- ),
- 'SECOND' => array('category' => Calculation_Function::CATEGORY_DATE_AND_TIME,
- 'functionCall' => 'Calculation_DateTime::SECONDOFMINUTE',
- 'argumentCount' => '1'
- ),
- 'SERIESSUM' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'Calculation_MathTrig::SERIESSUM',
- 'argumentCount' => '4'
- ),
- 'SIGN' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'Calculation_MathTrig::SIGN',
- 'argumentCount' => '1'
- ),
- 'SIN' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'sin',
- 'argumentCount' => '1'
- ),
- 'SINH' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'sinh',
- 'argumentCount' => '1'
- ),
- 'SKEW' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::SKEW',
- 'argumentCount' => '1+'
- ),
- 'SLN' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'Calculation_Financial::SLN',
- 'argumentCount' => '3'
- ),
- 'SLOPE' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::SLOPE',
- 'argumentCount' => '2'
- ),
- 'SMALL' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::SMALL',
- 'argumentCount' => '2'
- ),
- 'SQRT' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'sqrt',
- 'argumentCount' => '1'
- ),
- 'SQRTPI' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'Calculation_MathTrig::SQRTPI',
- 'argumentCount' => '1'
- ),
- 'STANDARDIZE' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::STANDARDIZE',
- 'argumentCount' => '3'
- ),
- 'STDEV' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::STDEV',
- 'argumentCount' => '1+'
- ),
- 'STDEVA' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::STDEVA',
- 'argumentCount' => '1+'
- ),
- 'STDEVP' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::STDEVP',
- 'argumentCount' => '1+'
- ),
- 'STDEVPA' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::STDEVPA',
- 'argumentCount' => '1+'
- ),
- 'STEYX' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::STEYX',
- 'argumentCount' => '2'
- ),
- 'SUBSTITUTE' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'Calculation_TextData::SUBSTITUTE',
- 'argumentCount' => '3,4'
- ),
- 'SUBTOTAL' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'Calculation_MathTrig::SUBTOTAL',
- 'argumentCount' => '2+'
- ),
- 'SUM' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'Calculation_MathTrig::SUM',
- 'argumentCount' => '1+'
- ),
- 'SUMIF' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'Calculation_MathTrig::SUMIF',
- 'argumentCount' => '2,3'
- ),
- 'SUMIFS' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'Calculation_Functions::DUMMY',
- 'argumentCount' => '?'
- ),
- 'SUMPRODUCT' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'Calculation_MathTrig::SUMPRODUCT',
- 'argumentCount' => '1+'
- ),
- 'SUMSQ' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'Calculation_MathTrig::SUMSQ',
- 'argumentCount' => '1+'
- ),
- 'SUMX2MY2' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'Calculation_MathTrig::SUMX2MY2',
- 'argumentCount' => '2'
- ),
- 'SUMX2PY2' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'Calculation_MathTrig::SUMX2PY2',
- 'argumentCount' => '2'
- ),
- 'SUMXMY2' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'Calculation_MathTrig::SUMXMY2',
- 'argumentCount' => '2'
- ),
- 'SYD' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'Calculation_Financial::SYD',
- 'argumentCount' => '4'
- ),
- 'T' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'Calculation_TextData::RETURNSTRING',
- 'argumentCount' => '1'
- ),
- 'TAN' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'tan',
- 'argumentCount' => '1'
- ),
- 'TANH' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'tanh',
- 'argumentCount' => '1'
- ),
- 'TBILLEQ' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'Calculation_Financial::TBILLEQ',
- 'argumentCount' => '3'
- ),
- 'TBILLPRICE' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'Calculation_Financial::TBILLPRICE',
- 'argumentCount' => '3'
- ),
- 'TBILLYIELD' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'Calculation_Financial::TBILLYIELD',
- 'argumentCount' => '3'
- ),
- 'TDIST' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::TDIST',
- 'argumentCount' => '3'
- ),
- 'TEXT' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'Calculation_TextData::TEXTFORMAT',
- 'argumentCount' => '2'
- ),
- 'TIME' => array('category' => Calculation_Function::CATEGORY_DATE_AND_TIME,
- 'functionCall' => 'Calculation_DateTime::TIME',
- 'argumentCount' => '3'
- ),
- 'TIMEVALUE' => array('category' => Calculation_Function::CATEGORY_DATE_AND_TIME,
- 'functionCall' => 'Calculation_DateTime::TIMEVALUE',
- 'argumentCount' => '1'
- ),
- 'TINV' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::TINV',
- 'argumentCount' => '2'
- ),
- 'TODAY' => array('category' => Calculation_Function::CATEGORY_DATE_AND_TIME,
- 'functionCall' => 'Calculation_DateTime::DATENOW',
- 'argumentCount' => '0'
- ),
- 'TRANSPOSE' => array('category' => Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
- 'functionCall' => 'Calculation_LookupRef::TRANSPOSE',
- 'argumentCount' => '1'
- ),
- 'TREND' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::TREND',
- 'argumentCount' => '1-4'
- ),
- 'TRIM' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'Calculation_TextData::TRIMSPACES',
- 'argumentCount' => '1'
- ),
- 'TRIMMEAN' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::TRIMMEAN',
- 'argumentCount' => '2'
- ),
- 'TRUE' => array('category' => Calculation_Function::CATEGORY_LOGICAL,
- 'functionCall' => 'Calculation_Logical::TRUE',
- 'argumentCount' => '0'
- ),
- 'TRUNC' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'Calculation_MathTrig::TRUNC',
- 'argumentCount' => '1,2'
- ),
- 'TTEST' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Functions::DUMMY',
- 'argumentCount' => '4'
- ),
- 'TYPE' => array('category' => Calculation_Function::CATEGORY_INFORMATION,
- 'functionCall' => 'Calculation_Functions::TYPE',
- 'argumentCount' => '1'
- ),
- 'UPPER' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'Calculation_TextData::UPPERCASE',
- 'argumentCount' => '1'
- ),
- 'USDOLLAR' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'Calculation_Functions::DUMMY',
- 'argumentCount' => '2'
- ),
- 'VALUE' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'Calculation_Functions::DUMMY',
- 'argumentCount' => '1'
- ),
- 'VAR' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::VARFunc',
- 'argumentCount' => '1+'
- ),
- 'VARA' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::VARA',
- 'argumentCount' => '1+'
- ),
- 'VARP' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::VARP',
- 'argumentCount' => '1+'
- ),
- 'VARPA' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::VARPA',
- 'argumentCount' => '1+'
- ),
- 'VDB' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'Calculation_Functions::DUMMY',
- 'argumentCount' => '5-7'
- ),
- 'VERSION' => array('category' => Calculation_Function::CATEGORY_INFORMATION,
- 'functionCall' => 'Calculation_Functions::VERSION',
- 'argumentCount' => '0'
- ),
- 'VLOOKUP' => array('category' => Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
- 'functionCall' => 'Calculation_LookupRef::VLOOKUP',
- 'argumentCount' => '3,4'
- ),
- 'WEEKDAY' => array('category' => Calculation_Function::CATEGORY_DATE_AND_TIME,
- 'functionCall' => 'Calculation_DateTime::DAYOFWEEK',
- 'argumentCount' => '1,2'
- ),
- 'WEEKNUM' => array('category' => Calculation_Function::CATEGORY_DATE_AND_TIME,
- 'functionCall' => 'Calculation_DateTime::WEEKOFYEAR',
- 'argumentCount' => '1,2'
- ),
- 'WEIBULL' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::WEIBULL',
- 'argumentCount' => '4'
- ),
- 'WORKDAY' => array('category' => Calculation_Function::CATEGORY_DATE_AND_TIME,
- 'functionCall' => 'Calculation_DateTime::WORKDAY',
- 'argumentCount' => '2+'
- ),
- 'XIRR' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'Calculation_Financial::XIRR',
- 'argumentCount' => '2,3'
- ),
- 'XNPV' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'Calculation_Financial::XNPV',
- 'argumentCount' => '3'
- ),
- 'YEAR' => array('category' => Calculation_Function::CATEGORY_DATE_AND_TIME,
- 'functionCall' => 'Calculation_DateTime::YEAR',
- 'argumentCount' => '1'
- ),
- 'YEARFRAC' => array('category' => Calculation_Function::CATEGORY_DATE_AND_TIME,
- 'functionCall' => 'Calculation_DateTime::YEARFRAC',
- 'argumentCount' => '2,3'
- ),
- 'YIELD' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'Calculation_Functions::DUMMY',
- 'argumentCount' => '6,7'
- ),
- 'YIELDDISC' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'Calculation_Financial::YIELDDISC',
- 'argumentCount' => '4,5'
- ),
- 'YIELDMAT' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'Calculation_Financial::YIELDMAT',
- 'argumentCount' => '5,6'
- ),
- 'ZTEST' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'Calculation_Statistical::ZTEST',
- 'argumentCount' => '2-3'
- )
- );
+ // PHPExcel functions
+ private static $_PHPExcelFunctions = array( // PHPExcel functions
+ 'ABS' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
+ 'functionCall' => 'abs',
+ 'argumentCount' => '1'
+ ),
+ 'ACCRINT' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
+ 'functionCall' => 'Calculation_Financial::ACCRINT',
+ 'argumentCount' => '4-7'
+ ),
+ 'ACCRINTM' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
+ 'functionCall' => 'Calculation_Financial::ACCRINTM',
+ 'argumentCount' => '3-5'
+ ),
+ 'ACOS' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
+ 'functionCall' => 'acos',
+ 'argumentCount' => '1'
+ ),
+ 'ACOSH' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
+ 'functionCall' => 'acosh',
+ 'argumentCount' => '1'
+ ),
+ 'ADDRESS' => array('category' => Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
+ 'functionCall' => 'Calculation_LookupRef::CELL_ADDRESS',
+ 'argumentCount' => '2-5'
+ ),
+ 'AMORDEGRC' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
+ 'functionCall' => 'Calculation_Financial::AMORDEGRC',
+ 'argumentCount' => '6,7'
+ ),
+ 'AMORLINC' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
+ 'functionCall' => 'Calculation_Financial::AMORLINC',
+ 'argumentCount' => '6,7'
+ ),
+ 'AND' => array('category' => Calculation_Function::CATEGORY_LOGICAL,
+ 'functionCall' => 'Calculation_Logical::LOGICAL_AND',
+ 'argumentCount' => '1+'
+ ),
+ 'AREAS' => array('category' => Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
+ 'functionCall' => 'Calculation_Functions::DUMMY',
+ 'argumentCount' => '1'
+ ),
+ 'ASC' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
+ 'functionCall' => 'Calculation_Functions::DUMMY',
+ 'argumentCount' => '1'
+ ),
+ 'ASIN' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
+ 'functionCall' => 'asin',
+ 'argumentCount' => '1'
+ ),
+ 'ASINH' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
+ 'functionCall' => 'asinh',
+ 'argumentCount' => '1'
+ ),
+ 'ATAN' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
+ 'functionCall' => 'atan',
+ 'argumentCount' => '1'
+ ),
+ 'ATAN2' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
+ 'functionCall' => 'Calculation_MathTrig::ATAN2',
+ 'argumentCount' => '2'
+ ),
+ 'ATANH' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
+ 'functionCall' => 'atanh',
+ 'argumentCount' => '1'
+ ),
+ 'AVEDEV' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::AVEDEV',
+ 'argumentCount' => '1+'
+ ),
+ 'AVERAGE' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::AVERAGE',
+ 'argumentCount' => '1+'
+ ),
+ 'AVERAGEA' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::AVERAGEA',
+ 'argumentCount' => '1+'
+ ),
+ 'AVERAGEIF' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::AVERAGEIF',
+ 'argumentCount' => '2,3'
+ ),
+ 'AVERAGEIFS' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Functions::DUMMY',
+ 'argumentCount' => '3+'
+ ),
+ 'BAHTTEXT' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
+ 'functionCall' => 'Calculation_Functions::DUMMY',
+ 'argumentCount' => '1'
+ ),
+ 'BESSELI' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
+ 'functionCall' => 'Calculation_Engineering::BESSELI',
+ 'argumentCount' => '2'
+ ),
+ 'BESSELJ' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
+ 'functionCall' => 'Calculation_Engineering::BESSELJ',
+ 'argumentCount' => '2'
+ ),
+ 'BESSELK' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
+ 'functionCall' => 'Calculation_Engineering::BESSELK',
+ 'argumentCount' => '2'
+ ),
+ 'BESSELY' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
+ 'functionCall' => 'Calculation_Engineering::BESSELY',
+ 'argumentCount' => '2'
+ ),
+ 'BETADIST' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::BETADIST',
+ 'argumentCount' => '3-5'
+ ),
+ 'BETAINV' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::BETAINV',
+ 'argumentCount' => '3-5'
+ ),
+ 'BIN2DEC' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
+ 'functionCall' => 'Calculation_Engineering::BINTODEC',
+ 'argumentCount' => '1'
+ ),
+ 'BIN2HEX' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
+ 'functionCall' => 'Calculation_Engineering::BINTOHEX',
+ 'argumentCount' => '1,2'
+ ),
+ 'BIN2OCT' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
+ 'functionCall' => 'Calculation_Engineering::BINTOOCT',
+ 'argumentCount' => '1,2'
+ ),
+ 'BINOMDIST' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::BINOMDIST',
+ 'argumentCount' => '4'
+ ),
+ 'CEILING' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
+ 'functionCall' => 'Calculation_MathTrig::CEILING',
+ 'argumentCount' => '2'
+ ),
+ 'CELL' => array('category' => Calculation_Function::CATEGORY_INFORMATION,
+ 'functionCall' => 'Calculation_Functions::DUMMY',
+ 'argumentCount' => '1,2'
+ ),
+ 'CHAR' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
+ 'functionCall' => 'Calculation_TextData::CHARACTER',
+ 'argumentCount' => '1'
+ ),
+ 'CHIDIST' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::CHIDIST',
+ 'argumentCount' => '2'
+ ),
+ 'CHIINV' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::CHIINV',
+ 'argumentCount' => '2'
+ ),
+ 'CHITEST' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Functions::DUMMY',
+ 'argumentCount' => '2'
+ ),
+ 'CHOOSE' => array('category' => Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
+ 'functionCall' => 'Calculation_LookupRef::CHOOSE',
+ 'argumentCount' => '2+'
+ ),
+ 'CLEAN' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
+ 'functionCall' => 'Calculation_TextData::TRIMNONPRINTABLE',
+ 'argumentCount' => '1'
+ ),
+ 'CODE' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
+ 'functionCall' => 'Calculation_TextData::ASCIICODE',
+ 'argumentCount' => '1'
+ ),
+ 'COLUMN' => array('category' => Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
+ 'functionCall' => 'Calculation_LookupRef::COLUMN',
+ 'argumentCount' => '-1',
+ 'passByReference' => array(TRUE)
+ ),
+ 'COLUMNS' => array('category' => Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
+ 'functionCall' => 'Calculation_LookupRef::COLUMNS',
+ 'argumentCount' => '1'
+ ),
+ 'COMBIN' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
+ 'functionCall' => 'Calculation_MathTrig::COMBIN',
+ 'argumentCount' => '2'
+ ),
+ 'COMPLEX' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
+ 'functionCall' => 'Calculation_Engineering::COMPLEX',
+ 'argumentCount' => '2,3'
+ ),
+ 'CONCATENATE' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
+ 'functionCall' => 'Calculation_TextData::CONCATENATE',
+ 'argumentCount' => '1+'
+ ),
+ 'CONFIDENCE' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::CONFIDENCE',
+ 'argumentCount' => '3'
+ ),
+ 'CONVERT' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
+ 'functionCall' => 'Calculation_Engineering::CONVERTUOM',
+ 'argumentCount' => '3'
+ ),
+ 'CORREL' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::CORREL',
+ 'argumentCount' => '2'
+ ),
+ 'COS' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
+ 'functionCall' => 'cos',
+ 'argumentCount' => '1'
+ ),
+ 'COSH' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
+ 'functionCall' => 'cosh',
+ 'argumentCount' => '1'
+ ),
+ 'COUNT' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::COUNT',
+ 'argumentCount' => '1+'
+ ),
+ 'COUNTA' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::COUNTA',
+ 'argumentCount' => '1+'
+ ),
+ 'COUNTBLANK' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::COUNTBLANK',
+ 'argumentCount' => '1'
+ ),
+ 'COUNTIF' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::COUNTIF',
+ 'argumentCount' => '2'
+ ),
+ 'COUNTIFS' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Functions::DUMMY',
+ 'argumentCount' => '2'
+ ),
+ 'COUPDAYBS' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
+ 'functionCall' => 'Calculation_Financial::COUPDAYBS',
+ 'argumentCount' => '3,4'
+ ),
+ 'COUPDAYS' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
+ 'functionCall' => 'Calculation_Financial::COUPDAYS',
+ 'argumentCount' => '3,4'
+ ),
+ 'COUPDAYSNC' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
+ 'functionCall' => 'Calculation_Financial::COUPDAYSNC',
+ 'argumentCount' => '3,4'
+ ),
+ 'COUPNCD' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
+ 'functionCall' => 'Calculation_Financial::COUPNCD',
+ 'argumentCount' => '3,4'
+ ),
+ 'COUPNUM' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
+ 'functionCall' => 'Calculation_Financial::COUPNUM',
+ 'argumentCount' => '3,4'
+ ),
+ 'COUPPCD' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
+ 'functionCall' => 'Calculation_Financial::COUPPCD',
+ 'argumentCount' => '3,4'
+ ),
+ 'COVAR' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::COVAR',
+ 'argumentCount' => '2'
+ ),
+ 'CRITBINOM' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::CRITBINOM',
+ 'argumentCount' => '3'
+ ),
+ 'CUBEKPIMEMBER' => array('category' => Calculation_Function::CATEGORY_CUBE,
+ 'functionCall' => 'Calculation_Functions::DUMMY',
+ 'argumentCount' => '?'
+ ),
+ 'CUBEMEMBER' => array('category' => Calculation_Function::CATEGORY_CUBE,
+ 'functionCall' => 'Calculation_Functions::DUMMY',
+ 'argumentCount' => '?'
+ ),
+ 'CUBEMEMBERPROPERTY' => array('category' => Calculation_Function::CATEGORY_CUBE,
+ 'functionCall' => 'Calculation_Functions::DUMMY',
+ 'argumentCount' => '?'
+ ),
+ 'CUBERANKEDMEMBER' => array('category' => Calculation_Function::CATEGORY_CUBE,
+ 'functionCall' => 'Calculation_Functions::DUMMY',
+ 'argumentCount' => '?'
+ ),
+ 'CUBESET' => array('category' => Calculation_Function::CATEGORY_CUBE,
+ 'functionCall' => 'Calculation_Functions::DUMMY',
+ 'argumentCount' => '?'
+ ),
+ 'CUBESETCOUNT' => array('category' => Calculation_Function::CATEGORY_CUBE,
+ 'functionCall' => 'Calculation_Functions::DUMMY',
+ 'argumentCount' => '?'
+ ),
+ 'CUBEVALUE' => array('category' => Calculation_Function::CATEGORY_CUBE,
+ 'functionCall' => 'Calculation_Functions::DUMMY',
+ 'argumentCount' => '?'
+ ),
+ 'CUMIPMT' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
+ 'functionCall' => 'Calculation_Financial::CUMIPMT',
+ 'argumentCount' => '6'
+ ),
+ 'CUMPRINC' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
+ 'functionCall' => 'Calculation_Financial::CUMPRINC',
+ 'argumentCount' => '6'
+ ),
+ 'DATE' => array('category' => Calculation_Function::CATEGORY_DATE_AND_TIME,
+ 'functionCall' => 'Calculation_DateTime::DATE',
+ 'argumentCount' => '3'
+ ),
+ 'DATEDIF' => array('category' => Calculation_Function::CATEGORY_DATE_AND_TIME,
+ 'functionCall' => 'Calculation_DateTime::DATEDIF',
+ 'argumentCount' => '2,3'
+ ),
+ 'DATEVALUE' => array('category' => Calculation_Function::CATEGORY_DATE_AND_TIME,
+ 'functionCall' => 'Calculation_DateTime::DATEVALUE',
+ 'argumentCount' => '1'
+ ),
+ 'DAVERAGE' => array('category' => Calculation_Function::CATEGORY_DATABASE,
+ 'functionCall' => 'Calculation_Database::DAVERAGE',
+ 'argumentCount' => '3'
+ ),
+ 'DAY' => array('category' => Calculation_Function::CATEGORY_DATE_AND_TIME,
+ 'functionCall' => 'Calculation_DateTime::DAYOFMONTH',
+ 'argumentCount' => '1'
+ ),
+ 'DAYS360' => array('category' => Calculation_Function::CATEGORY_DATE_AND_TIME,
+ 'functionCall' => 'Calculation_DateTime::DAYS360',
+ 'argumentCount' => '2,3'
+ ),
+ 'DB' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
+ 'functionCall' => 'Calculation_Financial::DB',
+ 'argumentCount' => '4,5'
+ ),
+ 'DCOUNT' => array('category' => Calculation_Function::CATEGORY_DATABASE,
+ 'functionCall' => 'Calculation_Database::DCOUNT',
+ 'argumentCount' => '3'
+ ),
+ 'DCOUNTA' => array('category' => Calculation_Function::CATEGORY_DATABASE,
+ 'functionCall' => 'Calculation_Database::DCOUNTA',
+ 'argumentCount' => '3'
+ ),
+ 'DDB' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
+ 'functionCall' => 'Calculation_Financial::DDB',
+ 'argumentCount' => '4,5'
+ ),
+ 'DEC2BIN' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
+ 'functionCall' => 'Calculation_Engineering::DECTOBIN',
+ 'argumentCount' => '1,2'
+ ),
+ 'DEC2HEX' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
+ 'functionCall' => 'Calculation_Engineering::DECTOHEX',
+ 'argumentCount' => '1,2'
+ ),
+ 'DEC2OCT' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
+ 'functionCall' => 'Calculation_Engineering::DECTOOCT',
+ 'argumentCount' => '1,2'
+ ),
+ 'DEGREES' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
+ 'functionCall' => 'rad2deg',
+ 'argumentCount' => '1'
+ ),
+ 'DELTA' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
+ 'functionCall' => 'Calculation_Engineering::DELTA',
+ 'argumentCount' => '1,2'
+ ),
+ 'DEVSQ' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::DEVSQ',
+ 'argumentCount' => '1+'
+ ),
+ 'DGET' => array('category' => Calculation_Function::CATEGORY_DATABASE,
+ 'functionCall' => 'Calculation_Database::DGET',
+ 'argumentCount' => '3'
+ ),
+ 'DISC' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
+ 'functionCall' => 'Calculation_Financial::DISC',
+ 'argumentCount' => '4,5'
+ ),
+ 'DMAX' => array('category' => Calculation_Function::CATEGORY_DATABASE,
+ 'functionCall' => 'Calculation_Database::DMAX',
+ 'argumentCount' => '3'
+ ),
+ 'DMIN' => array('category' => Calculation_Function::CATEGORY_DATABASE,
+ 'functionCall' => 'Calculation_Database::DMIN',
+ 'argumentCount' => '3'
+ ),
+ 'DOLLAR' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
+ 'functionCall' => 'Calculation_TextData::DOLLAR',
+ 'argumentCount' => '1,2'
+ ),
+ 'DOLLARDE' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
+ 'functionCall' => 'Calculation_Financial::DOLLARDE',
+ 'argumentCount' => '2'
+ ),
+ 'DOLLARFR' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
+ 'functionCall' => 'Calculation_Financial::DOLLARFR',
+ 'argumentCount' => '2'
+ ),
+ 'DPRODUCT' => array('category' => Calculation_Function::CATEGORY_DATABASE,
+ 'functionCall' => 'Calculation_Database::DPRODUCT',
+ 'argumentCount' => '3'
+ ),
+ 'DSTDEV' => array('category' => Calculation_Function::CATEGORY_DATABASE,
+ 'functionCall' => 'Calculation_Database::DSTDEV',
+ 'argumentCount' => '3'
+ ),
+ 'DSTDEVP' => array('category' => Calculation_Function::CATEGORY_DATABASE,
+ 'functionCall' => 'Calculation_Database::DSTDEVP',
+ 'argumentCount' => '3'
+ ),
+ 'DSUM' => array('category' => Calculation_Function::CATEGORY_DATABASE,
+ 'functionCall' => 'Calculation_Database::DSUM',
+ 'argumentCount' => '3'
+ ),
+ 'DURATION' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
+ 'functionCall' => 'Calculation_Functions::DUMMY',
+ 'argumentCount' => '5,6'
+ ),
+ 'DVAR' => array('category' => Calculation_Function::CATEGORY_DATABASE,
+ 'functionCall' => 'Calculation_Database::DVAR',
+ 'argumentCount' => '3'
+ ),
+ 'DVARP' => array('category' => Calculation_Function::CATEGORY_DATABASE,
+ 'functionCall' => 'Calculation_Database::DVARP',
+ 'argumentCount' => '3'
+ ),
+ 'EDATE' => array('category' => Calculation_Function::CATEGORY_DATE_AND_TIME,
+ 'functionCall' => 'Calculation_DateTime::EDATE',
+ 'argumentCount' => '2'
+ ),
+ 'EFFECT' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
+ 'functionCall' => 'Calculation_Financial::EFFECT',
+ 'argumentCount' => '2'
+ ),
+ 'EOMONTH' => array('category' => Calculation_Function::CATEGORY_DATE_AND_TIME,
+ 'functionCall' => 'Calculation_DateTime::EOMONTH',
+ 'argumentCount' => '2'
+ ),
+ 'ERF' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
+ 'functionCall' => 'Calculation_Engineering::ERF',
+ 'argumentCount' => '1,2'
+ ),
+ 'ERFC' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
+ 'functionCall' => 'Calculation_Engineering::ERFC',
+ 'argumentCount' => '1'
+ ),
+ 'ERROR.TYPE' => array('category' => Calculation_Function::CATEGORY_INFORMATION,
+ 'functionCall' => 'Calculation_Functions::ERROR_TYPE',
+ 'argumentCount' => '1'
+ ),
+ 'EVEN' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
+ 'functionCall' => 'Calculation_MathTrig::EVEN',
+ 'argumentCount' => '1'
+ ),
+ 'EXACT' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
+ 'functionCall' => 'Calculation_Functions::DUMMY',
+ 'argumentCount' => '2'
+ ),
+ 'EXP' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
+ 'functionCall' => 'exp',
+ 'argumentCount' => '1'
+ ),
+ 'EXPONDIST' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::EXPONDIST',
+ 'argumentCount' => '3'
+ ),
+ 'FACT' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
+ 'functionCall' => 'Calculation_MathTrig::FACT',
+ 'argumentCount' => '1'
+ ),
+ 'FACTDOUBLE' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
+ 'functionCall' => 'Calculation_MathTrig::FACTDOUBLE',
+ 'argumentCount' => '1'
+ ),
+ 'FALSE' => array('category' => Calculation_Function::CATEGORY_LOGICAL,
+ 'functionCall' => 'Calculation_Logical::FALSE',
+ 'argumentCount' => '0'
+ ),
+ 'FDIST' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Functions::DUMMY',
+ 'argumentCount' => '3'
+ ),
+ 'FIND' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
+ 'functionCall' => 'Calculation_TextData::SEARCHSENSITIVE',
+ 'argumentCount' => '2,3'
+ ),
+ 'FINDB' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
+ 'functionCall' => 'Calculation_TextData::SEARCHSENSITIVE',
+ 'argumentCount' => '2,3'
+ ),
+ 'FINV' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Functions::DUMMY',
+ 'argumentCount' => '3'
+ ),
+ 'FISHER' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::FISHER',
+ 'argumentCount' => '1'
+ ),
+ 'FISHERINV' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::FISHERINV',
+ 'argumentCount' => '1'
+ ),
+ 'FIXED' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
+ 'functionCall' => 'Calculation_TextData::FIXEDFORMAT',
+ 'argumentCount' => '1-3'
+ ),
+ 'FLOOR' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
+ 'functionCall' => 'Calculation_MathTrig::FLOOR',
+ 'argumentCount' => '2'
+ ),
+ 'FORECAST' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::FORECAST',
+ 'argumentCount' => '3'
+ ),
+ 'FREQUENCY' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Functions::DUMMY',
+ 'argumentCount' => '2'
+ ),
+ 'FTEST' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Functions::DUMMY',
+ 'argumentCount' => '2'
+ ),
+ 'FV' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
+ 'functionCall' => 'Calculation_Financial::FV',
+ 'argumentCount' => '3-5'
+ ),
+ 'FVSCHEDULE' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
+ 'functionCall' => 'Calculation_Financial::FVSCHEDULE',
+ 'argumentCount' => '2'
+ ),
+ 'GAMMADIST' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::GAMMADIST',
+ 'argumentCount' => '4'
+ ),
+ 'GAMMAINV' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::GAMMAINV',
+ 'argumentCount' => '3'
+ ),
+ 'GAMMALN' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::GAMMALN',
+ 'argumentCount' => '1'
+ ),
+ 'GCD' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
+ 'functionCall' => 'Calculation_MathTrig::GCD',
+ 'argumentCount' => '1+'
+ ),
+ 'GEOMEAN' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::GEOMEAN',
+ 'argumentCount' => '1+'
+ ),
+ 'GESTEP' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
+ 'functionCall' => 'Calculation_Engineering::GESTEP',
+ 'argumentCount' => '1,2'
+ ),
+ 'GETPIVOTDATA' => array('category' => Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
+ 'functionCall' => 'Calculation_Functions::DUMMY',
+ 'argumentCount' => '2+'
+ ),
+ 'GROWTH' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::GROWTH',
+ 'argumentCount' => '1-4'
+ ),
+ 'HARMEAN' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::HARMEAN',
+ 'argumentCount' => '1+'
+ ),
+ 'HEX2BIN' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
+ 'functionCall' => 'Calculation_Engineering::HEXTOBIN',
+ 'argumentCount' => '1,2'
+ ),
+ 'HEX2DEC' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
+ 'functionCall' => 'Calculation_Engineering::HEXTODEC',
+ 'argumentCount' => '1'
+ ),
+ 'HEX2OCT' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
+ 'functionCall' => 'Calculation_Engineering::HEXTOOCT',
+ 'argumentCount' => '1,2'
+ ),
+ 'HLOOKUP' => array('category' => Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
+ 'functionCall' => 'Calculation_LookupRef::HLOOKUP',
+ 'argumentCount' => '3,4'
+ ),
+ 'HOUR' => array('category' => Calculation_Function::CATEGORY_DATE_AND_TIME,
+ 'functionCall' => 'Calculation_DateTime::HOUROFDAY',
+ 'argumentCount' => '1'
+ ),
+ 'HYPERLINK' => array('category' => Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
+ 'functionCall' => 'Calculation_LookupRef::HYPERLINK',
+ 'argumentCount' => '1,2',
+ 'passCellReference'=> TRUE
+ ),
+ 'HYPGEOMDIST' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::HYPGEOMDIST',
+ 'argumentCount' => '4'
+ ),
+ 'IF' => array('category' => Calculation_Function::CATEGORY_LOGICAL,
+ 'functionCall' => 'Calculation_Logical::STATEMENT_IF',
+ 'argumentCount' => '1-3'
+ ),
+ 'IFERROR' => array('category' => Calculation_Function::CATEGORY_LOGICAL,
+ 'functionCall' => 'Calculation_Logical::IFERROR',
+ 'argumentCount' => '2'
+ ),
+ 'IMABS' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
+ 'functionCall' => 'Calculation_Engineering::IMABS',
+ 'argumentCount' => '1'
+ ),
+ 'IMAGINARY' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
+ 'functionCall' => 'Calculation_Engineering::IMAGINARY',
+ 'argumentCount' => '1'
+ ),
+ 'IMARGUMENT' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
+ 'functionCall' => 'Calculation_Engineering::IMARGUMENT',
+ 'argumentCount' => '1'
+ ),
+ 'IMCONJUGATE' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
+ 'functionCall' => 'Calculation_Engineering::IMCONJUGATE',
+ 'argumentCount' => '1'
+ ),
+ 'IMCOS' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
+ 'functionCall' => 'Calculation_Engineering::IMCOS',
+ 'argumentCount' => '1'
+ ),
+ 'IMDIV' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
+ 'functionCall' => 'Calculation_Engineering::IMDIV',
+ 'argumentCount' => '2'
+ ),
+ 'IMEXP' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
+ 'functionCall' => 'Calculation_Engineering::IMEXP',
+ 'argumentCount' => '1'
+ ),
+ 'IMLN' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
+ 'functionCall' => 'Calculation_Engineering::IMLN',
+ 'argumentCount' => '1'
+ ),
+ 'IMLOG10' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
+ 'functionCall' => 'Calculation_Engineering::IMLOG10',
+ 'argumentCount' => '1'
+ ),
+ 'IMLOG2' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
+ 'functionCall' => 'Calculation_Engineering::IMLOG2',
+ 'argumentCount' => '1'
+ ),
+ 'IMPOWER' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
+ 'functionCall' => 'Calculation_Engineering::IMPOWER',
+ 'argumentCount' => '2'
+ ),
+ 'IMPRODUCT' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
+ 'functionCall' => 'Calculation_Engineering::IMPRODUCT',
+ 'argumentCount' => '1+'
+ ),
+ 'IMREAL' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
+ 'functionCall' => 'Calculation_Engineering::IMREAL',
+ 'argumentCount' => '1'
+ ),
+ 'IMSIN' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
+ 'functionCall' => 'Calculation_Engineering::IMSIN',
+ 'argumentCount' => '1'
+ ),
+ 'IMSQRT' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
+ 'functionCall' => 'Calculation_Engineering::IMSQRT',
+ 'argumentCount' => '1'
+ ),
+ 'IMSUB' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
+ 'functionCall' => 'Calculation_Engineering::IMSUB',
+ 'argumentCount' => '2'
+ ),
+ 'IMSUM' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
+ 'functionCall' => 'Calculation_Engineering::IMSUM',
+ 'argumentCount' => '1+'
+ ),
+ 'INDEX' => array('category' => Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
+ 'functionCall' => 'Calculation_LookupRef::INDEX',
+ 'argumentCount' => '1-4'
+ ),
+ 'INDIRECT' => array('category' => Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
+ 'functionCall' => 'Calculation_LookupRef::INDIRECT',
+ 'argumentCount' => '1,2',
+ 'passCellReference'=> TRUE
+ ),
+ 'INFO' => array('category' => Calculation_Function::CATEGORY_INFORMATION,
+ 'functionCall' => 'Calculation_Functions::DUMMY',
+ 'argumentCount' => '1'
+ ),
+ 'INT' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
+ 'functionCall' => 'Calculation_MathTrig::INT',
+ 'argumentCount' => '1'
+ ),
+ 'INTERCEPT' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::INTERCEPT',
+ 'argumentCount' => '2'
+ ),
+ 'INTRATE' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
+ 'functionCall' => 'Calculation_Financial::INTRATE',
+ 'argumentCount' => '4,5'
+ ),
+ 'IPMT' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
+ 'functionCall' => 'Calculation_Financial::IPMT',
+ 'argumentCount' => '4-6'
+ ),
+ 'IRR' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
+ 'functionCall' => 'Calculation_Financial::IRR',
+ 'argumentCount' => '1,2'
+ ),
+ 'ISBLANK' => array('category' => Calculation_Function::CATEGORY_INFORMATION,
+ 'functionCall' => 'Calculation_Functions::IS_BLANK',
+ 'argumentCount' => '1'
+ ),
+ 'ISERR' => array('category' => Calculation_Function::CATEGORY_INFORMATION,
+ 'functionCall' => 'Calculation_Functions::IS_ERR',
+ 'argumentCount' => '1'
+ ),
+ 'ISERROR' => array('category' => Calculation_Function::CATEGORY_INFORMATION,
+ 'functionCall' => 'Calculation_Functions::IS_ERROR',
+ 'argumentCount' => '1'
+ ),
+ 'ISEVEN' => array('category' => Calculation_Function::CATEGORY_INFORMATION,
+ 'functionCall' => 'Calculation_Functions::IS_EVEN',
+ 'argumentCount' => '1'
+ ),
+ 'ISLOGICAL' => array('category' => Calculation_Function::CATEGORY_INFORMATION,
+ 'functionCall' => 'Calculation_Functions::IS_LOGICAL',
+ 'argumentCount' => '1'
+ ),
+ 'ISNA' => array('category' => Calculation_Function::CATEGORY_INFORMATION,
+ 'functionCall' => 'Calculation_Functions::IS_NA',
+ 'argumentCount' => '1'
+ ),
+ 'ISNONTEXT' => array('category' => Calculation_Function::CATEGORY_INFORMATION,
+ 'functionCall' => 'Calculation_Functions::IS_NONTEXT',
+ 'argumentCount' => '1'
+ ),
+ 'ISNUMBER' => array('category' => Calculation_Function::CATEGORY_INFORMATION,
+ 'functionCall' => 'Calculation_Functions::IS_NUMBER',
+ 'argumentCount' => '1'
+ ),
+ 'ISODD' => array('category' => Calculation_Function::CATEGORY_INFORMATION,
+ 'functionCall' => 'Calculation_Functions::IS_ODD',
+ 'argumentCount' => '1'
+ ),
+ 'ISPMT' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
+ 'functionCall' => 'Calculation_Financial::ISPMT',
+ 'argumentCount' => '4'
+ ),
+ 'ISREF' => array('category' => Calculation_Function::CATEGORY_INFORMATION,
+ 'functionCall' => 'Calculation_Functions::DUMMY',
+ 'argumentCount' => '1'
+ ),
+ 'ISTEXT' => array('category' => Calculation_Function::CATEGORY_INFORMATION,
+ 'functionCall' => 'Calculation_Functions::IS_TEXT',
+ 'argumentCount' => '1'
+ ),
+ 'JIS' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
+ 'functionCall' => 'Calculation_Functions::DUMMY',
+ 'argumentCount' => '1'
+ ),
+ 'KURT' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::KURT',
+ 'argumentCount' => '1+'
+ ),
+ 'LARGE' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::LARGE',
+ 'argumentCount' => '2'
+ ),
+ 'LCM' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
+ 'functionCall' => 'Calculation_MathTrig::LCM',
+ 'argumentCount' => '1+'
+ ),
+ 'LEFT' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
+ 'functionCall' => 'Calculation_TextData::LEFT',
+ 'argumentCount' => '1,2'
+ ),
+ 'LEFTB' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
+ 'functionCall' => 'Calculation_TextData::LEFT',
+ 'argumentCount' => '1,2'
+ ),
+ 'LEN' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
+ 'functionCall' => 'Calculation_TextData::STRINGLENGTH',
+ 'argumentCount' => '1'
+ ),
+ 'LENB' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
+ 'functionCall' => 'Calculation_TextData::STRINGLENGTH',
+ 'argumentCount' => '1'
+ ),
+ 'LINEST' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::LINEST',
+ 'argumentCount' => '1-4'
+ ),
+ 'LN' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
+ 'functionCall' => 'log',
+ 'argumentCount' => '1'
+ ),
+ 'LOG' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
+ 'functionCall' => 'Calculation_MathTrig::LOG_BASE',
+ 'argumentCount' => '1,2'
+ ),
+ 'LOG10' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
+ 'functionCall' => 'log10',
+ 'argumentCount' => '1'
+ ),
+ 'LOGEST' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::LOGEST',
+ 'argumentCount' => '1-4'
+ ),
+ 'LOGINV' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::LOGINV',
+ 'argumentCount' => '3'
+ ),
+ 'LOGNORMDIST' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::LOGNORMDIST',
+ 'argumentCount' => '3'
+ ),
+ 'LOOKUP' => array('category' => Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
+ 'functionCall' => 'Calculation_LookupRef::LOOKUP',
+ 'argumentCount' => '2,3'
+ ),
+ 'LOWER' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
+ 'functionCall' => 'Calculation_TextData::LOWERCASE',
+ 'argumentCount' => '1'
+ ),
+ 'MATCH' => array('category' => Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
+ 'functionCall' => 'Calculation_LookupRef::MATCH',
+ 'argumentCount' => '2,3'
+ ),
+ 'MAX' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::MAX',
+ 'argumentCount' => '1+'
+ ),
+ 'MAXA' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::MAXA',
+ 'argumentCount' => '1+'
+ ),
+ 'MAXIF' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::MAXIF',
+ 'argumentCount' => '2+'
+ ),
+ 'MDETERM' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
+ 'functionCall' => 'Calculation_MathTrig::MDETERM',
+ 'argumentCount' => '1'
+ ),
+ 'MDURATION' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
+ 'functionCall' => 'Calculation_Functions::DUMMY',
+ 'argumentCount' => '5,6'
+ ),
+ 'MEDIAN' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::MEDIAN',
+ 'argumentCount' => '1+'
+ ),
+ 'MEDIANIF' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Functions::DUMMY',
+ 'argumentCount' => '2+'
+ ),
+ 'MID' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
+ 'functionCall' => 'Calculation_TextData::MID',
+ 'argumentCount' => '3'
+ ),
+ 'MIDB' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
+ 'functionCall' => 'Calculation_TextData::MID',
+ 'argumentCount' => '3'
+ ),
+ 'MIN' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::MIN',
+ 'argumentCount' => '1+'
+ ),
+ 'MINA' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::MINA',
+ 'argumentCount' => '1+'
+ ),
+ 'MINIF' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::MINIF',
+ 'argumentCount' => '2+'
+ ),
+ 'MINUTE' => array('category' => Calculation_Function::CATEGORY_DATE_AND_TIME,
+ 'functionCall' => 'Calculation_DateTime::MINUTEOFHOUR',
+ 'argumentCount' => '1'
+ ),
+ 'MINVERSE' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
+ 'functionCall' => 'Calculation_MathTrig::MINVERSE',
+ 'argumentCount' => '1'
+ ),
+ 'MIRR' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
+ 'functionCall' => 'Calculation_Financial::MIRR',
+ 'argumentCount' => '3'
+ ),
+ 'MMULT' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
+ 'functionCall' => 'Calculation_MathTrig::MMULT',
+ 'argumentCount' => '2'
+ ),
+ 'MOD' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
+ 'functionCall' => 'Calculation_MathTrig::MOD',
+ 'argumentCount' => '2'
+ ),
+ 'MODE' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::MODE',
+ 'argumentCount' => '1+'
+ ),
+ 'MONTH' => array('category' => Calculation_Function::CATEGORY_DATE_AND_TIME,
+ 'functionCall' => 'Calculation_DateTime::MONTHOFYEAR',
+ 'argumentCount' => '1'
+ ),
+ 'MROUND' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
+ 'functionCall' => 'Calculation_MathTrig::MROUND',
+ 'argumentCount' => '2'
+ ),
+ 'MULTINOMIAL' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
+ 'functionCall' => 'Calculation_MathTrig::MULTINOMIAL',
+ 'argumentCount' => '1+'
+ ),
+ 'N' => array('category' => Calculation_Function::CATEGORY_INFORMATION,
+ 'functionCall' => 'Calculation_Functions::N',
+ 'argumentCount' => '1'
+ ),
+ 'NA' => array('category' => Calculation_Function::CATEGORY_INFORMATION,
+ 'functionCall' => 'Calculation_Functions::NA',
+ 'argumentCount' => '0'
+ ),
+ 'NEGBINOMDIST' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::NEGBINOMDIST',
+ 'argumentCount' => '3'
+ ),
+ 'NETWORKDAYS' => array('category' => Calculation_Function::CATEGORY_DATE_AND_TIME,
+ 'functionCall' => 'Calculation_DateTime::NETWORKDAYS',
+ 'argumentCount' => '2+'
+ ),
+ 'NOMINAL' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
+ 'functionCall' => 'Calculation_Financial::NOMINAL',
+ 'argumentCount' => '2'
+ ),
+ 'NORMDIST' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::NORMDIST',
+ 'argumentCount' => '4'
+ ),
+ 'NORMINV' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::NORMINV',
+ 'argumentCount' => '3'
+ ),
+ 'NORMSDIST' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::NORMSDIST',
+ 'argumentCount' => '1'
+ ),
+ 'NORMSINV' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::NORMSINV',
+ 'argumentCount' => '1'
+ ),
+ 'NOT' => array('category' => Calculation_Function::CATEGORY_LOGICAL,
+ 'functionCall' => 'Calculation_Logical::NOT',
+ 'argumentCount' => '1'
+ ),
+ 'NOW' => array('category' => Calculation_Function::CATEGORY_DATE_AND_TIME,
+ 'functionCall' => 'Calculation_DateTime::DATETIMENOW',
+ 'argumentCount' => '0'
+ ),
+ 'NPER' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
+ 'functionCall' => 'Calculation_Financial::NPER',
+ 'argumentCount' => '3-5'
+ ),
+ 'NPV' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
+ 'functionCall' => 'Calculation_Financial::NPV',
+ 'argumentCount' => '2+'
+ ),
+ 'OCT2BIN' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
+ 'functionCall' => 'Calculation_Engineering::OCTTOBIN',
+ 'argumentCount' => '1,2'
+ ),
+ 'OCT2DEC' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
+ 'functionCall' => 'Calculation_Engineering::OCTTODEC',
+ 'argumentCount' => '1'
+ ),
+ 'OCT2HEX' => array('category' => Calculation_Function::CATEGORY_ENGINEERING,
+ 'functionCall' => 'Calculation_Engineering::OCTTOHEX',
+ 'argumentCount' => '1,2'
+ ),
+ 'ODD' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
+ 'functionCall' => 'Calculation_MathTrig::ODD',
+ 'argumentCount' => '1'
+ ),
+ 'ODDFPRICE' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
+ 'functionCall' => 'Calculation_Functions::DUMMY',
+ 'argumentCount' => '8,9'
+ ),
+ 'ODDFYIELD' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
+ 'functionCall' => 'Calculation_Functions::DUMMY',
+ 'argumentCount' => '8,9'
+ ),
+ 'ODDLPRICE' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
+ 'functionCall' => 'Calculation_Functions::DUMMY',
+ 'argumentCount' => '7,8'
+ ),
+ 'ODDLYIELD' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
+ 'functionCall' => 'Calculation_Functions::DUMMY',
+ 'argumentCount' => '7,8'
+ ),
+ 'OFFSET' => array('category' => Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
+ 'functionCall' => 'Calculation_LookupRef::OFFSET',
+ 'argumentCount' => '3,5',
+ 'passCellReference'=> TRUE,
+ 'passByReference' => array(TRUE)
+ ),
+ 'OR' => array('category' => Calculation_Function::CATEGORY_LOGICAL,
+ 'functionCall' => 'Calculation_Logical::LOGICAL_OR',
+ 'argumentCount' => '1+'
+ ),
+ 'PEARSON' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::CORREL',
+ 'argumentCount' => '2'
+ ),
+ 'PERCENTILE' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::PERCENTILE',
+ 'argumentCount' => '2'
+ ),
+ 'PERCENTRANK' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::PERCENTRANK',
+ 'argumentCount' => '2,3'
+ ),
+ 'PERMUT' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::PERMUT',
+ 'argumentCount' => '2'
+ ),
+ 'PHONETIC' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
+ 'functionCall' => 'Calculation_Functions::DUMMY',
+ 'argumentCount' => '1'
+ ),
+ 'PI' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
+ 'functionCall' => 'pi',
+ 'argumentCount' => '0'
+ ),
+ 'PMT' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
+ 'functionCall' => 'Calculation_Financial::PMT',
+ 'argumentCount' => '3-5'
+ ),
+ 'POISSON' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::POISSON',
+ 'argumentCount' => '3'
+ ),
+ 'POWER' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
+ 'functionCall' => 'Calculation_MathTrig::POWER',
+ 'argumentCount' => '2'
+ ),
+ 'PPMT' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
+ 'functionCall' => 'Calculation_Financial::PPMT',
+ 'argumentCount' => '4-6'
+ ),
+ 'PRICE' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
+ 'functionCall' => 'Calculation_Financial::PRICE',
+ 'argumentCount' => '6,7'
+ ),
+ 'PRICEDISC' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
+ 'functionCall' => 'Calculation_Financial::PRICEDISC',
+ 'argumentCount' => '4,5'
+ ),
+ 'PRICEMAT' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
+ 'functionCall' => 'Calculation_Financial::PRICEMAT',
+ 'argumentCount' => '5,6'
+ ),
+ 'PROB' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Functions::DUMMY',
+ 'argumentCount' => '3,4'
+ ),
+ 'PRODUCT' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
+ 'functionCall' => 'Calculation_MathTrig::PRODUCT',
+ 'argumentCount' => '1+'
+ ),
+ 'PROPER' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
+ 'functionCall' => 'Calculation_TextData::PROPERCASE',
+ 'argumentCount' => '1'
+ ),
+ 'PV' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
+ 'functionCall' => 'Calculation_Financial::PV',
+ 'argumentCount' => '3-5'
+ ),
+ 'QUARTILE' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::QUARTILE',
+ 'argumentCount' => '2'
+ ),
+ 'QUOTIENT' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
+ 'functionCall' => 'Calculation_MathTrig::QUOTIENT',
+ 'argumentCount' => '2'
+ ),
+ 'RADIANS' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
+ 'functionCall' => 'deg2rad',
+ 'argumentCount' => '1'
+ ),
+ 'RAND' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
+ 'functionCall' => 'Calculation_MathTrig::RAND',
+ 'argumentCount' => '0'
+ ),
+ 'RANDBETWEEN' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
+ 'functionCall' => 'Calculation_MathTrig::RAND',
+ 'argumentCount' => '2'
+ ),
+ 'RANK' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::RANK',
+ 'argumentCount' => '2,3'
+ ),
+ 'RATE' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
+ 'functionCall' => 'Calculation_Financial::RATE',
+ 'argumentCount' => '3-6'
+ ),
+ 'RECEIVED' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
+ 'functionCall' => 'Calculation_Financial::RECEIVED',
+ 'argumentCount' => '4-5'
+ ),
+ 'REPLACE' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
+ 'functionCall' => 'Calculation_TextData::REPLACE',
+ 'argumentCount' => '4'
+ ),
+ 'REPLACEB' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
+ 'functionCall' => 'Calculation_TextData::REPLACE',
+ 'argumentCount' => '4'
+ ),
+ 'REPT' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
+ 'functionCall' => 'str_repeat',
+ 'argumentCount' => '2'
+ ),
+ 'RIGHT' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
+ 'functionCall' => 'Calculation_TextData::RIGHT',
+ 'argumentCount' => '1,2'
+ ),
+ 'RIGHTB' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
+ 'functionCall' => 'Calculation_TextData::RIGHT',
+ 'argumentCount' => '1,2'
+ ),
+ 'ROMAN' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
+ 'functionCall' => 'Calculation_MathTrig::ROMAN',
+ 'argumentCount' => '1,2'
+ ),
+ 'ROUND' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
+ 'functionCall' => 'round',
+ 'argumentCount' => '2'
+ ),
+ 'ROUNDDOWN' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
+ 'functionCall' => 'Calculation_MathTrig::ROUNDDOWN',
+ 'argumentCount' => '2'
+ ),
+ 'ROUNDUP' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
+ 'functionCall' => 'Calculation_MathTrig::ROUNDUP',
+ 'argumentCount' => '2'
+ ),
+ 'ROW' => array('category' => Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
+ 'functionCall' => 'Calculation_LookupRef::ROW',
+ 'argumentCount' => '-1',
+ 'passByReference' => array(TRUE)
+ ),
+ 'ROWS' => array('category' => Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
+ 'functionCall' => 'Calculation_LookupRef::ROWS',
+ 'argumentCount' => '1'
+ ),
+ 'RSQ' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::RSQ',
+ 'argumentCount' => '2'
+ ),
+ 'RTD' => array('category' => Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
+ 'functionCall' => 'Calculation_Functions::DUMMY',
+ 'argumentCount' => '1+'
+ ),
+ 'SEARCH' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
+ 'functionCall' => 'Calculation_TextData::SEARCHINSENSITIVE',
+ 'argumentCount' => '2,3'
+ ),
+ 'SEARCHB' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
+ 'functionCall' => 'Calculation_TextData::SEARCHINSENSITIVE',
+ 'argumentCount' => '2,3'
+ ),
+ 'SECOND' => array('category' => Calculation_Function::CATEGORY_DATE_AND_TIME,
+ 'functionCall' => 'Calculation_DateTime::SECONDOFMINUTE',
+ 'argumentCount' => '1'
+ ),
+ 'SERIESSUM' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
+ 'functionCall' => 'Calculation_MathTrig::SERIESSUM',
+ 'argumentCount' => '4'
+ ),
+ 'SIGN' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
+ 'functionCall' => 'Calculation_MathTrig::SIGN',
+ 'argumentCount' => '1'
+ ),
+ 'SIN' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
+ 'functionCall' => 'sin',
+ 'argumentCount' => '1'
+ ),
+ 'SINH' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
+ 'functionCall' => 'sinh',
+ 'argumentCount' => '1'
+ ),
+ 'SKEW' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::SKEW',
+ 'argumentCount' => '1+'
+ ),
+ 'SLN' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
+ 'functionCall' => 'Calculation_Financial::SLN',
+ 'argumentCount' => '3'
+ ),
+ 'SLOPE' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::SLOPE',
+ 'argumentCount' => '2'
+ ),
+ 'SMALL' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::SMALL',
+ 'argumentCount' => '2'
+ ),
+ 'SQRT' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
+ 'functionCall' => 'sqrt',
+ 'argumentCount' => '1'
+ ),
+ 'SQRTPI' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
+ 'functionCall' => 'Calculation_MathTrig::SQRTPI',
+ 'argumentCount' => '1'
+ ),
+ 'STANDARDIZE' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::STANDARDIZE',
+ 'argumentCount' => '3'
+ ),
+ 'STDEV' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::STDEV',
+ 'argumentCount' => '1+'
+ ),
+ 'STDEVA' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::STDEVA',
+ 'argumentCount' => '1+'
+ ),
+ 'STDEVP' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::STDEVP',
+ 'argumentCount' => '1+'
+ ),
+ 'STDEVPA' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::STDEVPA',
+ 'argumentCount' => '1+'
+ ),
+ 'STEYX' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::STEYX',
+ 'argumentCount' => '2'
+ ),
+ 'SUBSTITUTE' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
+ 'functionCall' => 'Calculation_TextData::SUBSTITUTE',
+ 'argumentCount' => '3,4'
+ ),
+ 'SUBTOTAL' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
+ 'functionCall' => 'Calculation_MathTrig::SUBTOTAL',
+ 'argumentCount' => '2+'
+ ),
+ 'SUM' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
+ 'functionCall' => 'Calculation_MathTrig::SUM',
+ 'argumentCount' => '1+'
+ ),
+ 'SUMIF' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
+ 'functionCall' => 'Calculation_MathTrig::SUMIF',
+ 'argumentCount' => '2,3'
+ ),
+ 'SUMIFS' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
+ 'functionCall' => 'Calculation_Functions::DUMMY',
+ 'argumentCount' => '?'
+ ),
+ 'SUMPRODUCT' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
+ 'functionCall' => 'Calculation_MathTrig::SUMPRODUCT',
+ 'argumentCount' => '1+'
+ ),
+ 'SUMSQ' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
+ 'functionCall' => 'Calculation_MathTrig::SUMSQ',
+ 'argumentCount' => '1+'
+ ),
+ 'SUMX2MY2' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
+ 'functionCall' => 'Calculation_MathTrig::SUMX2MY2',
+ 'argumentCount' => '2'
+ ),
+ 'SUMX2PY2' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
+ 'functionCall' => 'Calculation_MathTrig::SUMX2PY2',
+ 'argumentCount' => '2'
+ ),
+ 'SUMXMY2' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
+ 'functionCall' => 'Calculation_MathTrig::SUMXMY2',
+ 'argumentCount' => '2'
+ ),
+ 'SYD' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
+ 'functionCall' => 'Calculation_Financial::SYD',
+ 'argumentCount' => '4'
+ ),
+ 'T' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
+ 'functionCall' => 'Calculation_TextData::RETURNSTRING',
+ 'argumentCount' => '1'
+ ),
+ 'TAN' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
+ 'functionCall' => 'tan',
+ 'argumentCount' => '1'
+ ),
+ 'TANH' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
+ 'functionCall' => 'tanh',
+ 'argumentCount' => '1'
+ ),
+ 'TBILLEQ' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
+ 'functionCall' => 'Calculation_Financial::TBILLEQ',
+ 'argumentCount' => '3'
+ ),
+ 'TBILLPRICE' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
+ 'functionCall' => 'Calculation_Financial::TBILLPRICE',
+ 'argumentCount' => '3'
+ ),
+ 'TBILLYIELD' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
+ 'functionCall' => 'Calculation_Financial::TBILLYIELD',
+ 'argumentCount' => '3'
+ ),
+ 'TDIST' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::TDIST',
+ 'argumentCount' => '3'
+ ),
+ 'TEXT' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
+ 'functionCall' => 'Calculation_TextData::TEXTFORMAT',
+ 'argumentCount' => '2'
+ ),
+ 'TIME' => array('category' => Calculation_Function::CATEGORY_DATE_AND_TIME,
+ 'functionCall' => 'Calculation_DateTime::TIME',
+ 'argumentCount' => '3'
+ ),
+ 'TIMEVALUE' => array('category' => Calculation_Function::CATEGORY_DATE_AND_TIME,
+ 'functionCall' => 'Calculation_DateTime::TIMEVALUE',
+ 'argumentCount' => '1'
+ ),
+ 'TINV' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::TINV',
+ 'argumentCount' => '2'
+ ),
+ 'TODAY' => array('category' => Calculation_Function::CATEGORY_DATE_AND_TIME,
+ 'functionCall' => 'Calculation_DateTime::DATENOW',
+ 'argumentCount' => '0'
+ ),
+ 'TRANSPOSE' => array('category' => Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
+ 'functionCall' => 'Calculation_LookupRef::TRANSPOSE',
+ 'argumentCount' => '1'
+ ),
+ 'TREND' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::TREND',
+ 'argumentCount' => '1-4'
+ ),
+ 'TRIM' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
+ 'functionCall' => 'Calculation_TextData::TRIMSPACES',
+ 'argumentCount' => '1'
+ ),
+ 'TRIMMEAN' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::TRIMMEAN',
+ 'argumentCount' => '2'
+ ),
+ 'TRUE' => array('category' => Calculation_Function::CATEGORY_LOGICAL,
+ 'functionCall' => 'Calculation_Logical::TRUE',
+ 'argumentCount' => '0'
+ ),
+ 'TRUNC' => array('category' => Calculation_Function::CATEGORY_MATH_AND_TRIG,
+ 'functionCall' => 'Calculation_MathTrig::TRUNC',
+ 'argumentCount' => '1,2'
+ ),
+ 'TTEST' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Functions::DUMMY',
+ 'argumentCount' => '4'
+ ),
+ 'TYPE' => array('category' => Calculation_Function::CATEGORY_INFORMATION,
+ 'functionCall' => 'Calculation_Functions::TYPE',
+ 'argumentCount' => '1'
+ ),
+ 'UPPER' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
+ 'functionCall' => 'Calculation_TextData::UPPERCASE',
+ 'argumentCount' => '1'
+ ),
+ 'USDOLLAR' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
+ 'functionCall' => 'Calculation_Functions::DUMMY',
+ 'argumentCount' => '2'
+ ),
+ 'VALUE' => array('category' => Calculation_Function::CATEGORY_TEXT_AND_DATA,
+ 'functionCall' => 'Calculation_Functions::DUMMY',
+ 'argumentCount' => '1'
+ ),
+ 'VAR' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::VARFunc',
+ 'argumentCount' => '1+'
+ ),
+ 'VARA' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::VARA',
+ 'argumentCount' => '1+'
+ ),
+ 'VARP' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::VARP',
+ 'argumentCount' => '1+'
+ ),
+ 'VARPA' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::VARPA',
+ 'argumentCount' => '1+'
+ ),
+ 'VDB' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
+ 'functionCall' => 'Calculation_Functions::DUMMY',
+ 'argumentCount' => '5-7'
+ ),
+ 'VERSION' => array('category' => Calculation_Function::CATEGORY_INFORMATION,
+ 'functionCall' => 'Calculation_Functions::VERSION',
+ 'argumentCount' => '0'
+ ),
+ 'VLOOKUP' => array('category' => Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
+ 'functionCall' => 'Calculation_LookupRef::VLOOKUP',
+ 'argumentCount' => '3,4'
+ ),
+ 'WEEKDAY' => array('category' => Calculation_Function::CATEGORY_DATE_AND_TIME,
+ 'functionCall' => 'Calculation_DateTime::DAYOFWEEK',
+ 'argumentCount' => '1,2'
+ ),
+ 'WEEKNUM' => array('category' => Calculation_Function::CATEGORY_DATE_AND_TIME,
+ 'functionCall' => 'Calculation_DateTime::WEEKOFYEAR',
+ 'argumentCount' => '1,2'
+ ),
+ 'WEIBULL' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::WEIBULL',
+ 'argumentCount' => '4'
+ ),
+ 'WORKDAY' => array('category' => Calculation_Function::CATEGORY_DATE_AND_TIME,
+ 'functionCall' => 'Calculation_DateTime::WORKDAY',
+ 'argumentCount' => '2+'
+ ),
+ 'XIRR' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
+ 'functionCall' => 'Calculation_Financial::XIRR',
+ 'argumentCount' => '2,3'
+ ),
+ 'XNPV' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
+ 'functionCall' => 'Calculation_Financial::XNPV',
+ 'argumentCount' => '3'
+ ),
+ 'YEAR' => array('category' => Calculation_Function::CATEGORY_DATE_AND_TIME,
+ 'functionCall' => 'Calculation_DateTime::YEAR',
+ 'argumentCount' => '1'
+ ),
+ 'YEARFRAC' => array('category' => Calculation_Function::CATEGORY_DATE_AND_TIME,
+ 'functionCall' => 'Calculation_DateTime::YEARFRAC',
+ 'argumentCount' => '2,3'
+ ),
+ 'YIELD' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
+ 'functionCall' => 'Calculation_Functions::DUMMY',
+ 'argumentCount' => '6,7'
+ ),
+ 'YIELDDISC' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
+ 'functionCall' => 'Calculation_Financial::YIELDDISC',
+ 'argumentCount' => '4,5'
+ ),
+ 'YIELDMAT' => array('category' => Calculation_Function::CATEGORY_FINANCIAL,
+ 'functionCall' => 'Calculation_Financial::YIELDMAT',
+ 'argumentCount' => '5,6'
+ ),
+ 'ZTEST' => array('category' => Calculation_Function::CATEGORY_STATISTICAL,
+ 'functionCall' => 'Calculation_Statistical::ZTEST',
+ 'argumentCount' => '2-3'
+ )
+ );
- // Internal functions used for special control purposes
- private static $_controlFunctions = array(
- 'MKMATRIX' => array('argumentCount' => '*',
- 'functionCall' => 'self::_mkMatrix'
- )
- );
+ // Internal functions used for special control purposes
+ private static $_controlFunctions = array(
+ 'MKMATRIX' => array('argumentCount' => '*',
+ 'functionCall' => 'self::_mkMatrix'
+ )
+ );
- private function __construct(Workbook $workbook = NULL) {
- $setPrecision = (PHP_INT_SIZE == 4) ? 14 : 16;
- $this->_savedPrecision = ini_get('precision');
- if ($this->_savedPrecision < $setPrecision) {
- ini_set('precision',$setPrecision);
- }
+ private function __construct(Workbook $workbook = null) {
+ $setPrecision = (PHP_INT_SIZE == 4) ? 14 : 16;
+ $this->_savedPrecision = ini_get('precision');
+ if ($this->_savedPrecision < $setPrecision) {
+ ini_set('precision',$setPrecision);
+ }
- if ($workbook !== NULL) {
- self::$_workbookSets[$workbook->getID()] = $this;
- }
+ if ($workbook !== null) {
+ self::$_workbookSets[$workbook->getID()] = $this;
+ }
- $this->_workbook = $workbook;
- $this->_cyclicReferenceStack = new CalcEngine_CyclicReferenceStack();
- $this->_debugLog = new CalcEngine_Logger($this->_cyclicReferenceStack);
- } // function __construct()
+ $this->_workbook = $workbook;
+ $this->_cyclicReferenceStack = new CalcEngine_CyclicReferenceStack();
+ $this->_debugLog = new CalcEngine_Logger($this->_cyclicReferenceStack);
+ } // function __construct()
- public function __destruct() {
- if ($this->_savedPrecision != ini_get('precision')) {
- ini_set('precision',$this->_savedPrecision);
- }
- }
-
- private static function _loadLocales() {
- $localeFileDirectory = PHPEXCEL_ROOT.'PHPExcel/locale/';
- foreach (glob($localeFileDirectory.'/*',GLOB_ONLYDIR) as $filename) {
- $filename = substr($filename,strlen($localeFileDirectory)+1);
- if ($filename != 'en') {
- self::$_validLocaleLanguages[] = $filename;
- }
- }
- }
-
- /**
- * Get an instance of this class
- *
- * @access public
- * @param PHPExcel $workbook Injected workbook for working with a PHPExcel object,
- * or NULL to create a standalone claculation engine
- * @return PHPExcel\Calculation
- */
- public static function getInstance(Workbook $workbook = NULL) {
- if ($workbook !== NULL) {
- if (isset(self::$_workbookSets[$workbook->getID()])) {
- return self::$_workbookSets[$workbook->getID()];
- }
- return new Calculation($workbook);
- }
-
- if (!isset(self::$_instance) || (self::$_instance === NULL)) {
- self::$_instance = new Calculation();
- }
-
- return self::$_instance;
- } // function getInstance()
-
- /**
- * Unset an instance of this class
- *
- * @access public
- * @param PHPExcel $workbook Injected workbook identifying the instance to unset
- */
- public static function unsetInstance(Workbook $workbook = NULL) {
- if ($workbook !== NULL) {
- if (isset(self::$_workbookSets[$workbook->getID()])) {
- unset(self::$_workbookSets[$workbook->getID()]);
- }
- }
+ public function __destruct() {
+ if ($this->_savedPrecision != ini_get('precision')) {
+ ini_set('precision',$this->_savedPrecision);
+ }
}
- /**
- * Flush the calculation cache for any existing instance of this class
- * but only if a PHPExcel\Calculation instance exists
- *
- * @access public
- * @return null
- */
- public function flushInstance() {
- $this->clearCalculationCache();
- } // function flushInstance()
-
-
- /**
- * Get the debuglog for this claculation engine instance
- *
- * @access public
- * @return PHPExcel\CalcEngine_Logger
- */
- public function getDebugLog() {
- return $this->_debugLog;
- }
-
- /**
- * __clone implementation. Cloning should not be allowed in a Singleton!
- *
- * @access public
- * @throws Calculation_Exception
- */
- public final function __clone() {
- throw new Calculation_Exception ('Cloning the calculation engine is not allowed!');
- } // function __clone()
-
-
- /**
- * Return the locale-specific translation of TRUE
- *
- * @access public
- * @return string locale-specific translation of TRUE
- */
- public static function getTRUE() {
- return self::$_localeBoolean['TRUE'];
- }
-
- /**
- * Return the locale-specific translation of FALSE
- *
- * @access public
- * @return string locale-specific translation of FALSE
- */
- public static function getFALSE() {
- return self::$_localeBoolean['FALSE'];
- }
-
- /**
- * Set the Array Return Type (Array or Value of first element in the array)
- *
- * @access public
- * @param string $returnType Array return type
- * @return boolean Success or failure
- */
- public static function setArrayReturnType($returnType) {
- if (($returnType == self::RETURN_ARRAY_AS_VALUE) ||
- ($returnType == self::RETURN_ARRAY_AS_ERROR) ||
- ($returnType == self::RETURN_ARRAY_AS_ARRAY)) {
- self::$returnArrayAsType = $returnType;
- return TRUE;
- }
- return FALSE;
- } // function setArrayReturnType()
-
-
- /**
- * Return the Array Return Type (Array or Value of first element in the array)
- *
- * @access public
- * @return string $returnType Array return type
- */
- public static function getArrayReturnType() {
- return self::$returnArrayAsType;
- } // function getArrayReturnType()
-
-
- /**
- * Is calculation caching enabled?
- *
- * @access public
- * @return boolean
- */
- public function getCalculationCacheEnabled() {
- return $this->_calculationCacheEnabled;
- } // function getCalculationCacheEnabled()
-
- /**
- * Enable/disable calculation cache
- *
- * @access public
- * @param boolean $pValue
- */
- public function setCalculationCacheEnabled($pValue = TRUE) {
- $this->_calculationCacheEnabled = $pValue;
- $this->clearCalculationCache();
- } // function setCalculationCacheEnabled()
-
-
- /**
- * Enable calculation cache
- */
- public function enableCalculationCache() {
- $this->setCalculationCacheEnabled(TRUE);
- } // function enableCalculationCache()
-
-
- /**
- * Disable calculation cache
- */
- public function disableCalculationCache() {
- $this->setCalculationCacheEnabled(FALSE);
- } // function disableCalculationCache()
-
-
- /**
- * Clear calculation cache
- */
- public function clearCalculationCache() {
- $this->_calculationCache = array();
- } // function clearCalculationCache()
-
- /**
- * Clear calculation cache for a specified worksheet
- *
- * @param string $worksheetName
- */
- public function clearCalculationCacheForWorksheet($worksheetName) {
- if (isset($this->_calculationCache[$worksheetName])) {
- unset($this->_calculationCache[$worksheetName]);
- }
- } // function clearCalculationCacheForWorksheet()
-
- /**
- * Rename calculation cache for a specified worksheet
- *
- * @param string $fromWorksheetName
- * @param string $toWorksheetName
- */
- public function renameCalculationCacheForWorksheet($fromWorksheetName, $toWorksheetName) {
- if (isset($this->_calculationCache[$fromWorksheetName])) {
- $this->_calculationCache[$toWorksheetName] = &$this->_calculationCache[$fromWorksheetName];
- unset($this->_calculationCache[$fromWorksheetName]);
- }
- } // function renameCalculationCacheForWorksheet()
-
-
- /**
- * Get the currently defined locale code
- *
- * @return string
- */
- public function getLocale() {
- return self::$_localeLanguage;
- } // function getLocale()
-
-
- /**
- * Set the locale code
- *
- * @param string $locale The locale to use for formula translation
- * @return boolean
- */
- public function setLocale($locale = 'en_us') {
- // Identify our locale and language
- $language = $locale = strtolower($locale);
- if (strpos($locale,'_') !== FALSE) {
- list($language) = explode('_',$locale);
- }
-
- if (count(self::$_validLocaleLanguages) == 1)
- self::_loadLocales();
-
- // Test whether we have any language data for this language (any locale)
- if (in_array($language,self::$_validLocaleLanguages)) {
- // initialise language/locale settings
- self::$_localeFunctions = array();
- self::$_localeArgumentSeparator = ',';
- self::$_localeBoolean = array('TRUE' => 'TRUE', 'FALSE' => 'FALSE', 'NULL' => 'NULL');
- // Default is English, if user isn't requesting english, then read the necessary data from the locale files
- if ($locale != 'en_us') {
- // Search for a file with a list of function names for locale
- $functionNamesFile = PHPEXCEL_ROOT . 'PHPExcel'.DIRECTORY_SEPARATOR.'locale'.DIRECTORY_SEPARATOR.str_replace('_',DIRECTORY_SEPARATOR,$locale).DIRECTORY_SEPARATOR.'functions';
- if (!file_exists($functionNamesFile)) {
- // If there isn't a locale specific function file, look for a language specific function file
- $functionNamesFile = PHPEXCEL_ROOT . 'PHPExcel'.DIRECTORY_SEPARATOR.'locale'.DIRECTORY_SEPARATOR.$language.DIRECTORY_SEPARATOR.'functions';
- if (!file_exists($functionNamesFile)) {
- return FALSE;
- }
- }
- // Retrieve the list of locale or language specific function names
- $localeFunctions = file($functionNamesFile,FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
- foreach ($localeFunctions as $localeFunction) {
- list($localeFunction) = explode('##',$localeFunction); // Strip out comments
- if (strpos($localeFunction,'=') !== FALSE) {
- list($fName,$lfName) = explode('=',$localeFunction);
- $fName = trim($fName);
- $lfName = trim($lfName);
- if ((isset(self::$_PHPExcelFunctions[$fName])) && ($lfName != '') && ($fName != $lfName)) {
- self::$_localeFunctions[$fName] = $lfName;
- }
- }
- }
- // Default the TRUE and FALSE constants to the locale names of the TRUE() and FALSE() functions
- if (isset(self::$_localeFunctions['TRUE'])) { self::$_localeBoolean['TRUE'] = self::$_localeFunctions['TRUE']; }
- if (isset(self::$_localeFunctions['FALSE'])) { self::$_localeBoolean['FALSE'] = self::$_localeFunctions['FALSE']; }
-
- $configFile = PHPEXCEL_ROOT . 'PHPExcel'.DIRECTORY_SEPARATOR.'locale'.DIRECTORY_SEPARATOR.str_replace('_',DIRECTORY_SEPARATOR,$locale).DIRECTORY_SEPARATOR.'config';
- if (!file_exists($configFile)) {
- $configFile = PHPEXCEL_ROOT . 'PHPExcel'.DIRECTORY_SEPARATOR.'locale'.DIRECTORY_SEPARATOR.$language.DIRECTORY_SEPARATOR.'config';
- }
- if (file_exists($configFile)) {
- $localeSettings = file($configFile,FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
- foreach ($localeSettings as $localeSetting) {
- list($localeSetting) = explode('##',$localeSetting); // Strip out comments
- if (strpos($localeSetting,'=') !== FALSE) {
- list($settingName,$settingValue) = explode('=',$localeSetting);
- $settingName = strtoupper(trim($settingName));
- switch ($settingName) {
- case 'ARGUMENTSEPARATOR' :
- self::$_localeArgumentSeparator = trim($settingValue);
- break;
- }
- }
- }
- }
- }
-
- self::$functionReplaceFromExcel = self::$functionReplaceToExcel =
- self::$functionReplaceFromLocale = self::$functionReplaceToLocale = NULL;
- self::$_localeLanguage = $locale;
- return TRUE;
- }
- return FALSE;
- } // function setLocale()
-
-
-
- public static function _translateSeparator($fromSeparator,$toSeparator,$formula,&$inBraces) {
- $strlen = mb_strlen($formula);
- for ($i = 0; $i < $strlen; ++$i) {
- $chr = mb_substr($formula,$i,1);
- switch ($chr) {
- case '{' : $inBraces = TRUE;
- break;
- case '}' : $inBraces = FALSE;
- break;
- case $fromSeparator :
- if (!$inBraces) {
- $formula = mb_substr($formula,0,$i).$toSeparator.mb_substr($formula,$i+1);
- }
- }
- }
- return $formula;
- }
-
- private static function _translateFormula($from,$to,$formula,$fromSeparator,$toSeparator) {
- // Convert any Excel function names to the required language
- if (self::$_localeLanguage !== 'en_us') {
- $inBraces = FALSE;
- // If there is the possibility of braces within a quoted string, then we don't treat those as matrix indicators
- if (strpos($formula,'"') !== FALSE) {
- // So instead we skip replacing in any quoted strings by only replacing in every other array element after we've exploded
- // the formula
- $temp = explode('"',$formula);
- $i = FALSE;
- foreach($temp as &$value) {
- // Only count/replace in alternating array entries
- if ($i = !$i) {
- $value = preg_replace($from,$to,$value);
- $value = self::_translateSeparator($fromSeparator,$toSeparator,$value,$inBraces);
- }
- }
- unset($value);
- // Then rebuild the formula string
- $formula = implode('"',$temp);
- } else {
- // If there's no quoted strings, then we do a simple count/replace
- $formula = preg_replace($from,$to,$formula);
- $formula = self::_translateSeparator($fromSeparator,$toSeparator,$formula,$inBraces);
- }
- }
-
- return $formula;
- }
-
- private static $functionReplaceFromExcel = NULL;
- private static $functionReplaceToLocale = NULL;
-
- public function _translateFormulaToLocale($formula) {
- if (self::$functionReplaceFromExcel === NULL) {
- self::$functionReplaceFromExcel = array();
- foreach(array_keys(self::$_localeFunctions) as $excelFunctionName) {
- self::$functionReplaceFromExcel[] = '/(@?[^\w\.])'.preg_quote($excelFunctionName).'([\s]*\()/Ui';
- }
- foreach(array_keys(self::$_localeBoolean) as $excelBoolean) {
- self::$functionReplaceFromExcel[] = '/(@?[^\w\.])'.preg_quote($excelBoolean).'([^\w\.])/Ui';
- }
-
- }
-
- if (self::$functionReplaceToLocale === NULL) {
- self::$functionReplaceToLocale = array();
- foreach(array_values(self::$_localeFunctions) as $localeFunctionName) {
- self::$functionReplaceToLocale[] = '$1'.trim($localeFunctionName).'$2';
- }
- foreach(array_values(self::$_localeBoolean) as $localeBoolean) {
- self::$functionReplaceToLocale[] = '$1'.trim($localeBoolean).'$2';
- }
- }
-
- return self::_translateFormula(self::$functionReplaceFromExcel,self::$functionReplaceToLocale,$formula,',',self::$_localeArgumentSeparator);
- } // function _translateFormulaToLocale()
-
-
- private static $functionReplaceFromLocale = NULL;
- private static $functionReplaceToExcel = NULL;
-
- public function _translateFormulaToEnglish($formula) {
- if (self::$functionReplaceFromLocale === NULL) {
- self::$functionReplaceFromLocale = array();
- foreach(array_values(self::$_localeFunctions) as $localeFunctionName) {
- self::$functionReplaceFromLocale[] = '/(@?[^\w\.])'.preg_quote($localeFunctionName).'([\s]*\()/Ui';
- }
- foreach(array_values(self::$_localeBoolean) as $excelBoolean) {
- self::$functionReplaceFromLocale[] = '/(@?[^\w\.])'.preg_quote($excelBoolean).'([^\w\.])/Ui';
- }
- }
-
- if (self::$functionReplaceToExcel === NULL) {
- self::$functionReplaceToExcel = array();
- foreach(array_keys(self::$_localeFunctions) as $excelFunctionName) {
- self::$functionReplaceToExcel[] = '$1'.trim($excelFunctionName).'$2';
- }
- foreach(array_keys(self::$_localeBoolean) as $excelBoolean) {
- self::$functionReplaceToExcel[] = '$1'.trim($excelBoolean).'$2';
- }
- }
-
- return self::_translateFormula(self::$functionReplaceFromLocale,self::$functionReplaceToExcel,$formula,self::$_localeArgumentSeparator,',');
- } // function _translateFormulaToEnglish()
-
-
- public static function _localeFunc($function) {
- if (self::$_localeLanguage !== 'en_us') {
- $functionName = trim($function,'(');
- if (isset(self::$_localeFunctions[$functionName])) {
- $brace = ($functionName != $function);
- $function = self::$_localeFunctions[$functionName];
- if ($brace) { $function .= '('; }
- }
- }
- return $function;
- }
-
-
-
-
- /**
- * Wrap string values in quotes
- *
- * @param mixed $value
- * @return mixed
- */
- public static function _wrapResult($value) {
- if (is_string($value)) {
- // Error values cannot be "wrapped"
- if (preg_match('/^'.self::CALCULATION_REGEXP_ERROR.'$/i', $value, $match)) {
- // Return Excel errors "as is"
- return $value;
- }
- // Return strings wrapped in quotes
- return '"'.$value.'"';
- // Convert numeric errors to NaN error
- } else if((is_float($value)) && ((is_nan($value)) || (is_infinite($value)))) {
- return Calculation_Functions::NaN();
- }
-
- return $value;
- } // function _wrapResult()
-
-
- /**
- * Remove quotes used as a wrapper to identify string values
- *
- * @param mixed $value
- * @return mixed
- */
- public static function _unwrapResult($value) {
- if (is_string($value)) {
- if ((isset($value{0})) && ($value{0} == '"') && (substr($value,-1) == '"')) {
- return substr($value,1,-1);
- }
- // Convert numeric errors to NaN error
- } else if((is_float($value)) && ((is_nan($value)) || (is_infinite($value)))) {
- return Calculation_Functions::NaN();
- }
- return $value;
- } // function _unwrapResult()
-
-
-
-
- /**
- * Calculate cell value (using formula from a cell ID)
- * Retained for backward compatibility
- *
- * @access public
- * @param PHPExcel\Cell $pCell Cell to calculate
- * @return mixed
- * @throws PHPExcel\Calculation_Exception
- */
- public function calculate(Cell $pCell = NULL) {
- try {
- return $this->calculateCellValue($pCell);
- } catch (Exception $e) {
- throw new Calculation_Exception($e->getMessage());
- }
- } // function calculate()
-
-
- /**
- * Calculate the value of a cell formula
- *
- * @access public
- * @param PHPExcel\Cell $pCell Cell to calculate
- * @param Boolean $resetLog Flag indicating whether the debug log should be reset or not
- * @return mixed
- * @throws Calculation_Exception
- */
- public function calculateCellValue(Cell $pCell = NULL, $resetLog = TRUE) {
- if ($pCell === NULL) {
- return NULL;
- }
-
- $returnArrayAsType = self::$returnArrayAsType;
- if ($resetLog) {
- // Initialise the logging settings if requested
- $this->formulaError = null;
- $this->_debugLog->clearLog();
- $this->_cyclicReferenceStack->clear();
- $this->_cyclicFormulaCount = 1;
-
- self::$returnArrayAsType = self::RETURN_ARRAY_AS_ARRAY;
- }
-
- // Execute the calculation for the cell formula
- try {
- $result = self::_unwrapResult($this->_calculateFormulaValue($pCell->getValue(), $pCell->getCoordinate(), $pCell));
- } catch (Exception $e) {
- throw new Calculation_Exception($e->getMessage());
- }
-
- if ((is_array($result)) && (self::$returnArrayAsType != self::RETURN_ARRAY_AS_ARRAY)) {
- self::$returnArrayAsType = $returnArrayAsType;
- $testResult = Calculation_Functions::flattenArray($result);
- if (self::$returnArrayAsType == self::RETURN_ARRAY_AS_ERROR) {
- return Calculation_Functions::VALUE();
- }
- // If there's only a single cell in the array, then we allow it
- if (count($testResult) != 1) {
- // If keys are numeric, then it's a matrix result rather than a cell range result, so we permit it
- $r = array_keys($result);
- $r = array_shift($r);
- if (!is_numeric($r)) { return Calculation_Functions::VALUE(); }
- if (is_array($result[$r])) {
- $c = array_keys($result[$r]);
- $c = array_shift($c);
- if (!is_numeric($c)) {
- return Calculation_Functions::VALUE();
- }
- }
- }
- $result = array_shift($testResult);
- }
- self::$returnArrayAsType = $returnArrayAsType;
-
-
- if ($result === NULL) {
- return 0;
- } elseif((is_float($result)) && ((is_nan($result)) || (is_infinite($result)))) {
- return Calculation_Functions::NaN();
- }
- return $result;
- } // function calculateCellValue(
-
-
- /**
- * Validate and parse a formula string
- *
- * @param string $formula Formula to parse
- * @return array
- * @throws Calculation_Exception
- */
- public function parseFormula($formula) {
- // Basic validation that this is indeed a formula
- // We return an empty array if not
- $formula = trim($formula);
- if ((!isset($formula{0})) || ($formula{0} != '=')) return array();
- $formula = ltrim(substr($formula,1));
- if (!isset($formula{0})) return array();
-
- // Parse the formula and return the token stack
- return $this->_parseFormula($formula);
- } // function parseFormula()
-
-
- /**
- * Calculate the value of a formula
- *
- * @param string $formula Formula to parse
- * @param string $cellID Address of the cell to calculate
- * @param PHPExcel\Cell $pCell Cell to calculate
- * @return mixed
- * @throws Calculation_Exception
- */
- public function calculateFormula($formula, $cellID=NULL, Cell $pCell = NULL) {
- // Initialise the logging settings
- $this->formulaError = null;
- $this->_debugLog->clearLog();
- $this->_cyclicReferenceStack->clear();
-
- // Disable calculation cacheing because it only applies to cell calculations, not straight formulae
- // But don't actually flush any cache
- $resetCache = $this->getCalculationCacheEnabled();
- $this->_calculationCacheEnabled = FALSE;
- // Execute the calculation
- try {
- $result = self::_unwrapResult($this->_calculateFormulaValue($formula, $cellID, $pCell));
- } catch (Exception $e) {
- throw new Calculation_Exception($e->getMessage());
- }
-
- // Reset calculation cacheing to its previous state
- $this->_calculationCacheEnabled = $resetCache;
-
- return $result;
- } // function calculateFormula()
+ private static function _loadLocales() {
+ $localeFileDirectory = PHPEXCEL_ROOT.'PHPExcel/locale/';
+ foreach (glob($localeFileDirectory.'/*',GLOB_ONLYDIR) as $filename) {
+ $filename = substr($filename,strlen($localeFileDirectory)+1);
+ if ($filename != 'en') {
+ self::$_validLocaleLanguages[] = $filename;
+ }
+ }
+ }
+
+ /**
+ * Get an instance of this class
+ *
+ * @access public
+ * @param PHPExcel $workbook Injected workbook for working with a PHPExcel object,
+ * or null to create a standalone claculation engine
+ * @return PHPExcel\Calculation
+ */
+ public static function getInstance(Workbook $workbook = null) {
+ if ($workbook !== null) {
+ if (isset(self::$_workbookSets[$workbook->getID()])) {
+ return self::$_workbookSets[$workbook->getID()];
+ }
+ return new Calculation($workbook);
+ }
+
+ if (!isset(self::$_instance) || (self::$_instance === null)) {
+ self::$_instance = new Calculation();
+ }
+
+ return self::$_instance;
+ } // function getInstance()
+
+ /**
+ * Unset an instance of this class
+ *
+ * @access public
+ * @param PHPExcel $workbook Injected workbook identifying the instance to unset
+ */
+ public static function unsetInstance(Workbook $workbook = null) {
+ if ($workbook !== null) {
+ if (isset(self::$_workbookSets[$workbook->getID()])) {
+ unset(self::$_workbookSets[$workbook->getID()]);
+ }
+ }
+ }
+
+ /**
+ * Flush the calculation cache for any existing instance of this class
+ * but only if a PHPExcel\Calculation instance exists
+ *
+ * @access public
+ * @return null
+ */
+ public function flushInstance() {
+ $this->clearCalculationCache();
+ } // function flushInstance()
+
+
+ /**
+ * Get the debuglog for this claculation engine instance
+ *
+ * @access public
+ * @return PHPExcel\CalcEngine_Logger
+ */
+ public function getDebugLog() {
+ return $this->_debugLog;
+ }
+
+ /**
+ * __clone implementation. Cloning should not be allowed in a Singleton!
+ *
+ * @access public
+ * @throws Calculation_Exception
+ */
+ public final function __clone() {
+ throw new Calculation_Exception ('Cloning the calculation engine is not allowed!');
+ } // function __clone()
+
+
+ /**
+ * Return the locale-specific translation of TRUE
+ *
+ * @access public
+ * @return string locale-specific translation of TRUE
+ */
+ public static function getTRUE() {
+ return self::$_localeBoolean['TRUE'];
+ }
+
+ /**
+ * Return the locale-specific translation of FALSE
+ *
+ * @access public
+ * @return string locale-specific translation of FALSE
+ */
+ public static function getFALSE() {
+ return self::$_localeBoolean['FALSE'];
+ }
+
+ /**
+ * Set the Array Return Type (Array or Value of first element in the array)
+ *
+ * @access public
+ * @param string $returnType Array return type
+ * @return boolean Success or failure
+ */
+ public static function setArrayReturnType($returnType) {
+ if (($returnType == self::RETURN_ARRAY_AS_VALUE) ||
+ ($returnType == self::RETURN_ARRAY_AS_ERROR) ||
+ ($returnType == self::RETURN_ARRAY_AS_ARRAY)) {
+ self::$returnArrayAsType = $returnType;
+ return TRUE;
+ }
+ return false;
+ } // function setArrayReturnType()
+
+
+ /**
+ * Return the Array Return Type (Array or Value of first element in the array)
+ *
+ * @access public
+ * @return string $returnType Array return type
+ */
+ public static function getArrayReturnType() {
+ return self::$returnArrayAsType;
+ } // function getArrayReturnType()
+
+
+ /**
+ * Is calculation caching enabled?
+ *
+ * @access public
+ * @return boolean
+ */
+ public function getCalculationCacheEnabled() {
+ return $this->_calculationCacheEnabled;
+ } // function getCalculationCacheEnabled()
+
+ /**
+ * Enable/disable calculation cache
+ *
+ * @access public
+ * @param boolean $pValue
+ */
+ public function setCalculationCacheEnabled($pValue = TRUE) {
+ $this->_calculationCacheEnabled = $pValue;
+ $this->clearCalculationCache();
+ } // function setCalculationCacheEnabled()
+
+
+ /**
+ * Enable calculation cache
+ */
+ public function enableCalculationCache() {
+ $this->setCalculationCacheEnabled(TRUE);
+ } // function enableCalculationCache()
+
+
+ /**
+ * Disable calculation cache
+ */
+ public function disableCalculationCache() {
+ $this->setCalculationCacheEnabled(false);
+ } // function disableCalculationCache()
+
+
+ /**
+ * Clear calculation cache
+ */
+ public function clearCalculationCache() {
+ $this->_calculationCache = array();
+ } // function clearCalculationCache()
+
+ /**
+ * Clear calculation cache for a specified worksheet
+ *
+ * @param string $worksheetName
+ */
+ public function clearCalculationCacheForWorksheet($worksheetName) {
+ if (isset($this->_calculationCache[$worksheetName])) {
+ unset($this->_calculationCache[$worksheetName]);
+ }
+ } // function clearCalculationCacheForWorksheet()
+
+ /**
+ * Rename calculation cache for a specified worksheet
+ *
+ * @param string $fromWorksheetName
+ * @param string $toWorksheetName
+ */
+ public function renameCalculationCacheForWorksheet($fromWorksheetName, $toWorksheetName) {
+ if (isset($this->_calculationCache[$fromWorksheetName])) {
+ $this->_calculationCache[$toWorksheetName] = &$this->_calculationCache[$fromWorksheetName];
+ unset($this->_calculationCache[$fromWorksheetName]);
+ }
+ } // function renameCalculationCacheForWorksheet()
+
+
+ /**
+ * Get the currently defined locale code
+ *
+ * @return string
+ */
+ public function getLocale() {
+ return self::$_localeLanguage;
+ } // function getLocale()
+
+
+ /**
+ * Set the locale code
+ *
+ * @param string $locale The locale to use for formula translation
+ * @return boolean
+ */
+ public function setLocale($locale = 'en_us') {
+ // Identify our locale and language
+ $language = $locale = strtolower($locale);
+ if (strpos($locale,'_') !== false) {
+ list($language) = explode('_',$locale);
+ }
+
+ if (count(self::$_validLocaleLanguages) == 1)
+ self::_loadLocales();
+
+ // Test whether we have any language data for this language (any locale)
+ if (in_array($language,self::$_validLocaleLanguages)) {
+ // initialise language/locale settings
+ self::$_localeFunctions = array();
+ self::$_localeArgumentSeparator = ',';
+ self::$_localeBoolean = array('TRUE' => 'TRUE', 'FALSE' => 'FALSE', 'NULL' => 'NULL');
+ // Default is English, if user isn't requesting english, then read the necessary data from the locale files
+ if ($locale != 'en_us') {
+ // Search for a file with a list of function names for locale
+ $functionNamesFile = PHPEXCEL_ROOT . 'PHPExcel'.DIRECTORY_SEPARATOR.'locale'.DIRECTORY_SEPARATOR.str_replace('_',DIRECTORY_SEPARATOR,$locale).DIRECTORY_SEPARATOR.'functions';
+ if (!file_exists($functionNamesFile)) {
+ // If there isn't a locale specific function file, look for a language specific function file
+ $functionNamesFile = PHPEXCEL_ROOT . 'PHPExcel'.DIRECTORY_SEPARATOR.'locale'.DIRECTORY_SEPARATOR.$language.DIRECTORY_SEPARATOR.'functions';
+ if (!file_exists($functionNamesFile)) {
+ return false;
+ }
+ }
+ // Retrieve the list of locale or language specific function names
+ $localeFunctions = file($functionNamesFile,FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
+ foreach ($localeFunctions as $localeFunction) {
+ list($localeFunction) = explode('##',$localeFunction); // Strip out comments
+ if (strpos($localeFunction,'=') !== false) {
+ list($fName,$lfName) = explode('=',$localeFunction);
+ $fName = trim($fName);
+ $lfName = trim($lfName);
+ if ((isset(self::$_PHPExcelFunctions[$fName])) && ($lfName != '') && ($fName != $lfName)) {
+ self::$_localeFunctions[$fName] = $lfName;
+ }
+ }
+ }
+ // Default the TRUE and FALSE constants to the locale names of the TRUE() and FALSE() functions
+ if (isset(self::$_localeFunctions['TRUE'])) { self::$_localeBoolean['TRUE'] = self::$_localeFunctions['TRUE']; }
+ if (isset(self::$_localeFunctions['FALSE'])) { self::$_localeBoolean['FALSE'] = self::$_localeFunctions['FALSE']; }
+
+ $configFile = PHPEXCEL_ROOT . 'PHPExcel'.DIRECTORY_SEPARATOR.'locale'.DIRECTORY_SEPARATOR.str_replace('_',DIRECTORY_SEPARATOR,$locale).DIRECTORY_SEPARATOR.'config';
+ if (!file_exists($configFile)) {
+ $configFile = PHPEXCEL_ROOT . 'PHPExcel'.DIRECTORY_SEPARATOR.'locale'.DIRECTORY_SEPARATOR.$language.DIRECTORY_SEPARATOR.'config';
+ }
+ if (file_exists($configFile)) {
+ $localeSettings = file($configFile,FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
+ foreach ($localeSettings as $localeSetting) {
+ list($localeSetting) = explode('##',$localeSetting); // Strip out comments
+ if (strpos($localeSetting,'=') !== false) {
+ list($settingName,$settingValue) = explode('=',$localeSetting);
+ $settingName = strtoupper(trim($settingName));
+ switch ($settingName) {
+ case 'ARGUMENTSEPARATOR' :
+ self::$_localeArgumentSeparator = trim($settingValue);
+ break;
+ }
+ }
+ }
+ }
+ }
+
+ self::$functionReplaceFromExcel = self::$functionReplaceToExcel =
+ self::$functionReplaceFromLocale = self::$functionReplaceToLocale = null;
+ self::$_localeLanguage = $locale;
+ return TRUE;
+ }
+ return false;
+ } // function setLocale()
+
+
+
+ public static function _translateSeparator($fromSeparator,$toSeparator,$formula,&$inBraces) {
+ $strlen = mb_strlen($formula);
+ for ($i = 0; $i < $strlen; ++$i) {
+ $chr = mb_substr($formula,$i,1);
+ switch ($chr) {
+ case '{' : $inBraces = true;
+ break;
+ case '}' : $inBraces = false;
+ break;
+ case $fromSeparator :
+ if (!$inBraces) {
+ $formula = mb_substr($formula,0,$i).$toSeparator.mb_substr($formula,$i+1);
+ }
+ }
+ }
+ return $formula;
+ }
+
+ private static function _translateFormula($from,$to,$formula,$fromSeparator,$toSeparator) {
+ // Convert any Excel function names to the required language
+ if (self::$_localeLanguage !== 'en_us') {
+ $inBraces = false;
+ // If there is the possibility of braces within a quoted string, then we don't treat those as matrix indicators
+ if (strpos($formula,'"') !== false) {
+ // So instead we skip replacing in any quoted strings by only replacing in every other array element after we've exploded
+ // the formula
+ $temp = explode('"',$formula);
+ $i = false;
+ foreach($temp as &$value) {
+ // Only count/replace in alternating array entries
+ if ($i = !$i) {
+ $value = preg_replace($from,$to,$value);
+ $value = self::_translateSeparator($fromSeparator,$toSeparator,$value,$inBraces);
+ }
+ }
+ unset($value);
+ // Then rebuild the formula string
+ $formula = implode('"',$temp);
+ } else {
+ // If there's no quoted strings, then we do a simple count/replace
+ $formula = preg_replace($from,$to,$formula);
+ $formula = self::_translateSeparator($fromSeparator,$toSeparator,$formula,$inBraces);
+ }
+ }
+
+ return $formula;
+ }
+
+ private static $functionReplaceFromExcel = null;
+ private static $functionReplaceToLocale = null;
+
+ public function _translateFormulaToLocale($formula) {
+ if (self::$functionReplaceFromExcel === null) {
+ self::$functionReplaceFromExcel = array();
+ foreach(array_keys(self::$_localeFunctions) as $excelFunctionName) {
+ self::$functionReplaceFromExcel[] = '/(@?[^\w\.])'.preg_quote($excelFunctionName).'([\s]*\()/Ui';
+ }
+ foreach(array_keys(self::$_localeBoolean) as $excelBoolean) {
+ self::$functionReplaceFromExcel[] = '/(@?[^\w\.])'.preg_quote($excelBoolean).'([^\w\.])/Ui';
+ }
+
+ }
+
+ if (self::$functionReplaceToLocale === null) {
+ self::$functionReplaceToLocale = array();
+ foreach(array_values(self::$_localeFunctions) as $localeFunctionName) {
+ self::$functionReplaceToLocale[] = '$1'.trim($localeFunctionName).'$2';
+ }
+ foreach(array_values(self::$_localeBoolean) as $localeBoolean) {
+ self::$functionReplaceToLocale[] = '$1'.trim($localeBoolean).'$2';
+ }
+ }
+
+ return self::_translateFormula(self::$functionReplaceFromExcel,self::$functionReplaceToLocale,$formula,',',self::$_localeArgumentSeparator);
+ } // function _translateFormulaToLocale()
+
+
+ private static $functionReplaceFromLocale = null;
+ private static $functionReplaceToExcel = null;
+
+ public function _translateFormulaToEnglish($formula) {
+ if (self::$functionReplaceFromLocale === null) {
+ self::$functionReplaceFromLocale = array();
+ foreach(array_values(self::$_localeFunctions) as $localeFunctionName) {
+ self::$functionReplaceFromLocale[] = '/(@?[^\w\.])'.preg_quote($localeFunctionName).'([\s]*\()/Ui';
+ }
+ foreach(array_values(self::$_localeBoolean) as $excelBoolean) {
+ self::$functionReplaceFromLocale[] = '/(@?[^\w\.])'.preg_quote($excelBoolean).'([^\w\.])/Ui';
+ }
+ }
+
+ if (self::$functionReplaceToExcel === null) {
+ self::$functionReplaceToExcel = array();
+ foreach(array_keys(self::$_localeFunctions) as $excelFunctionName) {
+ self::$functionReplaceToExcel[] = '$1'.trim($excelFunctionName).'$2';
+ }
+ foreach(array_keys(self::$_localeBoolean) as $excelBoolean) {
+ self::$functionReplaceToExcel[] = '$1'.trim($excelBoolean).'$2';
+ }
+ }
+
+ return self::_translateFormula(self::$functionReplaceFromLocale,self::$functionReplaceToExcel,$formula,self::$_localeArgumentSeparator,',');
+ } // function _translateFormulaToEnglish()
+
+
+ public static function _localeFunc($function) {
+ if (self::$_localeLanguage !== 'en_us') {
+ $functionName = trim($function,'(');
+ if (isset(self::$_localeFunctions[$functionName])) {
+ $brace = ($functionName != $function);
+ $function = self::$_localeFunctions[$functionName];
+ if ($brace) { $function .= '('; }
+ }
+ }
+ return $function;
+ }
+
+
+
+
+ /**
+ * Wrap string values in quotes
+ *
+ * @param mixed $value
+ * @return mixed
+ */
+ public static function _wrapResult($value) {
+ if (is_string($value)) {
+ // Error values cannot be "wrapped"
+ if (preg_match('/^'.self::CALCULATION_REGEXP_ERROR.'$/i', $value, $match)) {
+ // Return Excel errors "as is"
+ return $value;
+ }
+ // Return strings wrapped in quotes
+ return '"'.$value.'"';
+ // Convert numeric errors to NaN error
+ } else if((is_float($value)) && ((is_nan($value)) || (is_infinite($value)))) {
+ return Calculation_Functions::NaN();
+ }
+
+ return $value;
+ } // function _wrapResult()
+
+
+ /**
+ * Remove quotes used as a wrapper to identify string values
+ *
+ * @param mixed $value
+ * @return mixed
+ */
+ public static function _unwrapResult($value) {
+ if (is_string($value)) {
+ if ((isset($value{0})) && ($value{0} == '"') && (substr($value,-1) == '"')) {
+ return substr($value,1,-1);
+ }
+ // Convert numeric errors to NaN error
+ } else if((is_float($value)) && ((is_nan($value)) || (is_infinite($value)))) {
+ return Calculation_Functions::NaN();
+ }
+ return $value;
+ } // function _unwrapResult()
+
+
+
+
+ /**
+ * Calculate cell value (using formula from a cell ID)
+ * Retained for backward compatibility
+ *
+ * @access public
+ * @param PHPExcel\Cell $pCell Cell to calculate
+ * @return mixed
+ * @throws PHPExcel\Calculation_Exception
+ */
+ public function calculate(Cell $pCell = null) {
+ try {
+ return $this->calculateCellValue($pCell);
+ } catch (Exception $e) {
+ throw new Calculation_Exception($e->getMessage());
+ }
+ } // function calculate()
+
+
+ /**
+ * Calculate the value of a cell formula
+ *
+ * @access public
+ * @param PHPExcel\Cell $pCell Cell to calculate
+ * @param Boolean $resetLog Flag indicating whether the debug log should be reset or not
+ * @return mixed
+ * @throws Calculation_Exception
+ */
+ public function calculateCellValue(Cell $pCell = null, $resetLog = true) {
+ if ($pCell === null) {
+ return null;
+ }
+
+ $returnArrayAsType = self::$returnArrayAsType;
+ if ($resetLog) {
+ // Initialise the logging settings if requested
+ $this->formulaError = null;
+ $this->_debugLog->clearLog();
+ $this->_cyclicReferenceStack->clear();
+ $this->_cyclicFormulaCount = 1;
+
+ self::$returnArrayAsType = self::RETURN_ARRAY_AS_ARRAY;
+ }
+
+ // Execute the calculation for the cell formula
+ try {
+ $result = self::_unwrapResult($this->_calculateFormulaValue($pCell->getValue(), $pCell->getCoordinate(), $pCell));
+ } catch (Exception $e) {
+ throw new Calculation_Exception($e->getMessage());
+ }
+
+ if ((is_array($result)) && (self::$returnArrayAsType != self::RETURN_ARRAY_AS_ARRAY)) {
+ self::$returnArrayAsType = $returnArrayAsType;
+ $testResult = Calculation_Functions::flattenArray($result);
+ if (self::$returnArrayAsType == self::RETURN_ARRAY_AS_ERROR) {
+ return Calculation_Functions::VALUE();
+ }
+ // If there's only a single cell in the array, then we allow it
+ if (count($testResult) != 1) {
+ // If keys are numeric, then it's a matrix result rather than a cell range result, so we permit it
+ $r = array_keys($result);
+ $r = array_shift($r);
+ if (!is_numeric($r)) { return Calculation_Functions::VALUE(); }
+ if (is_array($result[$r])) {
+ $c = array_keys($result[$r]);
+ $c = array_shift($c);
+ if (!is_numeric($c)) {
+ return Calculation_Functions::VALUE();
+ }
+ }
+ }
+ $result = array_shift($testResult);
+ }
+ self::$returnArrayAsType = $returnArrayAsType;
+
+
+ if ($result === null) {
+ return 0;
+ } elseif((is_float($result)) && ((is_nan($result)) || (is_infinite($result)))) {
+ return Calculation_Functions::NaN();
+ }
+ return $result;
+ } // function calculateCellValue(
+
+
+ /**
+ * Validate and parse a formula string
+ *
+ * @param string $formula Formula to parse
+ * @return array
+ * @throws Calculation_Exception
+ */
+ public function parseFormula($formula) {
+ // Basic validation that this is indeed a formula
+ // We return an empty array if not
+ $formula = trim($formula);
+ if ((!isset($formula{0})) || ($formula{0} != '=')) return array();
+ $formula = ltrim(substr($formula,1));
+ if (!isset($formula{0})) return array();
+
+ // Parse the formula and return the token stack
+ return $this->_parseFormula($formula);
+ } // function parseFormula()
+
+
+ /**
+ * Calculate the value of a formula
+ *
+ * @param string $formula Formula to parse
+ * @param string $cellID Address of the cell to calculate
+ * @param PHPExcel\Cell $pCell Cell to calculate
+ * @return mixed
+ * @throws Calculation_Exception
+ */
+ public function calculateFormula($formula, $cellID=null, Cell $pCell = null) {
+ // Initialise the logging settings
+ $this->formulaError = null;
+ $this->_debugLog->clearLog();
+ $this->_cyclicReferenceStack->clear();
+
+ // Disable calculation cacheing because it only applies to cell calculations, not straight formulae
+ // But don't actually flush any cache
+ $resetCache = $this->getCalculationCacheEnabled();
+ $this->_calculationCacheEnabled = false;
+ // Execute the calculation
+ try {
+ $result = self::_unwrapResult($this->_calculateFormulaValue($formula, $cellID, $pCell));
+ } catch (Exception $e) {
+ throw new Calculation_Exception($e->getMessage());
+ }
+
+ // Reset calculation cacheing to its previous state
+ $this->_calculationCacheEnabled = $resetCache;
+
+ return $result;
+ } // function calculateFormula()
public function getValueFromCache($worksheetName, $cellID, &$cellValue) {
- // Is calculation cacheing enabled?
- // Is the value present in calculation cache?
+ // Is calculation cacheing enabled?
+ // Is the value present in calculation cache?
//echo 'Test cache for ',$worksheetName,'!',$cellID,PHP_EOL;
- $this->_debugLog->writeDebugLog('Testing cache value for cell ', $worksheetName, '!', $cellID);
- if (($this->_calculationCacheEnabled) && (isset($this->_calculationCache[$worksheetName][$cellID]))) {
+ $this->_debugLog->writeDebugLog('Testing cache value for cell ', $worksheetName, '!', $cellID);
+ if (($this->_calculationCacheEnabled) && (isset($this->_calculationCache[$worksheetName][$cellID]))) {
//echo 'Retrieve from cache',PHP_EOL;
- $this->_debugLog->writeDebugLog('Retrieving value for cell ', $worksheetName, '!', $cellID, ' from cache');
- // Return the cached result
- $cellValue = $this->_calculationCache[$worksheetName][$cellID];
- return TRUE;
- }
- return FALSE;
+ $this->_debugLog->writeDebugLog('Retrieving value for cell ', $worksheetName, '!', $cellID, ' from cache');
+ // Return the cached result
+ $cellValue = $this->_calculationCache[$worksheetName][$cellID];
+ return TRUE;
+ }
+ return false;
}
public function saveValueToCache($worksheetName, $cellID, $cellValue) {
- if ($this->_calculationCacheEnabled) {
- $this->_calculationCache[$worksheetName][$cellID] = $cellValue;
- }
- }
+ if ($this->_calculationCacheEnabled) {
+ $this->_calculationCache[$worksheetName][$cellID] = $cellValue;
+ }
+ }
- /**
- * Parse a cell formula and calculate its value
- *
- * @param string $formula The formula to parse and calculate
- * @param string $cellID The ID (e.g. A3) of the cell that we are calculating
- * @param PHPExcel\Cell $pCell Cell to calculate
- * @return mixed
- * @throws Calculation_Exception
- */
- public function _calculateFormulaValue($formula, $cellID=null, Cell $pCell = null) {
- $cellValue = '';
+ /**
+ * Parse a cell formula and calculate its value
+ *
+ * @param string $formula The formula to parse and calculate
+ * @param string $cellID The ID (e.g. A3) of the cell that we are calculating
+ * @param PHPExcel\Cell $pCell Cell to calculate
+ * @return mixed
+ * @throws Calculation_Exception
+ */
+ public function _calculateFormulaValue($formula, $cellID=null, Cell $pCell = null) {
+ $cellValue = '';
- // Basic validation that this is indeed a formula
- // We simply return the cell value if not
- $formula = trim($formula);
- if ($formula{0} != '=') return self::_wrapResult($formula);
- $formula = ltrim(substr($formula,1));
- if (!isset($formula{0})) return self::_wrapResult($formula);
+ // Basic validation that this is indeed a formula
+ // We simply return the cell value if not
+ $formula = trim($formula);
+ if ($formula{0} != '=') return self::_wrapResult($formula);
+ $formula = ltrim(substr($formula,1));
+ if (!isset($formula{0})) return self::_wrapResult($formula);
- $pCellParent = ($pCell !== NULL) ? $pCell->getWorksheet() : NULL;
- $wsTitle = ($pCellParent !== NULL) ? $pCellParent->getTitle() : "\x00Wrk";
+ $pCellParent = ($pCell !== null) ? $pCell->getWorksheet() : null;
+ $wsTitle = ($pCellParent !== null) ? $pCellParent->getTitle() : "\x00Wrk";
- if (($cellID !== NULL) && ($this->getValueFromCache($wsTitle, $cellID, $cellValue))) {
- return $cellValue;
- }
+ if (($cellID !== null) && ($this->getValueFromCache($wsTitle, $cellID, $cellValue))) {
+ return $cellValue;
+ }
- if (($wsTitle{0} !== "\x00") && ($this->_cyclicReferenceStack->onStack($wsTitle.'!'.$cellID))) {
- if ($this->cyclicFormulaCount <= 0) {
- return $this->_raiseFormulaError('Cyclic Reference in Formula');
- } elseif (($this->_cyclicFormulaCount >= $this->cyclicFormulaCount) &&
- ($this->_cyclicFormulaCell == $wsTitle.'!'.$cellID)) {
- return $cellValue;
- } elseif ($this->_cyclicFormulaCell == $wsTitle.'!'.$cellID) {
- ++$this->_cyclicFormulaCount;
- if ($this->_cyclicFormulaCount >= $this->cyclicFormulaCount) {
- return $cellValue;
- }
- } elseif ($this->_cyclicFormulaCell == '') {
- $this->_cyclicFormulaCell = $wsTitle.'!'.$cellID;
- if ($this->_cyclicFormulaCount >= $this->cyclicFormulaCount) {
- return $cellValue;
- }
- }
- }
+ if (($wsTitle{0} !== "\x00") && ($this->_cyclicReferenceStack->onStack($wsTitle.'!'.$cellID))) {
+ if ($this->cyclicFormulaCount <= 0) {
+ return $this->_raiseFormulaError('Cyclic Reference in Formula');
+ } elseif (($this->_cyclicFormulaCount >= $this->cyclicFormulaCount) &&
+ ($this->_cyclicFormulaCell == $wsTitle.'!'.$cellID)) {
+ return $cellValue;
+ } elseif ($this->_cyclicFormulaCell == $wsTitle.'!'.$cellID) {
+ ++$this->_cyclicFormulaCount;
+ if ($this->_cyclicFormulaCount >= $this->cyclicFormulaCount) {
+ return $cellValue;
+ }
+ } elseif ($this->_cyclicFormulaCell == '') {
+ $this->_cyclicFormulaCell = $wsTitle.'!'.$cellID;
+ if ($this->_cyclicFormulaCount >= $this->cyclicFormulaCount) {
+ return $cellValue;
+ }
+ }
+ }
- // Parse the formula onto the token stack and calculate the value
- $this->_cyclicReferenceStack->push($wsTitle.'!'.$cellID);
- $cellValue = $this->_processTokenStack($this->_parseFormula($formula, $pCell), $cellID, $pCell);
- $this->_cyclicReferenceStack->pop();
+ // Parse the formula onto the token stack and calculate the value
+ $this->_cyclicReferenceStack->push($wsTitle.'!'.$cellID);
+ $cellValue = $this->_processTokenStack($this->_parseFormula($formula, $pCell), $cellID, $pCell);
+ $this->_cyclicReferenceStack->pop();
- // Save to calculation cache
- if ($cellID !== NULL) {
- $this->saveValueToCache($wsTitle, $cellID, $cellValue);
- }
+ // Save to calculation cache
+ if ($cellID !== null) {
+ $this->saveValueToCache($wsTitle, $cellID, $cellValue);
+ }
- // Return the calculated value
- return $cellValue;
- } // function _calculateFormulaValue()
+ // Return the calculated value
+ return $cellValue;
+ } // function _calculateFormulaValue()
- /**
- * Ensure that paired matrix operands are both matrices and of the same size
- *
- * @param mixed &$operand1 First matrix operand
- * @param mixed &$operand2 Second matrix operand
- * @param integer $resize Flag indicating whether the matrices should be resized to match
- * and (if so), whether the smaller dimension should grow or the
- * larger should shrink.
- * 0 = no resize
- * 1 = shrink to fit
- * 2 = extend to fit
- */
- private static function _checkMatrixOperands(&$operand1,&$operand2,$resize = 1) {
- // Examine each of the two operands, and turn them into an array if they aren't one already
- // Note that this function should only be called if one or both of the operand is already an array
- if (!is_array($operand1)) {
- list($matrixRows,$matrixColumns) = self::_getMatrixDimensions($operand2);
- $operand1 = array_fill(0,$matrixRows,array_fill(0,$matrixColumns,$operand1));
- $resize = 0;
- } elseif (!is_array($operand2)) {
- list($matrixRows,$matrixColumns) = self::_getMatrixDimensions($operand1);
- $operand2 = array_fill(0,$matrixRows,array_fill(0,$matrixColumns,$operand2));
- $resize = 0;
- }
+ /**
+ * Ensure that paired matrix operands are both matrices and of the same size
+ *
+ * @param mixed &$operand1 First matrix operand
+ * @param mixed &$operand2 Second matrix operand
+ * @param integer $resize Flag indicating whether the matrices should be resized to match
+ * and (if so), whether the smaller dimension should grow or the
+ * larger should shrink.
+ * 0 = no resize
+ * 1 = shrink to fit
+ * 2 = extend to fit
+ */
+ private static function _checkMatrixOperands(&$operand1,&$operand2,$resize = 1) {
+ // Examine each of the two operands, and turn them into an array if they aren't one already
+ // Note that this function should only be called if one or both of the operand is already an array
+ if (!is_array($operand1)) {
+ list($matrixRows,$matrixColumns) = self::_getMatrixDimensions($operand2);
+ $operand1 = array_fill(0,$matrixRows,array_fill(0,$matrixColumns,$operand1));
+ $resize = 0;
+ } elseif (!is_array($operand2)) {
+ list($matrixRows,$matrixColumns) = self::_getMatrixDimensions($operand1);
+ $operand2 = array_fill(0,$matrixRows,array_fill(0,$matrixColumns,$operand2));
+ $resize = 0;
+ }
- list($matrix1Rows,$matrix1Columns) = self::_getMatrixDimensions($operand1);
- list($matrix2Rows,$matrix2Columns) = self::_getMatrixDimensions($operand2);
- if (($matrix1Rows == $matrix2Columns) && ($matrix2Rows == $matrix1Columns)) {
- $resize = 1;
- }
+ list($matrix1Rows,$matrix1Columns) = self::_getMatrixDimensions($operand1);
+ list($matrix2Rows,$matrix2Columns) = self::_getMatrixDimensions($operand2);
+ if (($matrix1Rows == $matrix2Columns) && ($matrix2Rows == $matrix1Columns)) {
+ $resize = 1;
+ }
- if ($resize == 2) {
- // Given two matrices of (potentially) unequal size, convert the smaller in each dimension to match the larger
- self::_resizeMatricesExtend($operand1,$operand2,$matrix1Rows,$matrix1Columns,$matrix2Rows,$matrix2Columns);
- } elseif ($resize == 1) {
- // Given two matrices of (potentially) unequal size, convert the larger in each dimension to match the smaller
- self::_resizeMatricesShrink($operand1,$operand2,$matrix1Rows,$matrix1Columns,$matrix2Rows,$matrix2Columns);
- }
- return array( $matrix1Rows,$matrix1Columns,$matrix2Rows,$matrix2Columns);
- } // function _checkMatrixOperands()
+ if ($resize == 2) {
+ // Given two matrices of (potentially) unequal size, convert the smaller in each dimension to match the larger
+ self::_resizeMatricesExtend($operand1,$operand2,$matrix1Rows,$matrix1Columns,$matrix2Rows,$matrix2Columns);
+ } elseif ($resize == 1) {
+ // Given two matrices of (potentially) unequal size, convert the larger in each dimension to match the smaller
+ self::_resizeMatricesShrink($operand1,$operand2,$matrix1Rows,$matrix1Columns,$matrix2Rows,$matrix2Columns);
+ }
+ return array( $matrix1Rows,$matrix1Columns,$matrix2Rows,$matrix2Columns);
+ } // function _checkMatrixOperands()
- /**
- * Read the dimensions of a matrix, and re-index it with straight numeric keys starting from row 0, column 0
- *
- * @param mixed &$matrix matrix operand
- * @return array An array comprising the number of rows, and number of columns
- */
- public static function _getMatrixDimensions(&$matrix) {
- $matrixRows = count($matrix);
- $matrixColumns = 0;
- foreach($matrix as $rowKey => $rowValue) {
- $matrixColumns = max(count($rowValue),$matrixColumns);
- if (!is_array($rowValue)) {
- $matrix[$rowKey] = array($rowValue);
- } else {
- $matrix[$rowKey] = array_values($rowValue);
- }
- }
- $matrix = array_values($matrix);
- return array($matrixRows,$matrixColumns);
- } // function _getMatrixDimensions()
+ /**
+ * Read the dimensions of a matrix, and re-index it with straight numeric keys starting from row 0, column 0
+ *
+ * @param mixed &$matrix matrix operand
+ * @return array An array comprising the number of rows, and number of columns
+ */
+ public static function _getMatrixDimensions(&$matrix) {
+ $matrixRows = count($matrix);
+ $matrixColumns = 0;
+ foreach($matrix as $rowKey => $rowValue) {
+ $matrixColumns = max(count($rowValue),$matrixColumns);
+ if (!is_array($rowValue)) {
+ $matrix[$rowKey] = array($rowValue);
+ } else {
+ $matrix[$rowKey] = array_values($rowValue);
+ }
+ }
+ $matrix = array_values($matrix);
+ return array($matrixRows,$matrixColumns);
+ } // function _getMatrixDimensions()
- /**
- * Ensure that paired matrix operands are both matrices of the same size
- *
- * @param mixed &$matrix1 First matrix operand
- * @param mixed &$matrix2 Second matrix operand
- * @param integer $matrix1Rows Row size of first matrix operand
- * @param integer $matrix1Columns Column size of first matrix operand
- * @param integer $matrix2Rows Row size of second matrix operand
- * @param integer $matrix2Columns Column size of second matrix operand
- */
- private static function _resizeMatricesShrink(&$matrix1,&$matrix2,$matrix1Rows,$matrix1Columns,$matrix2Rows,$matrix2Columns) {
- if (($matrix2Columns < $matrix1Columns) || ($matrix2Rows < $matrix1Rows)) {
- if ($matrix2Rows < $matrix1Rows) {
- for ($i = $matrix2Rows; $i < $matrix1Rows; ++$i) {
- unset($matrix1[$i]);
- }
- }
- if ($matrix2Columns < $matrix1Columns) {
- for ($i = 0; $i < $matrix1Rows; ++$i) {
- for ($j = $matrix2Columns; $j < $matrix1Columns; ++$j) {
- unset($matrix1[$i][$j]);
- }
- }
- }
- }
+ /**
+ * Ensure that paired matrix operands are both matrices of the same size
+ *
+ * @param mixed &$matrix1 First matrix operand
+ * @param mixed &$matrix2 Second matrix operand
+ * @param integer $matrix1Rows Row size of first matrix operand
+ * @param integer $matrix1Columns Column size of first matrix operand
+ * @param integer $matrix2Rows Row size of second matrix operand
+ * @param integer $matrix2Columns Column size of second matrix operand
+ */
+ private static function _resizeMatricesShrink(&$matrix1,&$matrix2,$matrix1Rows,$matrix1Columns,$matrix2Rows,$matrix2Columns) {
+ if (($matrix2Columns < $matrix1Columns) || ($matrix2Rows < $matrix1Rows)) {
+ if ($matrix2Rows < $matrix1Rows) {
+ for ($i = $matrix2Rows; $i < $matrix1Rows; ++$i) {
+ unset($matrix1[$i]);
+ }
+ }
+ if ($matrix2Columns < $matrix1Columns) {
+ for ($i = 0; $i < $matrix1Rows; ++$i) {
+ for ($j = $matrix2Columns; $j < $matrix1Columns; ++$j) {
+ unset($matrix1[$i][$j]);
+ }
+ }
+ }
+ }
- if (($matrix1Columns < $matrix2Columns) || ($matrix1Rows < $matrix2Rows)) {
- if ($matrix1Rows < $matrix2Rows) {
- for ($i = $matrix1Rows; $i < $matrix2Rows; ++$i) {
- unset($matrix2[$i]);
- }
- }
- if ($matrix1Columns < $matrix2Columns) {
- for ($i = 0; $i < $matrix2Rows; ++$i) {
- for ($j = $matrix1Columns; $j < $matrix2Columns; ++$j) {
- unset($matrix2[$i][$j]);
- }
- }
- }
- }
- } // function _resizeMatricesShrink()
+ if (($matrix1Columns < $matrix2Columns) || ($matrix1Rows < $matrix2Rows)) {
+ if ($matrix1Rows < $matrix2Rows) {
+ for ($i = $matrix1Rows; $i < $matrix2Rows; ++$i) {
+ unset($matrix2[$i]);
+ }
+ }
+ if ($matrix1Columns < $matrix2Columns) {
+ for ($i = 0; $i < $matrix2Rows; ++$i) {
+ for ($j = $matrix1Columns; $j < $matrix2Columns; ++$j) {
+ unset($matrix2[$i][$j]);
+ }
+ }
+ }
+ }
+ } // function _resizeMatricesShrink()
- /**
- * Ensure that paired matrix operands are both matrices of the same size
- *
- * @param mixed &$matrix1 First matrix operand
- * @param mixed &$matrix2 Second matrix operand
- * @param integer $matrix1Rows Row size of first matrix operand
- * @param integer $matrix1Columns Column size of first matrix operand
- * @param integer $matrix2Rows Row size of second matrix operand
- * @param integer $matrix2Columns Column size of second matrix operand
- */
- private static function _resizeMatricesExtend(&$matrix1,&$matrix2,$matrix1Rows,$matrix1Columns,$matrix2Rows,$matrix2Columns) {
- if (($matrix2Columns < $matrix1Columns) || ($matrix2Rows < $matrix1Rows)) {
- if ($matrix2Columns < $matrix1Columns) {
- for ($i = 0; $i < $matrix2Rows; ++$i) {
- $x = $matrix2[$i][$matrix2Columns-1];
- for ($j = $matrix2Columns; $j < $matrix1Columns; ++$j) {
- $matrix2[$i][$j] = $x;
- }
- }
- }
- if ($matrix2Rows < $matrix1Rows) {
- $x = $matrix2[$matrix2Rows-1];
- for ($i = 0; $i < $matrix1Rows; ++$i) {
- $matrix2[$i] = $x;
- }
- }
- }
+ /**
+ * Ensure that paired matrix operands are both matrices of the same size
+ *
+ * @param mixed &$matrix1 First matrix operand
+ * @param mixed &$matrix2 Second matrix operand
+ * @param integer $matrix1Rows Row size of first matrix operand
+ * @param integer $matrix1Columns Column size of first matrix operand
+ * @param integer $matrix2Rows Row size of second matrix operand
+ * @param integer $matrix2Columns Column size of second matrix operand
+ */
+ private static function _resizeMatricesExtend(&$matrix1,&$matrix2,$matrix1Rows,$matrix1Columns,$matrix2Rows,$matrix2Columns) {
+ if (($matrix2Columns < $matrix1Columns) || ($matrix2Rows < $matrix1Rows)) {
+ if ($matrix2Columns < $matrix1Columns) {
+ for ($i = 0; $i < $matrix2Rows; ++$i) {
+ $x = $matrix2[$i][$matrix2Columns-1];
+ for ($j = $matrix2Columns; $j < $matrix1Columns; ++$j) {
+ $matrix2[$i][$j] = $x;
+ }
+ }
+ }
+ if ($matrix2Rows < $matrix1Rows) {
+ $x = $matrix2[$matrix2Rows-1];
+ for ($i = 0; $i < $matrix1Rows; ++$i) {
+ $matrix2[$i] = $x;
+ }
+ }
+ }
- if (($matrix1Columns < $matrix2Columns) || ($matrix1Rows < $matrix2Rows)) {
- if ($matrix1Columns < $matrix2Columns) {
- for ($i = 0; $i < $matrix1Rows; ++$i) {
- $x = $matrix1[$i][$matrix1Columns-1];
- for ($j = $matrix1Columns; $j < $matrix2Columns; ++$j) {
- $matrix1[$i][$j] = $x;
- }
- }
- }
- if ($matrix1Rows < $matrix2Rows) {
- $x = $matrix1[$matrix1Rows-1];
- for ($i = 0; $i < $matrix2Rows; ++$i) {
- $matrix1[$i] = $x;
- }
- }
- }
- } // function _resizeMatricesExtend()
+ if (($matrix1Columns < $matrix2Columns) || ($matrix1Rows < $matrix2Rows)) {
+ if ($matrix1Columns < $matrix2Columns) {
+ for ($i = 0; $i < $matrix1Rows; ++$i) {
+ $x = $matrix1[$i][$matrix1Columns-1];
+ for ($j = $matrix1Columns; $j < $matrix2Columns; ++$j) {
+ $matrix1[$i][$j] = $x;
+ }
+ }
+ }
+ if ($matrix1Rows < $matrix2Rows) {
+ $x = $matrix1[$matrix1Rows-1];
+ for ($i = 0; $i < $matrix2Rows; ++$i) {
+ $matrix1[$i] = $x;
+ }
+ }
+ }
+ } // function _resizeMatricesExtend()
- /**
- * Format details of an operand for display in the log (based on operand type)
- *
- * @param mixed $value First matrix operand
- * @return mixed
- */
- private function _showValue($value) {
- if ($this->_debugLog->getWriteDebugLog()) {
- $testArray = Calculation_Functions::flattenArray($value);
- if (count($testArray) == 1) {
- $value = array_pop($testArray);
- }
+ /**
+ * Format details of an operand for display in the log (based on operand type)
+ *
+ * @param mixed $value First matrix operand
+ * @return mixed
+ */
+ private function _showValue($value) {
+ if ($this->_debugLog->getWriteDebugLog()) {
+ $testArray = Calculation_Functions::flattenArray($value);
+ if (count($testArray) == 1) {
+ $value = array_pop($testArray);
+ }
- if (is_array($value)) {
- $returnMatrix = array();
- $pad = $rpad = ', ';
- foreach($value as $row) {
- if (is_array($row)) {
- $returnMatrix[] = implode($pad,array_map(array($this,'_showValue'),$row));
- $rpad = '; ';
- } else {
- $returnMatrix[] = $this->_showValue($row);
- }
- }
- return '{ '.implode($rpad,$returnMatrix).' }';
- } elseif(is_string($value) && (trim($value,'"') == $value)) {
- return '"'.$value.'"';
- } elseif(is_bool($value)) {
- return ($value) ? self::$_localeBoolean['TRUE'] : self::$_localeBoolean['FALSE'];
- }
- }
- return Calculation_Functions::flattenSingleValue($value);
- } // function _showValue()
+ if (is_array($value)) {
+ $returnMatrix = array();
+ $pad = $rpad = ', ';
+ foreach($value as $row) {
+ if (is_array($row)) {
+ $returnMatrix[] = implode($pad,array_map(array($this,'_showValue'),$row));
+ $rpad = '; ';
+ } else {
+ $returnMatrix[] = $this->_showValue($row);
+ }
+ }
+ return '{ '.implode($rpad,$returnMatrix).' }';
+ } elseif(is_string($value) && (trim($value,'"') == $value)) {
+ return '"'.$value.'"';
+ } elseif(is_bool($value)) {
+ return ($value) ? self::$_localeBoolean['TRUE'] : self::$_localeBoolean['FALSE'];
+ }
+ }
+ return Calculation_Functions::flattenSingleValue($value);
+ } // function _showValue()
- /**
- * Format type and details of an operand for display in the log (based on operand type)
- *
- * @param mixed $value First matrix operand
- * @return mixed
- */
- private function _showTypeDetails($value) {
- if ($this->_debugLog->getWriteDebugLog()) {
- $testArray = Calculation_Functions::flattenArray($value);
- if (count($testArray) == 1) {
- $value = array_pop($testArray);
- }
+ /**
+ * Format type and details of an operand for display in the log (based on operand type)
+ *
+ * @param mixed $value First matrix operand
+ * @return mixed
+ */
+ private function _showTypeDetails($value) {
+ if ($this->_debugLog->getWriteDebugLog()) {
+ $testArray = Calculation_Functions::flattenArray($value);
+ if (count($testArray) == 1) {
+ $value = array_pop($testArray);
+ }
- if ($value === NULL) {
- return 'a NULL value';
- } elseif (is_float($value)) {
- $typeString = 'a floating point number';
- } elseif(is_int($value)) {
- $typeString = 'an integer number';
- } elseif(is_bool($value)) {
- $typeString = 'a boolean';
- } elseif(is_array($value)) {
- $typeString = 'a matrix';
- } else {
- if ($value == '') {
- return 'an empty string';
- } elseif ($value{0} == '#') {
- return 'a '.$value.' error';
- } else {
- $typeString = 'a string';
- }
- }
- return $typeString.' with a value of '.$this->_showValue($value);
- }
- } // function _showTypeDetails()
+ if ($value === null) {
+ return 'a NULL value';
+ } elseif (is_float($value)) {
+ $typeString = 'a floating point number';
+ } elseif(is_int($value)) {
+ $typeString = 'an integer number';
+ } elseif(is_bool($value)) {
+ $typeString = 'a boolean';
+ } elseif(is_array($value)) {
+ $typeString = 'a matrix';
+ } else {
+ if ($value == '') {
+ return 'an empty string';
+ } elseif ($value{0} == '#') {
+ return 'a '.$value.' error';
+ } else {
+ $typeString = 'a string';
+ }
+ }
+ return $typeString.' with a value of '.$this->_showValue($value);
+ }
+ } // function _showTypeDetails()
- private static function _convertMatrixReferences($formula) {
- static $matrixReplaceFrom = array('{',';','}');
- static $matrixReplaceTo = array('MKMATRIX(MKMATRIX(','),MKMATRIX(','))');
+ private static function _convertMatrixReferences($formula) {
+ static $matrixReplaceFrom = array('{',';','}');
+ static $matrixReplaceTo = array('MKMATRIX(MKMATRIX(','),MKMATRIX(','))');
- // Convert any Excel matrix references to the MKMATRIX() function
- if (strpos($formula,'{') !== FALSE) {
- // If there is the possibility of braces within a quoted string, then we don't treat those as matrix indicators
- if (strpos($formula,'"') !== FALSE) {
- // So instead we skip replacing in any quoted strings by only replacing in every other array element after we've exploded
- // the formula
- $temp = explode('"',$formula);
- // Open and Closed counts used for trapping mismatched braces in the formula
- $openCount = $closeCount = 0;
- $i = FALSE;
- foreach($temp as &$value) {
- // Only count/replace in alternating array entries
- if ($i = !$i) {
- $openCount += substr_count($value,'{');
- $closeCount += substr_count($value,'}');
- $value = str_replace($matrixReplaceFrom,$matrixReplaceTo,$value);
- }
- }
- unset($value);
- // Then rebuild the formula string
- $formula = implode('"',$temp);
- } else {
- // If there's no quoted strings, then we do a simple count/replace
- $openCount = substr_count($formula,'{');
- $closeCount = substr_count($formula,'}');
- $formula = str_replace($matrixReplaceFrom,$matrixReplaceTo,$formula);
- }
- // Trap for mismatched braces and trigger an appropriate error
- if ($openCount < $closeCount) {
- if ($openCount > 0) {
- return $this->_raiseFormulaError("Formula Error: Mismatched matrix braces '}'");
- } else {
- return $this->_raiseFormulaError("Formula Error: Unexpected '}' encountered");
- }
- } elseif ($openCount > $closeCount) {
- if ($closeCount > 0) {
- return $this->_raiseFormulaError("Formula Error: Mismatched matrix braces '{'");
- } else {
- return $this->_raiseFormulaError("Formula Error: Unexpected '{' encountered");
- }
- }
- }
+ // Convert any Excel matrix references to the MKMATRIX() function
+ if (strpos($formula,'{') !== false) {
+ // If there is the possibility of braces within a quoted string, then we don't treat those as matrix indicators
+ if (strpos($formula,'"') !== false) {
+ // So instead we skip replacing in any quoted strings by only replacing in every other array element after we've exploded
+ // the formula
+ $temp = explode('"',$formula);
+ // Open and Closed counts used for trapping mismatched braces in the formula
+ $openCount = $closeCount = 0;
+ $i = false;
+ foreach($temp as &$value) {
+ // Only count/replace in alternating array entries
+ if ($i = !$i) {
+ $openCount += substr_count($value,'{');
+ $closeCount += substr_count($value,'}');
+ $value = str_replace($matrixReplaceFrom,$matrixReplaceTo,$value);
+ }
+ }
+ unset($value);
+ // Then rebuild the formula string
+ $formula = implode('"',$temp);
+ } else {
+ // If there's no quoted strings, then we do a simple count/replace
+ $openCount = substr_count($formula,'{');
+ $closeCount = substr_count($formula,'}');
+ $formula = str_replace($matrixReplaceFrom,$matrixReplaceTo,$formula);
+ }
+ // Trap for mismatched braces and trigger an appropriate error
+ if ($openCount < $closeCount) {
+ if ($openCount > 0) {
+ return $this->_raiseFormulaError("Formula Error: Mismatched matrix braces '}'");
+ } else {
+ return $this->_raiseFormulaError("Formula Error: Unexpected '}' encountered");
+ }
+ } elseif ($openCount > $closeCount) {
+ if ($closeCount > 0) {
+ return $this->_raiseFormulaError("Formula Error: Mismatched matrix braces '{'");
+ } else {
+ return $this->_raiseFormulaError("Formula Error: Unexpected '{' encountered");
+ }
+ }
+ }
- return $formula;
- } // function _convertMatrixReferences()
+ return $formula;
+ } // function _convertMatrixReferences()
- private static function _mkMatrix() {
- return func_get_args();
- } // function _mkMatrix()
+ private static function _mkMatrix() {
+ return func_get_args();
+ } // function _mkMatrix()
- // Binary Operators
- // These operators always work on two values
- // Array key is the operator, the value indicates whether this is a left or right associative operator
- private static $_operatorAssociativity = array(
- '^' => 0, // Exponentiation
- '*' => 0, '/' => 0, // Multiplication and Division
- '+' => 0, '-' => 0, // Addition and Subtraction
- '&' => 0, // Concatenation
- '|' => 0, ':' => 0, // Intersect and Range
- '>' => 0, '<' => 0, '=' => 0, '>=' => 0, '<=' => 0, '<>' => 0 // Comparison
- );
+ // Binary Operators
+ // These operators always work on two values
+ // Array key is the operator, the value indicates whether this is a left or right associative operator
+ private static $_operatorAssociativity = array(
+ '^' => 0, // Exponentiation
+ '*' => 0, '/' => 0, // Multiplication and Division
+ '+' => 0, '-' => 0, // Addition and Subtraction
+ '&' => 0, // Concatenation
+ '|' => 0, ':' => 0, // Intersect and Range
+ '>' => 0, '<' => 0, '=' => 0, '>=' => 0, '<=' => 0, '<>' => 0 // Comparison
+ );
- // Comparison (Boolean) Operators
- // These operators work on two values, but always return a boolean result
- private static $_comparisonOperators = array('>' => TRUE, '<' => TRUE, '=' => TRUE, '>=' => TRUE, '<=' => TRUE, '<>' => TRUE);
+ // Comparison (Boolean) Operators
+ // These operators work on two values, but always return a boolean result
+ private static $_comparisonOperators = array('>' => TRUE, '<' => TRUE, '=' => TRUE, '>=' => TRUE, '<=' => TRUE, '<>' => TRUE);
- // Operator Precedence
- // This list includes all valid operators, whether binary (including boolean) or unary (such as %)
- // Array key is the operator, the value is its precedence
- private static $_operatorPrecedence = array(
- ':' => 8, // Range
- '|' => 7, // Intersect
- '~' => 6, // Negation
- '%' => 5, // Percentage
- '^' => 4, // Exponentiation
- '*' => 3, '/' => 3, // Multiplication and Division
- '+' => 2, '-' => 2, // Addition and Subtraction
- '&' => 1, // Concatenation
- '>' => 0, '<' => 0, '=' => 0, '>=' => 0, '<=' => 0, '<>' => 0 // Comparison
- );
+ // Operator Precedence
+ // This list includes all valid operators, whether binary (including boolean) or unary (such as %)
+ // Array key is the operator, the value is its precedence
+ private static $_operatorPrecedence = array(
+ ':' => 8, // Range
+ '|' => 7, // Intersect
+ '~' => 6, // Negation
+ '%' => 5, // Percentage
+ '^' => 4, // Exponentiation
+ '*' => 3, '/' => 3, // Multiplication and Division
+ '+' => 2, '-' => 2, // Addition and Subtraction
+ '&' => 1, // Concatenation
+ '>' => 0, '<' => 0, '=' => 0, '>=' => 0, '<=' => 0, '<>' => 0 // Comparison
+ );
- // Convert infix to postfix notation
- private function _parseFormula($formula, Cell $pCell = NULL) {
- if (($formula = self::_convertMatrixReferences(trim($formula))) === FALSE) {
- return FALSE;
- }
+ // Convert infix to postfix notation
+ private function _parseFormula($formula, Cell $pCell = null) {
+ if (($formula = self::_convertMatrixReferences(trim($formula))) === false) {
+ return false;
+ }
- // If we're using cell caching, then $pCell may well be flushed back to the cache (which detaches the parent worksheet),
- // so we store the parent worksheet so that we can re-attach it when necessary
- $pCellParent = ($pCell !== NULL) ? $pCell->getWorksheet() : NULL;
+ // If we're using cell caching, then $pCell may well be flushed back to the cache (which detaches the parent worksheet),
+ // so we store the parent worksheet so that we can re-attach it when necessary
+ $pCellParent = ($pCell !== null) ? $pCell->getWorksheet() : null;
- $regexpMatchString = '/^('.self::CALCULATION_REGEXP_FUNCTION.
- '|'.self::CALCULATION_REGEXP_NUMBER.
- '|'.self::CALCULATION_REGEXP_STRING.
- '|'.self::CALCULATION_REGEXP_OPENBRACE.
- '|'.self::CALCULATION_REGEXP_CELLREF.
- '|'.self::CALCULATION_REGEXP_NAMEDRANGE.
- '|'.self::CALCULATION_REGEXP_ERROR.
- ')/si';
+ $regexpMatchString = '/^('.self::CALCULATION_REGEXP_FUNCTION.
+ '|'.self::CALCULATION_REGEXP_NUMBER.
+ '|'.self::CALCULATION_REGEXP_STRING.
+ '|'.self::CALCULATION_REGEXP_OPENBRACE.
+ '|'.self::CALCULATION_REGEXP_CELLREF.
+ '|'.self::CALCULATION_REGEXP_NAMEDRANGE.
+ '|'.self::CALCULATION_REGEXP_ERROR.
+ ')/si';
- // Start with initialisation
- $index = 0;
- $stack = new Calculation_Token_Stack;
- $output = array();
- $expectingOperator = FALSE; // We use this test in syntax-checking the expression to determine when a
- // - is a negation or + is a positive operator rather than an operation
- $expectingOperand = FALSE; // We use this test in syntax-checking the expression to determine whether an operand
- // should be null in a function call
- // The guts of the lexical parser
- // Loop through the formula extracting each operator and operand in turn
- while(TRUE) {
+ // Start with initialisation
+ $index = 0;
+ $stack = new Calculation_Token_Stack;
+ $output = array();
+ $expectingOperator = false; // We use this test in syntax-checking the expression to determine when a
+ // - is a negation or + is a positive operator rather than an operation
+ $expectingOperand = false; // We use this test in syntax-checking the expression to determine whether an operand
+ // should be null in a function call
+ // The guts of the lexical parser
+ // Loop through the formula extracting each operator and operand in turn
+ while(TRUE) {
//echo 'Assessing Expression '.substr($formula, $index),PHP_EOL;
- $opCharacter = $formula{$index}; // Get the first character of the value at the current index position
+ $opCharacter = $formula{$index}; // Get the first character of the value at the current index position
//echo 'Initial character of expression block is '.$opCharacter,PHP_EOL;
- if ((isset(self::$_comparisonOperators[$opCharacter])) && (strlen($formula) > $index) && (isset(self::$_comparisonOperators[$formula{$index+1}]))) {
- $opCharacter .= $formula{++$index};
+ if ((isset(self::$_comparisonOperators[$opCharacter])) && (strlen($formula) > $index) && (isset(self::$_comparisonOperators[$formula{$index+1}]))) {
+ $opCharacter .= $formula{++$index};
//echo 'Initial character of expression block is comparison operator '.$opCharacter.PHP_EOL;
- }
+ }
- // Find out if we're currently at the beginning of a number, variable, cell reference, function, parenthesis or operand
- $isOperandOrFunction = preg_match($regexpMatchString, substr($formula, $index), $match);
+ // Find out if we're currently at the beginning of a number, variable, cell reference, function, parenthesis or operand
+ $isOperandOrFunction = preg_match($regexpMatchString, substr($formula, $index), $match);
//echo '$isOperandOrFunction is '.(($isOperandOrFunction) ? 'True' : 'False').PHP_EOL;
//var_dump($match);
- if ($opCharacter == '-' && !$expectingOperator) { // Is it a negation instead of a minus?
+ if ($opCharacter == '-' && !$expectingOperator) { // Is it a negation instead of a minus?
//echo 'Element is a Negation operator',PHP_EOL;
- $stack->push('Unary Operator','~'); // Put a negation on the stack
- ++$index; // and drop the negation symbol
- } elseif ($opCharacter == '%' && $expectingOperator) {
+ $stack->push('Unary Operator','~'); // Put a negation on the stack
+ ++$index; // and drop the negation symbol
+ } elseif ($opCharacter == '%' && $expectingOperator) {
//echo 'Element is a Percentage operator',PHP_EOL;
- $stack->push('Unary Operator','%'); // Put a percentage on the stack
- ++$index;
- } elseif ($opCharacter == '+' && !$expectingOperator) { // Positive (unary plus rather than binary operator plus) can be discarded?
+ $stack->push('Unary Operator','%'); // Put a percentage on the stack
+ ++$index;
+ } elseif ($opCharacter == '+' && !$expectingOperator) { // Positive (unary plus rather than binary operator plus) can be discarded?
//echo 'Element is a Positive number, not Plus operator',PHP_EOL;
- ++$index; // Drop the redundant plus symbol
- } elseif ((($opCharacter == '~') || ($opCharacter == '|')) && (!$isOperandOrFunction)) { // We have to explicitly deny a tilde or pipe, because they are legal
- return $this->_raiseFormulaError("Formula Error: Illegal character '~'"); // on the stack but not in the input expression
+ ++$index; // Drop the redundant plus symbol
+ } elseif ((($opCharacter == '~') || ($opCharacter == '|')) && (!$isOperandOrFunction)) { // We have to explicitly deny a tilde or pipe, because they are legal
+ return $this->_raiseFormulaError("Formula Error: Illegal character '~'"); // on the stack but not in the input expression
- } elseif ((isset(self::$_operators[$opCharacter]) or $isOperandOrFunction) && $expectingOperator) { // Are we putting an operator on the stack?
+ } elseif ((isset(self::$_operators[$opCharacter]) or $isOperandOrFunction) && $expectingOperator) { // Are we putting an operator on the stack?
//echo 'Element with value '.$opCharacter.' is an Operator',PHP_EOL;
- while($stack->count() > 0 &&
- ($o2 = $stack->last()) &&
- isset(self::$_operators[$o2['value']]) &&
- @(self::$_operatorAssociativity[$opCharacter] ? self::$_operatorPrecedence[$opCharacter] < self::$_operatorPrecedence[$o2['value']] : self::$_operatorPrecedence[$opCharacter] <= self::$_operatorPrecedence[$o2['value']])) {
- $output[] = $stack->pop(); // Swap operands and higher precedence operators from the stack to the output
- }
- $stack->push('Binary Operator',$opCharacter); // Finally put our current operator onto the stack
- ++$index;
- $expectingOperator = FALSE;
+ while($stack->count() > 0 &&
+ ($o2 = $stack->last()) &&
+ isset(self::$_operators[$o2['value']]) &&
+ @(self::$_operatorAssociativity[$opCharacter] ? self::$_operatorPrecedence[$opCharacter] < self::$_operatorPrecedence[$o2['value']] : self::$_operatorPrecedence[$opCharacter] <= self::$_operatorPrecedence[$o2['value']])) {
+ $output[] = $stack->pop(); // Swap operands and higher precedence operators from the stack to the output
+ }
+ $stack->push('Binary Operator',$opCharacter); // Finally put our current operator onto the stack
+ ++$index;
+ $expectingOperator = false;
- } elseif ($opCharacter == ')' && $expectingOperator) { // Are we expecting to close a parenthesis?
+ } elseif ($opCharacter == ')' && $expectingOperator) { // Are we expecting to close a parenthesis?
//echo 'Element is a Closing bracket',PHP_EOL;
- $expectingOperand = FALSE;
- while (($o2 = $stack->pop()) && $o2['value'] != '(') { // Pop off the stack back to the last (
- if ($o2 === NULL) return $this->_raiseFormulaError('Formula Error: Unexpected closing brace ")"');
- else $output[] = $o2;
- }
- $d = $stack->last(2);
- if (preg_match('/^'.self::CALCULATION_REGEXP_FUNCTION.'$/i', $d['value'], $matches)) { // Did this parenthesis just close a function?
- $functionName = $matches[1]; // Get the function name
+ $expectingOperand = false;
+ while (($o2 = $stack->pop()) && $o2['value'] != '(') { // Pop off the stack back to the last (
+ if ($o2 === null) return $this->_raiseFormulaError('Formula Error: Unexpected closing brace ")"');
+ else $output[] = $o2;
+ }
+ $d = $stack->last(2);
+ if (preg_match('/^'.self::CALCULATION_REGEXP_FUNCTION.'$/i', $d['value'], $matches)) { // Did this parenthesis just close a function?
+ $functionName = $matches[1]; // Get the function name
//echo 'Closed Function is '.$functionName,PHP_EOL;
- $d = $stack->pop();
- $argumentCount = $d['value']; // See how many arguments there were (argument count is the next value stored on the stack)
+ $d = $stack->pop();
+ $argumentCount = $d['value']; // See how many arguments there were (argument count is the next value stored on the stack)
//if ($argumentCount == 0) {
-// echo 'With no arguments',PHP_EOL;
+// echo 'With no arguments',PHP_EOL;
//} elseif ($argumentCount == 1) {
-// echo 'With 1 argument',PHP_EOL;
+// echo 'With 1 argument',PHP_EOL;
//} else {
-// echo 'With '.$argumentCount.' arguments',PHP_EOL;
+// echo 'With '.$argumentCount.' arguments',PHP_EOL;
//}
- $output[] = $d; // Dump the argument count on the output
- $output[] = $stack->pop(); // Pop the function and push onto the output
- if (isset(self::$_controlFunctions[$functionName])) {
+ $output[] = $d; // Dump the argument count on the output
+ $output[] = $stack->pop(); // Pop the function and push onto the output
+ if (isset(self::$_controlFunctions[$functionName])) {
//echo 'Built-in function '.$functionName,PHP_EOL;
- $expectedArgumentCount = self::$_controlFunctions[$functionName]['argumentCount'];
- $functionCall = self::$_controlFunctions[$functionName]['functionCall'];
- } elseif (isset(self::$_PHPExcelFunctions[$functionName])) {
+ $expectedArgumentCount = self::$_controlFunctions[$functionName]['argumentCount'];
+ $functionCall = self::$_controlFunctions[$functionName]['functionCall'];
+ } elseif (isset(self::$_PHPExcelFunctions[$functionName])) {
//echo 'PHPExcel function '.$functionName,PHP_EOL;
- $expectedArgumentCount = self::$_PHPExcelFunctions[$functionName]['argumentCount'];
- $functionCall = self::$_PHPExcelFunctions[$functionName]['functionCall'];
- } else { // did we somehow push a non-function on the stack? this should never happen
- return $this->_raiseFormulaError("Formula Error: Internal error, non-function on stack");
- }
- // Check the argument count
- $argumentCountError = FALSE;
- if (is_numeric($expectedArgumentCount)) {
- if ($expectedArgumentCount < 0) {
+ $expectedArgumentCount = self::$_PHPExcelFunctions[$functionName]['argumentCount'];
+ $functionCall = self::$_PHPExcelFunctions[$functionName]['functionCall'];
+ } else { // did we somehow push a non-function on the stack? this should never happen
+ return $this->_raiseFormulaError("Formula Error: Internal error, non-function on stack");
+ }
+ // Check the argument count
+ $argumentCountError = false;
+ if (is_numeric($expectedArgumentCount)) {
+ if ($expectedArgumentCount < 0) {
//echo '$expectedArgumentCount is between 0 and '.abs($expectedArgumentCount),PHP_EOL;
- if ($argumentCount > abs($expectedArgumentCount)) {
- $argumentCountError = TRUE;
- $expectedArgumentCountString = 'no more than '.abs($expectedArgumentCount);
- }
- } else {
+ if ($argumentCount > abs($expectedArgumentCount)) {
+ $argumentCountError = TRUE;
+ $expectedArgumentCountString = 'no more than '.abs($expectedArgumentCount);
+ }
+ } else {
//echo '$expectedArgumentCount is numeric '.$expectedArgumentCount,PHP_EOL;
- if ($argumentCount != $expectedArgumentCount) {
- $argumentCountError = TRUE;
- $expectedArgumentCountString = $expectedArgumentCount;
- }
- }
- } elseif ($expectedArgumentCount != '*') {
- $isOperandOrFunction = preg_match('/(\d*)([-+,])(\d*)/',$expectedArgumentCount,$argMatch);
+ if ($argumentCount != $expectedArgumentCount) {
+ $argumentCountError = TRUE;
+ $expectedArgumentCountString = $expectedArgumentCount;
+ }
+ }
+ } elseif ($expectedArgumentCount != '*') {
+ $isOperandOrFunction = preg_match('/(\d*)([-+,])(\d*)/',$expectedArgumentCount,$argMatch);
//print_r($argMatch);
//echo PHP_EOL;
- switch ($argMatch[2]) {
- case '+' :
- if ($argumentCount < $argMatch[1]) {
- $argumentCountError = TRUE;
- $expectedArgumentCountString = $argMatch[1].' or more ';
- }
- break;
- case '-' :
- if (($argumentCount < $argMatch[1]) || ($argumentCount > $argMatch[3])) {
- $argumentCountError = TRUE;
- $expectedArgumentCountString = 'between '.$argMatch[1].' and '.$argMatch[3];
- }
- break;
- case ',' :
- if (($argumentCount != $argMatch[1]) && ($argumentCount != $argMatch[3])) {
- $argumentCountError = TRUE;
- $expectedArgumentCountString = 'either '.$argMatch[1].' or '.$argMatch[3];
- }
- break;
- }
- }
- if ($argumentCountError) {
- return $this->_raiseFormulaError("Formula Error: Wrong number of arguments for $functionName() function: $argumentCount given, ".$expectedArgumentCountString." expected");
- }
- }
- ++$index;
+ switch ($argMatch[2]) {
+ case '+' :
+ if ($argumentCount < $argMatch[1]) {
+ $argumentCountError = TRUE;
+ $expectedArgumentCountString = $argMatch[1].' or more ';
+ }
+ break;
+ case '-' :
+ if (($argumentCount < $argMatch[1]) || ($argumentCount > $argMatch[3])) {
+ $argumentCountError = TRUE;
+ $expectedArgumentCountString = 'between '.$argMatch[1].' and '.$argMatch[3];
+ }
+ break;
+ case ',' :
+ if (($argumentCount != $argMatch[1]) && ($argumentCount != $argMatch[3])) {
+ $argumentCountError = TRUE;
+ $expectedArgumentCountString = 'either '.$argMatch[1].' or '.$argMatch[3];
+ }
+ break;
+ }
+ }
+ if ($argumentCountError) {
+ return $this->_raiseFormulaError("Formula Error: Wrong number of arguments for $functionName() function: $argumentCount given, ".$expectedArgumentCountString." expected");
+ }
+ }
+ ++$index;
- } elseif ($opCharacter == ',') { // Is this the separator for function arguments?
+ } elseif ($opCharacter == ',') { // Is this the separator for function arguments?
//echo 'Element is a Function argument separator',PHP_EOL;
- while (($o2 = $stack->pop()) && $o2['value'] != '(') { // Pop off the stack back to the last (
- if ($o2 === NULL) return $this->_raiseFormulaError("Formula Error: Unexpected ,");
- else $output[] = $o2; // pop the argument expression stuff and push onto the output
- }
- // If we've a comma when we're expecting an operand, then what we actually have is a null operand;
- // so push a null onto the stack
- if (($expectingOperand) || (!$expectingOperator)) {
- $output[] = array('type' => 'NULL Value', 'value' => self::$_ExcelConstants['NULL'], 'reference' => NULL);
- }
- // make sure there was a function
- $d = $stack->last(2);
- if (!preg_match('/^'.self::CALCULATION_REGEXP_FUNCTION.'$/i', $d['value'], $matches))
- return $this->_raiseFormulaError("Formula Error: Unexpected ,");
- $d = $stack->pop();
- $stack->push($d['type'],++$d['value'],$d['reference']); // increment the argument count
- $stack->push('Brace', '('); // put the ( back on, we'll need to pop back to it again
- $expectingOperator = FALSE;
- $expectingOperand = TRUE;
- ++$index;
+ while (($o2 = $stack->pop()) && $o2['value'] != '(') { // Pop off the stack back to the last (
+ if ($o2 === null) return $this->_raiseFormulaError("Formula Error: Unexpected ,");
+ else $output[] = $o2; // pop the argument expression stuff and push onto the output
+ }
+ // If we've a comma when we're expecting an operand, then what we actually have is a null operand;
+ // so push a null onto the stack
+ if (($expectingOperand) || (!$expectingOperator)) {
+ $output[] = array('type' => 'NULL Value', 'value' => self::$_ExcelConstants['NULL'], 'reference' => null);
+ }
+ // make sure there was a function
+ $d = $stack->last(2);
+ if (!preg_match('/^'.self::CALCULATION_REGEXP_FUNCTION.'$/i', $d['value'], $matches))
+ return $this->_raiseFormulaError("Formula Error: Unexpected ,");
+ $d = $stack->pop();
+ $stack->push($d['type'],++$d['value'],$d['reference']); // increment the argument count
+ $stack->push('Brace', '('); // put the ( back on, we'll need to pop back to it again
+ $expectingOperator = false;
+ $expectingOperand = TRUE;
+ ++$index;
- } elseif ($opCharacter == '(' && !$expectingOperator) {
-// echo 'Element is an Opening Bracket
- * References:
- *
';
- $stack->push('Brace', '(');
- ++$index;
+ } elseif ($opCharacter == '(' && !$expectingOperator) {
+// echo 'Element is an Opening Bracket
';
+ $stack->push('Brace', '(');
+ ++$index;
- } elseif ($isOperandOrFunction && !$expectingOperator) { // do we now have a function/variable/number?
- $expectingOperator = TRUE;
- $expectingOperand = FALSE;
- $val = $match[1];
- $length = strlen($val);
-// echo 'Element with value '.$val.' is an Operand, Variable, Constant, String, Number, Cell Reference or Function
';
+ } elseif ($isOperandOrFunction && !$expectingOperator) { // do we now have a function/variable/number?
+ $expectingOperator = TRUE;
+ $expectingOperand = false;
+ $val = $match[1];
+ $length = strlen($val);
+// echo 'Element with value '.$val.' is an Operand, Variable, Constant, String, Number, Cell Reference or Function
';
- if (preg_match('/^'.self::CALCULATION_REGEXP_FUNCTION.'$/i', $val, $matches)) {
- $val = preg_replace('/\s/','',$val);
-// echo 'Element '.$val.' is a Function
';
- if (isset(self::$_PHPExcelFunctions[strtoupper($matches[1])]) || isset(self::$_controlFunctions[strtoupper($matches[1])])) { // it's a function
- $stack->push('Function', strtoupper($val));
- $ax = preg_match('/^\s*(\s*\))/i', substr($formula, $index+$length), $amatch);
- if ($ax) {
- $stack->push('Operand Count for Function '.strtoupper($val).')', 0);
- $expectingOperator = TRUE;
- } else {
- $stack->push('Operand Count for Function '.strtoupper($val).')', 1);
- $expectingOperator = FALSE;
- }
- $stack->push('Brace', '(');
- } else { // it's a var w/ implicit multiplication
- $output[] = array('type' => 'Value', 'value' => $matches[1], 'reference' => NULL);
- }
- } elseif (preg_match('/^'.self::CALCULATION_REGEXP_CELLREF.'$/i', $val, $matches)) {
-// echo 'Element '.$val.' is a Cell reference
';
- // Watch for this case-change when modifying to allow cell references in different worksheets...
- // Should only be applied to the actual cell column, not the worksheet name
+ if (preg_match('/^'.self::CALCULATION_REGEXP_FUNCTION.'$/i', $val, $matches)) {
+ $val = preg_replace('/\s/','',$val);
+// echo 'Element '.$val.' is a Function
';
+ if (isset(self::$_PHPExcelFunctions[strtoupper($matches[1])]) || isset(self::$_controlFunctions[strtoupper($matches[1])])) { // it's a function
+ $stack->push('Function', strtoupper($val));
+ $ax = preg_match('/^\s*(\s*\))/i', substr($formula, $index+$length), $amatch);
+ if ($ax) {
+ $stack->push('Operand Count for Function '.strtoupper($val).')', 0);
+ $expectingOperator = TRUE;
+ } else {
+ $stack->push('Operand Count for Function '.strtoupper($val).')', 1);
+ $expectingOperator = false;
+ }
+ $stack->push('Brace', '(');
+ } else { // it's a var w/ implicit multiplication
+ $output[] = array('type' => 'Value', 'value' => $matches[1], 'reference' => null);
+ }
+ } elseif (preg_match('/^'.self::CALCULATION_REGEXP_CELLREF.'$/i', $val, $matches)) {
+// echo 'Element '.$val.' is a Cell reference
';
+ // Watch for this case-change when modifying to allow cell references in different worksheets...
+ // Should only be applied to the actual cell column, not the worksheet name
- // If the last entry on the stack was a : operator, then we have a cell range reference
- $testPrevOp = $stack->last(1);
- if ($testPrevOp['value'] == ':') {
- // If we have a worksheet reference, then we're playing with a 3D reference
- if ($matches[2] == '') {
- // Otherwise, we 'inherit' the worksheet reference from the start cell reference
- // The start of the cell range reference should be the last entry in $output
- $startCellRef = $output[count($output)-1]['value'];
- preg_match('/^'.self::CALCULATION_REGEXP_CELLREF.'$/i', $startCellRef, $startMatches);
- if ($startMatches[2] > '') {
- $val = $startMatches[2].'!'.$val;
- }
- } else {
- return $this->_raiseFormulaError("3D Range references are not yet supported");
- }
- }
+ // If the last entry on the stack was a : operator, then we have a cell range reference
+ $testPrevOp = $stack->last(1);
+ if ($testPrevOp['value'] == ':') {
+ // If we have a worksheet reference, then we're playing with a 3D reference
+ if ($matches[2] == '') {
+ // Otherwise, we 'inherit' the worksheet reference from the start cell reference
+ // The start of the cell range reference should be the last entry in $output
+ $startCellRef = $output[count($output)-1]['value'];
+ preg_match('/^'.self::CALCULATION_REGEXP_CELLREF.'$/i', $startCellRef, $startMatches);
+ if ($startMatches[2] > '') {
+ $val = $startMatches[2].'!'.$val;
+ }
+ } else {
+ return $this->_raiseFormulaError("3D Range references are not yet supported");
+ }
+ }
- $output[] = array('type' => 'Cell Reference', 'value' => $val, 'reference' => $val);
-// $expectingOperator = FALSE;
- } else { // it's a variable, constant, string, number or boolean
-// echo 'Element is a Variable, Constant, String, Number or Boolean
';
- // If the last entry on the stack was a : operator, then we may have a row or column range reference
- $testPrevOp = $stack->last(1);
- if ($testPrevOp['value'] == ':') {
- $startRowColRef = $output[count($output)-1]['value'];
- $rangeWS1 = '';
- if (strpos('!',$startRowColRef) !== FALSE) {
- list($rangeWS1,$startRowColRef) = explode('!',$startRowColRef);
- }
- if ($rangeWS1 != '') $rangeWS1 .= '!';
- $rangeWS2 = $rangeWS1;
- if (strpos('!',$val) !== FALSE) {
- list($rangeWS2,$val) = explode('!',$val);
- }
- if ($rangeWS2 != '') $rangeWS2 .= '!';
- if ((is_integer($startRowColRef)) && (ctype_digit($val)) &&
- ($startRowColRef <= 1048576) && ($val <= 1048576)) {
- // Row range
- $endRowColRef = ($pCellParent !== NULL) ? $pCellParent->getHighestColumn() : 'XFD'; // Max 16,384 columns for Excel2007
- $output[count($output)-1]['value'] = $rangeWS1.'A'.$startRowColRef;
- $val = $rangeWS2.$endRowColRef.$val;
- } elseif ((ctype_alpha($startRowColRef)) && (ctype_alpha($val)) &&
- (strlen($startRowColRef) <= 3) && (strlen($val) <= 3)) {
- // Column range
- $endRowColRef = ($pCellParent !== NULL) ? $pCellParent->getHighestRow() : 1048576; // Max 1,048,576 rows for Excel2007
- $output[count($output)-1]['value'] = $rangeWS1.strtoupper($startRowColRef).'1';
- $val = $rangeWS2.$val.$endRowColRef;
- }
- }
+ $output[] = array('type' => 'Cell Reference', 'value' => $val, 'reference' => $val);
+// $expectingOperator = false;
+ } else { // it's a variable, constant, string, number or boolean
+// echo 'Element is a Variable, Constant, String, Number or Boolean
';
+ // If the last entry on the stack was a : operator, then we may have a row or column range reference
+ $testPrevOp = $stack->last(1);
+ if ($testPrevOp['value'] == ':') {
+ $startRowColRef = $output[count($output)-1]['value'];
+ $rangeWS1 = '';
+ if (strpos('!',$startRowColRef) !== false) {
+ list($rangeWS1,$startRowColRef) = explode('!',$startRowColRef);
+ }
+ if ($rangeWS1 != '') $rangeWS1 .= '!';
+ $rangeWS2 = $rangeWS1;
+ if (strpos('!',$val) !== false) {
+ list($rangeWS2,$val) = explode('!',$val);
+ }
+ if ($rangeWS2 != '') $rangeWS2 .= '!';
+ if ((is_integer($startRowColRef)) && (ctype_digit($val)) &&
+ ($startRowColRef <= 1048576) && ($val <= 1048576)) {
+ // Row range
+ $endRowColRef = ($pCellParent !== null) ? $pCellParent->getHighestColumn() : 'XFD'; // Max 16,384 columns for Excel2007
+ $output[count($output)-1]['value'] = $rangeWS1.'A'.$startRowColRef;
+ $val = $rangeWS2.$endRowColRef.$val;
+ } elseif ((ctype_alpha($startRowColRef)) && (ctype_alpha($val)) &&
+ (strlen($startRowColRef) <= 3) && (strlen($val) <= 3)) {
+ // Column range
+ $endRowColRef = ($pCellParent !== null) ? $pCellParent->getHighestRow() : 1048576; // Max 1,048,576 rows for Excel2007
+ $output[count($output)-1]['value'] = $rangeWS1.strtoupper($startRowColRef).'1';
+ $val = $rangeWS2.$val.$endRowColRef;
+ }
+ }
- $localeConstant = FALSE;
- if ($opCharacter == '"') {
-// echo 'Element is a String
';
- // UnEscape any quotes within the string
- $val = self::_wrapResult(str_replace('""','"',self::_unwrapResult($val)));
- } elseif (is_numeric($val)) {
-// echo 'Element is a Number
';
- if ((strpos($val,'.') !== FALSE) || (stripos($val,'e') !== FALSE) || ($val > PHP_INT_MAX) || ($val < -PHP_INT_MAX)) {
-// echo 'Casting '.$val.' to float
';
- $val = (float) $val;
- } else {
-// echo 'Casting '.$val.' to integer
';
- $val = (integer) $val;
- }
- } elseif (isset(self::$_ExcelConstants[trim(strtoupper($val))])) {
- $excelConstant = trim(strtoupper($val));
-// echo 'Element '.$excelConstant.' is an Excel Constant
';
- $val = self::$_ExcelConstants[$excelConstant];
- } elseif (($localeConstant = array_search(trim(strtoupper($val)), self::$_localeBoolean)) !== FALSE) {
-// echo 'Element '.$localeConstant.' is an Excel Constant
';
- $val = self::$_ExcelConstants[$localeConstant];
- }
- $details = array('type' => 'Value', 'value' => $val, 'reference' => NULL);
- if ($localeConstant) { $details['localeValue'] = $localeConstant; }
- $output[] = $details;
- }
- $index += $length;
+ $localeConstant = false;
+ if ($opCharacter == '"') {
+// echo 'Element is a String
';
+ // UnEscape any quotes within the string
+ $val = self::_wrapResult(str_replace('""','"',self::_unwrapResult($val)));
+ } elseif (is_numeric($val)) {
+// echo 'Element is a Number
';
+ if ((strpos($val,'.') !== false) || (stripos($val,'e') !== false) || ($val > PHP_INT_MAX) || ($val < -PHP_INT_MAX)) {
+// echo 'Casting '.$val.' to float
';
+ $val = (float) $val;
+ } else {
+// echo 'Casting '.$val.' to integer
';
+ $val = (integer) $val;
+ }
+ } elseif (isset(self::$_ExcelConstants[trim(strtoupper($val))])) {
+ $excelConstant = trim(strtoupper($val));
+// echo 'Element '.$excelConstant.' is an Excel Constant
';
+ $val = self::$_ExcelConstants[$excelConstant];
+ } elseif (($localeConstant = array_search(trim(strtoupper($val)), self::$_localeBoolean)) !== false) {
+// echo 'Element '.$localeConstant.' is an Excel Constant
';
+ $val = self::$_ExcelConstants[$localeConstant];
+ }
+ $details = array('type' => 'Value', 'value' => $val, 'reference' => null);
+ if ($localeConstant) { $details['localeValue'] = $localeConstant; }
+ $output[] = $details;
+ }
+ $index += $length;
- } elseif ($opCharacter == '$') { // absolute row or column range
- ++$index;
- } elseif ($opCharacter == ')') { // miscellaneous error checking
- if ($expectingOperand) {
- $output[] = array('type' => 'NULL Value', 'value' => self::$_ExcelConstants['NULL'], 'reference' => NULL);
- $expectingOperand = FALSE;
- $expectingOperator = TRUE;
- } else {
- return $this->_raiseFormulaError("Formula Error: Unexpected ')'");
- }
- } elseif (isset(self::$_operators[$opCharacter]) && !$expectingOperator) {
- return $this->_raiseFormulaError("Formula Error: Unexpected operator '$opCharacter'");
- } else { // I don't even want to know what you did to get here
- return $this->_raiseFormulaError("Formula Error: An unexpected error occured");
- }
- // Test for end of formula string
- if ($index == strlen($formula)) {
- // Did we end with an operator?.
- // Only valid for the % unary operator
- if ((isset(self::$_operators[$opCharacter])) && ($opCharacter != '%')) {
- return $this->_raiseFormulaError("Formula Error: Operator '$opCharacter' has no operands");
- } else {
- break;
- }
- }
- // Ignore white space
- while (($formula{$index} == "\n") || ($formula{$index} == "\r")) {
- ++$index;
- }
- if ($formula{$index} == ' ') {
- while ($formula{$index} == ' ') {
- ++$index;
- }
- // If we're expecting an operator, but only have a space between the previous and next operands (and both are
- // Cell References) then we have an INTERSECTION operator
-// echo 'Possible Intersect Operator
';
- if (($expectingOperator) && (preg_match('/^'.self::CALCULATION_REGEXP_CELLREF.'.*/Ui', substr($formula, $index), $match)) &&
- ($output[count($output)-1]['type'] == 'Cell Reference')) {
-// echo 'Element is an Intersect Operator
';
- while($stack->count() > 0 &&
- ($o2 = $stack->last()) &&
- isset(self::$_operators[$o2['value']]) &&
- @(self::$_operatorAssociativity[$opCharacter] ? self::$_operatorPrecedence[$opCharacter] < self::$_operatorPrecedence[$o2['value']] : self::$_operatorPrecedence[$opCharacter] <= self::$_operatorPrecedence[$o2['value']])) {
- $output[] = $stack->pop(); // Swap operands and higher precedence operators from the stack to the output
- }
- $stack->push('Binary Operator','|'); // Put an Intersect Operator on the stack
- $expectingOperator = FALSE;
- }
- }
- }
+ } elseif ($opCharacter == '$') { // absolute row or column range
+ ++$index;
+ } elseif ($opCharacter == ')') { // miscellaneous error checking
+ if ($expectingOperand) {
+ $output[] = array('type' => 'NULL Value', 'value' => self::$_ExcelConstants['NULL'], 'reference' => null);
+ $expectingOperand = false;
+ $expectingOperator = TRUE;
+ } else {
+ return $this->_raiseFormulaError("Formula Error: Unexpected ')'");
+ }
+ } elseif (isset(self::$_operators[$opCharacter]) && !$expectingOperator) {
+ return $this->_raiseFormulaError("Formula Error: Unexpected operator '$opCharacter'");
+ } else { // I don't even want to know what you did to get here
+ return $this->_raiseFormulaError("Formula Error: An unexpected error occured");
+ }
+ // Test for end of formula string
+ if ($index == strlen($formula)) {
+ // Did we end with an operator?.
+ // Only valid for the % unary operator
+ if ((isset(self::$_operators[$opCharacter])) && ($opCharacter != '%')) {
+ return $this->_raiseFormulaError("Formula Error: Operator '$opCharacter' has no operands");
+ } else {
+ break;
+ }
+ }
+ // Ignore white space
+ while (($formula{$index} == "\n") || ($formula{$index} == "\r")) {
+ ++$index;
+ }
+ if ($formula{$index} == ' ') {
+ while ($formula{$index} == ' ') {
+ ++$index;
+ }
+ // If we're expecting an operator, but only have a space between the previous and next operands (and both are
+ // Cell References) then we have an INTERSECTION operator
+// echo 'Possible Intersect Operator
';
+ if (($expectingOperator) && (preg_match('/^'.self::CALCULATION_REGEXP_CELLREF.'.*/Ui', substr($formula, $index), $match)) &&
+ ($output[count($output)-1]['type'] == 'Cell Reference')) {
+// echo 'Element is an Intersect Operator
';
+ while($stack->count() > 0 &&
+ ($o2 = $stack->last()) &&
+ isset(self::$_operators[$o2['value']]) &&
+ @(self::$_operatorAssociativity[$opCharacter] ? self::$_operatorPrecedence[$opCharacter] < self::$_operatorPrecedence[$o2['value']] : self::$_operatorPrecedence[$opCharacter] <= self::$_operatorPrecedence[$o2['value']])) {
+ $output[] = $stack->pop(); // Swap operands and higher precedence operators from the stack to the output
+ }
+ $stack->push('Binary Operator','|'); // Put an Intersect Operator on the stack
+ $expectingOperator = false;
+ }
+ }
+ }
- while (($op = $stack->pop()) !== NULL) { // pop everything off the stack and push onto output
- if ((is_array($op) && $op['value'] == '(') || ($op === '('))
- return $this->_raiseFormulaError("Formula Error: Expecting ')'"); // if there are any opening braces on the stack, then braces were unbalanced
- $output[] = $op;
- }
- return $output;
- } // function _parseFormula()
+ while (($op = $stack->pop()) !== null) { // pop everything off the stack and push onto output
+ if ((is_array($op) && $op['value'] == '(') || ($op === '('))
+ return $this->_raiseFormulaError("Formula Error: Expecting ')'"); // if there are any opening braces on the stack, then braces were unbalanced
+ $output[] = $op;
+ }
+ return $output;
+ } // function _parseFormula()
- private static function _dataTestReference(&$operandData)
- {
- $operand = $operandData['value'];
- if (($operandData['reference'] === NULL) && (is_array($operand))) {
- $rKeys = array_keys($operand);
- $rowKey = array_shift($rKeys);
- $cKeys = array_keys(array_keys($operand[$rowKey]));
- $colKey = array_shift($cKeys);
- if (ctype_upper($colKey)) {
- $operandData['reference'] = $colKey.$rowKey;
- }
- }
- return $operand;
- }
+ private static function _dataTestReference(&$operandData)
+ {
+ $operand = $operandData['value'];
+ if (($operandData['reference'] === null) && (is_array($operand))) {
+ $rKeys = array_keys($operand);
+ $rowKey = array_shift($rKeys);
+ $cKeys = array_keys(array_keys($operand[$rowKey]));
+ $colKey = array_shift($cKeys);
+ if (ctype_upper($colKey)) {
+ $operandData['reference'] = $colKey.$rowKey;
+ }
+ }
+ return $operand;
+ }
- // evaluate postfix notation
- private function _processTokenStack($tokens, $cellID = NULL, Cell $pCell = NULL) {
- if ($tokens == FALSE) return FALSE;
+ // evaluate postfix notation
+ private function _processTokenStack($tokens, $cellID = null, Cell $pCell = null) {
+ if ($tokens == false) return false;
- // If we're using cell caching, then $pCell may well be flushed back to the cache (which detaches the parent cell collection),
- // so we store the parent cell collection so that we can re-attach it when necessary
- $pCellWorksheet = ($pCell !== NULL) ? $pCell->getWorksheet() : NULL;
- $pCellParent = ($pCell !== NULL) ? $pCell->getParent() : null;
- $stack = new Calculation_Token_Stack;
+ // If we're using cell caching, then $pCell may well be flushed back to the cache (which detaches the parent cell collection),
+ // so we store the parent cell collection so that we can re-attach it when necessary
+ $pCellWorksheet = ($pCell !== null) ? $pCell->getWorksheet() : null;
+ $pCellParent = ($pCell !== null) ? $pCell->getParent() : null;
+ $stack = new Calculation_Token_Stack;
- // Loop through each token in turn
- foreach ($tokens as $tokenData) {
-// print_r($tokenData);
-// echo '
';
- $token = $tokenData['value'];
-// echo 'Token is '.$token.'
';
- // if the token is a binary operator, pop the top two values off the stack, do the operation, and push the result back on the stack
- if (isset(self::$_binaryOperators[$token])) {
-// echo 'Token is a binary operator
';
- // We must have two operands, error if we don't
- if (($operand2Data = $stack->pop()) === NULL) return $this->_raiseFormulaError('Internal error - Operand value missing from stack');
- if (($operand1Data = $stack->pop()) === NULL) return $this->_raiseFormulaError('Internal error - Operand value missing from stack');
+ // Loop through each token in turn
+ foreach ($tokens as $tokenData) {
+// print_r($tokenData);
+// echo '
';
+ $token = $tokenData['value'];
+// echo 'Token is '.$token.'
';
+ // if the token is a binary operator, pop the top two values off the stack, do the operation, and push the result back on the stack
+ if (isset(self::$_binaryOperators[$token])) {
+// echo 'Token is a binary operator
';
+ // We must have two operands, error if we don't
+ if (($operand2Data = $stack->pop()) === null) return $this->_raiseFormulaError('Internal error - Operand value missing from stack');
+ if (($operand1Data = $stack->pop()) === null) return $this->_raiseFormulaError('Internal error - Operand value missing from stack');
- $operand1 = self::_dataTestReference($operand1Data);
- $operand2 = self::_dataTestReference($operand2Data);
+ $operand1 = self::_dataTestReference($operand1Data);
+ $operand2 = self::_dataTestReference($operand2Data);
- // Log what we're doing
- if ($token == ':') {
- $this->_debugLog->writeDebugLog('Evaluating Range ', $this->_showValue($operand1Data['reference']), ' ', $token, ' ', $this->_showValue($operand2Data['reference']));
- } else {
- $this->_debugLog->writeDebugLog('Evaluating ', $this->_showValue($operand1), ' ', $token, ' ', $this->_showValue($operand2));
- }
+ // Log what we're doing
+ if ($token == ':') {
+ $this->_debugLog->writeDebugLog('Evaluating Range ', $this->_showValue($operand1Data['reference']), ' ', $token, ' ', $this->_showValue($operand2Data['reference']));
+ } else {
+ $this->_debugLog->writeDebugLog('Evaluating ', $this->_showValue($operand1), ' ', $token, ' ', $this->_showValue($operand2));
+ }
- // Process the operation in the appropriate manner
- switch ($token) {
- // Comparison (Boolean) Operators
- case '>' : // Greater than
- case '<' : // Less than
- case '>=' : // Greater than or Equal to
- case '<=' : // Less than or Equal to
- case '=' : // Equality
- case '<>' : // Inequality
- $this->_executeBinaryComparisonOperation($cellID,$operand1,$operand2,$token,$stack);
- break;
- // Binary Operators
- case ':' : // Range
- $sheet1 = $sheet2 = '';
- if (strpos($operand1Data['reference'],'!') !== FALSE) {
- list($sheet1,$operand1Data['reference']) = explode('!',$operand1Data['reference']);
- } else {
- $sheet1 = ($pCellParent !== NULL) ? $pCellWorksheet->getTitle() : '';
- }
- if (strpos($operand2Data['reference'],'!') !== FALSE) {
- list($sheet2,$operand2Data['reference']) = explode('!',$operand2Data['reference']);
- } else {
- $sheet2 = $sheet1;
- }
- if ($sheet1 == $sheet2) {
- if ($operand1Data['reference'] === NULL) {
- if ((trim($operand1Data['value']) != '') && (is_numeric($operand1Data['value']))) {
- $operand1Data['reference'] = $pCell->getColumn().$operand1Data['value'];
- } elseif (trim($operand1Data['reference']) == '') {
- $operand1Data['reference'] = $pCell->getCoordinate();
- } else {
- $operand1Data['reference'] = $operand1Data['value'].$pCell->getRow();
- }
- }
- if ($operand2Data['reference'] === NULL) {
- if ((trim($operand2Data['value']) != '') && (is_numeric($operand2Data['value']))) {
- $operand2Data['reference'] = $pCell->getColumn().$operand2Data['value'];
- } elseif (trim($operand2Data['reference']) == '') {
- $operand2Data['reference'] = $pCell->getCoordinate();
- } else {
- $operand2Data['reference'] = $operand2Data['value'].$pCell->getRow();
- }
- }
+ // Process the operation in the appropriate manner
+ switch ($token) {
+ // Comparison (Boolean) Operators
+ case '>' : // Greater than
+ case '<' : // Less than
+ case '>=' : // Greater than or Equal to
+ case '<=' : // Less than or Equal to
+ case '=' : // Equality
+ case '<>' : // Inequality
+ $this->_executeBinaryComparisonOperation($cellID,$operand1,$operand2,$token,$stack);
+ break;
+ // Binary Operators
+ case ':' : // Range
+ $sheet1 = $sheet2 = '';
+ if (strpos($operand1Data['reference'],'!') !== false) {
+ list($sheet1,$operand1Data['reference']) = explode('!',$operand1Data['reference']);
+ } else {
+ $sheet1 = ($pCellParent !== null) ? $pCellWorksheet->getTitle() : '';
+ }
+ if (strpos($operand2Data['reference'],'!') !== false) {
+ list($sheet2,$operand2Data['reference']) = explode('!',$operand2Data['reference']);
+ } else {
+ $sheet2 = $sheet1;
+ }
+ if ($sheet1 == $sheet2) {
+ if ($operand1Data['reference'] === null) {
+ if ((trim($operand1Data['value']) != '') && (is_numeric($operand1Data['value']))) {
+ $operand1Data['reference'] = $pCell->getColumn().$operand1Data['value'];
+ } elseif (trim($operand1Data['reference']) == '') {
+ $operand1Data['reference'] = $pCell->getCoordinate();
+ } else {
+ $operand1Data['reference'] = $operand1Data['value'].$pCell->getRow();
+ }
+ }
+ if ($operand2Data['reference'] === null) {
+ if ((trim($operand2Data['value']) != '') && (is_numeric($operand2Data['value']))) {
+ $operand2Data['reference'] = $pCell->getColumn().$operand2Data['value'];
+ } elseif (trim($operand2Data['reference']) == '') {
+ $operand2Data['reference'] = $pCell->getCoordinate();
+ } else {
+ $operand2Data['reference'] = $operand2Data['value'].$pCell->getRow();
+ }
+ }
- $oData = array_merge(explode(':',$operand1Data['reference']),explode(':',$operand2Data['reference']));
- $oCol = $oRow = array();
- foreach($oData as $oDatum) {
- $oCR = Cell::coordinateFromString($oDatum);
- $oCol[] = Cell::columnIndexFromString($oCR[0]) - 1;
- $oRow[] = $oCR[1];
- }
- $cellRef = Cell::stringFromColumnIndex(min($oCol)).min($oRow).':'.Cell::stringFromColumnIndex(max($oCol)).max($oRow);
- if ($pCellParent !== NULL) {
- $cellValue = $this->extractCellRange($cellRef, $this->_workbook->getSheetByName($sheet1), FALSE);
- } else {
- return $this->_raiseFormulaError('Unable to access Cell Reference');
- }
- $stack->push('Cell Reference',$cellValue,$cellRef);
- } else {
- $stack->push('Error',Calculation_Functions::REF(),NULL);
- }
+ $oData = array_merge(explode(':',$operand1Data['reference']),explode(':',$operand2Data['reference']));
+ $oCol = $oRow = array();
+ foreach($oData as $oDatum) {
+ $oCR = Cell::coordinateFromString($oDatum);
+ $oCol[] = Cell::columnIndexFromString($oCR[0]) - 1;
+ $oRow[] = $oCR[1];
+ }
+ $cellRef = Cell::stringFromColumnIndex(min($oCol)).min($oRow).':'.Cell::stringFromColumnIndex(max($oCol)).max($oRow);
+ if ($pCellParent !== null) {
+ $cellValue = $this->extractCellRange($cellRef, $this->_workbook->getSheetByName($sheet1), false);
+ } else {
+ return $this->_raiseFormulaError('Unable to access Cell Reference');
+ }
+ $stack->push('Cell Reference',$cellValue,$cellRef);
+ } else {
+ $stack->push('Error',Calculation_Functions::REF(),null);
+ }
- break;
- case '+' : // Addition
- $this->_executeNumericBinaryOperation($cellID,$operand1,$operand2,$token,'plusEquals',$stack);
- break;
- case '-' : // Subtraction
- $this->_executeNumericBinaryOperation($cellID,$operand1,$operand2,$token,'minusEquals',$stack);
- break;
- case '*' : // Multiplication
- $this->_executeNumericBinaryOperation($cellID,$operand1,$operand2,$token,'arrayTimesEquals',$stack);
- break;
- case '/' : // Division
- $this->_executeNumericBinaryOperation($cellID,$operand1,$operand2,$token,'arrayRightDivide',$stack);
- break;
- case '^' : // Exponential
- $this->_executeNumericBinaryOperation($cellID,$operand1,$operand2,$token,'power',$stack);
- break;
- case '&' : // Concatenation
- // If either of the operands is a matrix, we need to treat them both as matrices
- // (converting the other operand to a matrix if need be); then perform the required
- // matrix operation
- if (is_bool($operand1)) {
- $operand1 = ($operand1) ? self::$_localeBoolean['TRUE'] : self::$_localeBoolean['FALSE'];
- }
- if (is_bool($operand2)) {
- $operand2 = ($operand2) ? self::$_localeBoolean['TRUE'] : self::$_localeBoolean['FALSE'];
- }
- if ((is_array($operand1)) || (is_array($operand2))) {
- // Ensure that both operands are arrays/matrices
- self::_checkMatrixOperands($operand1,$operand2,2);
- try {
- // Convert operand 1 from a PHP array to a matrix
- $matrix = new Shared_JAMA_Matrix($operand1);
- // Perform the required operation against the operand 1 matrix, passing in operand 2
- $matrixResult = $matrix->concat($operand2);
- $result = $matrixResult->getArray();
- } catch (Exception $ex) {
- $this->_debugLog->writeDebugLog('JAMA Matrix Exception: ', $ex->getMessage());
- $result = '#VALUE!';
- }
- } else {
- $result = '"'.str_replace('""','"',self::_unwrapResult($operand1,'"').self::_unwrapResult($operand2,'"')).'"';
- }
- $this->_debugLog->writeDebugLog('Evaluation Result is ', $this->_showTypeDetails($result));
- $stack->push('Value',$result);
- break;
- case '|' : // Intersect
- $rowIntersect = array_intersect_key($operand1,$operand2);
- $cellIntersect = $oCol = $oRow = array();
- foreach(array_keys($rowIntersect) as $row) {
- $oRow[] = $row;
- foreach($rowIntersect[$row] as $col => $data) {
- $oCol[] = Cell::columnIndexFromString($col) - 1;
- $cellIntersect[$row] = array_intersect_key($operand1[$row],$operand2[$row]);
- }
- }
- $cellRef = Cell::stringFromColumnIndex(min($oCol)).min($oRow).':'.Cell::stringFromColumnIndex(max($oCol)).max($oRow);
- $this->_debugLog->writeDebugLog('Evaluation Result is ', $this->_showTypeDetails($cellIntersect));
- $stack->push('Value',$cellIntersect,$cellRef);
- break;
- }
+ break;
+ case '+' : // Addition
+ $this->_executeNumericBinaryOperation($cellID,$operand1,$operand2,$token,'plusEquals',$stack);
+ break;
+ case '-' : // Subtraction
+ $this->_executeNumericBinaryOperation($cellID,$operand1,$operand2,$token,'minusEquals',$stack);
+ break;
+ case '*' : // Multiplication
+ $this->_executeNumericBinaryOperation($cellID,$operand1,$operand2,$token,'arrayTimesEquals',$stack);
+ break;
+ case '/' : // Division
+ $this->_executeNumericBinaryOperation($cellID,$operand1,$operand2,$token,'arrayRightDivide',$stack);
+ break;
+ case '^' : // Exponential
+ $this->_executeNumericBinaryOperation($cellID,$operand1,$operand2,$token,'power',$stack);
+ break;
+ case '&' : // Concatenation
+ // If either of the operands is a matrix, we need to treat them both as matrices
+ // (converting the other operand to a matrix if need be); then perform the required
+ // matrix operation
+ if (is_bool($operand1)) {
+ $operand1 = ($operand1) ? self::$_localeBoolean['TRUE'] : self::$_localeBoolean['FALSE'];
+ }
+ if (is_bool($operand2)) {
+ $operand2 = ($operand2) ? self::$_localeBoolean['TRUE'] : self::$_localeBoolean['FALSE'];
+ }
+ if ((is_array($operand1)) || (is_array($operand2))) {
+ // Ensure that both operands are arrays/matrices
+ self::_checkMatrixOperands($operand1,$operand2,2);
+ try {
+ // Convert operand 1 from a PHP array to a matrix
+ $matrix = new Shared_JAMA_Matrix($operand1);
+ // Perform the required operation against the operand 1 matrix, passing in operand 2
+ $matrixResult = $matrix->concat($operand2);
+ $result = $matrixResult->getArray();
+ } catch (Exception $ex) {
+ $this->_debugLog->writeDebugLog('JAMA Matrix Exception: ', $ex->getMessage());
+ $result = '#VALUE!';
+ }
+ } else {
+ $result = '"'.str_replace('""','"',self::_unwrapResult($operand1,'"').self::_unwrapResult($operand2,'"')).'"';
+ }
+ $this->_debugLog->writeDebugLog('Evaluation Result is ', $this->_showTypeDetails($result));
+ $stack->push('Value',$result);
+ break;
+ case '|' : // Intersect
+ $rowIntersect = array_intersect_key($operand1,$operand2);
+ $cellIntersect = $oCol = $oRow = array();
+ foreach(array_keys($rowIntersect) as $row) {
+ $oRow[] = $row;
+ foreach($rowIntersect[$row] as $col => $data) {
+ $oCol[] = Cell::columnIndexFromString($col) - 1;
+ $cellIntersect[$row] = array_intersect_key($operand1[$row],$operand2[$row]);
+ }
+ }
+ $cellRef = Cell::stringFromColumnIndex(min($oCol)).min($oRow).':'.Cell::stringFromColumnIndex(max($oCol)).max($oRow);
+ $this->_debugLog->writeDebugLog('Evaluation Result is ', $this->_showTypeDetails($cellIntersect));
+ $stack->push('Value',$cellIntersect,$cellRef);
+ break;
+ }
- // if the token is a unary operator, pop one value off the stack, do the operation, and push it back on
- } elseif (($token === '~') || ($token === '%')) {
-// echo 'Token is a unary operator
';
- if (($arg = $stack->pop()) === NULL) return $this->_raiseFormulaError('Internal error - Operand value missing from stack');
- $arg = $arg['value'];
- if ($token === '~') {
-// echo 'Token is a negation operator
';
- $this->_debugLog->writeDebugLog('Evaluating Negation of ', $this->_showValue($arg));
- $multiplier = -1;
- } else {
-// echo 'Token is a percentile operator
';
- $this->_debugLog->writeDebugLog('Evaluating Percentile of ', $this->_showValue($arg));
- $multiplier = 0.01;
- }
- if (is_array($arg)) {
- self::_checkMatrixOperands($arg,$multiplier,2);
- try {
- $matrix1 = new Shared_JAMA_Matrix($arg);
- $matrixResult = $matrix1->arrayTimesEquals($multiplier);
- $result = $matrixResult->getArray();
- } catch (Exception $ex) {
- $this->_debugLog->writeDebugLog('JAMA Matrix Exception: ', $ex->getMessage());
- $result = '#VALUE!';
- }
- $this->_debugLog->writeDebugLog('Evaluation Result is ', $this->_showTypeDetails($result));
- $stack->push('Value',$result);
- } else {
- $this->_executeNumericBinaryOperation($cellID,$multiplier,$arg,'*','arrayTimesEquals',$stack);
- }
+ // if the token is a unary operator, pop one value off the stack, do the operation, and push it back on
+ } elseif (($token === '~') || ($token === '%')) {
+// echo 'Token is a unary operator
';
+ if (($arg = $stack->pop()) === null) return $this->_raiseFormulaError('Internal error - Operand value missing from stack');
+ $arg = $arg['value'];
+ if ($token === '~') {
+// echo 'Token is a negation operator
';
+ $this->_debugLog->writeDebugLog('Evaluating Negation of ', $this->_showValue($arg));
+ $multiplier = -1;
+ } else {
+// echo 'Token is a percentile operator
';
+ $this->_debugLog->writeDebugLog('Evaluating Percentile of ', $this->_showValue($arg));
+ $multiplier = 0.01;
+ }
+ if (is_array($arg)) {
+ self::_checkMatrixOperands($arg,$multiplier,2);
+ try {
+ $matrix1 = new Shared_JAMA_Matrix($arg);
+ $matrixResult = $matrix1->arrayTimesEquals($multiplier);
+ $result = $matrixResult->getArray();
+ } catch (Exception $ex) {
+ $this->_debugLog->writeDebugLog('JAMA Matrix Exception: ', $ex->getMessage());
+ $result = '#VALUE!';
+ }
+ $this->_debugLog->writeDebugLog('Evaluation Result is ', $this->_showTypeDetails($result));
+ $stack->push('Value',$result);
+ } else {
+ $this->_executeNumericBinaryOperation($cellID,$multiplier,$arg,'*','arrayTimesEquals',$stack);
+ }
- } elseif (preg_match('/^'.self::CALCULATION_REGEXP_CELLREF.'$/i', $token, $matches)) {
- $cellRef = NULL;
-// echo 'Element '.$token.' is a Cell reference
';
- if (isset($matches[8])) {
-// echo 'Reference is a Range of cells
';
- if ($pCell === NULL) {
-// We can't access the range, so return a REF error
- $cellValue = Calculation_Functions::REF();
- } else {
- $cellRef = $matches[6].$matches[7].':'.$matches[9].$matches[10];
- if ($matches[2] > '') {
- $matches[2] = trim($matches[2],"\"'");
- if ((strpos($matches[2],'[') !== FALSE) || (strpos($matches[2],']') !== FALSE)) {
- // It's a Reference to an external workbook (not currently supported)
- return $this->_raiseFormulaError('Unable to access External Workbook');
- }
- $matches[2] = trim($matches[2],"\"'");
-// echo '$cellRef='.$cellRef.' in worksheet '.$matches[2].'
';
- $this->_debugLog->writeDebugLog('Evaluating Cell Range ', $cellRef, ' in worksheet ', $matches[2]);
- if ($pCellParent !== NULL) {
- $cellValue = $this->extractCellRange($cellRef, $this->_workbook->getSheetByName($matches[2]), FALSE);
- } else {
- return $this->_raiseFormulaError('Unable to access Cell Reference');
- }
- $this->_debugLog->writeDebugLog('Evaluation Result for cells ', $cellRef, ' in worksheet ', $matches[2], ' is ', $this->_showTypeDetails($cellValue));
-// $cellRef = $matches[2].'!'.$cellRef;
- } else {
-// echo '$cellRef='.$cellRef.' in current worksheet
';
- $this->_debugLog->writeDebugLog('Evaluating Cell Range ', $cellRef, ' in current worksheet');
- if ($pCellParent !== NULL) {
- $cellValue = $this->extractCellRange($cellRef, $pCellWorksheet, FALSE);
- } else {
- return $this->_raiseFormulaError('Unable to access Cell Reference');
- }
- $this->_debugLog->writeDebugLog('Evaluation Result for cells ', $cellRef, ' is ', $this->_showTypeDetails($cellValue));
- }
- }
- } else {
-// echo 'Reference is a single Cell
';
- if ($pCell === NULL) {
-// We can't access the cell, so return a REF error
- $cellValue = Calculation_Functions::REF();
- } else {
- $cellRef = $matches[6].$matches[7];
- if ($matches[2] > '') {
- $matches[2] = trim($matches[2],"\"'");
- if ((strpos($matches[2],'[') !== FALSE) || (strpos($matches[2],']') !== FALSE)) {
- // It's a Reference to an external workbook (not currently supported)
- return $this->_raiseFormulaError('Unable to access External Workbook');
- }
-// echo '$cellRef='.$cellRef.' in worksheet '.$matches[2].'
';
- $this->_debugLog->writeDebugLog('Evaluating Cell ', $cellRef, ' in worksheet ', $matches[2]);
- if ($pCellParent !== NULL) {
- if ($this->_workbook->getSheetByName($matches[2])->cellExists($cellRef)) {
- $cellValue = $this->extractCellRange($cellRef, $this->_workbook->getSheetByName($matches[2]), FALSE);
- $pCell->attach($pCellParent);
- } else {
- $cellValue = NULL;
- }
- } else {
- return $this->_raiseFormulaError('Unable to access Cell Reference');
- }
- $this->_debugLog->writeDebugLog('Evaluation Result for cell ', $cellRef, ' in worksheet ', $matches[2], ' is ', $this->_showTypeDetails($cellValue));
-// $cellRef = $matches[2].'!'.$cellRef;
- } else {
-// echo '$cellRef='.$cellRef.' in current worksheet
';
- $this->_debugLog->writeDebugLog('Evaluating Cell ', $cellRef, ' in current worksheet');
- if ($pCellParent->isDataSet($cellRef)) {
- $cellValue = $this->extractCellRange($cellRef, $pCellWorksheet, FALSE);
- $pCell->attach($pCellParent);
- } else {
- $cellValue = NULL;
- }
- $this->_debugLog->writeDebugLog('Evaluation Result for cell ', $cellRef, ' is ', $this->_showTypeDetails($cellValue));
- }
- }
- }
- $stack->push('Value',$cellValue,$cellRef);
+ } elseif (preg_match('/^'.self::CALCULATION_REGEXP_CELLREF.'$/i', $token, $matches)) {
+ $cellRef = null;
+// echo 'Element '.$token.' is a Cell reference
';
+ if (isset($matches[8])) {
+// echo 'Reference is a Range of cells
';
+ if ($pCell === null) {
+// We can't access the range, so return a REF error
+ $cellValue = Calculation_Functions::REF();
+ } else {
+ $cellRef = $matches[6].$matches[7].':'.$matches[9].$matches[10];
+ if ($matches[2] > '') {
+ $matches[2] = trim($matches[2],"\"'");
+ if ((strpos($matches[2],'[') !== false) || (strpos($matches[2],']') !== false)) {
+ // It's a Reference to an external workbook (not currently supported)
+ return $this->_raiseFormulaError('Unable to access External Workbook');
+ }
+ $matches[2] = trim($matches[2],"\"'");
+// echo '$cellRef='.$cellRef.' in worksheet '.$matches[2].'
';
+ $this->_debugLog->writeDebugLog('Evaluating Cell Range ', $cellRef, ' in worksheet ', $matches[2]);
+ if ($pCellParent !== null) {
+ $cellValue = $this->extractCellRange($cellRef, $this->_workbook->getSheetByName($matches[2]), false);
+ } else {
+ return $this->_raiseFormulaError('Unable to access Cell Reference');
+ }
+ $this->_debugLog->writeDebugLog('Evaluation Result for cells ', $cellRef, ' in worksheet ', $matches[2], ' is ', $this->_showTypeDetails($cellValue));
+// $cellRef = $matches[2].'!'.$cellRef;
+ } else {
+// echo '$cellRef='.$cellRef.' in current worksheet
';
+ $this->_debugLog->writeDebugLog('Evaluating Cell Range ', $cellRef, ' in current worksheet');
+ if ($pCellParent !== null) {
+ $cellValue = $this->extractCellRange($cellRef, $pCellWorksheet, false);
+ } else {
+ return $this->_raiseFormulaError('Unable to access Cell Reference');
+ }
+ $this->_debugLog->writeDebugLog('Evaluation Result for cells ', $cellRef, ' is ', $this->_showTypeDetails($cellValue));
+ }
+ }
+ } else {
+// echo 'Reference is a single Cell
';
+ if ($pCell === null) {
+// We can't access the cell, so return a REF error
+ $cellValue = Calculation_Functions::REF();
+ } else {
+ $cellRef = $matches[6].$matches[7];
+ if ($matches[2] > '') {
+ $matches[2] = trim($matches[2],"\"'");
+ if ((strpos($matches[2],'[') !== false) || (strpos($matches[2],']') !== false)) {
+ // It's a Reference to an external workbook (not currently supported)
+ return $this->_raiseFormulaError('Unable to access External Workbook');
+ }
+// echo '$cellRef='.$cellRef.' in worksheet '.$matches[2].'
';
+ $this->_debugLog->writeDebugLog('Evaluating Cell ', $cellRef, ' in worksheet ', $matches[2]);
+ if ($pCellParent !== null) {
+ if ($this->_workbook->getSheetByName($matches[2])->cellExists($cellRef)) {
+ $cellValue = $this->extractCellRange($cellRef, $this->_workbook->getSheetByName($matches[2]), false);
+ $pCell->attach($pCellParent);
+ } else {
+ $cellValue = null;
+ }
+ } else {
+ return $this->_raiseFormulaError('Unable to access Cell Reference');
+ }
+ $this->_debugLog->writeDebugLog('Evaluation Result for cell ', $cellRef, ' in worksheet ', $matches[2], ' is ', $this->_showTypeDetails($cellValue));
+// $cellRef = $matches[2].'!'.$cellRef;
+ } else {
+// echo '$cellRef='.$cellRef.' in current worksheet
';
+ $this->_debugLog->writeDebugLog('Evaluating Cell ', $cellRef, ' in current worksheet');
+ if ($pCellParent->isDataSet($cellRef)) {
+ $cellValue = $this->extractCellRange($cellRef, $pCellWorksheet, false);
+ $pCell->attach($pCellParent);
+ } else {
+ $cellValue = null;
+ }
+ $this->_debugLog->writeDebugLog('Evaluation Result for cell ', $cellRef, ' is ', $this->_showTypeDetails($cellValue));
+ }
+ }
+ }
+ $stack->push('Value',$cellValue,$cellRef);
- // if the token is a function, pop arguments off the stack, hand them to the function, and push the result back on
- } elseif (preg_match('/^'.self::CALCULATION_REGEXP_FUNCTION.'$/i', $token, $matches)) {
-// echo 'Token is a function
';
- $functionName = $matches[1];
- $argCount = $stack->pop();
- $argCount = $argCount['value'];
- if ($functionName != 'MKMATRIX') {
- $this->_debugLog->writeDebugLog('Evaluating Function ', self::_localeFunc($functionName), '() with ', (($argCount == 0) ? 'no' : $argCount), ' argument', (($argCount == 1) ? '' : 's'));
- }
- if ((isset(self::$_PHPExcelFunctions[$functionName])) || (isset(self::$_controlFunctions[$functionName]))) { // function
- if (isset(self::$_PHPExcelFunctions[$functionName])) {
- $functionCall = self::$_PHPExcelFunctions[$functionName]['functionCall'];
- $passByReference = isset(self::$_PHPExcelFunctions[$functionName]['passByReference']);
- $passCellReference = isset(self::$_PHPExcelFunctions[$functionName]['passCellReference']);
- } elseif (isset(self::$_controlFunctions[$functionName])) {
- $functionCall = self::$_controlFunctions[$functionName]['functionCall'];
- $passByReference = isset(self::$_controlFunctions[$functionName]['passByReference']);
- $passCellReference = isset(self::$_controlFunctions[$functionName]['passCellReference']);
- }
- // get the arguments for this function
-// echo 'Function '.$functionName.' expects '.$argCount.' arguments
';
- $args = $argArrayVals = array();
- for ($i = 0; $i < $argCount; ++$i) {
- $arg = $stack->pop();
- $a = $argCount - $i - 1;
- if (($passByReference) &&
- (isset(self::$_PHPExcelFunctions[$functionName]['passByReference'][$a])) &&
- (self::$_PHPExcelFunctions[$functionName]['passByReference'][$a])) {
- if ($arg['reference'] === NULL) {
- $args[] = $cellID;
- if ($functionName != 'MKMATRIX') { $argArrayVals[] = $this->_showValue($cellID); }
- } else {
- $args[] = $arg['reference'];
- if ($functionName != 'MKMATRIX') { $argArrayVals[] = $this->_showValue($arg['reference']); }
- }
- } else {
- $args[] = self::_unwrapResult($arg['value']);
- if ($functionName != 'MKMATRIX') { $argArrayVals[] = $this->_showValue($arg['value']); }
- }
- }
- // Reverse the order of the arguments
- krsort($args);
- if (($passByReference) && ($argCount == 0)) {
- $args[] = $cellID;
- $argArrayVals[] = $this->_showValue($cellID);
- }
-// echo 'Arguments are: ';
-// print_r($args);
-// echo '
';
- if ($functionName != 'MKMATRIX') {
- if ($this->_debugLog->getWriteDebugLog()) {
- krsort($argArrayVals);
- $this->_debugLog->writeDebugLog('Evaluating ', self::_localeFunc($functionName), '( ', implode(self::$_localeArgumentSeparator.' ',Calculation_Functions::flattenArray($argArrayVals)), ' )');
- }
- }
- // Process each argument in turn, building the return value as an array
-// if (($argCount == 1) && (is_array($args[1])) && ($functionName != 'MKMATRIX')) {
-// $operand1 = $args[1];
-// $this->_debugLog->writeDebugLog('Argument is a matrix: ', $this->_showValue($operand1));
-// $result = array();
-// $row = 0;
-// foreach($operand1 as $args) {
-// if (is_array($args)) {
-// foreach($args as $arg) {
-// $this->_debugLog->writeDebugLog('Evaluating ', self::_localeFunc($functionName), '( ', $this->_showValue($arg), ' )');
-// $r = call_user_func_array($functionCall,$arg);
-// $this->_debugLog->writeDebugLog('Evaluation Result for ', self::_localeFunc($functionName), '() function call is ', $this->_showTypeDetails($r));
-// $result[$row][] = $r;
-// }
-// ++$row;
-// } else {
-// $this->_debugLog->writeDebugLog('Evaluating ', self::_localeFunc($functionName), '( ', $this->_showValue($args), ' )');
-// $r = call_user_func_array($functionCall,$args);
-// $this->_debugLog->writeDebugLog('Evaluation Result for ', self::_localeFunc($functionName), '() function call is ', $this->_showTypeDetails($r));
-// $result[] = $r;
-// }
-// }
-// } else {
- // Process the argument with the appropriate function call
- if ($passCellReference) {
- $args[] = $pCell;
- }
- if (strpos($functionCall,'::') !== FALSE) {
+ // if the token is a function, pop arguments off the stack, hand them to the function, and push the result back on
+ } elseif (preg_match('/^'.self::CALCULATION_REGEXP_FUNCTION.'$/i', $token, $matches)) {
+// echo 'Token is a function
';
+ $functionName = $matches[1];
+ $argCount = $stack->pop();
+ $argCount = $argCount['value'];
+ if ($functionName != 'MKMATRIX') {
+ $this->_debugLog->writeDebugLog('Evaluating Function ', self::_localeFunc($functionName), '() with ', (($argCount == 0) ? 'no' : $argCount), ' argument', (($argCount == 1) ? '' : 's'));
+ }
+ if ((isset(self::$_PHPExcelFunctions[$functionName])) || (isset(self::$_controlFunctions[$functionName]))) { // function
+ if (isset(self::$_PHPExcelFunctions[$functionName])) {
+ $functionCall = self::$_PHPExcelFunctions[$functionName]['functionCall'];
+ $passByReference = isset(self::$_PHPExcelFunctions[$functionName]['passByReference']);
+ $passCellReference = isset(self::$_PHPExcelFunctions[$functionName]['passCellReference']);
+ } elseif (isset(self::$_controlFunctions[$functionName])) {
+ $functionCall = self::$_controlFunctions[$functionName]['functionCall'];
+ $passByReference = isset(self::$_controlFunctions[$functionName]['passByReference']);
+ $passCellReference = isset(self::$_controlFunctions[$functionName]['passCellReference']);
+ }
+ // get the arguments for this function
+// echo 'Function '.$functionName.' expects '.$argCount.' arguments
';
+ $args = $argArrayVals = array();
+ for ($i = 0; $i < $argCount; ++$i) {
+ $arg = $stack->pop();
+ $a = $argCount - $i - 1;
+ if (($passByReference) &&
+ (isset(self::$_PHPExcelFunctions[$functionName]['passByReference'][$a])) &&
+ (self::$_PHPExcelFunctions[$functionName]['passByReference'][$a])) {
+ if ($arg['reference'] === null) {
+ $args[] = $cellID;
+ if ($functionName != 'MKMATRIX') { $argArrayVals[] = $this->_showValue($cellID); }
+ } else {
+ $args[] = $arg['reference'];
+ if ($functionName != 'MKMATRIX') { $argArrayVals[] = $this->_showValue($arg['reference']); }
+ }
+ } else {
+ $args[] = self::_unwrapResult($arg['value']);
+ if ($functionName != 'MKMATRIX') { $argArrayVals[] = $this->_showValue($arg['value']); }
+ }
+ }
+ // Reverse the order of the arguments
+ krsort($args);
+ if (($passByReference) && ($argCount == 0)) {
+ $args[] = $cellID;
+ $argArrayVals[] = $this->_showValue($cellID);
+ }
+// echo 'Arguments are: ';
+// print_r($args);
+// echo '
';
+ if ($functionName != 'MKMATRIX') {
+ if ($this->_debugLog->getWriteDebugLog()) {
+ krsort($argArrayVals);
+ $this->_debugLog->writeDebugLog('Evaluating ', self::_localeFunc($functionName), '( ', implode(self::$_localeArgumentSeparator.' ',Calculation_Functions::flattenArray($argArrayVals)), ' )');
+ }
+ }
+ // Process each argument in turn, building the return value as an array
+// if (($argCount == 1) && (is_array($args[1])) && ($functionName != 'MKMATRIX')) {
+// $operand1 = $args[1];
+// $this->_debugLog->writeDebugLog('Argument is a matrix: ', $this->_showValue($operand1));
+// $result = array();
+// $row = 0;
+// foreach($operand1 as $args) {
+// if (is_array($args)) {
+// foreach($args as $arg) {
+// $this->_debugLog->writeDebugLog('Evaluating ', self::_localeFunc($functionName), '( ', $this->_showValue($arg), ' )');
+// $r = call_user_func_array($functionCall,$arg);
+// $this->_debugLog->writeDebugLog('Evaluation Result for ', self::_localeFunc($functionName), '() function call is ', $this->_showTypeDetails($r));
+// $result[$row][] = $r;
+// }
+// ++$row;
+// } else {
+// $this->_debugLog->writeDebugLog('Evaluating ', self::_localeFunc($functionName), '( ', $this->_showValue($args), ' )');
+// $r = call_user_func_array($functionCall,$args);
+// $this->_debugLog->writeDebugLog('Evaluation Result for ', self::_localeFunc($functionName), '() function call is ', $this->_showTypeDetails($r));
+// $result[] = $r;
+// }
+// }
+// } else {
+ // Process the argument with the appropriate function call
+ if ($passCellReference) {
+ $args[] = $pCell;
+ }
+ if (strpos($functionCall,'::') !== false) {
$functionCall = __NAMESPACE__ . '\\' . $functionCall;
- $result = call_user_func_array(explode('::',$functionCall),$args);
- } else {
- foreach($args as &$arg) {
- $arg = Calculation_Functions::flattenSingleValue($arg);
- }
- unset($arg);
- $result = call_user_func_array($functionCall,$args);
- }
-// }
- if ($functionName != 'MKMATRIX') {
- $this->_debugLog->writeDebugLog('Evaluation Result for ', self::_localeFunc($functionName), '() function call is ', $this->_showTypeDetails($result));
- }
- $stack->push('Value',self::_wrapResult($result));
- }
+ $result = call_user_func_array(explode('::',$functionCall),$args);
+ } else {
+ foreach($args as &$arg) {
+ $arg = Calculation_Functions::flattenSingleValue($arg);
+ }
+ unset($arg);
+ $result = call_user_func_array($functionCall,$args);
+ }
+// }
+ if ($functionName != 'MKMATRIX') {
+ $this->_debugLog->writeDebugLog('Evaluation Result for ', self::_localeFunc($functionName), '() function call is ', $this->_showTypeDetails($result));
+ }
+ $stack->push('Value',self::_wrapResult($result));
+ }
- } else {
- // if the token is a number, boolean, string or an Excel error, push it onto the stack
- if (isset(self::$_ExcelConstants[strtoupper($token)])) {
- $excelConstant = strtoupper($token);
-// echo 'Token is a PHPExcel constant: '.$excelConstant.'
';
- $stack->push('Constant Value',self::$_ExcelConstants[$excelConstant]);
- $this->_debugLog->writeDebugLog('Evaluating Constant ', $excelConstant, ' as ', $this->_showTypeDetails(self::$_ExcelConstants[$excelConstant]));
- } elseif ((is_numeric($token)) || ($token === NULL) || (is_bool($token)) || ($token == '') || ($token{0} == '"') || ($token{0} == '#')) {
-// echo 'Token is a number, boolean, string, null or an Excel error
';
- $stack->push('Value',$token);
- // if the token is a named range, push the named range name onto the stack
- } elseif (preg_match('/^'.self::CALCULATION_REGEXP_NAMEDRANGE.'$/i', $token, $matches)) {
-// echo 'Token is a named range
';
- $namedRange = $matches[6];
-// echo 'Named Range is '.$namedRange.'
';
- $this->_debugLog->writeDebugLog('Evaluating Named Range ', $namedRange);
- $cellValue = $this->extractNamedRange($namedRange, ((NULL !== $pCell) ? $pCellWorksheet : NULL), FALSE);
- $pCell->attach($pCellParent);
- $this->_debugLog->writeDebugLog('Evaluation Result for named range ', $namedRange, ' is ', $this->_showTypeDetails($cellValue));
- $stack->push('Named Range',$cellValue,$namedRange);
- } else {
- return $this->_raiseFormulaError("undefined variable '$token'");
- }
- }
- }
- // when we're out of tokens, the stack should have a single element, the final result
- if ($stack->count() != 1) return $this->_raiseFormulaError("internal error");
- $output = $stack->pop();
- $output = $output['value'];
+ } else {
+ // if the token is a number, boolean, string or an Excel error, push it onto the stack
+ if (isset(self::$_ExcelConstants[strtoupper($token)])) {
+ $excelConstant = strtoupper($token);
+// echo 'Token is a PHPExcel constant: '.$excelConstant.'
';
+ $stack->push('Constant Value',self::$_ExcelConstants[$excelConstant]);
+ $this->_debugLog->writeDebugLog('Evaluating Constant ', $excelConstant, ' as ', $this->_showTypeDetails(self::$_ExcelConstants[$excelConstant]));
+ } elseif ((is_numeric($token)) || ($token === null) || (is_bool($token)) || ($token == '') || ($token{0} == '"') || ($token{0} == '#')) {
+// echo 'Token is a number, boolean, string, null or an Excel error
';
+ $stack->push('Value',$token);
+ // if the token is a named range, push the named range name onto the stack
+ } elseif (preg_match('/^'.self::CALCULATION_REGEXP_NAMEDRANGE.'$/i', $token, $matches)) {
+// echo 'Token is a named range
';
+ $namedRange = $matches[6];
+// echo 'Named Range is '.$namedRange.'
';
+ $this->_debugLog->writeDebugLog('Evaluating Named Range ', $namedRange);
+ $cellValue = $this->extractNamedRange($namedRange, ((null !== $pCell) ? $pCellWorksheet : null), false);
+ $pCell->attach($pCellParent);
+ $this->_debugLog->writeDebugLog('Evaluation Result for named range ', $namedRange, ' is ', $this->_showTypeDetails($cellValue));
+ $stack->push('Named Range',$cellValue,$namedRange);
+ } else {
+ return $this->_raiseFormulaError("undefined variable '$token'");
+ }
+ }
+ }
+ // when we're out of tokens, the stack should have a single element, the final result
+ if ($stack->count() != 1) return $this->_raiseFormulaError("internal error");
+ $output = $stack->pop();
+ $output = $output['value'];
-// if ((is_array($output)) && (self::$returnArrayAsType != self::RETURN_ARRAY_AS_ARRAY)) {
-// return array_shift(Calculation_Functions::flattenArray($output));
-// }
- return $output;
- } // function _processTokenStack()
+// if ((is_array($output)) && (self::$returnArrayAsType != self::RETURN_ARRAY_AS_ARRAY)) {
+// return array_shift(Calculation_Functions::flattenArray($output));
+// }
+ return $output;
+ } // function _processTokenStack()
- private function _validateBinaryOperand($cellID, &$operand, &$stack) {
- if (is_array($operand)) {
- if ((count($operand, COUNT_RECURSIVE) - count($operand)) == 1) {
- do {
- $operand = array_pop($operand);
- } while (is_array($operand));
- }
- }
- // Numbers, matrices and booleans can pass straight through, as they're already valid
- if (is_string($operand)) {
- // We only need special validations for the operand if it is a string
- // Start by stripping off the quotation marks we use to identify true excel string values internally
- if ($operand > '' && $operand{0} == '"') { $operand = self::_unwrapResult($operand); }
- // If the string is a numeric value, we treat it as a numeric, so no further testing
- if (!is_numeric($operand)) {
- // If not a numeric, test to see if the value is an Excel error, and so can't be used in normal binary operations
- if ($operand > '' && $operand{0} == '#') {
- $stack->push('Value', $operand);
- $this->_debugLog->writeDebugLog('Evaluation Result is ', $this->_showTypeDetails($operand));
- return FALSE;
- } elseif (!Shared_String::convertToNumberIfFraction($operand)) {
- // If not a numeric or a fraction, then it's a text string, and so can't be used in mathematical binary operations
- $stack->push('Value', '#VALUE!');
- $this->_debugLog->writeDebugLog('Evaluation Result is a ', $this->_showTypeDetails('#VALUE!'));
- return FALSE;
- }
- }
- }
+ private function _validateBinaryOperand($cellID, &$operand, &$stack) {
+ if (is_array($operand)) {
+ if ((count($operand, COUNT_RECURSIVE) - count($operand)) == 1) {
+ do {
+ $operand = array_pop($operand);
+ } while (is_array($operand));
+ }
+ }
+ // Numbers, matrices and booleans can pass straight through, as they're already valid
+ if (is_string($operand)) {
+ // We only need special validations for the operand if it is a string
+ // Start by stripping off the quotation marks we use to identify true excel string values internally
+ if ($operand > '' && $operand{0} == '"') { $operand = self::_unwrapResult($operand); }
+ // If the string is a numeric value, we treat it as a numeric, so no further testing
+ if (!is_numeric($operand)) {
+ // If not a numeric, test to see if the value is an Excel error, and so can't be used in normal binary operations
+ if ($operand > '' && $operand{0} == '#') {
+ $stack->push('Value', $operand);
+ $this->_debugLog->writeDebugLog('Evaluation Result is ', $this->_showTypeDetails($operand));
+ return false;
+ } elseif (!Shared_String::convertToNumberIfFraction($operand)) {
+ // If not a numeric or a fraction, then it's a text string, and so can't be used in mathematical binary operations
+ $stack->push('Value', '#VALUE!');
+ $this->_debugLog->writeDebugLog('Evaluation Result is a ', $this->_showTypeDetails('#VALUE!'));
+ return false;
+ }
+ }
+ }
- // return a true if the value of the operand is one that we can use in normal binary operations
- return TRUE;
- } // function _validateBinaryOperand()
+ // return a true if the value of the operand is one that we can use in normal binary operations
+ return TRUE;
+ } // function _validateBinaryOperand()
- private function _executeBinaryComparisonOperation($cellID, $operand1, $operand2, $operation, &$stack, $recursingArrays=FALSE) {
- // If we're dealing with matrix operations, we want a matrix result
- if ((is_array($operand1)) || (is_array($operand2))) {
- $result = array();
- if ((is_array($operand1)) && (!is_array($operand2))) {
- foreach($operand1 as $x => $operandData) {
- $this->_debugLog->writeDebugLog('Evaluating Comparison ', $this->_showValue($operandData), ' ', $operation, ' ', $this->_showValue($operand2));
- $this->_executeBinaryComparisonOperation($cellID,$operandData,$operand2,$operation,$stack);
- $r = $stack->pop();
- $result[$x] = $r['value'];
- }
- } elseif ((!is_array($operand1)) && (is_array($operand2))) {
- foreach($operand2 as $x => $operandData) {
- $this->_debugLog->writeDebugLog('Evaluating Comparison ', $this->_showValue($operand1), ' ', $operation, ' ', $this->_showValue($operandData));
- $this->_executeBinaryComparisonOperation($cellID,$operand1,$operandData,$operation,$stack);
- $r = $stack->pop();
- $result[$x] = $r['value'];
- }
- } else {
- if (!$recursingArrays) { self::_checkMatrixOperands($operand1,$operand2,2); }
- foreach($operand1 as $x => $operandData) {
- $this->_debugLog->writeDebugLog('Evaluating Comparison ', $this->_showValue($operandData), ' ', $operation, ' ', $this->_showValue($operand2[$x]));
- $this->_executeBinaryComparisonOperation($cellID,$operandData,$operand2[$x],$operation,$stack,TRUE);
- $r = $stack->pop();
- $result[$x] = $r['value'];
- }
- }
- // Log the result details
- $this->_debugLog->writeDebugLog('Comparison Evaluation Result is ', $this->_showTypeDetails($result));
- // And push the result onto the stack
- $stack->push('Array',$result);
- return TRUE;
- }
+ private function _executeBinaryComparisonOperation($cellID, $operand1, $operand2, $operation, &$stack, $recursingArrays=false) {
+ // If we're dealing with matrix operations, we want a matrix result
+ if ((is_array($operand1)) || (is_array($operand2))) {
+ $result = array();
+ if ((is_array($operand1)) && (!is_array($operand2))) {
+ foreach($operand1 as $x => $operandData) {
+ $this->_debugLog->writeDebugLog('Evaluating Comparison ', $this->_showValue($operandData), ' ', $operation, ' ', $this->_showValue($operand2));
+ $this->_executeBinaryComparisonOperation($cellID,$operandData,$operand2,$operation,$stack);
+ $r = $stack->pop();
+ $result[$x] = $r['value'];
+ }
+ } elseif ((!is_array($operand1)) && (is_array($operand2))) {
+ foreach($operand2 as $x => $operandData) {
+ $this->_debugLog->writeDebugLog('Evaluating Comparison ', $this->_showValue($operand1), ' ', $operation, ' ', $this->_showValue($operandData));
+ $this->_executeBinaryComparisonOperation($cellID,$operand1,$operandData,$operation,$stack);
+ $r = $stack->pop();
+ $result[$x] = $r['value'];
+ }
+ } else {
+ if (!$recursingArrays) { self::_checkMatrixOperands($operand1,$operand2,2); }
+ foreach($operand1 as $x => $operandData) {
+ $this->_debugLog->writeDebugLog('Evaluating Comparison ', $this->_showValue($operandData), ' ', $operation, ' ', $this->_showValue($operand2[$x]));
+ $this->_executeBinaryComparisonOperation($cellID,$operandData,$operand2[$x],$operation,$stack,TRUE);
+ $r = $stack->pop();
+ $result[$x] = $r['value'];
+ }
+ }
+ // Log the result details
+ $this->_debugLog->writeDebugLog('Comparison Evaluation Result is ', $this->_showTypeDetails($result));
+ // And push the result onto the stack
+ $stack->push('Array',$result);
+ return TRUE;
+ }
- // Simple validate the two operands if they are string values
- if (is_string($operand1) && $operand1 > '' && $operand1{0} == '"') { $operand1 = self::_unwrapResult($operand1); }
- if (is_string($operand2) && $operand2 > '' && $operand2{0} == '"') { $operand2 = self::_unwrapResult($operand2); }
+ // Simple validate the two operands if they are string values
+ if (is_string($operand1) && $operand1 > '' && $operand1{0} == '"') { $operand1 = self::_unwrapResult($operand1); }
+ if (is_string($operand2) && $operand2 > '' && $operand2{0} == '"') { $operand2 = self::_unwrapResult($operand2); }
- // execute the necessary operation
- switch ($operation) {
- // Greater than
- case '>':
- $result = ($operand1 > $operand2);
- break;
- // Less than
- case '<':
- $result = ($operand1 < $operand2);
- break;
- // Equality
- case '=':
- $result = ($operand1 == $operand2);
- break;
- // Greater than or equal
- case '>=':
- $result = ($operand1 >= $operand2);
- break;
- // Less than or equal
- case '<=':
- $result = ($operand1 <= $operand2);
- break;
- // Inequality
- case '<>':
- $result = ($operand1 != $operand2);
- break;
- }
+ // execute the necessary operation
+ switch ($operation) {
+ // Greater than
+ case '>':
+ $result = ($operand1 > $operand2);
+ break;
+ // Less than
+ case '<':
+ $result = ($operand1 < $operand2);
+ break;
+ // Equality
+ case '=':
+ $result = ($operand1 == $operand2);
+ break;
+ // Greater than or equal
+ case '>=':
+ $result = ($operand1 >= $operand2);
+ break;
+ // Less than or equal
+ case '<=':
+ $result = ($operand1 <= $operand2);
+ break;
+ // Inequality
+ case '<>':
+ $result = ($operand1 != $operand2);
+ break;
+ }
- // Log the result details
- $this->_debugLog->writeDebugLog('Evaluation Result is ', $this->_showTypeDetails($result));
- // And push the result onto the stack
- $stack->push('Value',$result);
- return TRUE;
- } // function _executeBinaryComparisonOperation()
+ // Log the result details
+ $this->_debugLog->writeDebugLog('Evaluation Result is ', $this->_showTypeDetails($result));
+ // And push the result onto the stack
+ $stack->push('Value',$result);
+ return TRUE;
+ } // function _executeBinaryComparisonOperation()
- private function _executeNumericBinaryOperation($cellID,$operand1,$operand2,$operation,$matrixFunction,&$stack) {
- // Validate the two operands
- if (!$this->_validateBinaryOperand($cellID,$operand1,$stack)) return FALSE;
- if (!$this->_validateBinaryOperand($cellID,$operand2,$stack)) return FALSE;
+ private function _executeNumericBinaryOperation($cellID,$operand1,$operand2,$operation,$matrixFunction,&$stack) {
+ // Validate the two operands
+ if (!$this->_validateBinaryOperand($cellID,$operand1,$stack)) return false;
+ if (!$this->_validateBinaryOperand($cellID,$operand2,$stack)) return false;
- // If either of the operands is a matrix, we need to treat them both as matrices
- // (converting the other operand to a matrix if need be); then perform the required
- // matrix operation
- if ((is_array($operand1)) || (is_array($operand2))) {
- // Ensure that both operands are arrays/matrices of the same size
- self::_checkMatrixOperands($operand1, $operand2, 2);
+ // If either of the operands is a matrix, we need to treat them both as matrices
+ // (converting the other operand to a matrix if need be); then perform the required
+ // matrix operation
+ if ((is_array($operand1)) || (is_array($operand2))) {
+ // Ensure that both operands are arrays/matrices of the same size
+ self::_checkMatrixOperands($operand1, $operand2, 2);
- try {
- // Convert operand 1 from a PHP array to a matrix
- $matrix = new Shared_JAMA_Matrix($operand1);
- // Perform the required operation against the operand 1 matrix, passing in operand 2
- $matrixResult = $matrix->$matrixFunction($operand2);
- $result = $matrixResult->getArray();
- } catch (Exception $ex) {
- $this->_debugLog->writeDebugLog('JAMA Matrix Exception: ', $ex->getMessage());
- $result = '#VALUE!';
- }
- } else {
- if ((Calculation_Functions::getCompatibilityMode() != Calculation_Functions::COMPATIBILITY_OPENOFFICE) &&
- ((is_string($operand1) && !is_numeric($operand1)) || (is_string($operand2) && !is_numeric($operand2)))) {
- $result = Calculation_Functions::VALUE();
- } else {
- // If we're dealing with non-matrix operations, execute the necessary operation
- switch ($operation) {
- // Addition
- case '+':
- $result = $operand1+$operand2;
- break;
- // Subtraction
- case '-':
- $result = $operand1-$operand2;
- break;
- // Multiplication
- case '*':
- $result = $operand1*$operand2;
- break;
- // Division
- case '/':
- if ($operand2 == 0) {
- // Trap for Divide by Zero error
- $stack->push('Value','#DIV/0!');
- $this->_debugLog->writeDebugLog('Evaluation Result is ', $this->_showTypeDetails('#DIV/0!'));
- return FALSE;
- } else {
- $result = $operand1/$operand2;
- }
- break;
- // Power
- case '^':
- $result = pow($operand1,$operand2);
- break;
- }
- }
- }
+ try {
+ // Convert operand 1 from a PHP array to a matrix
+ $matrix = new Shared_JAMA_Matrix($operand1);
+ // Perform the required operation against the operand 1 matrix, passing in operand 2
+ $matrixResult = $matrix->$matrixFunction($operand2);
+ $result = $matrixResult->getArray();
+ } catch (Exception $ex) {
+ $this->_debugLog->writeDebugLog('JAMA Matrix Exception: ', $ex->getMessage());
+ $result = '#VALUE!';
+ }
+ } else {
+ if ((Calculation_Functions::getCompatibilityMode() != Calculation_Functions::COMPATIBILITY_OPENOFFICE) &&
+ ((is_string($operand1) && !is_numeric($operand1)) || (is_string($operand2) && !is_numeric($operand2)))) {
+ $result = Calculation_Functions::VALUE();
+ } else {
+ // If we're dealing with non-matrix operations, execute the necessary operation
+ switch ($operation) {
+ // Addition
+ case '+':
+ $result = $operand1+$operand2;
+ break;
+ // Subtraction
+ case '-':
+ $result = $operand1-$operand2;
+ break;
+ // Multiplication
+ case '*':
+ $result = $operand1*$operand2;
+ break;
+ // Division
+ case '/':
+ if ($operand2 == 0) {
+ // Trap for Divide by Zero error
+ $stack->push('Value','#DIV/0!');
+ $this->_debugLog->writeDebugLog('Evaluation Result is ', $this->_showTypeDetails('#DIV/0!'));
+ return false;
+ } else {
+ $result = $operand1/$operand2;
+ }
+ break;
+ // Power
+ case '^':
+ $result = pow($operand1,$operand2);
+ break;
+ }
+ }
+ }
- // Log the result details
- $this->_debugLog->writeDebugLog('Evaluation Result is ', $this->_showTypeDetails($result));
- // And push the result onto the stack
- $stack->push('Value',$result);
- return TRUE;
- } // function _executeNumericBinaryOperation()
+ // Log the result details
+ $this->_debugLog->writeDebugLog('Evaluation Result is ', $this->_showTypeDetails($result));
+ // And push the result onto the stack
+ $stack->push('Value',$result);
+ return TRUE;
+ } // function _executeNumericBinaryOperation()
- // trigger an error, but nicely, if need be
- protected function _raiseFormulaError($errorMessage) {
- $this->formulaError = $errorMessage;
- $this->_cyclicReferenceStack->clear();
- if (!$this->suppressFormulaErrors) throw new Calculation_Exception($errorMessage);
- trigger_error($errorMessage, E_USER_ERROR);
- } // function _raiseFormulaError()
+ // trigger an error, but nicely, if need be
+ protected function _raiseFormulaError($errorMessage) {
+ $this->formulaError = $errorMessage;
+ $this->_cyclicReferenceStack->clear();
+ if (!$this->suppressFormulaErrors) throw new Calculation_Exception($errorMessage);
+ trigger_error($errorMessage, E_USER_ERROR);
+ } // function _raiseFormulaError()
- /**
- * Extract range values
- *
- * @param string &$pRange String based range representation
- * @param PHPExcel\Worksheet $pSheet Worksheet
- * @param boolean $resetLog Flag indicating whether calculation log should be reset or not
- * @return mixed Array of values in range if range contains more than one element. Otherwise, a single value is returned.
- * @throws Calculation_Exception
- */
- public function extractCellRange(&$pRange = 'A1', Worksheet $pSheet = NULL, $resetLog = TRUE) {
- // Return value
- $returnValue = array ();
+ /**
+ * Extract range values
+ *
+ * @param string &$pRange String based range representation
+ * @param PHPExcel\Worksheet $pSheet Worksheet
+ * @param boolean $resetLog Flag indicating whether calculation log should be reset or not
+ * @return mixed Array of values in range if range contains more than one element. Otherwise, a single value is returned.
+ * @throws Calculation_Exception
+ */
+ public function extractCellRange(&$pRange = 'A1', Worksheet $pSheet = null, $resetLog = true) {
+ // Return value
+ $returnValue = array ();
-// echo 'extractCellRange('.$pRange.')',PHP_EOL;
- if ($pSheet !== NULL) {
- $pSheetName = $pSheet->getTitle();
-// echo 'Passed sheet name is '.$pSheetName.PHP_EOL;
-// echo 'Range reference is '.$pRange.PHP_EOL;
- if (strpos ($pRange, '!') !== false) {
-// echo '$pRange reference includes sheet reference',PHP_EOL;
- list($pSheetName,$pRange) = Worksheet::extractSheetTitle($pRange, true);
-// echo 'New sheet name is '.$pSheetName,PHP_EOL;
-// echo 'Adjusted Range reference is '.$pRange,PHP_EOL;
- $pSheet = $this->_workbook->getSheetByName($pSheetName);
- }
+// echo 'extractCellRange('.$pRange.')',PHP_EOL;
+ if ($pSheet !== null) {
+ $pSheetName = $pSheet->getTitle();
+// echo 'Passed sheet name is '.$pSheetName.PHP_EOL;
+// echo 'Range reference is '.$pRange.PHP_EOL;
+ if (strpos ($pRange, '!') !== false) {
+// echo '$pRange reference includes sheet reference',PHP_EOL;
+ list($pSheetName,$pRange) = Worksheet::extractSheetTitle($pRange, true);
+// echo 'New sheet name is '.$pSheetName,PHP_EOL;
+// echo 'Adjusted Range reference is '.$pRange,PHP_EOL;
+ $pSheet = $this->_workbook->getSheetByName($pSheetName);
+ }
- // Extract range
- $aReferences = Cell::extractAllCellReferencesInRange($pRange);
- $pRange = $pSheetName.'!'.$pRange;
- if (!isset($aReferences[1])) {
- // Single cell in range
- sscanf($aReferences[0],'%[A-Z]%d', $currentCol, $currentRow);
- $cellValue = NULL;
- if ($pSheet->cellExists($aReferences[0])) {
- $returnValue[$currentRow][$currentCol] = $pSheet->getCell($aReferences[0])->getCalculatedValue($resetLog);
- } else {
- $returnValue[$currentRow][$currentCol] = NULL;
- }
- } else {
- // Extract cell data for all cells in the range
- foreach ($aReferences as $reference) {
- // Extract range
- sscanf($reference,'%[A-Z]%d', $currentCol, $currentRow);
- $cellValue = NULL;
- if ($pSheet->cellExists($reference)) {
- $returnValue[$currentRow][$currentCol] = $pSheet->getCell($reference)->getCalculatedValue($resetLog);
- } else {
- $returnValue[$currentRow][$currentCol] = NULL;
- }
- }
- }
- }
+ // Extract range
+ $aReferences = Cell::extractAllCellReferencesInRange($pRange);
+ $pRange = $pSheetName.'!'.$pRange;
+ if (!isset($aReferences[1])) {
+ // Single cell in range
+ sscanf($aReferences[0],'%[A-Z]%d', $currentCol, $currentRow);
+ $cellValue = null;
+ if ($pSheet->cellExists($aReferences[0])) {
+ $returnValue[$currentRow][$currentCol] = $pSheet->getCell($aReferences[0])->getCalculatedValue($resetLog);
+ } else {
+ $returnValue[$currentRow][$currentCol] = null;
+ }
+ } else {
+ // Extract cell data for all cells in the range
+ foreach ($aReferences as $reference) {
+ // Extract range
+ sscanf($reference,'%[A-Z]%d', $currentCol, $currentRow);
+ $cellValue = null;
+ if ($pSheet->cellExists($reference)) {
+ $returnValue[$currentRow][$currentCol] = $pSheet->getCell($reference)->getCalculatedValue($resetLog);
+ } else {
+ $returnValue[$currentRow][$currentCol] = null;
+ }
+ }
+ }
+ }
- // Return
- return $returnValue;
- } // function extractCellRange()
+ // Return
+ return $returnValue;
+ } // function extractCellRange()
- /**
- * Extract range values
- *
- * @param string &$pRange String based range representation
- * @param PHPExcel\Worksheet $pSheet Worksheet
- * @return mixed Array of values in range if range contains more than one element. Otherwise, a single value is returned.
- * @param boolean $resetLog Flag indicating whether calculation log should be reset or not
- * @throws Calculation_Exception
- */
- public function extractNamedRange(&$pRange = 'A1', Worksheet $pSheet = NULL, $resetLog = TRUE) {
- // Return value
- $returnValue = array ();
+ /**
+ * Extract range values
+ *
+ * @param string &$pRange String based range representation
+ * @param PHPExcel\Worksheet $pSheet Worksheet
+ * @return mixed Array of values in range if range contains more than one element. Otherwise, a single value is returned.
+ * @param boolean $resetLog Flag indicating whether calculation log should be reset or not
+ * @throws Calculation_Exception
+ */
+ public function extractNamedRange(&$pRange = 'A1', Worksheet $pSheet = null, $resetLog = true) {
+ // Return value
+ $returnValue = array ();
-// echo 'extractNamedRange('.$pRange.')
';
- if ($pSheet !== NULL) {
- $pSheetName = $pSheet->getTitle();
-// echo 'Current sheet name is '.$pSheetName.'
';
-// echo 'Range reference is '.$pRange.'
';
- if (strpos ($pRange, '!') !== false) {
-// echo '$pRange reference includes sheet reference',PHP_EOL;
- list($pSheetName,$pRange) = Worksheet::extractSheetTitle($pRange, true);
-// echo 'New sheet name is '.$pSheetName,PHP_EOL;
-// echo 'Adjusted Range reference is '.$pRange,PHP_EOL;
- $pSheet = $this->_workbook->getSheetByName($pSheetName);
- }
+// echo 'extractNamedRange('.$pRange.')
';
+ if ($pSheet !== null) {
+ $pSheetName = $pSheet->getTitle();
+// echo 'Current sheet name is '.$pSheetName.'
';
+// echo 'Range reference is '.$pRange.'
';
+ if (strpos ($pRange, '!') !== false) {
+// echo '$pRange reference includes sheet reference',PHP_EOL;
+ list($pSheetName,$pRange) = Worksheet::extractSheetTitle($pRange, true);
+// echo 'New sheet name is '.$pSheetName,PHP_EOL;
+// echo 'Adjusted Range reference is '.$pRange,PHP_EOL;
+ $pSheet = $this->_workbook->getSheetByName($pSheetName);
+ }
- // Named range?
- $namedRange = NamedRange::resolveRange($pRange, $pSheet);
- if ($namedRange !== NULL) {
- $pSheet = $namedRange->getWorksheet();
-// echo 'Named Range '.$pRange.' (';
- $pRange = $namedRange->getRange();
- $splitRange = Cell::splitRange($pRange);
- // Convert row and column references
- if (ctype_alpha($splitRange[0][0])) {
- $pRange = $splitRange[0][0] . '1:' . $splitRange[0][1] . $namedRange->getWorksheet()->getHighestRow();
- } elseif(ctype_digit($splitRange[0][0])) {
- $pRange = 'A' . $splitRange[0][0] . ':' . $namedRange->getWorksheet()->getHighestColumn() . $splitRange[0][1];
- }
-// echo $pRange.') is in sheet '.$namedRange->getWorksheet()->getTitle().'
';
+ // Named range?
+ $namedRange = NamedRange::resolveRange($pRange, $pSheet);
+ if ($namedRange !== null) {
+ $pSheet = $namedRange->getWorksheet();
+// echo 'Named Range '.$pRange.' (';
+ $pRange = $namedRange->getRange();
+ $splitRange = Cell::splitRange($pRange);
+ // Convert row and column references
+ if (ctype_alpha($splitRange[0][0])) {
+ $pRange = $splitRange[0][0] . '1:' . $splitRange[0][1] . $namedRange->getWorksheet()->getHighestRow();
+ } elseif(ctype_digit($splitRange[0][0])) {
+ $pRange = 'A' . $splitRange[0][0] . ':' . $namedRange->getWorksheet()->getHighestColumn() . $splitRange[0][1];
+ }
+// echo $pRange.') is in sheet '.$namedRange->getWorksheet()->getTitle().'
';
-// if ($pSheet->getTitle() != $namedRange->getWorksheet()->getTitle()) {
-// if (!$namedRange->getLocalOnly()) {
-// $pSheet = $namedRange->getWorksheet();
-// } else {
-// return $returnValue;
-// }
-// }
- } else {
- return Calculation_Functions::REF();
- }
+// if ($pSheet->getTitle() != $namedRange->getWorksheet()->getTitle()) {
+// if (!$namedRange->getLocalOnly()) {
+// $pSheet = $namedRange->getWorksheet();
+// } else {
+// return $returnValue;
+// }
+// }
+ } else {
+ return Calculation_Functions::REF();
+ }
- // Extract range
- $aReferences = Cell::extractAllCellReferencesInRange($pRange);
-// var_dump($aReferences);
- if (!isset($aReferences[1])) {
- // Single cell (or single column or row) in range
- list($currentCol,$currentRow) = Cell::coordinateFromString($aReferences[0]);
- $cellValue = NULL;
- if ($pSheet->cellExists($aReferences[0])) {
- $returnValue[$currentRow][$currentCol] = $pSheet->getCell($aReferences[0])->getCalculatedValue($resetLog);
- } else {
- $returnValue[$currentRow][$currentCol] = NULL;
- }
- } else {
- // Extract cell data for all cells in the range
- foreach ($aReferences as $reference) {
- // Extract range
- list($currentCol,$currentRow) = Cell::coordinateFromString($reference);
-// echo 'NAMED RANGE: $currentCol='.$currentCol.' $currentRow='.$currentRow.'
';
- $cellValue = NULL;
- if ($pSheet->cellExists($reference)) {
- $returnValue[$currentRow][$currentCol] = $pSheet->getCell($reference)->getCalculatedValue($resetLog);
- } else {
- $returnValue[$currentRow][$currentCol] = NULL;
- }
- }
- }
-// print_r($returnValue);
-// echo '
';
- }
+ // Extract range
+ $aReferences = Cell::extractAllCellReferencesInRange($pRange);
+// var_dump($aReferences);
+ if (!isset($aReferences[1])) {
+ // Single cell (or single column or row) in range
+ list($currentCol,$currentRow) = Cell::coordinateFromString($aReferences[0]);
+ $cellValue = null;
+ if ($pSheet->cellExists($aReferences[0])) {
+ $returnValue[$currentRow][$currentCol] = $pSheet->getCell($aReferences[0])->getCalculatedValue($resetLog);
+ } else {
+ $returnValue[$currentRow][$currentCol] = null;
+ }
+ } else {
+ // Extract cell data for all cells in the range
+ foreach ($aReferences as $reference) {
+ // Extract range
+ list($currentCol,$currentRow) = Cell::coordinateFromString($reference);
+// echo 'NAMED RANGE: $currentCol='.$currentCol.' $currentRow='.$currentRow.'
';
+ $cellValue = null;
+ if ($pSheet->cellExists($reference)) {
+ $returnValue[$currentRow][$currentCol] = $pSheet->getCell($reference)->getCalculatedValue($resetLog);
+ } else {
+ $returnValue[$currentRow][$currentCol] = null;
+ }
+ }
+ }
+// print_r($returnValue);
+// echo '
';
+ }
- // Return
- return $returnValue;
- } // function extractNamedRange()
+ // Return
+ return $returnValue;
+ } // function extractNamedRange()
- /**
- * Is a specific function implemented?
- *
- * @param string $pFunction Function Name
- * @return boolean
- */
- public function isImplemented($pFunction = '') {
- $pFunction = strtoupper ($pFunction);
- if (isset(self::$_PHPExcelFunctions[$pFunction])) {
- return (self::$_PHPExcelFunctions[$pFunction]['functionCall'] != 'Calculation_Functions::DUMMY');
- } else {
- return FALSE;
- }
- } // function isImplemented()
+ /**
+ * Is a specific function implemented?
+ *
+ * @param string $pFunction Function Name
+ * @return boolean
+ */
+ public function isImplemented($pFunction = '') {
+ $pFunction = strtoupper ($pFunction);
+ if (isset(self::$_PHPExcelFunctions[$pFunction])) {
+ return (self::$_PHPExcelFunctions[$pFunction]['functionCall'] != 'Calculation_Functions::DUMMY');
+ } else {
+ return false;
+ }
+ } // function isImplemented()
- /**
- * Get a list of all implemented functions as an array of function objects
- *
- * @return array of Calculation_Function
- */
- public function listFunctions() {
- // Return value
- $returnValue = array();
- // Loop functions
- foreach(self::$_PHPExcelFunctions as $functionName => $function) {
- if ($function['functionCall'] != 'Calculation_Functions::DUMMY') {
- $returnValue[$functionName] = new Calculation_Function($function['category'],
- $functionName,
- $function['functionCall']
- );
- }
- }
+ /**
+ * Get a list of all implemented functions as an array of function objects
+ *
+ * @return array of Calculation_Function
+ */
+ public function listFunctions() {
+ // Return value
+ $returnValue = array();
+ // Loop functions
+ foreach(self::$_PHPExcelFunctions as $functionName => $function) {
+ if ($function['functionCall'] != 'Calculation_Functions::DUMMY') {
+ $returnValue[$functionName] = new Calculation_Function($function['category'],
+ $functionName,
+ $function['functionCall']
+ );
+ }
+ }
- // Return
- return $returnValue;
- } // function listFunctions()
+ // Return
+ return $returnValue;
+ } // function listFunctions()
- /**
- * Get a list of all Excel function names
- *
- * @return array
- */
- public function listAllFunctionNames() {
- return array_keys(self::$_PHPExcelFunctions);
- } // function listAllFunctionNames()
+ /**
+ * Get a list of all Excel function names
+ *
+ * @return array
+ */
+ public function listAllFunctionNames() {
+ return array_keys(self::$_PHPExcelFunctions);
+ } // function listAllFunctionNames()
- /**
- * Get a list of implemented Excel function names
- *
- * @return array
- */
- public function listFunctionNames() {
- // Return value
- $returnValue = array();
- // Loop functions
- foreach(self::$_PHPExcelFunctions as $functionName => $function) {
- if ($function['functionCall'] != 'Calculation_Functions::DUMMY') {
- $returnValue[] = $functionName;
- }
- }
-
- // Return
- return $returnValue;
- } // function listFunctionNames()
+ /**
+ * Get a list of implemented Excel function names
+ *
+ * @return array
+ */
+ public function listFunctionNames() {
+ // Return value
+ $returnValue = array();
+ // Loop functions
+ foreach(self::$_PHPExcelFunctions as $functionName => $function) {
+ if ($function['functionCall'] != 'Calculation_Functions::DUMMY') {
+ $returnValue[] = $functionName;
+ }
+ }
+ // Return
+ return $returnValue;
+ } // function listFunctionNames()
}
diff --git a/Classes/PHPExcel/Calculation/Database.php b/Classes/PHPExcel/Calculation/Database.php
index b18aa29..5033eb3 100644
--- a/Classes/PHPExcel/Calculation/Database.php
+++ b/Classes/PHPExcel/Calculation/Database.php
@@ -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,687 +31,685 @@ namespace PHPExcel;
/**
* PHPExcel\Calculation_Database
*
- * @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_Database {
- /**
- * __fieldExtract
- *
- * Extracts the column ID to use for the data field.
- *
- * @access private
- * @param mixed[] $database The range of cells that makes up the list or database.
- * A database is a list of related data in which rows of related
- * information are records, and columns of data are fields. The
- * first row of the list contains labels for each column.
- * @param mixed $field Indicates which column is used in the function. Enter the
- * column label enclosed between double quotation marks, such as
- * "Age" or "Yield," or a number (without quotation marks) that
- * represents the position of the column within the list: 1 for
- * the first column, 2 for the second column, and so on.
- * @return string|NULL
- *
- */
- private static function __fieldExtract($database,$field) {
- $field = strtoupper(Calculation_Functions::flattenSingleValue($field));
- $fieldNames = array_map('strtoupper',array_shift($database));
+ /**
+ * __fieldExtract
+ *
+ * Extracts the column ID to use for the data field.
+ *
+ * @access private
+ * @param mixed[] $database The range of cells that makes up the list or database.
+ * A database is a list of related data in which rows of related
+ * information are records, and columns of data are fields. The
+ * first row of the list contains labels for each column.
+ * @param mixed $field Indicates which column is used in the function. Enter the
+ * column label enclosed between double quotation marks, such as
+ * "Age" or "Yield," or a number (without quotation marks) that
+ * represents the position of the column within the list: 1 for
+ * the first column, 2 for the second column, and so on.
+ * @return string|null
+ *
+ */
+ private static function __fieldExtract($database,$field) {
+ $field = strtoupper(Calculation_Functions::flattenSingleValue($field));
+ $fieldNames = array_map('strtoupper',array_shift($database));
- if (is_numeric($field)) {
- $keys = array_keys($fieldNames);
- return $keys[$field-1];
- }
- $key = array_search($field,$fieldNames);
- return ($key) ? $key : NULL;
- }
+ if (is_numeric($field)) {
+ $keys = array_keys($fieldNames);
+ return $keys[$field-1];
+ }
+ $key = array_search($field,$fieldNames);
+ return ($key) ? $key : null;
+ }
- /**
- * __filter
- *
- * Parses the selection criteria, extracts the database rows that match those criteria, and
- * returns that subset of rows.
- *
- * @access private
- * @param mixed[] $database The range of cells that makes up the list or database.
- * A database is a list of related data in which rows of related
- * information are records, and columns of data are fields. The
- * first row of the list contains labels for each column.
- * @param mixed[] $criteria The range of cells that contains the conditions you specify.
- * You can use any range for the criteria argument, as long as it
- * includes at least one column label and at least one cell below
- * the column label in which you specify a condition for the
- * column.
- * @return array of mixed
- *
- */
- private static function __filter($database,$criteria) {
- $fieldNames = array_shift($database);
- $criteriaNames = array_shift($criteria);
+ /**
+ * __filter
+ *
+ * Parses the selection criteria, extracts the database rows that match those criteria, and
+ * returns that subset of rows.
+ *
+ * @access private
+ * @param mixed[] $database The range of cells that makes up the list or database.
+ * A database is a list of related data in which rows of related
+ * information are records, and columns of data are fields. The
+ * first row of the list contains labels for each column.
+ * @param mixed[] $criteria The range of cells that contains the conditions you specify.
+ * You can use any range for the criteria argument, as long as it
+ * includes at least one column label and at least one cell below
+ * the column label in which you specify a condition for the
+ * column.
+ * @return array of mixed
+ *
+ */
+ private static function __filter($database,$criteria) {
+ $fieldNames = array_shift($database);
+ $criteriaNames = array_shift($criteria);
- // Convert the criteria into a set of AND/OR conditions with [:placeholders]
- $testConditions = $testValues = array();
- $testConditionsCount = 0;
- foreach($criteriaNames as $key => $criteriaName) {
- $testCondition = array();
- $testConditionCount = 0;
- foreach($criteria as $row => $criterion) {
- if ($criterion[$key] > '') {
- $testCondition[] = '[:'.$criteriaName.']'.Calculation_Functions::_ifCondition($criterion[$key]);
- $testConditionCount++;
- }
- }
- if ($testConditionCount > 1) {
- $testConditions[] = 'OR('.implode(',',$testCondition).')';
- $testConditionsCount++;
- } elseif($testConditionCount == 1) {
- $testConditions[] = $testCondition[0];
- $testConditionsCount++;
- }
- }
+ // Convert the criteria into a set of AND/OR conditions with [:placeholders]
+ $testConditions = $testValues = array();
+ $testConditionsCount = 0;
+ foreach($criteriaNames as $key => $criteriaName) {
+ $testCondition = array();
+ $testConditionCount = 0;
+ foreach($criteria as $row => $criterion) {
+ if ($criterion[$key] > '') {
+ $testCondition[] = '[:'.$criteriaName.']'.Calculation_Functions::_ifCondition($criterion[$key]);
+ $testConditionCount++;
+ }
+ }
+ if ($testConditionCount > 1) {
+ $testConditions[] = 'OR('.implode(',',$testCondition).')';
+ $testConditionsCount++;
+ } elseif($testConditionCount == 1) {
+ $testConditions[] = $testCondition[0];
+ $testConditionsCount++;
+ }
+ }
- if ($testConditionsCount > 1) {
- $testConditionSet = 'AND('.implode(',',$testConditions).')';
- } elseif($testConditionsCount == 1) {
- $testConditionSet = $testConditions[0];
- }
+ if ($testConditionsCount > 1) {
+ $testConditionSet = 'AND('.implode(',',$testConditions).')';
+ } elseif($testConditionsCount == 1) {
+ $testConditionSet = $testConditions[0];
+ }
- // Loop through each row of the database
- foreach($database as $dataRow => $dataValues) {
- // Substitute actual values from the database row for our [:placeholders]
- $testConditionList = $testConditionSet;
- foreach($criteriaNames as $key => $criteriaName) {
- $k = array_search($criteriaName,$fieldNames);
- if (isset($dataValues[$k])) {
- $dataValue = $dataValues[$k];
- $dataValue = (is_string($dataValue)) ? Calculation::_wrapResult(strtoupper($dataValue)) : $dataValue;
- $testConditionList = str_replace('[:'.$criteriaName.']',$dataValue,$testConditionList);
- }
- }
- // evaluate the criteria against the row data
- $result = Calculation::getInstance()->_calculateFormulaValue('='.$testConditionList);
- // If the row failed to meet the criteria, remove it from the database
- if (!$result) {
- unset($database[$dataRow]);
- }
- }
+ // Loop through each row of the database
+ foreach($database as $dataRow => $dataValues) {
+ // Substitute actual values from the database row for our [:placeholders]
+ $testConditionList = $testConditionSet;
+ foreach($criteriaNames as $key => $criteriaName) {
+ $k = array_search($criteriaName,$fieldNames);
+ if (isset($dataValues[$k])) {
+ $dataValue = $dataValues[$k];
+ $dataValue = (is_string($dataValue)) ? Calculation::_wrapResult(strtoupper($dataValue)) : $dataValue;
+ $testConditionList = str_replace('[:'.$criteriaName.']',$dataValue,$testConditionList);
+ }
+ }
+ // evaluate the criteria against the row data
+ $result = Calculation::getInstance()->_calculateFormulaValue('='.$testConditionList);
+ // If the row failed to meet the criteria, remove it from the database
+ if (!$result) {
+ unset($database[$dataRow]);
+ }
+ }
- return $database;
- }
+ return $database;
+ }
- /**
- * DAVERAGE
- *
- * Averages the values in a column of a list or database that match conditions you specify.
- *
- * Excel Function:
- * DAVERAGE(database,field,criteria)
- *
- * @access public
- * @category Database Functions
- * @param mixed[] $database The range of cells that makes up the list or database.
- * A database is a list of related data in which rows of related
- * information are records, and columns of data are fields. The
- * first row of the list contains labels for each column.
- * @param string|integer $field Indicates which column is used in the function. Enter the
- * column label enclosed between double quotation marks, such as
- * "Age" or "Yield," or a number (without quotation marks) that
- * represents the position of the column within the list: 1 for
- * the first column, 2 for the second column, and so on.
- * @param mixed[] $criteria The range of cells that contains the conditions you specify.
- * You can use any range for the criteria argument, as long as it
- * includes at least one column label and at least one cell below
- * the column label in which you specify a condition for the
- * column.
- * @return float
- *
- */
- public static function DAVERAGE($database,$field,$criteria) {
- $field = self::__fieldExtract($database,$field);
- if (is_null($field)) {
- return NULL;
- }
- // reduce the database to a set of rows that match all the criteria
- $database = self::__filter($database,$criteria);
- // extract an array of values for the requested column
- $colData = array();
- foreach($database as $row) {
- $colData[] = $row[$field];
- }
+ /**
+ * DAVERAGE
+ *
+ * Averages the values in a column of a list or database that match conditions you specify.
+ *
+ * Excel Function:
+ * DAVERAGE(database,field,criteria)
+ *
+ * @access public
+ * @category Database Functions
+ * @param mixed[] $database The range of cells that makes up the list or database.
+ * A database is a list of related data in which rows of related
+ * information are records, and columns of data are fields. The
+ * first row of the list contains labels for each column.
+ * @param string|integer $field Indicates which column is used in the function. Enter the
+ * column label enclosed between double quotation marks, such as
+ * "Age" or "Yield," or a number (without quotation marks) that
+ * represents the position of the column within the list: 1 for
+ * the first column, 2 for the second column, and so on.
+ * @param mixed[] $criteria The range of cells that contains the conditions you specify.
+ * You can use any range for the criteria argument, as long as it
+ * includes at least one column label and at least one cell below
+ * the column label in which you specify a condition for the
+ * column.
+ * @return float
+ *
+ */
+ public static function DAVERAGE($database,$field,$criteria) {
+ $field = self::__fieldExtract($database,$field);
+ if (is_null($field)) {
+ return null;
+ }
+ // reduce the database to a set of rows that match all the criteria
+ $database = self::__filter($database,$criteria);
+ // extract an array of values for the requested column
+ $colData = array();
+ foreach($database as $row) {
+ $colData[] = $row[$field];
+ }
- // Return
- return Calculation_Statistical::AVERAGE($colData);
- } // function DAVERAGE()
+ // Return
+ return Calculation_Statistical::AVERAGE($colData);
+ } // function DAVERAGE()
- /**
- * DCOUNT
- *
- * Counts the cells that contain numbers in a column of a list or database that match conditions
- * that you specify.
- *
- * Excel Function:
- * DCOUNT(database,[field],criteria)
- *
- * Excel Function:
- * DAVERAGE(database,field,criteria)
- *
- * @access public
- * @category Database Functions
- * @param mixed[] $database The range of cells that makes up the list or database.
- * A database is a list of related data in which rows of related
- * information are records, and columns of data are fields. The
- * first row of the list contains labels for each column.
- * @param string|integer $field Indicates which column is used in the function. Enter the
- * column label enclosed between double quotation marks, such as
- * "Age" or "Yield," or a number (without quotation marks) that
- * represents the position of the column within the list: 1 for
- * the first column, 2 for the second column, and so on.
- * @param mixed[] $criteria The range of cells that contains the conditions you specify.
- * You can use any range for the criteria argument, as long as it
- * includes at least one column label and at least one cell below
- * the column label in which you specify a condition for the
- * column.
- * @return integer
- *
- * @TODO The field argument is optional. If field is omitted, DCOUNT counts all records in the
- * database that match the criteria.
- *
- */
- public static function DCOUNT($database,$field,$criteria) {
- $field = self::__fieldExtract($database,$field);
- if (is_null($field)) {
- return NULL;
- }
+ /**
+ * DCOUNT
+ *
+ * Counts the cells that contain numbers in a column of a list or database that match conditions
+ * that you specify.
+ *
+ * Excel Function:
+ * DCOUNT(database,[field],criteria)
+ *
+ * Excel Function:
+ * DAVERAGE(database,field,criteria)
+ *
+ * @access public
+ * @category Database Functions
+ * @param mixed[] $database The range of cells that makes up the list or database.
+ * A database is a list of related data in which rows of related
+ * information are records, and columns of data are fields. The
+ * first row of the list contains labels for each column.
+ * @param string|integer $field Indicates which column is used in the function. Enter the
+ * column label enclosed between double quotation marks, such as
+ * "Age" or "Yield," or a number (without quotation marks) that
+ * represents the position of the column within the list: 1 for
+ * the first column, 2 for the second column, and so on.
+ * @param mixed[] $criteria The range of cells that contains the conditions you specify.
+ * You can use any range for the criteria argument, as long as it
+ * includes at least one column label and at least one cell below
+ * the column label in which you specify a condition for the
+ * column.
+ * @return integer
+ *
+ * @TODO The field argument is optional. If field is omitted, DCOUNT counts all records in the
+ * database that match the criteria.
+ *
+ */
+ public static function DCOUNT($database,$field,$criteria) {
+ $field = self::__fieldExtract($database,$field);
+ if (is_null($field)) {
+ return null;
+ }
- // reduce the database to a set of rows that match all the criteria
- $database = self::__filter($database,$criteria);
- // extract an array of values for the requested column
- $colData = array();
- foreach($database as $row) {
- $colData[] = $row[$field];
- }
+ // reduce the database to a set of rows that match all the criteria
+ $database = self::__filter($database,$criteria);
+ // extract an array of values for the requested column
+ $colData = array();
+ foreach($database as $row) {
+ $colData[] = $row[$field];
+ }
- // Return
- return Calculation_Statistical::COUNT($colData);
- } // function DCOUNT()
+ // Return
+ return Calculation_Statistical::COUNT($colData);
+ } // function DCOUNT()
- /**
- * DCOUNTA
- *
- * Counts the nonblank cells in a column of a list or database that match conditions that you specify.
- *
- * Excel Function:
- * DCOUNTA(database,[field],criteria)
- *
- * @access public
- * @category Database Functions
- * @param mixed[] $database The range of cells that makes up the list or database.
- * A database is a list of related data in which rows of related
- * information are records, and columns of data are fields. The
- * first row of the list contains labels for each column.
- * @param string|integer $field Indicates which column is used in the function. Enter the
- * column label enclosed between double quotation marks, such as
- * "Age" or "Yield," or a number (without quotation marks) that
- * represents the position of the column within the list: 1 for
- * the first column, 2 for the second column, and so on.
- * @param mixed[] $criteria The range of cells that contains the conditions you specify.
- * You can use any range for the criteria argument, as long as it
- * includes at least one column label and at least one cell below
- * the column label in which you specify a condition for the
- * column.
- * @return integer
- *
- * @TODO The field argument is optional. If field is omitted, DCOUNTA counts all records in the
- * database that match the criteria.
- *
- */
- public static function DCOUNTA($database,$field,$criteria) {
- $field = self::__fieldExtract($database,$field);
- if (is_null($field)) {
- return NULL;
- }
+ /**
+ * DCOUNTA
+ *
+ * Counts the nonblank cells in a column of a list or database that match conditions that you specify.
+ *
+ * Excel Function:
+ * DCOUNTA(database,[field],criteria)
+ *
+ * @access public
+ * @category Database Functions
+ * @param mixed[] $database The range of cells that makes up the list or database.
+ * A database is a list of related data in which rows of related
+ * information are records, and columns of data are fields. The
+ * first row of the list contains labels for each column.
+ * @param string|integer $field Indicates which column is used in the function. Enter the
+ * column label enclosed between double quotation marks, such as
+ * "Age" or "Yield," or a number (without quotation marks) that
+ * represents the position of the column within the list: 1 for
+ * the first column, 2 for the second column, and so on.
+ * @param mixed[] $criteria The range of cells that contains the conditions you specify.
+ * You can use any range for the criteria argument, as long as it
+ * includes at least one column label and at least one cell below
+ * the column label in which you specify a condition for the
+ * column.
+ * @return integer
+ *
+ * @TODO The field argument is optional. If field is omitted, DCOUNTA counts all records in the
+ * database that match the criteria.
+ *
+ */
+ public static function DCOUNTA($database,$field,$criteria) {
+ $field = self::__fieldExtract($database,$field);
+ if (is_null($field)) {
+ return null;
+ }
- // reduce the database to a set of rows that match all the criteria
- $database = self::__filter($database,$criteria);
- // extract an array of values for the requested column
- $colData = array();
- foreach($database as $row) {
- $colData[] = $row[$field];
- }
+ // reduce the database to a set of rows that match all the criteria
+ $database = self::__filter($database,$criteria);
+ // extract an array of values for the requested column
+ $colData = array();
+ foreach($database as $row) {
+ $colData[] = $row[$field];
+ }
- // Return
- return Calculation_Statistical::COUNTA($colData);
- } // function DCOUNTA()
+ // Return
+ return Calculation_Statistical::COUNTA($colData);
+ } // function DCOUNTA()
- /**
- * DGET
- *
- * Extracts a single value from a column of a list or database that matches conditions that you
- * specify.
- *
- * Excel Function:
- * DGET(database,field,criteria)
- *
- * @access public
- * @category Database Functions
- * @param mixed[] $database The range of cells that makes up the list or database.
- * A database is a list of related data in which rows of related
- * information are records, and columns of data are fields. The
- * first row of the list contains labels for each column.
- * @param string|integer $field Indicates which column is used in the function. Enter the
- * column label enclosed between double quotation marks, such as
- * "Age" or "Yield," or a number (without quotation marks) that
- * represents the position of the column within the list: 1 for
- * the first column, 2 for the second column, and so on.
- * @param mixed[] $criteria The range of cells that contains the conditions you specify.
- * You can use any range for the criteria argument, as long as it
- * includes at least one column label and at least one cell below
- * the column label in which you specify a condition for the
- * column.
- * @return mixed
- *
- */
- public static function DGET($database,$field,$criteria) {
- $field = self::__fieldExtract($database,$field);
- if (is_null($field)) {
- return NULL;
- }
+ /**
+ * DGET
+ *
+ * Extracts a single value from a column of a list or database that matches conditions that you
+ * specify.
+ *
+ * Excel Function:
+ * DGET(database,field,criteria)
+ *
+ * @access public
+ * @category Database Functions
+ * @param mixed[] $database The range of cells that makes up the list or database.
+ * A database is a list of related data in which rows of related
+ * information are records, and columns of data are fields. The
+ * first row of the list contains labels for each column.
+ * @param string|integer $field Indicates which column is used in the function. Enter the
+ * column label enclosed between double quotation marks, such as
+ * "Age" or "Yield," or a number (without quotation marks) that
+ * represents the position of the column within the list: 1 for
+ * the first column, 2 for the second column, and so on.
+ * @param mixed[] $criteria The range of cells that contains the conditions you specify.
+ * You can use any range for the criteria argument, as long as it
+ * includes at least one column label and at least one cell below
+ * the column label in which you specify a condition for the
+ * column.
+ * @return mixed
+ *
+ */
+ public static function DGET($database,$field,$criteria) {
+ $field = self::__fieldExtract($database,$field);
+ if (is_null($field)) {
+ return null;
+ }
- // reduce the database to a set of rows that match all the criteria
- $database = self::__filter($database,$criteria);
- // extract an array of values for the requested column
- $colData = array();
- foreach($database as $row) {
- $colData[] = $row[$field];
- }
+ // reduce the database to a set of rows that match all the criteria
+ $database = self::__filter($database,$criteria);
+ // extract an array of values for the requested column
+ $colData = array();
+ foreach($database as $row) {
+ $colData[] = $row[$field];
+ }
- // Return
- if (count($colData) > 1) {
- return Calculation_Functions::NaN();
- }
+ // Return
+ if (count($colData) > 1) {
+ return Calculation_Functions::NaN();
+ }
- return $colData[0];
- } // function DGET()
+ return $colData[0];
+ } // function DGET()
- /**
- * DMAX
- *
- * Returns the largest number in a column of a list or database that matches conditions you that
- * specify.
- *
- * Excel Function:
- * DMAX(database,field,criteria)
- *
- * @access public
- * @category Database Functions
- * @param mixed[] $database The range of cells that makes up the list or database.
- * A database is a list of related data in which rows of related
- * information are records, and columns of data are fields. The
- * first row of the list contains labels for each column.
- * @param string|integer $field Indicates which column is used in the function. Enter the
- * column label enclosed between double quotation marks, such as
- * "Age" or "Yield," or a number (without quotation marks) that
- * represents the position of the column within the list: 1 for
- * the first column, 2 for the second column, and so on.
- * @param mixed[] $criteria The range of cells that contains the conditions you specify.
- * You can use any range for the criteria argument, as long as it
- * includes at least one column label and at least one cell below
- * the column label in which you specify a condition for the
- * column.
- * @return float
- *
- */
- public static function DMAX($database,$field,$criteria) {
- $field = self::__fieldExtract($database,$field);
- if (is_null($field)) {
- return NULL;
- }
+ /**
+ * DMAX
+ *
+ * Returns the largest number in a column of a list or database that matches conditions you that
+ * specify.
+ *
+ * Excel Function:
+ * DMAX(database,field,criteria)
+ *
+ * @access public
+ * @category Database Functions
+ * @param mixed[] $database The range of cells that makes up the list or database.
+ * A database is a list of related data in which rows of related
+ * information are records, and columns of data are fields. The
+ * first row of the list contains labels for each column.
+ * @param string|integer $field Indicates which column is used in the function. Enter the
+ * column label enclosed between double quotation marks, such as
+ * "Age" or "Yield," or a number (without quotation marks) that
+ * represents the position of the column within the list: 1 for
+ * the first column, 2 for the second column, and so on.
+ * @param mixed[] $criteria The range of cells that contains the conditions you specify.
+ * You can use any range for the criteria argument, as long as it
+ * includes at least one column label and at least one cell below
+ * the column label in which you specify a condition for the
+ * column.
+ * @return float
+ *
+ */
+ public static function DMAX($database,$field,$criteria) {
+ $field = self::__fieldExtract($database,$field);
+ if (is_null($field)) {
+ return null;
+ }
- // reduce the database to a set of rows that match all the criteria
- $database = self::__filter($database,$criteria);
- // extract an array of values for the requested column
- $colData = array();
- foreach($database as $row) {
- $colData[] = $row[$field];
- }
+ // reduce the database to a set of rows that match all the criteria
+ $database = self::__filter($database,$criteria);
+ // extract an array of values for the requested column
+ $colData = array();
+ foreach($database as $row) {
+ $colData[] = $row[$field];
+ }
- // Return
- return Calculation_Statistical::MAX($colData);
- } // function DMAX()
+ // Return
+ return Calculation_Statistical::MAX($colData);
+ } // function DMAX()
- /**
- * DMIN
- *
- * Returns the smallest number in a column of a list or database that matches conditions you that
- * specify.
- *
- * Excel Function:
- * DMIN(database,field,criteria)
- *
- * @access public
- * @category Database Functions
- * @param mixed[] $database The range of cells that makes up the list or database.
- * A database is a list of related data in which rows of related
- * information are records, and columns of data are fields. The
- * first row of the list contains labels for each column.
- * @param string|integer $field Indicates which column is used in the function. Enter the
- * column label enclosed between double quotation marks, such as
- * "Age" or "Yield," or a number (without quotation marks) that
- * represents the position of the column within the list: 1 for
- * the first column, 2 for the second column, and so on.
- * @param mixed[] $criteria The range of cells that contains the conditions you specify.
- * You can use any range for the criteria argument, as long as it
- * includes at least one column label and at least one cell below
- * the column label in which you specify a condition for the
- * column.
- * @return float
- *
- */
- public static function DMIN($database,$field,$criteria) {
- $field = self::__fieldExtract($database,$field);
- if (is_null($field)) {
- return NULL;
- }
+ /**
+ * DMIN
+ *
+ * Returns the smallest number in a column of a list or database that matches conditions you that
+ * specify.
+ *
+ * Excel Function:
+ * DMIN(database,field,criteria)
+ *
+ * @access public
+ * @category Database Functions
+ * @param mixed[] $database The range of cells that makes up the list or database.
+ * A database is a list of related data in which rows of related
+ * information are records, and columns of data are fields. The
+ * first row of the list contains labels for each column.
+ * @param string|integer $field Indicates which column is used in the function. Enter the
+ * column label enclosed between double quotation marks, such as
+ * "Age" or "Yield," or a number (without quotation marks) that
+ * represents the position of the column within the list: 1 for
+ * the first column, 2 for the second column, and so on.
+ * @param mixed[] $criteria The range of cells that contains the conditions you specify.
+ * You can use any range for the criteria argument, as long as it
+ * includes at least one column label and at least one cell below
+ * the column label in which you specify a condition for the
+ * column.
+ * @return float
+ *
+ */
+ public static function DMIN($database,$field,$criteria) {
+ $field = self::__fieldExtract($database,$field);
+ if (is_null($field)) {
+ return null;
+ }
- // reduce the database to a set of rows that match all the criteria
- $database = self::__filter($database,$criteria);
- // extract an array of values for the requested column
- $colData = array();
- foreach($database as $row) {
- $colData[] = $row[$field];
- }
+ // reduce the database to a set of rows that match all the criteria
+ $database = self::__filter($database,$criteria);
+ // extract an array of values for the requested column
+ $colData = array();
+ foreach($database as $row) {
+ $colData[] = $row[$field];
+ }
- // Return
- return Calculation_Statistical::MIN($colData);
- } // function DMIN()
+ // Return
+ return Calculation_Statistical::MIN($colData);
+ } // function DMIN()
- /**
- * DPRODUCT
- *
- * Multiplies the values in a column of a list or database that match conditions that you specify.
- *
- * Excel Function:
- * DPRODUCT(database,field,criteria)
- *
- * @access public
- * @category Database Functions
- * @param mixed[] $database The range of cells that makes up the list or database.
- * A database is a list of related data in which rows of related
- * information are records, and columns of data are fields. The
- * first row of the list contains labels for each column.
- * @param string|integer $field Indicates which column is used in the function. Enter the
- * column label enclosed between double quotation marks, such as
- * "Age" or "Yield," or a number (without quotation marks) that
- * represents the position of the column within the list: 1 for
- * the first column, 2 for the second column, and so on.
- * @param mixed[] $criteria The range of cells that contains the conditions you specify.
- * You can use any range for the criteria argument, as long as it
- * includes at least one column label and at least one cell below
- * the column label in which you specify a condition for the
- * column.
- * @return float
- *
- */
- public static function DPRODUCT($database,$field,$criteria) {
- $field = self::__fieldExtract($database,$field);
- if (is_null($field)) {
- return NULL;
- }
+ /**
+ * DPRODUCT
+ *
+ * Multiplies the values in a column of a list or database that match conditions that you specify.
+ *
+ * Excel Function:
+ * DPRODUCT(database,field,criteria)
+ *
+ * @access public
+ * @category Database Functions
+ * @param mixed[] $database The range of cells that makes up the list or database.
+ * A database is a list of related data in which rows of related
+ * information are records, and columns of data are fields. The
+ * first row of the list contains labels for each column.
+ * @param string|integer $field Indicates which column is used in the function. Enter the
+ * column label enclosed between double quotation marks, such as
+ * "Age" or "Yield," or a number (without quotation marks) that
+ * represents the position of the column within the list: 1 for
+ * the first column, 2 for the second column, and so on.
+ * @param mixed[] $criteria The range of cells that contains the conditions you specify.
+ * You can use any range for the criteria argument, as long as it
+ * includes at least one column label and at least one cell below
+ * the column label in which you specify a condition for the
+ * column.
+ * @return float
+ *
+ */
+ public static function DPRODUCT($database,$field,$criteria) {
+ $field = self::__fieldExtract($database,$field);
+ if (is_null($field)) {
+ return null;
+ }
- // reduce the database to a set of rows that match all the criteria
- $database = self::__filter($database,$criteria);
- // extract an array of values for the requested column
- $colData = array();
- foreach($database as $row) {
- $colData[] = $row[$field];
- }
+ // reduce the database to a set of rows that match all the criteria
+ $database = self::__filter($database,$criteria);
+ // extract an array of values for the requested column
+ $colData = array();
+ foreach($database as $row) {
+ $colData[] = $row[$field];
+ }
- // Return
- return Calculation_MathTrig::PRODUCT($colData);
- } // function DPRODUCT()
+ // Return
+ return Calculation_MathTrig::PRODUCT($colData);
+ } // function DPRODUCT()
- /**
- * DSTDEV
- *
- * Estimates the standard deviation of a population based on a sample by using the numbers in a
- * column of a list or database that match conditions that you specify.
- *
- * Excel Function:
- * DSTDEV(database,field,criteria)
- *
- * @access public
- * @category Database Functions
- * @param mixed[] $database The range of cells that makes up the list or database.
- * A database is a list of related data in which rows of related
- * information are records, and columns of data are fields. The
- * first row of the list contains labels for each column.
- * @param string|integer $field Indicates which column is used in the function. Enter the
- * column label enclosed between double quotation marks, such as
- * "Age" or "Yield," or a number (without quotation marks) that
- * represents the position of the column within the list: 1 for
- * the first column, 2 for the second column, and so on.
- * @param mixed[] $criteria The range of cells that contains the conditions you specify.
- * You can use any range for the criteria argument, as long as it
- * includes at least one column label and at least one cell below
- * the column label in which you specify a condition for the
- * column.
- * @return float
- *
- */
- public static function DSTDEV($database,$field,$criteria) {
- $field = self::__fieldExtract($database,$field);
- if (is_null($field)) {
- return NULL;
- }
+ /**
+ * DSTDEV
+ *
+ * Estimates the standard deviation of a population based on a sample by using the numbers in a
+ * column of a list or database that match conditions that you specify.
+ *
+ * Excel Function:
+ * DSTDEV(database,field,criteria)
+ *
+ * @access public
+ * @category Database Functions
+ * @param mixed[] $database The range of cells that makes up the list or database.
+ * A database is a list of related data in which rows of related
+ * information are records, and columns of data are fields. The
+ * first row of the list contains labels for each column.
+ * @param string|integer $field Indicates which column is used in the function. Enter the
+ * column label enclosed between double quotation marks, such as
+ * "Age" or "Yield," or a number (without quotation marks) that
+ * represents the position of the column within the list: 1 for
+ * the first column, 2 for the second column, and so on.
+ * @param mixed[] $criteria The range of cells that contains the conditions you specify.
+ * You can use any range for the criteria argument, as long as it
+ * includes at least one column label and at least one cell below
+ * the column label in which you specify a condition for the
+ * column.
+ * @return float
+ *
+ */
+ public static function DSTDEV($database,$field,$criteria) {
+ $field = self::__fieldExtract($database,$field);
+ if (is_null($field)) {
+ return null;
+ }
- // reduce the database to a set of rows that match all the criteria
- $database = self::__filter($database,$criteria);
- // extract an array of values for the requested column
- $colData = array();
- foreach($database as $row) {
- $colData[] = $row[$field];
- }
+ // reduce the database to a set of rows that match all the criteria
+ $database = self::__filter($database,$criteria);
+ // extract an array of values for the requested column
+ $colData = array();
+ foreach($database as $row) {
+ $colData[] = $row[$field];
+ }
- // Return
- return Calculation_Statistical::STDEV($colData);
- } // function DSTDEV()
+ // Return
+ return Calculation_Statistical::STDEV($colData);
+ } // function DSTDEV()
- /**
- * DSTDEVP
- *
- * Calculates the standard deviation of a population based on the entire population by using the
- * numbers in a column of a list or database that match conditions that you specify.
- *
- * Excel Function:
- * DSTDEVP(database,field,criteria)
- *
- * @access public
- * @category Database Functions
- * @param mixed[] $database The range of cells that makes up the list or database.
- * A database is a list of related data in which rows of related
- * information are records, and columns of data are fields. The
- * first row of the list contains labels for each column.
- * @param string|integer $field Indicates which column is used in the function. Enter the
- * column label enclosed between double quotation marks, such as
- * "Age" or "Yield," or a number (without quotation marks) that
- * represents the position of the column within the list: 1 for
- * the first column, 2 for the second column, and so on.
- * @param mixed[] $criteria The range of cells that contains the conditions you specify.
- * You can use any range for the criteria argument, as long as it
- * includes at least one column label and at least one cell below
- * the column label in which you specify a condition for the
- * column.
- * @return float
- *
- */
- public static function DSTDEVP($database,$field,$criteria) {
- $field = self::__fieldExtract($database,$field);
- if (is_null($field)) {
- return NULL;
- }
+ /**
+ * DSTDEVP
+ *
+ * Calculates the standard deviation of a population based on the entire population by using the
+ * numbers in a column of a list or database that match conditions that you specify.
+ *
+ * Excel Function:
+ * DSTDEVP(database,field,criteria)
+ *
+ * @access public
+ * @category Database Functions
+ * @param mixed[] $database The range of cells that makes up the list or database.
+ * A database is a list of related data in which rows of related
+ * information are records, and columns of data are fields. The
+ * first row of the list contains labels for each column.
+ * @param string|integer $field Indicates which column is used in the function. Enter the
+ * column label enclosed between double quotation marks, such as
+ * "Age" or "Yield," or a number (without quotation marks) that
+ * represents the position of the column within the list: 1 for
+ * the first column, 2 for the second column, and so on.
+ * @param mixed[] $criteria The range of cells that contains the conditions you specify.
+ * You can use any range for the criteria argument, as long as it
+ * includes at least one column label and at least one cell below
+ * the column label in which you specify a condition for the
+ * column.
+ * @return float
+ *
+ */
+ public static function DSTDEVP($database,$field,$criteria) {
+ $field = self::__fieldExtract($database,$field);
+ if (is_null($field)) {
+ return null;
+ }
- // reduce the database to a set of rows that match all the criteria
- $database = self::__filter($database,$criteria);
- // extract an array of values for the requested column
- $colData = array();
- foreach($database as $row) {
- $colData[] = $row[$field];
- }
+ // reduce the database to a set of rows that match all the criteria
+ $database = self::__filter($database,$criteria);
+ // extract an array of values for the requested column
+ $colData = array();
+ foreach($database as $row) {
+ $colData[] = $row[$field];
+ }
- // Return
- return Calculation_Statistical::STDEVP($colData);
- } // function DSTDEVP()
+ // Return
+ return Calculation_Statistical::STDEVP($colData);
+ } // function DSTDEVP()
- /**
- * DSUM
- *
- * Adds the numbers in a column of a list or database that match conditions that you specify.
- *
- * Excel Function:
- * DSUM(database,field,criteria)
- *
- * @access public
- * @category Database Functions
- * @param mixed[] $database The range of cells that makes up the list or database.
- * A database is a list of related data in which rows of related
- * information are records, and columns of data are fields. The
- * first row of the list contains labels for each column.
- * @param string|integer $field Indicates which column is used in the function. Enter the
- * column label enclosed between double quotation marks, such as
- * "Age" or "Yield," or a number (without quotation marks) that
- * represents the position of the column within the list: 1 for
- * the first column, 2 for the second column, and so on.
- * @param mixed[] $criteria The range of cells that contains the conditions you specify.
- * You can use any range for the criteria argument, as long as it
- * includes at least one column label and at least one cell below
- * the column label in which you specify a condition for the
- * column.
- * @return float
- *
- */
- public static function DSUM($database,$field,$criteria) {
- $field = self::__fieldExtract($database,$field);
- if (is_null($field)) {
- return NULL;
- }
+ /**
+ * DSUM
+ *
+ * Adds the numbers in a column of a list or database that match conditions that you specify.
+ *
+ * Excel Function:
+ * DSUM(database,field,criteria)
+ *
+ * @access public
+ * @category Database Functions
+ * @param mixed[] $database The range of cells that makes up the list or database.
+ * A database is a list of related data in which rows of related
+ * information are records, and columns of data are fields. The
+ * first row of the list contains labels for each column.
+ * @param string|integer $field Indicates which column is used in the function. Enter the
+ * column label enclosed between double quotation marks, such as
+ * "Age" or "Yield," or a number (without quotation marks) that
+ * represents the position of the column within the list: 1 for
+ * the first column, 2 for the second column, and so on.
+ * @param mixed[] $criteria The range of cells that contains the conditions you specify.
+ * You can use any range for the criteria argument, as long as it
+ * includes at least one column label and at least one cell below
+ * the column label in which you specify a condition for the
+ * column.
+ * @return float
+ *
+ */
+ public static function DSUM($database,$field,$criteria) {
+ $field = self::__fieldExtract($database,$field);
+ if (is_null($field)) {
+ return null;
+ }
- // reduce the database to a set of rows that match all the criteria
- $database = self::__filter($database,$criteria);
- // extract an array of values for the requested column
- $colData = array();
- foreach($database as $row) {
- $colData[] = $row[$field];
- }
+ // reduce the database to a set of rows that match all the criteria
+ $database = self::__filter($database,$criteria);
+ // extract an array of values for the requested column
+ $colData = array();
+ foreach($database as $row) {
+ $colData[] = $row[$field];
+ }
- // Return
- return Calculation_MathTrig::SUM($colData);
- } // function DSUM()
+ // Return
+ return Calculation_MathTrig::SUM($colData);
+ } // function DSUM()
- /**
- * DVAR
- *
- * Estimates the variance of a population based on a sample by using the numbers in a column
- * of a list or database that match conditions that you specify.
- *
- * Excel Function:
- * DVAR(database,field,criteria)
- *
- * @access public
- * @category Database Functions
- * @param mixed[] $database The range of cells that makes up the list or database.
- * A database is a list of related data in which rows of related
- * information are records, and columns of data are fields. The
- * first row of the list contains labels for each column.
- * @param string|integer $field Indicates which column is used in the function. Enter the
- * column label enclosed between double quotation marks, such as
- * "Age" or "Yield," or a number (without quotation marks) that
- * represents the position of the column within the list: 1 for
- * the first column, 2 for the second column, and so on.
- * @param mixed[] $criteria The range of cells that contains the conditions you specify.
- * You can use any range for the criteria argument, as long as it
- * includes at least one column label and at least one cell below
- * the column label in which you specify a condition for the
- * column.
- * @return float
- *
- */
- public static function DVAR($database,$field,$criteria) {
- $field = self::__fieldExtract($database,$field);
- if (is_null($field)) {
- return NULL;
- }
+ /**
+ * DVAR
+ *
+ * Estimates the variance of a population based on a sample by using the numbers in a column
+ * of a list or database that match conditions that you specify.
+ *
+ * Excel Function:
+ * DVAR(database,field,criteria)
+ *
+ * @access public
+ * @category Database Functions
+ * @param mixed[] $database The range of cells that makes up the list or database.
+ * A database is a list of related data in which rows of related
+ * information are records, and columns of data are fields. The
+ * first row of the list contains labels for each column.
+ * @param string|integer $field Indicates which column is used in the function. Enter the
+ * column label enclosed between double quotation marks, such as
+ * "Age" or "Yield," or a number (without quotation marks) that
+ * represents the position of the column within the list: 1 for
+ * the first column, 2 for the second column, and so on.
+ * @param mixed[] $criteria The range of cells that contains the conditions you specify.
+ * You can use any range for the criteria argument, as long as it
+ * includes at least one column label and at least one cell below
+ * the column label in which you specify a condition for the
+ * column.
+ * @return float
+ *
+ */
+ public static function DVAR($database,$field,$criteria) {
+ $field = self::__fieldExtract($database,$field);
+ if (is_null($field)) {
+ return null;
+ }
- // reduce the database to a set of rows that match all the criteria
- $database = self::__filter($database,$criteria);
- // extract an array of values for the requested column
- $colData = array();
- foreach($database as $row) {
- $colData[] = $row[$field];
- }
+ // reduce the database to a set of rows that match all the criteria
+ $database = self::__filter($database,$criteria);
+ // extract an array of values for the requested column
+ $colData = array();
+ foreach($database as $row) {
+ $colData[] = $row[$field];
+ }
- // Return
- return Calculation_Statistical::VARFunc($colData);
- } // function DVAR()
+ // Return
+ return Calculation_Statistical::VARFunc($colData);
+ } // function DVAR()
- /**
- * DVARP
- *
- * Calculates the variance of a population based on the entire population by using the numbers
- * in a column of a list or database that match conditions that you specify.
- *
- * Excel Function:
- * DVARP(database,field,criteria)
- *
- * @access public
- * @category Database Functions
- * @param mixed[] $database The range of cells that makes up the list or database.
- * A database is a list of related data in which rows of related
- * information are records, and columns of data are fields. The
- * first row of the list contains labels for each column.
- * @param string|integer $field Indicates which column is used in the function. Enter the
- * column label enclosed between double quotation marks, such as
- * "Age" or "Yield," or a number (without quotation marks) that
- * represents the position of the column within the list: 1 for
- * the first column, 2 for the second column, and so on.
- * @param mixed[] $criteria The range of cells that contains the conditions you specify.
- * You can use any range for the criteria argument, as long as it
- * includes at least one column label and at least one cell below
- * the column label in which you specify a condition for the
- * column.
- * @return float
- *
- */
- public static function DVARP($database,$field,$criteria) {
- $field = self::__fieldExtract($database,$field);
- if (is_null($field)) {
- return NULL;
- }
-
- // reduce the database to a set of rows that match all the criteria
- $database = self::__filter($database,$criteria);
- // extract an array of values for the requested column
- $colData = array();
- foreach($database as $row) {
- $colData[] = $row[$field];
- }
-
- // Return
- return Calculation_Statistical::VARP($colData);
- } // function DVARP()
+ /**
+ * DVARP
+ *
+ * Calculates the variance of a population based on the entire population by using the numbers
+ * in a column of a list or database that match conditions that you specify.
+ *
+ * Excel Function:
+ * DVARP(database,field,criteria)
+ *
+ * @access public
+ * @category Database Functions
+ * @param mixed[] $database The range of cells that makes up the list or database.
+ * A database is a list of related data in which rows of related
+ * information are records, and columns of data are fields. The
+ * first row of the list contains labels for each column.
+ * @param string|integer $field Indicates which column is used in the function. Enter the
+ * column label enclosed between double quotation marks, such as
+ * "Age" or "Yield," or a number (without quotation marks) that
+ * represents the position of the column within the list: 1 for
+ * the first column, 2 for the second column, and so on.
+ * @param mixed[] $criteria The range of cells that contains the conditions you specify.
+ * You can use any range for the criteria argument, as long as it
+ * includes at least one column label and at least one cell below
+ * the column label in which you specify a condition for the
+ * column.
+ * @return float
+ *
+ */
+ public static function DVARP($database,$field,$criteria) {
+ $field = self::__fieldExtract($database,$field);
+ if (is_null($field)) {
+ return null;
+ }
+ // reduce the database to a set of rows that match all the criteria
+ $database = self::__filter($database,$criteria);
+ // extract an array of values for the requested column
+ $colData = array();
+ foreach($database as $row) {
+ $colData[] = $row[$field];
+ }
+ // Return
+ return Calculation_Statistical::VARP($colData);
+ } // function DVARP()
}
diff --git a/Classes/PHPExcel/Calculation/DateTime.php b/Classes/PHPExcel/Calculation/DateTime.php
index 04f70bf..ddf942e 100644
--- a/Classes/PHPExcel/Calculation/DateTime.php
+++ b/Classes/PHPExcel/Calculation/DateTime.php
@@ -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,1437 +31,1435 @@ namespace PHPExcel;
/**
* PHPExcel\Calculation_DateTime
*
- * @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_DateTime {
- /**
- * Identify if a year is a leap year or not
- *
- * @param integer $year The year to test
- * @return boolean TRUE if the year is a leap year, otherwise FALSE
- */
- public static function _isLeapYear($year) {
- return ((($year % 4) == 0) && (($year % 100) != 0) || (($year % 400) == 0));
- } // function _isLeapYear()
+ /**
+ * Identify if a year is a leap year or not
+ *
+ * @param integer $year The year to test
+ * @return boolean true if the year is a leap year, otherwise false
+ */
+ public static function _isLeapYear($year) {
+ return ((($year % 4) == 0) && (($year % 100) != 0) || (($year % 400) == 0));
+ } // function _isLeapYear()
- /**
- * Return the number of days between two dates based on a 360 day calendar
- *
- * @param integer $startDay Day of month of the start date
- * @param integer $startMonth Month of the start date
- * @param integer $startYear Year of the start date
- * @param integer $endDay Day of month of the start date
- * @param integer $endMonth Month of the start date
- * @param integer $endYear Year of the start date
- * @param boolean $methodUS Whether to use the US method or the European method of calculation
- * @return integer Number of days between the start date and the end date
- */
- private static function _dateDiff360($startDay, $startMonth, $startYear, $endDay, $endMonth, $endYear, $methodUS) {
- if ($startDay == 31) {
- --$startDay;
- } elseif ($methodUS && ($startMonth == 2 && ($startDay == 29 || ($startDay == 28 && !self::_isLeapYear($startYear))))) {
- $startDay = 30;
- }
- if ($endDay == 31) {
- if ($methodUS && $startDay != 30) {
- $endDay = 1;
- if ($endMonth == 12) {
- ++$endYear;
- $endMonth = 1;
- } else {
- ++$endMonth;
- }
- } else {
- $endDay = 30;
- }
- }
+ /**
+ * Return the number of days between two dates based on a 360 day calendar
+ *
+ * @param integer $startDay Day of month of the start date
+ * @param integer $startMonth Month of the start date
+ * @param integer $startYear Year of the start date
+ * @param integer $endDay Day of month of the start date
+ * @param integer $endMonth Month of the start date
+ * @param integer $endYear Year of the start date
+ * @param boolean $methodUS Whether to use the US method or the European method of calculation
+ * @return integer Number of days between the start date and the end date
+ */
+ private static function _dateDiff360($startDay, $startMonth, $startYear, $endDay, $endMonth, $endYear, $methodUS) {
+ if ($startDay == 31) {
+ --$startDay;
+ } elseif ($methodUS && ($startMonth == 2 && ($startDay == 29 || ($startDay == 28 && !self::_isLeapYear($startYear))))) {
+ $startDay = 30;
+ }
+ if ($endDay == 31) {
+ if ($methodUS && $startDay != 30) {
+ $endDay = 1;
+ if ($endMonth == 12) {
+ ++$endYear;
+ $endMonth = 1;
+ } else {
+ ++$endMonth;
+ }
+ } else {
+ $endDay = 30;
+ }
+ }
- return $endDay + $endMonth * 30 + $endYear * 360 - $startDay - $startMonth * 30 - $startYear * 360;
- } // function _dateDiff360()
+ return $endDay + $endMonth * 30 + $endYear * 360 - $startDay - $startMonth * 30 - $startYear * 360;
+ } // function _dateDiff360()
- /**
- * _getDateValue
- *
- * @param string $dateValue
- * @return mixed Excel date/time serial value, or string if error
- */
- public static function _getDateValue($dateValue) {
- if (!is_numeric($dateValue)) {
- if ((is_string($dateValue)) &&
- (Calculation_Functions::getCompatibilityMode() == Calculation_Functions::COMPATIBILITY_GNUMERIC)) {
- return Calculation_Functions::VALUE();
- }
- if ((is_object($dateValue)) && ($dateValue instanceof DateTime)) {
- $dateValue = Shared_Date::PHPToExcel($dateValue);
- } else {
- $saveReturnDateType = Calculation_Functions::getReturnDateType();
- Calculation_Functions::setReturnDateType(Calculation_Functions::RETURNDATE_EXCEL);
- $dateValue = self::DATEVALUE($dateValue);
- Calculation_Functions::setReturnDateType($saveReturnDateType);
- }
- }
- return $dateValue;
- } // function _getDateValue()
+ /**
+ * _getDateValue
+ *
+ * @param string $dateValue
+ * @return mixed Excel date/time serial value, or string if error
+ */
+ public static function _getDateValue($dateValue) {
+ if (!is_numeric($dateValue)) {
+ if ((is_string($dateValue)) &&
+ (Calculation_Functions::getCompatibilityMode() == Calculation_Functions::COMPATIBILITY_GNUMERIC)) {
+ return Calculation_Functions::VALUE();
+ }
+ if ((is_object($dateValue)) && ($dateValue instanceof DateTime)) {
+ $dateValue = Shared_Date::PHPToExcel($dateValue);
+ } else {
+ $saveReturnDateType = Calculation_Functions::getReturnDateType();
+ Calculation_Functions::setReturnDateType(Calculation_Functions::RETURNDATE_EXCEL);
+ $dateValue = self::DATEVALUE($dateValue);
+ Calculation_Functions::setReturnDateType($saveReturnDateType);
+ }
+ }
+ return $dateValue;
+ } // function _getDateValue()
- /**
- * _getTimeValue
- *
- * @param string $timeValue
- * @return mixed Excel date/time serial value, or string if error
- */
- private static function _getTimeValue($timeValue) {
- $saveReturnDateType = Calculation_Functions::getReturnDateType();
- Calculation_Functions::setReturnDateType(Calculation_Functions::RETURNDATE_EXCEL);
- $timeValue = self::TIMEVALUE($timeValue);
- Calculation_Functions::setReturnDateType($saveReturnDateType);
- return $timeValue;
- } // function _getTimeValue()
+ /**
+ * _getTimeValue
+ *
+ * @param string $timeValue
+ * @return mixed Excel date/time serial value, or string if error
+ */
+ private static function _getTimeValue($timeValue) {
+ $saveReturnDateType = Calculation_Functions::getReturnDateType();
+ Calculation_Functions::setReturnDateType(Calculation_Functions::RETURNDATE_EXCEL);
+ $timeValue = self::TIMEVALUE($timeValue);
+ Calculation_Functions::setReturnDateType($saveReturnDateType);
+ return $timeValue;
+ } // function _getTimeValue()
- private static function _adjustDateByMonths($dateValue = 0, $adjustmentMonths = 0) {
- // Execute function
- $PHPDateObject = Shared_Date::ExcelToPHPObject($dateValue);
- $oMonth = (int) $PHPDateObject->format('m');
- $oYear = (int) $PHPDateObject->format('Y');
+ private static function _adjustDateByMonths($dateValue = 0, $adjustmentMonths = 0) {
+ // Execute function
+ $PHPDateObject = Shared_Date::ExcelToPHPObject($dateValue);
+ $oMonth = (int) $PHPDateObject->format('m');
+ $oYear = (int) $PHPDateObject->format('Y');
- $adjustmentMonthsString = (string) $adjustmentMonths;
- if ($adjustmentMonths > 0) {
- $adjustmentMonthsString = '+'.$adjustmentMonths;
- }
- if ($adjustmentMonths != 0) {
- $PHPDateObject->modify($adjustmentMonthsString.' months');
- }
- $nMonth = (int) $PHPDateObject->format('m');
- $nYear = (int) $PHPDateObject->format('Y');
+ $adjustmentMonthsString = (string) $adjustmentMonths;
+ if ($adjustmentMonths > 0) {
+ $adjustmentMonthsString = '+'.$adjustmentMonths;
+ }
+ if ($adjustmentMonths != 0) {
+ $PHPDateObject->modify($adjustmentMonthsString.' months');
+ }
+ $nMonth = (int) $PHPDateObject->format('m');
+ $nYear = (int) $PHPDateObject->format('Y');
- $monthDiff = ($nMonth - $oMonth) + (($nYear - $oYear) * 12);
- if ($monthDiff != $adjustmentMonths) {
- $adjustDays = (int) $PHPDateObject->format('d');
- $adjustDaysString = '-'.$adjustDays.' days';
- $PHPDateObject->modify($adjustDaysString);
- }
- return $PHPDateObject;
- } // function _adjustDateByMonths()
+ $monthDiff = ($nMonth - $oMonth) + (($nYear - $oYear) * 12);
+ if ($monthDiff != $adjustmentMonths) {
+ $adjustDays = (int) $PHPDateObject->format('d');
+ $adjustDaysString = '-'.$adjustDays.' days';
+ $PHPDateObject->modify($adjustDaysString);
+ }
+ return $PHPDateObject;
+ } // function _adjustDateByMonths()
- /**
- * DATETIMENOW
- *
- * Returns the current date and time.
- * The NOW function is useful when you need to display the current date and time on a worksheet or
- * calculate a value based on the current date and time, and have that value updated each time you
- * open the worksheet.
- *
- * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the date
- * and time format of your regional settings. PHPExcel does not change cell formatting in this way.
- *
- * Excel Function:
- * NOW()
- *
- * @access public
- * @category Date/Time Functions
- * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
- * depending on the value of the ReturnDateType flag
- */
- public static function DATETIMENOW() {
- $saveTimeZone = date_default_timezone_get();
- date_default_timezone_set('UTC');
- $retValue = False;
- switch (Calculation_Functions::getReturnDateType()) {
- case Calculation_Functions::RETURNDATE_EXCEL :
- $retValue = (float) Shared_Date::PHPToExcel(time());
- break;
- case Calculation_Functions::RETURNDATE_PHP_NUMERIC :
- $retValue = (integer) time();
- break;
- case Calculation_Functions::RETURNDATE_PHP_OBJECT :
- $retValue = new DateTime();
- break;
- }
- date_default_timezone_set($saveTimeZone);
+ /**
+ * DATETIMENOW
+ *
+ * Returns the current date and time.
+ * The NOW function is useful when you need to display the current date and time on a worksheet or
+ * calculate a value based on the current date and time, and have that value updated each time you
+ * open the worksheet.
+ *
+ * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the date
+ * and time format of your regional settings. PHPExcel does not change cell formatting in this way.
+ *
+ * Excel Function:
+ * NOW()
+ *
+ * @access public
+ * @category Date/Time Functions
+ * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
+ * depending on the value of the ReturnDateType flag
+ */
+ public static function DATETIMENOW() {
+ $saveTimeZone = date_default_timezone_get();
+ date_default_timezone_set('UTC');
+ $retValue = False;
+ switch (Calculation_Functions::getReturnDateType()) {
+ case Calculation_Functions::RETURNDATE_EXCEL :
+ $retValue = (float) Shared_Date::PHPToExcel(time());
+ break;
+ case Calculation_Functions::RETURNDATE_PHP_NUMERIC :
+ $retValue = (integer) time();
+ break;
+ case Calculation_Functions::RETURNDATE_PHP_OBJECT :
+ $retValue = new DateTime();
+ break;
+ }
+ date_default_timezone_set($saveTimeZone);
- return $retValue;
- } // function DATETIMENOW()
+ return $retValue;
+ } // function DATETIMENOW()
- /**
- * DATENOW
- *
- * Returns the current date.
- * The NOW function is useful when you need to display the current date and time on a worksheet or
- * calculate a value based on the current date and time, and have that value updated each time you
- * open the worksheet.
- *
- * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the date
- * and time format of your regional settings. PHPExcel does not change cell formatting in this way.
- *
- * Excel Function:
- * TODAY()
- *
- * @access public
- * @category Date/Time Functions
- * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
- * depending on the value of the ReturnDateType flag
- */
- public static function DATENOW() {
- $saveTimeZone = date_default_timezone_get();
- date_default_timezone_set('UTC');
- $retValue = False;
- $excelDateTime = floor(Shared_Date::PHPToExcel(time()));
- switch (Calculation_Functions::getReturnDateType()) {
- case Calculation_Functions::RETURNDATE_EXCEL :
- $retValue = (float) $excelDateTime;
- break;
- case Calculation_Functions::RETURNDATE_PHP_NUMERIC :
- $retValue = (integer) Shared_Date::ExcelToPHP($excelDateTime);
- break;
- case Calculation_Functions::RETURNDATE_PHP_OBJECT :
- $retValue = Shared_Date::ExcelToPHPObject($excelDateTime);
- break;
- }
- date_default_timezone_set($saveTimeZone);
+ /**
+ * DATENOW
+ *
+ * Returns the current date.
+ * The NOW function is useful when you need to display the current date and time on a worksheet or
+ * calculate a value based on the current date and time, and have that value updated each time you
+ * open the worksheet.
+ *
+ * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the date
+ * and time format of your regional settings. PHPExcel does not change cell formatting in this way.
+ *
+ * Excel Function:
+ * TODAY()
+ *
+ * @access public
+ * @category Date/Time Functions
+ * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
+ * depending on the value of the ReturnDateType flag
+ */
+ public static function DATENOW() {
+ $saveTimeZone = date_default_timezone_get();
+ date_default_timezone_set('UTC');
+ $retValue = False;
+ $excelDateTime = floor(Shared_Date::PHPToExcel(time()));
+ switch (Calculation_Functions::getReturnDateType()) {
+ case Calculation_Functions::RETURNDATE_EXCEL :
+ $retValue = (float) $excelDateTime;
+ break;
+ case Calculation_Functions::RETURNDATE_PHP_NUMERIC :
+ $retValue = (integer) Shared_Date::ExcelToPHP($excelDateTime);
+ break;
+ case Calculation_Functions::RETURNDATE_PHP_OBJECT :
+ $retValue = Shared_Date::ExcelToPHPObject($excelDateTime);
+ break;
+ }
+ date_default_timezone_set($saveTimeZone);
- return $retValue;
- } // function DATENOW()
+ return $retValue;
+ } // function DATENOW()
- /**
- * DATE
- *
- * The DATE function returns a value that represents a particular date.
- *
- * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the date
- * format of your regional settings. PHPExcel does not change cell formatting in this way.
- *
- * Excel Function:
- * DATE(year,month,day)
- *
- * PHPExcel is a lot more forgiving than MS Excel when passing non numeric values to this function.
- * A Month name or abbreviation (English only at this point) such as 'January' or 'Jan' will still be accepted,
- * as will a day value with a suffix (e.g. '21st' rather than simply 21); again only English language.
- *
- * @access public
- * @category Date/Time Functions
- * @param integer $year The value of the year argument can include one to four digits.
- * Excel interprets the year argument according to the configured
- * date system: 1900 or 1904.
- * If year is between 0 (zero) and 1899 (inclusive), Excel adds that
- * value to 1900 to calculate the year. For example, DATE(108,1,2)
- * returns January 2, 2008 (1900+108).
- * If year is between 1900 and 9999 (inclusive), Excel uses that
- * value as the year. For example, DATE(2008,1,2) returns January 2,
- * 2008.
- * If year is less than 0 or is 10000 or greater, Excel returns the
- * #NUM! error value.
- * @param integer $month A positive or negative integer representing the month of the year
- * from 1 to 12 (January to December).
- * If month is greater than 12, month adds that number of months to
- * the first month in the year specified. For example, DATE(2008,14,2)
- * returns the serial number representing February 2, 2009.
- * If month is less than 1, month subtracts the magnitude of that
- * number of months, plus 1, from the first month in the year
- * specified. For example, DATE(2008,-3,2) returns the serial number
- * representing September 2, 2007.
- * @param integer $day A positive or negative integer representing the day of the month
- * from 1 to 31.
- * If day is greater than the number of days in the month specified,
- * day adds that number of days to the first day in the month. For
- * example, DATE(2008,1,35) returns the serial number representing
- * February 4, 2008.
- * If day is less than 1, day subtracts the magnitude that number of
- * days, plus one, from the first day of the month specified. For
- * example, DATE(2008,1,-15) returns the serial number representing
- * December 16, 2007.
- * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
- * depending on the value of the ReturnDateType flag
- */
- public static function DATE($year = 0, $month = 1, $day = 1) {
- $year = Calculation_Functions::flattenSingleValue($year);
- $month = Calculation_Functions::flattenSingleValue($month);
- $day = Calculation_Functions::flattenSingleValue($day);
+ /**
+ * DATE
+ *
+ * The DATE function returns a value that represents a particular date.
+ *
+ * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the date
+ * format of your regional settings. PHPExcel does not change cell formatting in this way.
+ *
+ * Excel Function:
+ * DATE(year,month,day)
+ *
+ * PHPExcel is a lot more forgiving than MS Excel when passing non numeric values to this function.
+ * A Month name or abbreviation (English only at this point) such as 'January' or 'Jan' will still be accepted,
+ * as will a day value with a suffix (e.g. '21st' rather than simply 21); again only English language.
+ *
+ * @access public
+ * @category Date/Time Functions
+ * @param integer $year The value of the year argument can include one to four digits.
+ * Excel interprets the year argument according to the configured
+ * date system: 1900 or 1904.
+ * If year is between 0 (zero) and 1899 (inclusive), Excel adds that
+ * value to 1900 to calculate the year. For example, DATE(108,1,2)
+ * returns January 2, 2008 (1900+108).
+ * If year is between 1900 and 9999 (inclusive), Excel uses that
+ * value as the year. For example, DATE(2008,1,2) returns January 2,
+ * 2008.
+ * If year is less than 0 or is 10000 or greater, Excel returns the
+ * #NUM! error value.
+ * @param integer $month A positive or negative integer representing the month of the year
+ * from 1 to 12 (January to December).
+ * If month is greater than 12, month adds that number of months to
+ * the first month in the year specified. For example, DATE(2008,14,2)
+ * returns the serial number representing February 2, 2009.
+ * If month is less than 1, month subtracts the magnitude of that
+ * number of months, plus 1, from the first month in the year
+ * specified. For example, DATE(2008,-3,2) returns the serial number
+ * representing September 2, 2007.
+ * @param integer $day A positive or negative integer representing the day of the month
+ * from 1 to 31.
+ * If day is greater than the number of days in the month specified,
+ * day adds that number of days to the first day in the month. For
+ * example, DATE(2008,1,35) returns the serial number representing
+ * February 4, 2008.
+ * If day is less than 1, day subtracts the magnitude that number of
+ * days, plus one, from the first day of the month specified. For
+ * example, DATE(2008,1,-15) returns the serial number representing
+ * December 16, 2007.
+ * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
+ * depending on the value of the ReturnDateType flag
+ */
+ public static function DATE($year = 0, $month = 1, $day = 1) {
+ $year = Calculation_Functions::flattenSingleValue($year);
+ $month = Calculation_Functions::flattenSingleValue($month);
+ $day = Calculation_Functions::flattenSingleValue($day);
- if (($month !== NULL) && (!is_numeric($month))) {
+ if (($month !== null) && (!is_numeric($month))) {
$month = Shared_Date::monthStringToNumber($month);
- }
+ }
- if (($day !== NULL) && (!is_numeric($day))) {
+ if (($day !== null) && (!is_numeric($day))) {
$day = Shared_Date::dayStringToNumber($day);
- }
-
- $year = ($year !== NULL) ? Shared_String::testStringAsNumeric($year) : 0;
- $month = ($month !== NULL) ? Shared_String::testStringAsNumeric($month) : 0;
- $day = ($day !== NULL) ? Shared_String::testStringAsNumeric($day) : 0;
- if ((!is_numeric($year)) ||
- (!is_numeric($month)) ||
- (!is_numeric($day))) {
- return Calculation_Functions::VALUE();
- }
- $year = (integer) $year;
- $month = (integer) $month;
- $day = (integer) $day;
-
- $baseYear = Shared_Date::getExcelCalendar();
- // Validate parameters
- if ($year < ($baseYear-1900)) {
- return Calculation_Functions::NaN();
- }
- if ((($baseYear-1900) != 0) && ($year < $baseYear) && ($year >= 1900)) {
- return Calculation_Functions::NaN();
- }
-
- if (($year < $baseYear) && ($year >= ($baseYear-1900))) {
- $year += 1900;
- }
-
- if ($month < 1) {
- // Handle year/month adjustment if month < 1
- --$month;
- $year += ceil($month / 12) - 1;
- $month = 13 - abs($month % 12);
- } elseif ($month > 12) {
- // Handle year/month adjustment if month > 12
- $year += floor($month / 12);
- $month = ($month % 12);
- }
-
- // Re-validate the year parameter after adjustments
- if (($year < $baseYear) || ($year >= 10000)) {
- return Calculation_Functions::NaN();
- }
-
- // Execute function
- $excelDateValue = Shared_Date::FormattedPHPToExcel($year, $month, $day);
- switch (Calculation_Functions::getReturnDateType()) {
- case Calculation_Functions::RETURNDATE_EXCEL :
- return (float) $excelDateValue;
- case Calculation_Functions::RETURNDATE_PHP_NUMERIC :
- return (integer) Shared_Date::ExcelToPHP($excelDateValue);
- case Calculation_Functions::RETURNDATE_PHP_OBJECT :
- return Shared_Date::ExcelToPHPObject($excelDateValue);
- }
- } // function DATE()
-
-
- /**
- * TIME
- *
- * The TIME function returns a value that represents a particular time.
- *
- * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the time
- * format of your regional settings. PHPExcel does not change cell formatting in this way.
- *
- * Excel Function:
- * TIME(hour,minute,second)
- *
- * @access public
- * @category Date/Time Functions
- * @param integer $hour A number from 0 (zero) to 32767 representing the hour.
- * Any value greater than 23 will be divided by 24 and the remainder
- * will be treated as the hour value. For example, TIME(27,0,0) =
- * TIME(3,0,0) = .125 or 3:00 AM.
- * @param integer $minute A number from 0 to 32767 representing the minute.
- * Any value greater than 59 will be converted to hours and minutes.
- * For example, TIME(0,750,0) = TIME(12,30,0) = .520833 or 12:30 PM.
- * @param integer $second A number from 0 to 32767 representing the second.
- * Any value greater than 59 will be converted to hours, minutes,
- * and seconds. For example, TIME(0,0,2000) = TIME(0,33,22) = .023148
- * or 12:33:20 AM
- * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
- * depending on the value of the ReturnDateType flag
- */
- public static function TIME($hour = 0, $minute = 0, $second = 0) {
- $hour = Calculation_Functions::flattenSingleValue($hour);
- $minute = Calculation_Functions::flattenSingleValue($minute);
- $second = Calculation_Functions::flattenSingleValue($second);
-
- if ($hour == '') { $hour = 0; }
- if ($minute == '') { $minute = 0; }
- if ($second == '') { $second = 0; }
-
- if ((!is_numeric($hour)) || (!is_numeric($minute)) || (!is_numeric($second))) {
- return Calculation_Functions::VALUE();
- }
- $hour = (integer) $hour;
- $minute = (integer) $minute;
- $second = (integer) $second;
-
- if ($second < 0) {
- $minute += floor($second / 60);
- $second = 60 - abs($second % 60);
- if ($second == 60) { $second = 0; }
- } elseif ($second >= 60) {
- $minute += floor($second / 60);
- $second = $second % 60;
- }
- if ($minute < 0) {
- $hour += floor($minute / 60);
- $minute = 60 - abs($minute % 60);
- if ($minute == 60) { $minute = 0; }
- } elseif ($minute >= 60) {
- $hour += floor($minute / 60);
- $minute = $minute % 60;
- }
-
- if ($hour > 23) {
- $hour = $hour % 24;
- } elseif ($hour < 0) {
- return Calculation_Functions::NaN();
- }
-
- // Execute function
- switch (Calculation_Functions::getReturnDateType()) {
- case Calculation_Functions::RETURNDATE_EXCEL :
- $date = 0;
- $calendar = Shared_Date::getExcelCalendar();
- if ($calendar != Shared_Date::CALENDAR_WINDOWS_1900) {
- $date = 1;
- }
- return (float) Shared_Date::FormattedPHPToExcel($calendar, 1, $date, $hour, $minute, $second);
- case Calculation_Functions::RETURNDATE_PHP_NUMERIC :
- return (integer) Shared_Date::ExcelToPHP(Shared_Date::FormattedPHPToExcel(1970, 1, 1, $hour, $minute, $second)); // -2147468400; // -2147472000 + 3600
- case Calculation_Functions::RETURNDATE_PHP_OBJECT :
- $dayAdjust = 0;
- if ($hour < 0) {
- $dayAdjust = floor($hour / 24);
- $hour = 24 - abs($hour % 24);
- if ($hour == 24) { $hour = 0; }
- } elseif ($hour >= 24) {
- $dayAdjust = floor($hour / 24);
- $hour = $hour % 24;
- }
- $phpDateObject = new DateTime('1900-01-01 '.$hour.':'.$minute.':'.$second);
- if ($dayAdjust != 0) {
- $phpDateObject->modify($dayAdjust.' days');
- }
- return $phpDateObject;
- }
- } // function TIME()
-
-
- /**
- * DATEVALUE
- *
- * Returns a value that represents a particular date.
- * Use DATEVALUE to convert a date represented by a text string to an Excel or PHP date/time stamp
- * value.
- *
- * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the date
- * format of your regional settings. PHPExcel does not change cell formatting in this way.
- *
- * Excel Function:
- * DATEVALUE(dateValue)
- *
- * @access public
- * @category Date/Time Functions
- * @param string $dateValue Text that represents a date in a Microsoft Excel date format.
- * For example, "1/30/2008" or "30-Jan-2008" are text strings within
- * quotation marks that represent dates. Using the default date
- * system in Excel for Windows, date_text must represent a date from
- * January 1, 1900, to December 31, 9999. Using the default date
- * system in Excel for the Macintosh, date_text must represent a date
- * from January 1, 1904, to December 31, 9999. DATEVALUE returns the
- * #VALUE! error value if date_text is out of this range.
- * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
- * depending on the value of the ReturnDateType flag
- */
- public static function DATEVALUE($dateValue = 1) {
- $dateValue = trim(Calculation_Functions::flattenSingleValue($dateValue),'"');
- // Strip any ordinals because they're allowed in Excel (English only)
- $dateValue = preg_replace('/(\d)(st|nd|rd|th)([ -\/])/Ui','$1$3',$dateValue);
- // Convert separators (/ . or space) to hyphens (should also handle dot used for ordinals in some countries, e.g. Denmark, Germany)
- $dateValue = str_replace(array('/','.','-',' '),array(' ',' ',' ',' '),$dateValue);
-
- $yearFound = false;
- $t1 = explode(' ',$dateValue);
- foreach($t1 as &$t) {
- if ((is_numeric($t)) && ($t > 31)) {
- if ($yearFound) {
- return Calculation_Functions::VALUE();
- } else {
- if ($t < 100) { $t += 1900; }
- $yearFound = true;
- }
- }
- }
- if ((count($t1) == 1) && (strpos($t,':') != false)) {
- // We've been fed a time value without any date
- return 0.0;
- } elseif (count($t1) == 2) {
- // We only have two parts of the date: either day/month or month/year
- if ($yearFound) {
- array_unshift($t1,1);
- } else {
- array_push($t1,date('Y'));
- }
- }
- unset($t);
- $dateValue = implode(' ',$t1);
-
- $PHPDateArray = date_parse($dateValue);
- if (($PHPDateArray === False) || ($PHPDateArray['error_count'] > 0)) {
- $testVal1 = strtok($dateValue,'- ');
- if ($testVal1 !== False) {
- $testVal2 = strtok('- ');
- if ($testVal2 !== False) {
- $testVal3 = strtok('- ');
- if ($testVal3 === False) {
- $testVal3 = strftime('%Y');
- }
- } else {
- return Calculation_Functions::VALUE();
- }
- } else {
- return Calculation_Functions::VALUE();
- }
- $PHPDateArray = date_parse($testVal1.'-'.$testVal2.'-'.$testVal3);
- if (($PHPDateArray === False) || ($PHPDateArray['error_count'] > 0)) {
- $PHPDateArray = date_parse($testVal2.'-'.$testVal1.'-'.$testVal3);
- if (($PHPDateArray === False) || ($PHPDateArray['error_count'] > 0)) {
- return Calculation_Functions::VALUE();
- }
- }
- }
-
- if (($PHPDateArray !== False) && ($PHPDateArray['error_count'] == 0)) {
- // Execute function
- if ($PHPDateArray['year'] == '') { $PHPDateArray['year'] = strftime('%Y'); }
- if ($PHPDateArray['year'] < 1900)
- return Calculation_Functions::VALUE();
- if ($PHPDateArray['month'] == '') { $PHPDateArray['month'] = strftime('%m'); }
- if ($PHPDateArray['day'] == '') { $PHPDateArray['day'] = strftime('%d'); }
- $excelDateValue = floor(Shared_Date::FormattedPHPToExcel($PHPDateArray['year'],$PHPDateArray['month'],$PHPDateArray['day'],$PHPDateArray['hour'],$PHPDateArray['minute'],$PHPDateArray['second']));
-
- switch (Calculation_Functions::getReturnDateType()) {
- case Calculation_Functions::RETURNDATE_EXCEL :
- return (float) $excelDateValue;
- case Calculation_Functions::RETURNDATE_PHP_NUMERIC :
- return (integer) Shared_Date::ExcelToPHP($excelDateValue);
- case Calculation_Functions::RETURNDATE_PHP_OBJECT :
- return new DateTime($PHPDateArray['year'].'-'.$PHPDateArray['month'].'-'.$PHPDateArray['day'].' 00:00:00');
- }
- }
- return Calculation_Functions::VALUE();
- } // function DATEVALUE()
-
-
- /**
- * TIMEVALUE
- *
- * Returns a value that represents a particular time.
- * Use TIMEVALUE to convert a time represented by a text string to an Excel or PHP date/time stamp
- * value.
- *
- * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the time
- * format of your regional settings. PHPExcel does not change cell formatting in this way.
- *
- * Excel Function:
- * TIMEVALUE(timeValue)
- *
- * @access public
- * @category Date/Time Functions
- * @param string $timeValue A text string that represents a time in any one of the Microsoft
- * Excel time formats; for example, "6:45 PM" and "18:45" text strings
- * within quotation marks that represent time.
- * Date information in time_text is ignored.
- * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
- * depending on the value of the ReturnDateType flag
- */
- public static function TIMEVALUE($timeValue) {
- $timeValue = trim(Calculation_Functions::flattenSingleValue($timeValue),'"');
- $timeValue = str_replace(array('/','.'),array('-','-'),$timeValue);
-
- $PHPDateArray = date_parse($timeValue);
- if (($PHPDateArray !== False) && ($PHPDateArray['error_count'] == 0)) {
- if (Calculation_Functions::getCompatibilityMode() == Calculation_Functions::COMPATIBILITY_OPENOFFICE) {
- $excelDateValue = Shared_Date::FormattedPHPToExcel($PHPDateArray['year'],$PHPDateArray['month'],$PHPDateArray['day'],$PHPDateArray['hour'],$PHPDateArray['minute'],$PHPDateArray['second']);
- } else {
- $excelDateValue = Shared_Date::FormattedPHPToExcel(1900,1,1,$PHPDateArray['hour'],$PHPDateArray['minute'],$PHPDateArray['second']) - 1;
- }
-
- switch (Calculation_Functions::getReturnDateType()) {
- case Calculation_Functions::RETURNDATE_EXCEL :
- return (float) $excelDateValue;
- case Calculation_Functions::RETURNDATE_PHP_NUMERIC :
- return (integer) $phpDateValue = Shared_Date::ExcelToPHP($excelDateValue+25569) - 3600;;
- case Calculation_Functions::RETURNDATE_PHP_OBJECT :
- return new DateTime('1900-01-01 '.$PHPDateArray['hour'].':'.$PHPDateArray['minute'].':'.$PHPDateArray['second']);
- }
- }
- return Calculation_Functions::VALUE();
- } // function TIMEVALUE()
-
-
- /**
- * DATEDIF
- *
- * @param mixed $startDate Excel date serial value, PHP date/time stamp, PHP DateTime object
- * or a standard date string
- * @param mixed $endDate Excel date serial value, PHP date/time stamp, PHP DateTime object
- * or a standard date string
- * @param string $unit
- * @return integer Interval between the dates
- */
- public static function DATEDIF($startDate = 0, $endDate = 0, $unit = 'D') {
- $startDate = Calculation_Functions::flattenSingleValue($startDate);
- $endDate = Calculation_Functions::flattenSingleValue($endDate);
- $unit = strtoupper(Calculation_Functions::flattenSingleValue($unit));
-
- if (is_string($startDate = self::_getDateValue($startDate))) {
- return Calculation_Functions::VALUE();
- }
- if (is_string($endDate = self::_getDateValue($endDate))) {
- return Calculation_Functions::VALUE();
- }
-
- // Validate parameters
- if ($startDate >= $endDate) {
- return Calculation_Functions::NaN();
- }
-
- // Execute function
- $difference = $endDate - $startDate;
-
- $PHPStartDateObject = Shared_Date::ExcelToPHPObject($startDate);
- $startDays = $PHPStartDateObject->format('j');
- $startMonths = $PHPStartDateObject->format('n');
- $startYears = $PHPStartDateObject->format('Y');
-
- $PHPEndDateObject = Shared_Date::ExcelToPHPObject($endDate);
- $endDays = $PHPEndDateObject->format('j');
- $endMonths = $PHPEndDateObject->format('n');
- $endYears = $PHPEndDateObject->format('Y');
-
- $retVal = Calculation_Functions::NaN();
- switch ($unit) {
- case 'D':
- $retVal = intval($difference);
- break;
- case 'M':
- $retVal = intval($endMonths - $startMonths) + (intval($endYears - $startYears) * 12);
- // We're only interested in full months
- if ($endDays < $startDays) {
- --$retVal;
- }
- break;
- case 'Y':
- $retVal = intval($endYears - $startYears);
- // We're only interested in full months
- if ($endMonths < $startMonths) {
- --$retVal;
- } elseif (($endMonths == $startMonths) && ($endDays < $startDays)) {
- --$retVal;
- }
- break;
- case 'MD':
- if ($endDays < $startDays) {
- $retVal = $endDays;
- $PHPEndDateObject->modify('-'.$endDays.' days');
- $adjustDays = $PHPEndDateObject->format('j');
- if ($adjustDays > $startDays) {
- $retVal += ($adjustDays - $startDays);
- }
- } else {
- $retVal = $endDays - $startDays;
- }
- break;
- case 'YM':
- $retVal = intval($endMonths - $startMonths);
- if ($retVal < 0) $retVal = 12 + $retVal;
- // We're only interested in full months
- if ($endDays < $startDays) {
- --$retVal;
- }
- break;
- case 'YD':
- $retVal = intval($difference);
- if ($endYears > $startYears) {
- while ($endYears > $startYears) {
- $PHPEndDateObject->modify('-1 year');
- $endYears = $PHPEndDateObject->format('Y');
- }
- $retVal = $PHPEndDateObject->format('z') - $PHPStartDateObject->format('z');
- if ($retVal < 0) { $retVal += 365; }
- }
- break;
- default:
- $retVal = Calculation_Functions::NaN();
- }
- return $retVal;
- } // function DATEDIF()
-
-
- /**
- * DAYS360
- *
- * Returns the number of days between two dates based on a 360-day year (twelve 30-day months),
- * which is used in some accounting calculations. Use this function to help compute payments if
- * your accounting system is based on twelve 30-day months.
- *
- * Excel Function:
- * DAYS360(startDate,endDate[,method])
- *
- * @access public
- * @category Date/Time Functions
- * @param mixed $startDate Excel date serial value (float), PHP date timestamp (integer),
- * PHP DateTime object, or a standard date string
- * @param mixed $endDate Excel date serial value (float), PHP date timestamp (integer),
- * PHP DateTime object, or a standard date string
- * @param boolean $method US or European Method
- * FALSE or omitted: U.S. (NASD) method. If the starting date is
- * the last day of a month, it becomes equal to the 30th of the
- * same month. If the ending date is the last day of a month and
- * the starting date is earlier than the 30th of a month, the
- * ending date becomes equal to the 1st of the next month;
- * otherwise the ending date becomes equal to the 30th of the
- * same month.
- * TRUE: European method. Starting dates and ending dates that
- * occur on the 31st of a month become equal to the 30th of the
- * same month.
- * @return integer Number of days between start date and end date
- */
- public static function DAYS360($startDate = 0, $endDate = 0, $method = false) {
- $startDate = Calculation_Functions::flattenSingleValue($startDate);
- $endDate = Calculation_Functions::flattenSingleValue($endDate);
-
- if (is_string($startDate = self::_getDateValue($startDate))) {
- return Calculation_Functions::VALUE();
- }
- if (is_string($endDate = self::_getDateValue($endDate))) {
- return Calculation_Functions::VALUE();
- }
-
- if (!is_bool($method)) {
- return Calculation_Functions::VALUE();
- }
-
- // Execute function
- $PHPStartDateObject = Shared_Date::ExcelToPHPObject($startDate);
- $startDay = $PHPStartDateObject->format('j');
- $startMonth = $PHPStartDateObject->format('n');
- $startYear = $PHPStartDateObject->format('Y');
-
- $PHPEndDateObject = Shared_Date::ExcelToPHPObject($endDate);
- $endDay = $PHPEndDateObject->format('j');
- $endMonth = $PHPEndDateObject->format('n');
- $endYear = $PHPEndDateObject->format('Y');
-
- return self::_dateDiff360($startDay, $startMonth, $startYear, $endDay, $endMonth, $endYear, !$method);
- } // function DAYS360()
-
-
- /**
- * YEARFRAC
- *
- * Calculates the fraction of the year represented by the number of whole days between two dates
- * (the start_date and the end_date).
- * Use the YEARFRAC worksheet function to identify the proportion of a whole year's benefits or
- * obligations to assign to a specific term.
- *
- * Excel Function:
- * YEARFRAC(startDate,endDate[,method])
- *
- * @access public
- * @category Date/Time Functions
- * @param mixed $startDate Excel date serial value (float), PHP date timestamp (integer),
- * PHP DateTime object, or a standard date string
- * @param mixed $endDate Excel date serial value (float), PHP date timestamp (integer),
- * PHP DateTime object, or a standard date string
- * @param integer $method Method used for the calculation
- * 0 or omitted US (NASD) 30/360
- * 1 Actual/actual
- * 2 Actual/360
- * 3 Actual/365
- * 4 European 30/360
- * @return float fraction of the year
- */
- public static function YEARFRAC($startDate = 0, $endDate = 0, $method = 0) {
- $startDate = Calculation_Functions::flattenSingleValue($startDate);
- $endDate = Calculation_Functions::flattenSingleValue($endDate);
- $method = Calculation_Functions::flattenSingleValue($method);
-
- if (is_string($startDate = self::_getDateValue($startDate))) {
- return Calculation_Functions::VALUE();
- }
- if (is_string($endDate = self::_getDateValue($endDate))) {
- return Calculation_Functions::VALUE();
- }
-
- if (((is_numeric($method)) && (!is_string($method))) || ($method == '')) {
- switch($method) {
- case 0 :
- return self::DAYS360($startDate,$endDate) / 360;
- case 1 :
- $days = self::DATEDIF($startDate,$endDate);
- $startYear = self::YEAR($startDate);
- $endYear = self::YEAR($endDate);
- $years = $endYear - $startYear + 1;
- $leapDays = 0;
- if ($years == 1) {
- if (self::_isLeapYear($endYear)) {
- $startMonth = self::MONTHOFYEAR($startDate);
- $endMonth = self::MONTHOFYEAR($endDate);
- $endDay = self::DAYOFMONTH($endDate);
- if (($startMonth < 3) ||
- (($endMonth * 100 + $endDay) >= (2 * 100 + 29))) {
- $leapDays += 1;
- }
- }
- } else {
- for($year = $startYear; $year <= $endYear; ++$year) {
- if ($year == $startYear) {
- $startMonth = self::MONTHOFYEAR($startDate);
- $startDay = self::DAYOFMONTH($startDate);
- if ($startMonth < 3) {
- $leapDays += (self::_isLeapYear($year)) ? 1 : 0;
- }
- } elseif($year == $endYear) {
- $endMonth = self::MONTHOFYEAR($endDate);
- $endDay = self::DAYOFMONTH($endDate);
- if (($endMonth * 100 + $endDay) >= (2 * 100 + 29)) {
- $leapDays += (self::_isLeapYear($year)) ? 1 : 0;
- }
- } else {
- $leapDays += (self::_isLeapYear($year)) ? 1 : 0;
- }
- }
- if ($years == 2) {
- if (($leapDays == 0) && (self::_isLeapYear($startYear)) && ($days > 365)) {
- $leapDays = 1;
- } elseif ($days < 366) {
- $years = 1;
- }
- }
- $leapDays /= $years;
- }
- return $days / (365 + $leapDays);
- case 2 :
- return self::DATEDIF($startDate,$endDate) / 360;
- case 3 :
- return self::DATEDIF($startDate,$endDate) / 365;
- case 4 :
- return self::DAYS360($startDate,$endDate,True) / 360;
- }
- }
- return Calculation_Functions::VALUE();
- } // function YEARFRAC()
-
-
- /**
- * NETWORKDAYS
- *
- * Returns the number of whole working days between start_date and end_date. Working days
- * exclude weekends and any dates identified in holidays.
- * Use NETWORKDAYS to calculate employee benefits that accrue based on the number of days
- * worked during a specific term.
- *
- * Excel Function:
- * NETWORKDAYS(startDate,endDate[,holidays[,holiday[,...]]])
- *
- * @access public
- * @category Date/Time Functions
- * @param mixed $startDate Excel date serial value (float), PHP date timestamp (integer),
- * PHP DateTime object, or a standard date string
- * @param mixed $endDate Excel date serial value (float), PHP date timestamp (integer),
- * PHP DateTime object, or a standard date string
- * @param mixed $holidays,... Optional series of Excel date serial value (float), PHP date
- * timestamp (integer), PHP DateTime object, or a standard date
- * strings that will be excluded from the working calendar, such
- * as state and federal holidays and floating holidays.
- * @return integer Interval between the dates
- */
- public static function NETWORKDAYS($startDate,$endDate) {
- // Retrieve the mandatory start and end date that are referenced in the function definition
- $startDate = Calculation_Functions::flattenSingleValue($startDate);
- $endDate = Calculation_Functions::flattenSingleValue($endDate);
- // Flush the mandatory start and end date that are referenced in the function definition, and get the optional days
- $dateArgs = Calculation_Functions::flattenArray(func_get_args());
- array_shift($dateArgs);
- array_shift($dateArgs);
-
- // Validate the start and end dates
- if (is_string($startDate = $sDate = self::_getDateValue($startDate))) {
- return Calculation_Functions::VALUE();
- }
- $startDate = (float) floor($startDate);
- if (is_string($endDate = $eDate = self::_getDateValue($endDate))) {
- return Calculation_Functions::VALUE();
- }
- $endDate = (float) floor($endDate);
-
- if ($sDate > $eDate) {
- $startDate = $eDate;
- $endDate = $sDate;
- }
-
- // Execute function
- $startDoW = 6 - self::DAYOFWEEK($startDate,2);
- if ($startDoW < 0) { $startDoW = 0; }
- $endDoW = self::DAYOFWEEK($endDate,2);
- if ($endDoW >= 6) { $endDoW = 0; }
-
- $wholeWeekDays = floor(($endDate - $startDate) / 7) * 5;
- $partWeekDays = $endDoW + $startDoW;
- if ($partWeekDays > 5) {
- $partWeekDays -= 5;
- }
-
- // Test any extra holiday parameters
- $holidayCountedArray = array();
- foreach ($dateArgs as $holidayDate) {
- if (is_string($holidayDate = self::_getDateValue($holidayDate))) {
- return Calculation_Functions::VALUE();
- }
- if (($holidayDate >= $startDate) && ($holidayDate <= $endDate)) {
- if ((self::DAYOFWEEK($holidayDate,2) < 6) && (!in_array($holidayDate,$holidayCountedArray))) {
- --$partWeekDays;
- $holidayCountedArray[] = $holidayDate;
- }
- }
- }
-
- if ($sDate > $eDate) {
- return 0 - ($wholeWeekDays + $partWeekDays);
- }
- return $wholeWeekDays + $partWeekDays;
- } // function NETWORKDAYS()
-
-
- /**
- * WORKDAY
- *
- * Returns the date that is the indicated number of working days before or after a date (the
- * starting date). Working days exclude weekends and any dates identified as holidays.
- * Use WORKDAY to exclude weekends or holidays when you calculate invoice due dates, expected
- * delivery times, or the number of days of work performed.
- *
- * Excel Function:
- * WORKDAY(startDate,endDays[,holidays[,holiday[,...]]])
- *
- * @access public
- * @category Date/Time Functions
- * @param mixed $startDate Excel date serial value (float), PHP date timestamp (integer),
- * PHP DateTime object, or a standard date string
- * @param integer $endDays The number of nonweekend and nonholiday days before or after
- * startDate. A positive value for days yields a future date; a
- * negative value yields a past date.
- * @param mixed $holidays,... Optional series of Excel date serial value (float), PHP date
- * timestamp (integer), PHP DateTime object, or a standard date
- * strings that will be excluded from the working calendar, such
- * as state and federal holidays and floating holidays.
- * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
- * depending on the value of the ReturnDateType flag
- */
- public static function WORKDAY($startDate,$endDays) {
- // Retrieve the mandatory start date and days that are referenced in the function definition
- $startDate = Calculation_Functions::flattenSingleValue($startDate);
- $endDays = Calculation_Functions::flattenSingleValue($endDays);
- // Flush the mandatory start date and days that are referenced in the function definition, and get the optional days
- $dateArgs = Calculation_Functions::flattenArray(func_get_args());
- array_shift($dateArgs);
- array_shift($dateArgs);
-
- if ((is_string($startDate = self::_getDateValue($startDate))) || (!is_numeric($endDays))) {
- return Calculation_Functions::VALUE();
- }
- $startDate = (float) floor($startDate);
- $endDays = (int) floor($endDays);
- // If endDays is 0, we always return startDate
- if ($endDays == 0) { return $startDate; }
-
- $decrementing = ($endDays < 0) ? True : False;
-
- // Adjust the start date if it falls over a weekend
-
- $startDoW = self::DAYOFWEEK($startDate,3);
- if (self::DAYOFWEEK($startDate,3) >= 5) {
- $startDate += ($decrementing) ? -$startDoW + 4: 7 - $startDoW;
- ($decrementing) ? $endDays++ : $endDays--;
- }
-
- // Add endDays
- $endDate = (float) $startDate + (intval($endDays / 5) * 7) + ($endDays % 5);
-
- // Adjust the calculated end date if it falls over a weekend
- $endDoW = self::DAYOFWEEK($endDate,3);
- if ($endDoW >= 5) {
- $endDate += ($decrementing) ? -$endDoW + 4: 7 - $endDoW;
- }
-
- // Test any extra holiday parameters
- if (!empty($dateArgs)) {
- $holidayCountedArray = $holidayDates = array();
- foreach ($dateArgs as $holidayDate) {
- if (($holidayDate !== NULL) && (trim($holidayDate) > '')) {
- if (is_string($holidayDate = self::_getDateValue($holidayDate))) {
- return Calculation_Functions::VALUE();
- }
- if (self::DAYOFWEEK($holidayDate,3) < 5) {
- $holidayDates[] = $holidayDate;
- }
- }
- }
- if ($decrementing) {
- rsort($holidayDates, SORT_NUMERIC);
- } else {
- sort($holidayDates, SORT_NUMERIC);
- }
- foreach ($holidayDates as $holidayDate) {
- if ($decrementing) {
- if (($holidayDate <= $startDate) && ($holidayDate >= $endDate)) {
- if (!in_array($holidayDate,$holidayCountedArray)) {
- --$endDate;
- $holidayCountedArray[] = $holidayDate;
- }
- }
- } else {
- if (($holidayDate >= $startDate) && ($holidayDate <= $endDate)) {
- if (!in_array($holidayDate,$holidayCountedArray)) {
- ++$endDate;
- $holidayCountedArray[] = $holidayDate;
- }
- }
- }
- // Adjust the calculated end date if it falls over a weekend
- $endDoW = self::DAYOFWEEK($endDate,3);
- if ($endDoW >= 5) {
- $endDate += ($decrementing) ? -$endDoW + 4: 7 - $endDoW;
- }
-
- }
- }
-
- switch (Calculation_Functions::getReturnDateType()) {
- case Calculation_Functions::RETURNDATE_EXCEL :
- return (float) $endDate;
- case Calculation_Functions::RETURNDATE_PHP_NUMERIC :
- return (integer) Shared_Date::ExcelToPHP($endDate);
- case Calculation_Functions::RETURNDATE_PHP_OBJECT :
- return Shared_Date::ExcelToPHPObject($endDate);
- }
- } // function WORKDAY()
-
-
- /**
- * DAYOFMONTH
- *
- * Returns the day of the month, for a specified date. The day is given as an integer
- * ranging from 1 to 31.
- *
- * Excel Function:
- * DAY(dateValue)
- *
- * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer),
- * PHP DateTime object, or a standard date string
- * @return int Day of the month
- */
- public static function DAYOFMONTH($dateValue = 1) {
- $dateValue = Calculation_Functions::flattenSingleValue($dateValue);
-
- if (is_string($dateValue = self::_getDateValue($dateValue))) {
- return Calculation_Functions::VALUE();
- } elseif ($dateValue == 0.0) {
- return 0;
- } elseif ($dateValue < 0.0) {
- return Calculation_Functions::NaN();
- }
-
- // Execute function
- $PHPDateObject = Shared_Date::ExcelToPHPObject($dateValue);
-
- return (int) $PHPDateObject->format('j');
- } // function DAYOFMONTH()
-
-
- /**
- * DAYOFWEEK
- *
- * Returns the day of the week for a specified date. The day is given as an integer
- * ranging from 0 to 7 (dependent on the requested style).
- *
- * Excel Function:
- * WEEKDAY(dateValue[,style])
- *
- * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer),
- * PHP DateTime object, or a standard date string
- * @param int $style A number that determines the type of return value
- * 1 or omitted Numbers 1 (Sunday) through 7 (Saturday).
- * 2 Numbers 1 (Monday) through 7 (Sunday).
- * 3 Numbers 0 (Monday) through 6 (Sunday).
- * @return int Day of the week value
- */
- public static function DAYOFWEEK($dateValue = 1, $style = 1) {
- $dateValue = Calculation_Functions::flattenSingleValue($dateValue);
- $style = Calculation_Functions::flattenSingleValue($style);
-
- if (!is_numeric($style)) {
- return Calculation_Functions::VALUE();
- } elseif (($style < 1) || ($style > 3)) {
- return Calculation_Functions::NaN();
- }
- $style = floor($style);
-
- if (is_string($dateValue = self::_getDateValue($dateValue))) {
- return Calculation_Functions::VALUE();
- } elseif ($dateValue < 0.0) {
- return Calculation_Functions::NaN();
- }
-
- // Execute function
- $PHPDateObject = Shared_Date::ExcelToPHPObject($dateValue);
- $DoW = $PHPDateObject->format('w');
-
- $firstDay = 1;
- switch ($style) {
- case 1: ++$DoW;
- break;
- case 2: if ($DoW == 0) { $DoW = 7; }
- break;
- case 3: if ($DoW == 0) { $DoW = 7; }
- $firstDay = 0;
- --$DoW;
- break;
- }
- if (Calculation_Functions::getCompatibilityMode() == Calculation_Functions::COMPATIBILITY_EXCEL) {
- // Test for Excel's 1900 leap year, and introduce the error as required
- if (($PHPDateObject->format('Y') == 1900) && ($PHPDateObject->format('n') <= 2)) {
- --$DoW;
- if ($DoW < $firstDay) {
- $DoW += 7;
- }
- }
- }
-
- return (int) $DoW;
- } // function DAYOFWEEK()
-
-
- /**
- * WEEKOFYEAR
- *
- * Returns the week of the year for a specified date.
- * The WEEKNUM function considers the week containing January 1 to be the first week of the year.
- * However, there is a European standard that defines the first week as the one with the majority
- * of days (four or more) falling in the new year. This means that for years in which there are
- * three days or less in the first week of January, the WEEKNUM function returns week numbers
- * that are incorrect according to the European standard.
- *
- * Excel Function:
- * WEEKNUM(dateValue[,style])
- *
- * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer),
- * PHP DateTime object, or a standard date string
- * @param boolean $method Week begins on Sunday or Monday
- * 1 or omitted Week begins on Sunday.
- * 2 Week begins on Monday.
- * @return int Week Number
- */
- public static function WEEKOFYEAR($dateValue = 1, $method = 1) {
- $dateValue = Calculation_Functions::flattenSingleValue($dateValue);
- $method = Calculation_Functions::flattenSingleValue($method);
-
- if (!is_numeric($method)) {
- return Calculation_Functions::VALUE();
- } elseif (($method < 1) || ($method > 2)) {
- return Calculation_Functions::NaN();
- }
- $method = floor($method);
-
- if (is_string($dateValue = self::_getDateValue($dateValue))) {
- return Calculation_Functions::VALUE();
- } elseif ($dateValue < 0.0) {
- return Calculation_Functions::NaN();
- }
-
- // Execute function
- $PHPDateObject = Shared_Date::ExcelToPHPObject($dateValue);
- $dayOfYear = $PHPDateObject->format('z');
- $dow = $PHPDateObject->format('w');
- $PHPDateObject->modify('-'.$dayOfYear.' days');
- $dow = $PHPDateObject->format('w');
- $daysInFirstWeek = 7 - (($dow + (2 - $method)) % 7);
- $dayOfYear -= $daysInFirstWeek;
- $weekOfYear = ceil($dayOfYear / 7) + 1;
-
- return (int) $weekOfYear;
- } // function WEEKOFYEAR()
-
-
- /**
- * MONTHOFYEAR
- *
- * Returns the month of a date represented by a serial number.
- * The month is given as an integer, ranging from 1 (January) to 12 (December).
- *
- * Excel Function:
- * MONTH(dateValue)
- *
- * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer),
- * PHP DateTime object, or a standard date string
- * @return int Month of the year
- */
- public static function MONTHOFYEAR($dateValue = 1) {
- $dateValue = Calculation_Functions::flattenSingleValue($dateValue);
-
- if (is_string($dateValue = self::_getDateValue($dateValue))) {
- return Calculation_Functions::VALUE();
- } elseif ($dateValue < 0.0) {
- return Calculation_Functions::NaN();
- }
-
- // Execute function
- $PHPDateObject = Shared_Date::ExcelToPHPObject($dateValue);
-
- return (int) $PHPDateObject->format('n');
- } // function MONTHOFYEAR()
-
-
- /**
- * YEAR
- *
- * Returns the year corresponding to a date.
- * The year is returned as an integer in the range 1900-9999.
- *
- * Excel Function:
- * YEAR(dateValue)
- *
- * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer),
- * PHP DateTime object, or a standard date string
- * @return int Year
- */
- public static function YEAR($dateValue = 1) {
- $dateValue = Calculation_Functions::flattenSingleValue($dateValue);
-
- if (is_string($dateValue = self::_getDateValue($dateValue))) {
- return Calculation_Functions::VALUE();
- } elseif ($dateValue < 0.0) {
- return Calculation_Functions::NaN();
- }
-
- // Execute function
- $PHPDateObject = Shared_Date::ExcelToPHPObject($dateValue);
-
- return (int) $PHPDateObject->format('Y');
- } // function YEAR()
-
-
- /**
- * HOUROFDAY
- *
- * Returns the hour of a time value.
- * The hour is given as an integer, ranging from 0 (12:00 A.M.) to 23 (11:00 P.M.).
- *
- * Excel Function:
- * HOUR(timeValue)
- *
- * @param mixed $timeValue Excel date serial value (float), PHP date timestamp (integer),
- * PHP DateTime object, or a standard time string
- * @return int Hour
- */
- public static function HOUROFDAY($timeValue = 0) {
- $timeValue = Calculation_Functions::flattenSingleValue($timeValue);
-
- if (!is_numeric($timeValue)) {
- if (Calculation_Functions::getCompatibilityMode() == Calculation_Functions::COMPATIBILITY_GNUMERIC) {
- $testVal = strtok($timeValue,'/-: ');
- if (strlen($testVal) < strlen($timeValue)) {
- return Calculation_Functions::VALUE();
- }
- }
- $timeValue = self::_getTimeValue($timeValue);
- if (is_string($timeValue)) {
- return Calculation_Functions::VALUE();
- }
- }
- // Execute function
- if ($timeValue >= 1) {
- $timeValue = fmod($timeValue,1);
- } elseif ($timeValue < 0.0) {
- return Calculation_Functions::NaN();
- }
- $timeValue = Shared_Date::ExcelToPHP($timeValue);
-
- return (int) gmdate('G',$timeValue);
- } // function HOUROFDAY()
-
-
- /**
- * MINUTEOFHOUR
- *
- * Returns the minutes of a time value.
- * The minute is given as an integer, ranging from 0 to 59.
- *
- * Excel Function:
- * MINUTE(timeValue)
- *
- * @param mixed $timeValue Excel date serial value (float), PHP date timestamp (integer),
- * PHP DateTime object, or a standard time string
- * @return int Minute
- */
- public static function MINUTEOFHOUR($timeValue = 0) {
- $timeValue = $timeTester = Calculation_Functions::flattenSingleValue($timeValue);
-
- if (!is_numeric($timeValue)) {
- if (Calculation_Functions::getCompatibilityMode() == Calculation_Functions::COMPATIBILITY_GNUMERIC) {
- $testVal = strtok($timeValue,'/-: ');
- if (strlen($testVal) < strlen($timeValue)) {
- return Calculation_Functions::VALUE();
- }
- }
- $timeValue = self::_getTimeValue($timeValue);
- if (is_string($timeValue)) {
- return Calculation_Functions::VALUE();
- }
- }
- // Execute function
- if ($timeValue >= 1) {
- $timeValue = fmod($timeValue,1);
- } elseif ($timeValue < 0.0) {
- return Calculation_Functions::NaN();
- }
- $timeValue = Shared_Date::ExcelToPHP($timeValue);
-
- return (int) gmdate('i',$timeValue);
- } // function MINUTEOFHOUR()
-
-
- /**
- * SECONDOFMINUTE
- *
- * Returns the seconds of a time value.
- * The second is given as an integer in the range 0 (zero) to 59.
- *
- * Excel Function:
- * SECOND(timeValue)
- *
- * @param mixed $timeValue Excel date serial value (float), PHP date timestamp (integer),
- * PHP DateTime object, or a standard time string
- * @return int Second
- */
- public static function SECONDOFMINUTE($timeValue = 0) {
- $timeValue = Calculation_Functions::flattenSingleValue($timeValue);
-
- if (!is_numeric($timeValue)) {
- if (Calculation_Functions::getCompatibilityMode() == Calculation_Functions::COMPATIBILITY_GNUMERIC) {
- $testVal = strtok($timeValue,'/-: ');
- if (strlen($testVal) < strlen($timeValue)) {
- return Calculation_Functions::VALUE();
- }
- }
- $timeValue = self::_getTimeValue($timeValue);
- if (is_string($timeValue)) {
- return Calculation_Functions::VALUE();
- }
- }
- // Execute function
- if ($timeValue >= 1) {
- $timeValue = fmod($timeValue,1);
- } elseif ($timeValue < 0.0) {
- return Calculation_Functions::NaN();
- }
- $timeValue = Shared_Date::ExcelToPHP($timeValue);
-
- return (int) gmdate('s',$timeValue);
- } // function SECONDOFMINUTE()
-
-
- /**
- * EDATE
- *
- * Returns the serial number that represents the date that is the indicated number of months
- * before or after a specified date (the start_date).
- * Use EDATE to calculate maturity dates or due dates that fall on the same day of the month
- * as the date of issue.
- *
- * Excel Function:
- * EDATE(dateValue,adjustmentMonths)
- *
- * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer),
- * PHP DateTime object, or a standard date string
- * @param int $adjustmentMonths The number of months before or after start_date.
- * A positive value for months yields a future date;
- * a negative value yields a past date.
- * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
- * depending on the value of the ReturnDateType flag
- */
- public static function EDATE($dateValue = 1, $adjustmentMonths = 0) {
- $dateValue = Calculation_Functions::flattenSingleValue($dateValue);
- $adjustmentMonths = Calculation_Functions::flattenSingleValue($adjustmentMonths);
-
- if (!is_numeric($adjustmentMonths)) {
- return Calculation_Functions::VALUE();
- }
- $adjustmentMonths = floor($adjustmentMonths);
-
- if (is_string($dateValue = self::_getDateValue($dateValue))) {
- return Calculation_Functions::VALUE();
- }
-
- // Execute function
- $PHPDateObject = self::_adjustDateByMonths($dateValue,$adjustmentMonths);
-
- switch (Calculation_Functions::getReturnDateType()) {
- case Calculation_Functions::RETURNDATE_EXCEL :
- return (float) Shared_Date::PHPToExcel($PHPDateObject);
- case Calculation_Functions::RETURNDATE_PHP_NUMERIC :
- return (integer) Shared_Date::ExcelToPHP(Shared_Date::PHPToExcel($PHPDateObject));
- case Calculation_Functions::RETURNDATE_PHP_OBJECT :
- return $PHPDateObject;
- }
- } // function EDATE()
-
-
- /**
- * EOMONTH
- *
- * Returns the date value for the last day of the month that is the indicated number of months
- * before or after start_date.
- * Use EOMONTH to calculate maturity dates or due dates that fall on the last day of the month.
- *
- * Excel Function:
- * EOMONTH(dateValue,adjustmentMonths)
- *
- * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer),
- * PHP DateTime object, or a standard date string
- * @param int $adjustmentMonths The number of months before or after start_date.
- * A positive value for months yields a future date;
- * a negative value yields a past date.
- * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
- * depending on the value of the ReturnDateType flag
- */
- public static function EOMONTH($dateValue = 1, $adjustmentMonths = 0) {
- $dateValue = Calculation_Functions::flattenSingleValue($dateValue);
- $adjustmentMonths = Calculation_Functions::flattenSingleValue($adjustmentMonths);
-
- if (!is_numeric($adjustmentMonths)) {
- return Calculation_Functions::VALUE();
- }
- $adjustmentMonths = floor($adjustmentMonths);
-
- if (is_string($dateValue = self::_getDateValue($dateValue))) {
- return Calculation_Functions::VALUE();
- }
-
- // Execute function
- $PHPDateObject = self::_adjustDateByMonths($dateValue,$adjustmentMonths+1);
- $adjustDays = (int) $PHPDateObject->format('d');
- $adjustDaysString = '-'.$adjustDays.' days';
- $PHPDateObject->modify($adjustDaysString);
-
- switch (Calculation_Functions::getReturnDateType()) {
- case Calculation_Functions::RETURNDATE_EXCEL :
- return (float) Shared_Date::PHPToExcel($PHPDateObject);
- case Calculation_Functions::RETURNDATE_PHP_NUMERIC :
- return (integer) Shared_Date::ExcelToPHP(Shared_Date::PHPToExcel($PHPDateObject));
- case Calculation_Functions::RETURNDATE_PHP_OBJECT :
- return $PHPDateObject;
- }
- } // function EOMONTH()
-
+ }
+
+ $year = ($year !== null) ? Shared_String::testStringAsNumeric($year) : 0;
+ $month = ($month !== null) ? Shared_String::testStringAsNumeric($month) : 0;
+ $day = ($day !== null) ? Shared_String::testStringAsNumeric($day) : 0;
+ if ((!is_numeric($year)) ||
+ (!is_numeric($month)) ||
+ (!is_numeric($day))) {
+ return Calculation_Functions::VALUE();
+ }
+ $year = (integer) $year;
+ $month = (integer) $month;
+ $day = (integer) $day;
+
+ $baseYear = Shared_Date::getExcelCalendar();
+ // Validate parameters
+ if ($year < ($baseYear-1900)) {
+ return Calculation_Functions::NaN();
+ }
+ if ((($baseYear-1900) != 0) && ($year < $baseYear) && ($year >= 1900)) {
+ return Calculation_Functions::NaN();
+ }
+
+ if (($year < $baseYear) && ($year >= ($baseYear-1900))) {
+ $year += 1900;
+ }
+
+ if ($month < 1) {
+ // Handle year/month adjustment if month < 1
+ --$month;
+ $year += ceil($month / 12) - 1;
+ $month = 13 - abs($month % 12);
+ } elseif ($month > 12) {
+ // Handle year/month adjustment if month > 12
+ $year += floor($month / 12);
+ $month = ($month % 12);
+ }
+
+ // Re-validate the year parameter after adjustments
+ if (($year < $baseYear) || ($year >= 10000)) {
+ return Calculation_Functions::NaN();
+ }
+
+ // Execute function
+ $excelDateValue = Shared_Date::FormattedPHPToExcel($year, $month, $day);
+ switch (Calculation_Functions::getReturnDateType()) {
+ case Calculation_Functions::RETURNDATE_EXCEL :
+ return (float) $excelDateValue;
+ case Calculation_Functions::RETURNDATE_PHP_NUMERIC :
+ return (integer) Shared_Date::ExcelToPHP($excelDateValue);
+ case Calculation_Functions::RETURNDATE_PHP_OBJECT :
+ return Shared_Date::ExcelToPHPObject($excelDateValue);
+ }
+ } // function DATE()
+
+
+ /**
+ * TIME
+ *
+ * The TIME function returns a value that represents a particular time.
+ *
+ * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the time
+ * format of your regional settings. PHPExcel does not change cell formatting in this way.
+ *
+ * Excel Function:
+ * TIME(hour,minute,second)
+ *
+ * @access public
+ * @category Date/Time Functions
+ * @param integer $hour A number from 0 (zero) to 32767 representing the hour.
+ * Any value greater than 23 will be divided by 24 and the remainder
+ * will be treated as the hour value. For example, TIME(27,0,0) =
+ * TIME(3,0,0) = .125 or 3:00 AM.
+ * @param integer $minute A number from 0 to 32767 representing the minute.
+ * Any value greater than 59 will be converted to hours and minutes.
+ * For example, TIME(0,750,0) = TIME(12,30,0) = .520833 or 12:30 PM.
+ * @param integer $second A number from 0 to 32767 representing the second.
+ * Any value greater than 59 will be converted to hours, minutes,
+ * and seconds. For example, TIME(0,0,2000) = TIME(0,33,22) = .023148
+ * or 12:33:20 AM
+ * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
+ * depending on the value of the ReturnDateType flag
+ */
+ public static function TIME($hour = 0, $minute = 0, $second = 0) {
+ $hour = Calculation_Functions::flattenSingleValue($hour);
+ $minute = Calculation_Functions::flattenSingleValue($minute);
+ $second = Calculation_Functions::flattenSingleValue($second);
+
+ if ($hour == '') { $hour = 0; }
+ if ($minute == '') { $minute = 0; }
+ if ($second == '') { $second = 0; }
+
+ if ((!is_numeric($hour)) || (!is_numeric($minute)) || (!is_numeric($second))) {
+ return Calculation_Functions::VALUE();
+ }
+ $hour = (integer) $hour;
+ $minute = (integer) $minute;
+ $second = (integer) $second;
+
+ if ($second < 0) {
+ $minute += floor($second / 60);
+ $second = 60 - abs($second % 60);
+ if ($second == 60) { $second = 0; }
+ } elseif ($second >= 60) {
+ $minute += floor($second / 60);
+ $second = $second % 60;
+ }
+ if ($minute < 0) {
+ $hour += floor($minute / 60);
+ $minute = 60 - abs($minute % 60);
+ if ($minute == 60) { $minute = 0; }
+ } elseif ($minute >= 60) {
+ $hour += floor($minute / 60);
+ $minute = $minute % 60;
+ }
+
+ if ($hour > 23) {
+ $hour = $hour % 24;
+ } elseif ($hour < 0) {
+ return Calculation_Functions::NaN();
+ }
+
+ // Execute function
+ switch (Calculation_Functions::getReturnDateType()) {
+ case Calculation_Functions::RETURNDATE_EXCEL :
+ $date = 0;
+ $calendar = Shared_Date::getExcelCalendar();
+ if ($calendar != Shared_Date::CALENDAR_WINDOWS_1900) {
+ $date = 1;
+ }
+ return (float) Shared_Date::FormattedPHPToExcel($calendar, 1, $date, $hour, $minute, $second);
+ case Calculation_Functions::RETURNDATE_PHP_NUMERIC :
+ return (integer) Shared_Date::ExcelToPHP(Shared_Date::FormattedPHPToExcel(1970, 1, 1, $hour, $minute, $second)); // -2147468400; // -2147472000 + 3600
+ case Calculation_Functions::RETURNDATE_PHP_OBJECT :
+ $dayAdjust = 0;
+ if ($hour < 0) {
+ $dayAdjust = floor($hour / 24);
+ $hour = 24 - abs($hour % 24);
+ if ($hour == 24) { $hour = 0; }
+ } elseif ($hour >= 24) {
+ $dayAdjust = floor($hour / 24);
+ $hour = $hour % 24;
+ }
+ $phpDateObject = new DateTime('1900-01-01 '.$hour.':'.$minute.':'.$second);
+ if ($dayAdjust != 0) {
+ $phpDateObject->modify($dayAdjust.' days');
+ }
+ return $phpDateObject;
+ }
+ } // function TIME()
+
+
+ /**
+ * DATEVALUE
+ *
+ * Returns a value that represents a particular date.
+ * Use DATEVALUE to convert a date represented by a text string to an Excel or PHP date/time stamp
+ * value.
+ *
+ * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the date
+ * format of your regional settings. PHPExcel does not change cell formatting in this way.
+ *
+ * Excel Function:
+ * DATEVALUE(dateValue)
+ *
+ * @access public
+ * @category Date/Time Functions
+ * @param string $dateValue Text that represents a date in a Microsoft Excel date format.
+ * For example, "1/30/2008" or "30-Jan-2008" are text strings within
+ * quotation marks that represent dates. Using the default date
+ * system in Excel for Windows, date_text must represent a date from
+ * January 1, 1900, to December 31, 9999. Using the default date
+ * system in Excel for the Macintosh, date_text must represent a date
+ * from January 1, 1904, to December 31, 9999. DATEVALUE returns the
+ * #VALUE! error value if date_text is out of this range.
+ * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
+ * depending on the value of the ReturnDateType flag
+ */
+ public static function DATEVALUE($dateValue = 1) {
+ $dateValue = trim(Calculation_Functions::flattenSingleValue($dateValue),'"');
+ // Strip any ordinals because they're allowed in Excel (English only)
+ $dateValue = preg_replace('/(\d)(st|nd|rd|th)([ -\/])/Ui','$1$3',$dateValue);
+ // Convert separators (/ . or space) to hyphens (should also handle dot used for ordinals in some countries, e.g. Denmark, Germany)
+ $dateValue = str_replace(array('/','.','-',' '),array(' ',' ',' ',' '),$dateValue);
+
+ $yearFound = false;
+ $t1 = explode(' ',$dateValue);
+ foreach($t1 as &$t) {
+ if ((is_numeric($t)) && ($t > 31)) {
+ if ($yearFound) {
+ return Calculation_Functions::VALUE();
+ } else {
+ if ($t < 100) { $t += 1900; }
+ $yearFound = true;
+ }
+ }
+ }
+ if ((count($t1) == 1) && (strpos($t,':') != false)) {
+ // We've been fed a time value without any date
+ return 0.0;
+ } elseif (count($t1) == 2) {
+ // We only have two parts of the date: either day/month or month/year
+ if ($yearFound) {
+ array_unshift($t1,1);
+ } else {
+ array_push($t1,date('Y'));
+ }
+ }
+ unset($t);
+ $dateValue = implode(' ',$t1);
+
+ $PHPDateArray = date_parse($dateValue);
+ if (($PHPDateArray === False) || ($PHPDateArray['error_count'] > 0)) {
+ $testVal1 = strtok($dateValue,'- ');
+ if ($testVal1 !== False) {
+ $testVal2 = strtok('- ');
+ if ($testVal2 !== False) {
+ $testVal3 = strtok('- ');
+ if ($testVal3 === False) {
+ $testVal3 = strftime('%Y');
+ }
+ } else {
+ return Calculation_Functions::VALUE();
+ }
+ } else {
+ return Calculation_Functions::VALUE();
+ }
+ $PHPDateArray = date_parse($testVal1.'-'.$testVal2.'-'.$testVal3);
+ if (($PHPDateArray === False) || ($PHPDateArray['error_count'] > 0)) {
+ $PHPDateArray = date_parse($testVal2.'-'.$testVal1.'-'.$testVal3);
+ if (($PHPDateArray === False) || ($PHPDateArray['error_count'] > 0)) {
+ return Calculation_Functions::VALUE();
+ }
+ }
+ }
+
+ if (($PHPDateArray !== False) && ($PHPDateArray['error_count'] == 0)) {
+ // Execute function
+ if ($PHPDateArray['year'] == '') { $PHPDateArray['year'] = strftime('%Y'); }
+ if ($PHPDateArray['year'] < 1900)
+ return Calculation_Functions::VALUE();
+ if ($PHPDateArray['month'] == '') { $PHPDateArray['month'] = strftime('%m'); }
+ if ($PHPDateArray['day'] == '') { $PHPDateArray['day'] = strftime('%d'); }
+ $excelDateValue = floor(Shared_Date::FormattedPHPToExcel($PHPDateArray['year'],$PHPDateArray['month'],$PHPDateArray['day'],$PHPDateArray['hour'],$PHPDateArray['minute'],$PHPDateArray['second']));
+
+ switch (Calculation_Functions::getReturnDateType()) {
+ case Calculation_Functions::RETURNDATE_EXCEL :
+ return (float) $excelDateValue;
+ case Calculation_Functions::RETURNDATE_PHP_NUMERIC :
+ return (integer) Shared_Date::ExcelToPHP($excelDateValue);
+ case Calculation_Functions::RETURNDATE_PHP_OBJECT :
+ return new DateTime($PHPDateArray['year'].'-'.$PHPDateArray['month'].'-'.$PHPDateArray['day'].' 00:00:00');
+ }
+ }
+ return Calculation_Functions::VALUE();
+ } // function DATEVALUE()
+
+
+ /**
+ * TIMEVALUE
+ *
+ * Returns a value that represents a particular time.
+ * Use TIMEVALUE to convert a time represented by a text string to an Excel or PHP date/time stamp
+ * value.
+ *
+ * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the time
+ * format of your regional settings. PHPExcel does not change cell formatting in this way.
+ *
+ * Excel Function:
+ * TIMEVALUE(timeValue)
+ *
+ * @access public
+ * @category Date/Time Functions
+ * @param string $timeValue A text string that represents a time in any one of the Microsoft
+ * Excel time formats; for example, "6:45 PM" and "18:45" text strings
+ * within quotation marks that represent time.
+ * Date information in time_text is ignored.
+ * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
+ * depending on the value of the ReturnDateType flag
+ */
+ public static function TIMEVALUE($timeValue) {
+ $timeValue = trim(Calculation_Functions::flattenSingleValue($timeValue),'"');
+ $timeValue = str_replace(array('/','.'),array('-','-'),$timeValue);
+
+ $PHPDateArray = date_parse($timeValue);
+ if (($PHPDateArray !== False) && ($PHPDateArray['error_count'] == 0)) {
+ if (Calculation_Functions::getCompatibilityMode() == Calculation_Functions::COMPATIBILITY_OPENOFFICE) {
+ $excelDateValue = Shared_Date::FormattedPHPToExcel($PHPDateArray['year'],$PHPDateArray['month'],$PHPDateArray['day'],$PHPDateArray['hour'],$PHPDateArray['minute'],$PHPDateArray['second']);
+ } else {
+ $excelDateValue = Shared_Date::FormattedPHPToExcel(1900,1,1,$PHPDateArray['hour'],$PHPDateArray['minute'],$PHPDateArray['second']) - 1;
+ }
+
+ switch (Calculation_Functions::getReturnDateType()) {
+ case Calculation_Functions::RETURNDATE_EXCEL :
+ return (float) $excelDateValue;
+ case Calculation_Functions::RETURNDATE_PHP_NUMERIC :
+ return (integer) $phpDateValue = Shared_Date::ExcelToPHP($excelDateValue+25569) - 3600;;
+ case Calculation_Functions::RETURNDATE_PHP_OBJECT :
+ return new DateTime('1900-01-01 '.$PHPDateArray['hour'].':'.$PHPDateArray['minute'].':'.$PHPDateArray['second']);
+ }
+ }
+ return Calculation_Functions::VALUE();
+ } // function TIMEVALUE()
+
+
+ /**
+ * DATEDIF
+ *
+ * @param mixed $startDate Excel date serial value, PHP date/time stamp, PHP DateTime object
+ * or a standard date string
+ * @param mixed $endDate Excel date serial value, PHP date/time stamp, PHP DateTime object
+ * or a standard date string
+ * @param string $unit
+ * @return integer Interval between the dates
+ */
+ public static function DATEDIF($startDate = 0, $endDate = 0, $unit = 'D') {
+ $startDate = Calculation_Functions::flattenSingleValue($startDate);
+ $endDate = Calculation_Functions::flattenSingleValue($endDate);
+ $unit = strtoupper(Calculation_Functions::flattenSingleValue($unit));
+
+ if (is_string($startDate = self::_getDateValue($startDate))) {
+ return Calculation_Functions::VALUE();
+ }
+ if (is_string($endDate = self::_getDateValue($endDate))) {
+ return Calculation_Functions::VALUE();
+ }
+
+ // Validate parameters
+ if ($startDate >= $endDate) {
+ return Calculation_Functions::NaN();
+ }
+
+ // Execute function
+ $difference = $endDate - $startDate;
+
+ $PHPStartDateObject = Shared_Date::ExcelToPHPObject($startDate);
+ $startDays = $PHPStartDateObject->format('j');
+ $startMonths = $PHPStartDateObject->format('n');
+ $startYears = $PHPStartDateObject->format('Y');
+
+ $PHPEndDateObject = Shared_Date::ExcelToPHPObject($endDate);
+ $endDays = $PHPEndDateObject->format('j');
+ $endMonths = $PHPEndDateObject->format('n');
+ $endYears = $PHPEndDateObject->format('Y');
+
+ $retVal = Calculation_Functions::NaN();
+ switch ($unit) {
+ case 'D':
+ $retVal = intval($difference);
+ break;
+ case 'M':
+ $retVal = intval($endMonths - $startMonths) + (intval($endYears - $startYears) * 12);
+ // We're only interested in full months
+ if ($endDays < $startDays) {
+ --$retVal;
+ }
+ break;
+ case 'Y':
+ $retVal = intval($endYears - $startYears);
+ // We're only interested in full months
+ if ($endMonths < $startMonths) {
+ --$retVal;
+ } elseif (($endMonths == $startMonths) && ($endDays < $startDays)) {
+ --$retVal;
+ }
+ break;
+ case 'MD':
+ if ($endDays < $startDays) {
+ $retVal = $endDays;
+ $PHPEndDateObject->modify('-'.$endDays.' days');
+ $adjustDays = $PHPEndDateObject->format('j');
+ if ($adjustDays > $startDays) {
+ $retVal += ($adjustDays - $startDays);
+ }
+ } else {
+ $retVal = $endDays - $startDays;
+ }
+ break;
+ case 'YM':
+ $retVal = intval($endMonths - $startMonths);
+ if ($retVal < 0) $retVal = 12 + $retVal;
+ // We're only interested in full months
+ if ($endDays < $startDays) {
+ --$retVal;
+ }
+ break;
+ case 'YD':
+ $retVal = intval($difference);
+ if ($endYears > $startYears) {
+ while ($endYears > $startYears) {
+ $PHPEndDateObject->modify('-1 year');
+ $endYears = $PHPEndDateObject->format('Y');
+ }
+ $retVal = $PHPEndDateObject->format('z') - $PHPStartDateObject->format('z');
+ if ($retVal < 0) { $retVal += 365; }
+ }
+ break;
+ default:
+ $retVal = Calculation_Functions::NaN();
+ }
+ return $retVal;
+ } // function DATEDIF()
+
+
+ /**
+ * DAYS360
+ *
+ * Returns the number of days between two dates based on a 360-day year (twelve 30-day months),
+ * which is used in some accounting calculations. Use this function to help compute payments if
+ * your accounting system is based on twelve 30-day months.
+ *
+ * Excel Function:
+ * DAYS360(startDate,endDate[,method])
+ *
+ * @access public
+ * @category Date/Time Functions
+ * @param mixed $startDate Excel date serial value (float), PHP date timestamp (integer),
+ * PHP DateTime object, or a standard date string
+ * @param mixed $endDate Excel date serial value (float), PHP date timestamp (integer),
+ * PHP DateTime object, or a standard date string
+ * @param boolean $method US or European Method
+ * FALSE or omitted: U.S. (NASD) method. If the starting date is
+ * the last day of a month, it becomes equal to the 30th of the
+ * same month. If the ending date is the last day of a month and
+ * the starting date is earlier than the 30th of a month, the
+ * ending date becomes equal to the 1st of the next month;
+ * otherwise the ending date becomes equal to the 30th of the
+ * same month.
+ * TRUE: European method. Starting dates and ending dates that
+ * occur on the 31st of a month become equal to the 30th of the
+ * same month.
+ * @return integer Number of days between start date and end date
+ */
+ public static function DAYS360($startDate = 0, $endDate = 0, $method = false) {
+ $startDate = Calculation_Functions::flattenSingleValue($startDate);
+ $endDate = Calculation_Functions::flattenSingleValue($endDate);
+
+ if (is_string($startDate = self::_getDateValue($startDate))) {
+ return Calculation_Functions::VALUE();
+ }
+ if (is_string($endDate = self::_getDateValue($endDate))) {
+ return Calculation_Functions::VALUE();
+ }
+
+ if (!is_bool($method)) {
+ return Calculation_Functions::VALUE();
+ }
+
+ // Execute function
+ $PHPStartDateObject = Shared_Date::ExcelToPHPObject($startDate);
+ $startDay = $PHPStartDateObject->format('j');
+ $startMonth = $PHPStartDateObject->format('n');
+ $startYear = $PHPStartDateObject->format('Y');
+
+ $PHPEndDateObject = Shared_Date::ExcelToPHPObject($endDate);
+ $endDay = $PHPEndDateObject->format('j');
+ $endMonth = $PHPEndDateObject->format('n');
+ $endYear = $PHPEndDateObject->format('Y');
+
+ return self::_dateDiff360($startDay, $startMonth, $startYear, $endDay, $endMonth, $endYear, !$method);
+ } // function DAYS360()
+
+
+ /**
+ * YEARFRAC
+ *
+ * Calculates the fraction of the year represented by the number of whole days between two dates
+ * (the start_date and the end_date).
+ * Use the YEARFRAC worksheet function to identify the proportion of a whole year's benefits or
+ * obligations to assign to a specific term.
+ *
+ * Excel Function:
+ * YEARFRAC(startDate,endDate[,method])
+ *
+ * @access public
+ * @category Date/Time Functions
+ * @param mixed $startDate Excel date serial value (float), PHP date timestamp (integer),
+ * PHP DateTime object, or a standard date string
+ * @param mixed $endDate Excel date serial value (float), PHP date timestamp (integer),
+ * PHP DateTime object, or a standard date string
+ * @param integer $method Method used for the calculation
+ * 0 or omitted US (NASD) 30/360
+ * 1 Actual/actual
+ * 2 Actual/360
+ * 3 Actual/365
+ * 4 European 30/360
+ * @return float fraction of the year
+ */
+ public static function YEARFRAC($startDate = 0, $endDate = 0, $method = 0) {
+ $startDate = Calculation_Functions::flattenSingleValue($startDate);
+ $endDate = Calculation_Functions::flattenSingleValue($endDate);
+ $method = Calculation_Functions::flattenSingleValue($method);
+
+ if (is_string($startDate = self::_getDateValue($startDate))) {
+ return Calculation_Functions::VALUE();
+ }
+ if (is_string($endDate = self::_getDateValue($endDate))) {
+ return Calculation_Functions::VALUE();
+ }
+
+ if (((is_numeric($method)) && (!is_string($method))) || ($method == '')) {
+ switch($method) {
+ case 0 :
+ return self::DAYS360($startDate,$endDate) / 360;
+ case 1 :
+ $days = self::DATEDIF($startDate,$endDate);
+ $startYear = self::YEAR($startDate);
+ $endYear = self::YEAR($endDate);
+ $years = $endYear - $startYear + 1;
+ $leapDays = 0;
+ if ($years == 1) {
+ if (self::_isLeapYear($endYear)) {
+ $startMonth = self::MONTHOFYEAR($startDate);
+ $endMonth = self::MONTHOFYEAR($endDate);
+ $endDay = self::DAYOFMONTH($endDate);
+ if (($startMonth < 3) ||
+ (($endMonth * 100 + $endDay) >= (2 * 100 + 29))) {
+ $leapDays += 1;
+ }
+ }
+ } else {
+ for($year = $startYear; $year <= $endYear; ++$year) {
+ if ($year == $startYear) {
+ $startMonth = self::MONTHOFYEAR($startDate);
+ $startDay = self::DAYOFMONTH($startDate);
+ if ($startMonth < 3) {
+ $leapDays += (self::_isLeapYear($year)) ? 1 : 0;
+ }
+ } elseif($year == $endYear) {
+ $endMonth = self::MONTHOFYEAR($endDate);
+ $endDay = self::DAYOFMONTH($endDate);
+ if (($endMonth * 100 + $endDay) >= (2 * 100 + 29)) {
+ $leapDays += (self::_isLeapYear($year)) ? 1 : 0;
+ }
+ } else {
+ $leapDays += (self::_isLeapYear($year)) ? 1 : 0;
+ }
+ }
+ if ($years == 2) {
+ if (($leapDays == 0) && (self::_isLeapYear($startYear)) && ($days > 365)) {
+ $leapDays = 1;
+ } elseif ($days < 366) {
+ $years = 1;
+ }
+ }
+ $leapDays /= $years;
+ }
+ return $days / (365 + $leapDays);
+ case 2 :
+ return self::DATEDIF($startDate,$endDate) / 360;
+ case 3 :
+ return self::DATEDIF($startDate,$endDate) / 365;
+ case 4 :
+ return self::DAYS360($startDate,$endDate,True) / 360;
+ }
+ }
+ return Calculation_Functions::VALUE();
+ } // function YEARFRAC()
+
+
+ /**
+ * NETWORKDAYS
+ *
+ * Returns the number of whole working days between start_date and end_date. Working days
+ * exclude weekends and any dates identified in holidays.
+ * Use NETWORKDAYS to calculate employee benefits that accrue based on the number of days
+ * worked during a specific term.
+ *
+ * Excel Function:
+ * NETWORKDAYS(startDate,endDate[,holidays[,holiday[,...]]])
+ *
+ * @access public
+ * @category Date/Time Functions
+ * @param mixed $startDate Excel date serial value (float), PHP date timestamp (integer),
+ * PHP DateTime object, or a standard date string
+ * @param mixed $endDate Excel date serial value (float), PHP date timestamp (integer),
+ * PHP DateTime object, or a standard date string
+ * @param mixed $holidays,... Optional series of Excel date serial value (float), PHP date
+ * timestamp (integer), PHP DateTime object, or a standard date
+ * strings that will be excluded from the working calendar, such
+ * as state and federal holidays and floating holidays.
+ * @return integer Interval between the dates
+ */
+ public static function NETWORKDAYS($startDate,$endDate) {
+ // Retrieve the mandatory start and end date that are referenced in the function definition
+ $startDate = Calculation_Functions::flattenSingleValue($startDate);
+ $endDate = Calculation_Functions::flattenSingleValue($endDate);
+ // Flush the mandatory start and end date that are referenced in the function definition, and get the optional days
+ $dateArgs = Calculation_Functions::flattenArray(func_get_args());
+ array_shift($dateArgs);
+ array_shift($dateArgs);
+
+ // Validate the start and end dates
+ if (is_string($startDate = $sDate = self::_getDateValue($startDate))) {
+ return Calculation_Functions::VALUE();
+ }
+ $startDate = (float) floor($startDate);
+ if (is_string($endDate = $eDate = self::_getDateValue($endDate))) {
+ return Calculation_Functions::VALUE();
+ }
+ $endDate = (float) floor($endDate);
+
+ if ($sDate > $eDate) {
+ $startDate = $eDate;
+ $endDate = $sDate;
+ }
+
+ // Execute function
+ $startDoW = 6 - self::DAYOFWEEK($startDate,2);
+ if ($startDoW < 0) { $startDoW = 0; }
+ $endDoW = self::DAYOFWEEK($endDate,2);
+ if ($endDoW >= 6) { $endDoW = 0; }
+
+ $wholeWeekDays = floor(($endDate - $startDate) / 7) * 5;
+ $partWeekDays = $endDoW + $startDoW;
+ if ($partWeekDays > 5) {
+ $partWeekDays -= 5;
+ }
+
+ // Test any extra holiday parameters
+ $holidayCountedArray = array();
+ foreach ($dateArgs as $holidayDate) {
+ if (is_string($holidayDate = self::_getDateValue($holidayDate))) {
+ return Calculation_Functions::VALUE();
+ }
+ if (($holidayDate >= $startDate) && ($holidayDate <= $endDate)) {
+ if ((self::DAYOFWEEK($holidayDate,2) < 6) && (!in_array($holidayDate,$holidayCountedArray))) {
+ --$partWeekDays;
+ $holidayCountedArray[] = $holidayDate;
+ }
+ }
+ }
+
+ if ($sDate > $eDate) {
+ return 0 - ($wholeWeekDays + $partWeekDays);
+ }
+ return $wholeWeekDays + $partWeekDays;
+ } // function NETWORKDAYS()
+
+
+ /**
+ * WORKDAY
+ *
+ * Returns the date that is the indicated number of working days before or after a date (the
+ * starting date). Working days exclude weekends and any dates identified as holidays.
+ * Use WORKDAY to exclude weekends or holidays when you calculate invoice due dates, expected
+ * delivery times, or the number of days of work performed.
+ *
+ * Excel Function:
+ * WORKDAY(startDate,endDays[,holidays[,holiday[,...]]])
+ *
+ * @access public
+ * @category Date/Time Functions
+ * @param mixed $startDate Excel date serial value (float), PHP date timestamp (integer),
+ * PHP DateTime object, or a standard date string
+ * @param integer $endDays The number of nonweekend and nonholiday days before or after
+ * startDate. A positive value for days yields a future date; a
+ * negative value yields a past date.
+ * @param mixed $holidays,... Optional series of Excel date serial value (float), PHP date
+ * timestamp (integer), PHP DateTime object, or a standard date
+ * strings that will be excluded from the working calendar, such
+ * as state and federal holidays and floating holidays.
+ * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
+ * depending on the value of the ReturnDateType flag
+ */
+ public static function WORKDAY($startDate,$endDays) {
+ // Retrieve the mandatory start date and days that are referenced in the function definition
+ $startDate = Calculation_Functions::flattenSingleValue($startDate);
+ $endDays = Calculation_Functions::flattenSingleValue($endDays);
+ // Flush the mandatory start date and days that are referenced in the function definition, and get the optional days
+ $dateArgs = Calculation_Functions::flattenArray(func_get_args());
+ array_shift($dateArgs);
+ array_shift($dateArgs);
+
+ if ((is_string($startDate = self::_getDateValue($startDate))) || (!is_numeric($endDays))) {
+ return Calculation_Functions::VALUE();
+ }
+ $startDate = (float) floor($startDate);
+ $endDays = (int) floor($endDays);
+ // If endDays is 0, we always return startDate
+ if ($endDays == 0) { return $startDate; }
+
+ $decrementing = ($endDays < 0) ? True : False;
+
+ // Adjust the start date if it falls over a weekend
+
+ $startDoW = self::DAYOFWEEK($startDate,3);
+ if (self::DAYOFWEEK($startDate,3) >= 5) {
+ $startDate += ($decrementing) ? -$startDoW + 4: 7 - $startDoW;
+ ($decrementing) ? $endDays++ : $endDays--;
+ }
+
+ // Add endDays
+ $endDate = (float) $startDate + (intval($endDays / 5) * 7) + ($endDays % 5);
+
+ // Adjust the calculated end date if it falls over a weekend
+ $endDoW = self::DAYOFWEEK($endDate,3);
+ if ($endDoW >= 5) {
+ $endDate += ($decrementing) ? -$endDoW + 4: 7 - $endDoW;
+ }
+
+ // Test any extra holiday parameters
+ if (!empty($dateArgs)) {
+ $holidayCountedArray = $holidayDates = array();
+ foreach ($dateArgs as $holidayDate) {
+ if (($holidayDate !== null) && (trim($holidayDate) > '')) {
+ if (is_string($holidayDate = self::_getDateValue($holidayDate))) {
+ return Calculation_Functions::VALUE();
+ }
+ if (self::DAYOFWEEK($holidayDate,3) < 5) {
+ $holidayDates[] = $holidayDate;
+ }
+ }
+ }
+ if ($decrementing) {
+ rsort($holidayDates, SORT_NUMERIC);
+ } else {
+ sort($holidayDates, SORT_NUMERIC);
+ }
+ foreach ($holidayDates as $holidayDate) {
+ if ($decrementing) {
+ if (($holidayDate <= $startDate) && ($holidayDate >= $endDate)) {
+ if (!in_array($holidayDate,$holidayCountedArray)) {
+ --$endDate;
+ $holidayCountedArray[] = $holidayDate;
+ }
+ }
+ } else {
+ if (($holidayDate >= $startDate) && ($holidayDate <= $endDate)) {
+ if (!in_array($holidayDate,$holidayCountedArray)) {
+ ++$endDate;
+ $holidayCountedArray[] = $holidayDate;
+ }
+ }
+ }
+ // Adjust the calculated end date if it falls over a weekend
+ $endDoW = self::DAYOFWEEK($endDate,3);
+ if ($endDoW >= 5) {
+ $endDate += ($decrementing) ? -$endDoW + 4: 7 - $endDoW;
+ }
+
+ }
+ }
+
+ switch (Calculation_Functions::getReturnDateType()) {
+ case Calculation_Functions::RETURNDATE_EXCEL :
+ return (float) $endDate;
+ case Calculation_Functions::RETURNDATE_PHP_NUMERIC :
+ return (integer) Shared_Date::ExcelToPHP($endDate);
+ case Calculation_Functions::RETURNDATE_PHP_OBJECT :
+ return Shared_Date::ExcelToPHPObject($endDate);
+ }
+ } // function WORKDAY()
+
+
+ /**
+ * DAYOFMONTH
+ *
+ * Returns the day of the month, for a specified date. The day is given as an integer
+ * ranging from 1 to 31.
+ *
+ * Excel Function:
+ * DAY(dateValue)
+ *
+ * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer),
+ * PHP DateTime object, or a standard date string
+ * @return int Day of the month
+ */
+ public static function DAYOFMONTH($dateValue = 1) {
+ $dateValue = Calculation_Functions::flattenSingleValue($dateValue);
+
+ if (is_string($dateValue = self::_getDateValue($dateValue))) {
+ return Calculation_Functions::VALUE();
+ } elseif ($dateValue == 0.0) {
+ return 0;
+ } elseif ($dateValue < 0.0) {
+ return Calculation_Functions::NaN();
+ }
+
+ // Execute function
+ $PHPDateObject = Shared_Date::ExcelToPHPObject($dateValue);
+
+ return (int) $PHPDateObject->format('j');
+ } // function DAYOFMONTH()
+
+
+ /**
+ * DAYOFWEEK
+ *
+ * Returns the day of the week for a specified date. The day is given as an integer
+ * ranging from 0 to 7 (dependent on the requested style).
+ *
+ * Excel Function:
+ * WEEKDAY(dateValue[,style])
+ *
+ * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer),
+ * PHP DateTime object, or a standard date string
+ * @param int $style A number that determines the type of return value
+ * 1 or omitted Numbers 1 (Sunday) through 7 (Saturday).
+ * 2 Numbers 1 (Monday) through 7 (Sunday).
+ * 3 Numbers 0 (Monday) through 6 (Sunday).
+ * @return int Day of the week value
+ */
+ public static function DAYOFWEEK($dateValue = 1, $style = 1) {
+ $dateValue = Calculation_Functions::flattenSingleValue($dateValue);
+ $style = Calculation_Functions::flattenSingleValue($style);
+
+ if (!is_numeric($style)) {
+ return Calculation_Functions::VALUE();
+ } elseif (($style < 1) || ($style > 3)) {
+ return Calculation_Functions::NaN();
+ }
+ $style = floor($style);
+
+ if (is_string($dateValue = self::_getDateValue($dateValue))) {
+ return Calculation_Functions::VALUE();
+ } elseif ($dateValue < 0.0) {
+ return Calculation_Functions::NaN();
+ }
+
+ // Execute function
+ $PHPDateObject = Shared_Date::ExcelToPHPObject($dateValue);
+ $DoW = $PHPDateObject->format('w');
+
+ $firstDay = 1;
+ switch ($style) {
+ case 1: ++$DoW;
+ break;
+ case 2: if ($DoW == 0) { $DoW = 7; }
+ break;
+ case 3: if ($DoW == 0) { $DoW = 7; }
+ $firstDay = 0;
+ --$DoW;
+ break;
+ }
+ if (Calculation_Functions::getCompatibilityMode() == Calculation_Functions::COMPATIBILITY_EXCEL) {
+ // Test for Excel's 1900 leap year, and introduce the error as required
+ if (($PHPDateObject->format('Y') == 1900) && ($PHPDateObject->format('n') <= 2)) {
+ --$DoW;
+ if ($DoW < $firstDay) {
+ $DoW += 7;
+ }
+ }
+ }
+
+ return (int) $DoW;
+ } // function DAYOFWEEK()
+
+
+ /**
+ * WEEKOFYEAR
+ *
+ * Returns the week of the year for a specified date.
+ * The WEEKNUM function considers the week containing January 1 to be the first week of the year.
+ * However, there is a European standard that defines the first week as the one with the majority
+ * of days (four or more) falling in the new year. This means that for years in which there are
+ * three days or less in the first week of January, the WEEKNUM function returns week numbers
+ * that are incorrect according to the European standard.
+ *
+ * Excel Function:
+ * WEEKNUM(dateValue[,style])
+ *
+ * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer),
+ * PHP DateTime object, or a standard date string
+ * @param boolean $method Week begins on Sunday or Monday
+ * 1 or omitted Week begins on Sunday.
+ * 2 Week begins on Monday.
+ * @return int Week Number
+ */
+ public static function WEEKOFYEAR($dateValue = 1, $method = 1) {
+ $dateValue = Calculation_Functions::flattenSingleValue($dateValue);
+ $method = Calculation_Functions::flattenSingleValue($method);
+
+ if (!is_numeric($method)) {
+ return Calculation_Functions::VALUE();
+ } elseif (($method < 1) || ($method > 2)) {
+ return Calculation_Functions::NaN();
+ }
+ $method = floor($method);
+
+ if (is_string($dateValue = self::_getDateValue($dateValue))) {
+ return Calculation_Functions::VALUE();
+ } elseif ($dateValue < 0.0) {
+ return Calculation_Functions::NaN();
+ }
+
+ // Execute function
+ $PHPDateObject = Shared_Date::ExcelToPHPObject($dateValue);
+ $dayOfYear = $PHPDateObject->format('z');
+ $dow = $PHPDateObject->format('w');
+ $PHPDateObject->modify('-'.$dayOfYear.' days');
+ $dow = $PHPDateObject->format('w');
+ $daysInFirstWeek = 7 - (($dow + (2 - $method)) % 7);
+ $dayOfYear -= $daysInFirstWeek;
+ $weekOfYear = ceil($dayOfYear / 7) + 1;
+
+ return (int) $weekOfYear;
+ } // function WEEKOFYEAR()
+
+
+ /**
+ * MONTHOFYEAR
+ *
+ * Returns the month of a date represented by a serial number.
+ * The month is given as an integer, ranging from 1 (January) to 12 (December).
+ *
+ * Excel Function:
+ * MONTH(dateValue)
+ *
+ * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer),
+ * PHP DateTime object, or a standard date string
+ * @return int Month of the year
+ */
+ public static function MONTHOFYEAR($dateValue = 1) {
+ $dateValue = Calculation_Functions::flattenSingleValue($dateValue);
+
+ if (is_string($dateValue = self::_getDateValue($dateValue))) {
+ return Calculation_Functions::VALUE();
+ } elseif ($dateValue < 0.0) {
+ return Calculation_Functions::NaN();
+ }
+
+ // Execute function
+ $PHPDateObject = Shared_Date::ExcelToPHPObject($dateValue);
+
+ return (int) $PHPDateObject->format('n');
+ } // function MONTHOFYEAR()
+
+
+ /**
+ * YEAR
+ *
+ * Returns the year corresponding to a date.
+ * The year is returned as an integer in the range 1900-9999.
+ *
+ * Excel Function:
+ * YEAR(dateValue)
+ *
+ * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer),
+ * PHP DateTime object, or a standard date string
+ * @return int Year
+ */
+ public static function YEAR($dateValue = 1) {
+ $dateValue = Calculation_Functions::flattenSingleValue($dateValue);
+
+ if (is_string($dateValue = self::_getDateValue($dateValue))) {
+ return Calculation_Functions::VALUE();
+ } elseif ($dateValue < 0.0) {
+ return Calculation_Functions::NaN();
+ }
+
+ // Execute function
+ $PHPDateObject = Shared_Date::ExcelToPHPObject($dateValue);
+
+ return (int) $PHPDateObject->format('Y');
+ } // function YEAR()
+
+
+ /**
+ * HOUROFDAY
+ *
+ * Returns the hour of a time value.
+ * The hour is given as an integer, ranging from 0 (12:00 A.M.) to 23 (11:00 P.M.).
+ *
+ * Excel Function:
+ * HOUR(timeValue)
+ *
+ * @param mixed $timeValue Excel date serial value (float), PHP date timestamp (integer),
+ * PHP DateTime object, or a standard time string
+ * @return int Hour
+ */
+ public static function HOUROFDAY($timeValue = 0) {
+ $timeValue = Calculation_Functions::flattenSingleValue($timeValue);
+
+ if (!is_numeric($timeValue)) {
+ if (Calculation_Functions::getCompatibilityMode() == Calculation_Functions::COMPATIBILITY_GNUMERIC) {
+ $testVal = strtok($timeValue,'/-: ');
+ if (strlen($testVal) < strlen($timeValue)) {
+ return Calculation_Functions::VALUE();
+ }
+ }
+ $timeValue = self::_getTimeValue($timeValue);
+ if (is_string($timeValue)) {
+ return Calculation_Functions::VALUE();
+ }
+ }
+ // Execute function
+ if ($timeValue >= 1) {
+ $timeValue = fmod($timeValue,1);
+ } elseif ($timeValue < 0.0) {
+ return Calculation_Functions::NaN();
+ }
+ $timeValue = Shared_Date::ExcelToPHP($timeValue);
+
+ return (int) gmdate('G',$timeValue);
+ } // function HOUROFDAY()
+
+
+ /**
+ * MINUTEOFHOUR
+ *
+ * Returns the minutes of a time value.
+ * The minute is given as an integer, ranging from 0 to 59.
+ *
+ * Excel Function:
+ * MINUTE(timeValue)
+ *
+ * @param mixed $timeValue Excel date serial value (float), PHP date timestamp (integer),
+ * PHP DateTime object, or a standard time string
+ * @return int Minute
+ */
+ public static function MINUTEOFHOUR($timeValue = 0) {
+ $timeValue = $timeTester = Calculation_Functions::flattenSingleValue($timeValue);
+
+ if (!is_numeric($timeValue)) {
+ if (Calculation_Functions::getCompatibilityMode() == Calculation_Functions::COMPATIBILITY_GNUMERIC) {
+ $testVal = strtok($timeValue,'/-: ');
+ if (strlen($testVal) < strlen($timeValue)) {
+ return Calculation_Functions::VALUE();
+ }
+ }
+ $timeValue = self::_getTimeValue($timeValue);
+ if (is_string($timeValue)) {
+ return Calculation_Functions::VALUE();
+ }
+ }
+ // Execute function
+ if ($timeValue >= 1) {
+ $timeValue = fmod($timeValue,1);
+ } elseif ($timeValue < 0.0) {
+ return Calculation_Functions::NaN();
+ }
+ $timeValue = Shared_Date::ExcelToPHP($timeValue);
+
+ return (int) gmdate('i',$timeValue);
+ } // function MINUTEOFHOUR()
+
+
+ /**
+ * SECONDOFMINUTE
+ *
+ * Returns the seconds of a time value.
+ * The second is given as an integer in the range 0 (zero) to 59.
+ *
+ * Excel Function:
+ * SECOND(timeValue)
+ *
+ * @param mixed $timeValue Excel date serial value (float), PHP date timestamp (integer),
+ * PHP DateTime object, or a standard time string
+ * @return int Second
+ */
+ public static function SECONDOFMINUTE($timeValue = 0) {
+ $timeValue = Calculation_Functions::flattenSingleValue($timeValue);
+
+ if (!is_numeric($timeValue)) {
+ if (Calculation_Functions::getCompatibilityMode() == Calculation_Functions::COMPATIBILITY_GNUMERIC) {
+ $testVal = strtok($timeValue,'/-: ');
+ if (strlen($testVal) < strlen($timeValue)) {
+ return Calculation_Functions::VALUE();
+ }
+ }
+ $timeValue = self::_getTimeValue($timeValue);
+ if (is_string($timeValue)) {
+ return Calculation_Functions::VALUE();
+ }
+ }
+ // Execute function
+ if ($timeValue >= 1) {
+ $timeValue = fmod($timeValue,1);
+ } elseif ($timeValue < 0.0) {
+ return Calculation_Functions::NaN();
+ }
+ $timeValue = Shared_Date::ExcelToPHP($timeValue);
+
+ return (int) gmdate('s',$timeValue);
+ } // function SECONDOFMINUTE()
+
+
+ /**
+ * EDATE
+ *
+ * Returns the serial number that represents the date that is the indicated number of months
+ * before or after a specified date (the start_date).
+ * Use EDATE to calculate maturity dates or due dates that fall on the same day of the month
+ * as the date of issue.
+ *
+ * Excel Function:
+ * EDATE(dateValue,adjustmentMonths)
+ *
+ * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer),
+ * PHP DateTime object, or a standard date string
+ * @param int $adjustmentMonths The number of months before or after start_date.
+ * A positive value for months yields a future date;
+ * a negative value yields a past date.
+ * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
+ * depending on the value of the ReturnDateType flag
+ */
+ public static function EDATE($dateValue = 1, $adjustmentMonths = 0) {
+ $dateValue = Calculation_Functions::flattenSingleValue($dateValue);
+ $adjustmentMonths = Calculation_Functions::flattenSingleValue($adjustmentMonths);
+
+ if (!is_numeric($adjustmentMonths)) {
+ return Calculation_Functions::VALUE();
+ }
+ $adjustmentMonths = floor($adjustmentMonths);
+
+ if (is_string($dateValue = self::_getDateValue($dateValue))) {
+ return Calculation_Functions::VALUE();
+ }
+
+ // Execute function
+ $PHPDateObject = self::_adjustDateByMonths($dateValue,$adjustmentMonths);
+
+ switch (Calculation_Functions::getReturnDateType()) {
+ case Calculation_Functions::RETURNDATE_EXCEL :
+ return (float) Shared_Date::PHPToExcel($PHPDateObject);
+ case Calculation_Functions::RETURNDATE_PHP_NUMERIC :
+ return (integer) Shared_Date::ExcelToPHP(Shared_Date::PHPToExcel($PHPDateObject));
+ case Calculation_Functions::RETURNDATE_PHP_OBJECT :
+ return $PHPDateObject;
+ }
+ } // function EDATE()
+
+
+ /**
+ * EOMONTH
+ *
+ * Returns the date value for the last day of the month that is the indicated number of months
+ * before or after start_date.
+ * Use EOMONTH to calculate maturity dates or due dates that fall on the last day of the month.
+ *
+ * Excel Function:
+ * EOMONTH(dateValue,adjustmentMonths)
+ *
+ * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer),
+ * PHP DateTime object, or a standard date string
+ * @param int $adjustmentMonths The number of months before or after start_date.
+ * A positive value for months yields a future date;
+ * a negative value yields a past date.
+ * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
+ * depending on the value of the ReturnDateType flag
+ */
+ public static function EOMONTH($dateValue = 1, $adjustmentMonths = 0) {
+ $dateValue = Calculation_Functions::flattenSingleValue($dateValue);
+ $adjustmentMonths = Calculation_Functions::flattenSingleValue($adjustmentMonths);
+
+ if (!is_numeric($adjustmentMonths)) {
+ return Calculation_Functions::VALUE();
+ }
+ $adjustmentMonths = floor($adjustmentMonths);
+
+ if (is_string($dateValue = self::_getDateValue($dateValue))) {
+ return Calculation_Functions::VALUE();
+ }
+
+ // Execute function
+ $PHPDateObject = self::_adjustDateByMonths($dateValue,$adjustmentMonths+1);
+ $adjustDays = (int) $PHPDateObject->format('d');
+ $adjustDaysString = '-'.$adjustDays.' days';
+ $PHPDateObject->modify($adjustDaysString);
+
+ switch (Calculation_Functions::getReturnDateType()) {
+ case Calculation_Functions::RETURNDATE_EXCEL :
+ return (float) Shared_Date::PHPToExcel($PHPDateObject);
+ case Calculation_Functions::RETURNDATE_PHP_NUMERIC :
+ return (integer) Shared_Date::ExcelToPHP(Shared_Date::PHPToExcel($PHPDateObject));
+ case Calculation_Functions::RETURNDATE_PHP_OBJECT :
+ return $PHPDateObject;
+ }
+ } // function EOMONTH()
}
-
diff --git a/Classes/PHPExcel/Calculation/Engineering.php b/Classes/PHPExcel/Calculation/Engineering.php
index 4d7bc77..3efc77c 100644
--- a/Classes/PHPExcel/Calculation/Engineering.php
+++ b/Classes/PHPExcel/Calculation/Engineering.php
@@ -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##
*/
@@ -35,2463 +35,2462 @@ define('EULER', 2.71828182845904523536);
/**
* PHPExcel\Calculation_Engineering
*
- * @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_Engineering {
- /**
- * Details of the Units of measure that can be used in CONVERTUOM()
- *
- * @var mixed[]
- */
- private static $_conversionUnits = array( 'g' => array( 'Group' => 'Mass', 'Unit Name' => 'Gram', 'AllowPrefix' => True ),
- 'sg' => array( 'Group' => 'Mass', 'Unit Name' => 'Slug', 'AllowPrefix' => False ),
- 'lbm' => array( 'Group' => 'Mass', 'Unit Name' => 'Pound mass (avoirdupois)', 'AllowPrefix' => False ),
- 'u' => array( 'Group' => 'Mass', 'Unit Name' => 'U (atomic mass unit)', 'AllowPrefix' => True ),
- 'ozm' => array( 'Group' => 'Mass', 'Unit Name' => 'Ounce mass (avoirdupois)', 'AllowPrefix' => False ),
- 'm' => array( 'Group' => 'Distance', 'Unit Name' => 'Meter', 'AllowPrefix' => True ),
- 'mi' => array( 'Group' => 'Distance', 'Unit Name' => 'Statute mile', 'AllowPrefix' => False ),
- 'Nmi' => array( 'Group' => 'Distance', 'Unit Name' => 'Nautical mile', 'AllowPrefix' => False ),
- 'in' => array( 'Group' => 'Distance', 'Unit Name' => 'Inch', 'AllowPrefix' => False ),
- 'ft' => array( 'Group' => 'Distance', 'Unit Name' => 'Foot', 'AllowPrefix' => False ),
- 'yd' => array( 'Group' => 'Distance', 'Unit Name' => 'Yard', 'AllowPrefix' => False ),
- 'ang' => array( 'Group' => 'Distance', 'Unit Name' => 'Angstrom', 'AllowPrefix' => True ),
- 'Pica' => array( 'Group' => 'Distance', 'Unit Name' => 'Pica (1/72 in)', 'AllowPrefix' => False ),
- 'yr' => array( 'Group' => 'Time', 'Unit Name' => 'Year', 'AllowPrefix' => False ),
- 'day' => array( 'Group' => 'Time', 'Unit Name' => 'Day', 'AllowPrefix' => False ),
- 'hr' => array( 'Group' => 'Time', 'Unit Name' => 'Hour', 'AllowPrefix' => False ),
- 'mn' => array( 'Group' => 'Time', 'Unit Name' => 'Minute', 'AllowPrefix' => False ),
- 'sec' => array( 'Group' => 'Time', 'Unit Name' => 'Second', 'AllowPrefix' => True ),
- 'Pa' => array( 'Group' => 'Pressure', 'Unit Name' => 'Pascal', 'AllowPrefix' => True ),
- 'p' => array( 'Group' => 'Pressure', 'Unit Name' => 'Pascal', 'AllowPrefix' => True ),
- 'atm' => array( 'Group' => 'Pressure', 'Unit Name' => 'Atmosphere', 'AllowPrefix' => True ),
- 'at' => array( 'Group' => 'Pressure', 'Unit Name' => 'Atmosphere', 'AllowPrefix' => True ),
- 'mmHg' => array( 'Group' => 'Pressure', 'Unit Name' => 'mm of Mercury', 'AllowPrefix' => True ),
- 'N' => array( 'Group' => 'Force', 'Unit Name' => 'Newton', 'AllowPrefix' => True ),
- 'dyn' => array( 'Group' => 'Force', 'Unit Name' => 'Dyne', 'AllowPrefix' => True ),
- 'dy' => array( 'Group' => 'Force', 'Unit Name' => 'Dyne', 'AllowPrefix' => True ),
- 'lbf' => array( 'Group' => 'Force', 'Unit Name' => 'Pound force', 'AllowPrefix' => False ),
- 'J' => array( 'Group' => 'Energy', 'Unit Name' => 'Joule', 'AllowPrefix' => True ),
- 'e' => array( 'Group' => 'Energy', 'Unit Name' => 'Erg', 'AllowPrefix' => True ),
- 'c' => array( 'Group' => 'Energy', 'Unit Name' => 'Thermodynamic calorie', 'AllowPrefix' => True ),
- 'cal' => array( 'Group' => 'Energy', 'Unit Name' => 'IT calorie', 'AllowPrefix' => True ),
- 'eV' => array( 'Group' => 'Energy', 'Unit Name' => 'Electron volt', 'AllowPrefix' => True ),
- 'ev' => array( 'Group' => 'Energy', 'Unit Name' => 'Electron volt', 'AllowPrefix' => True ),
- 'HPh' => array( 'Group' => 'Energy', 'Unit Name' => 'Horsepower-hour', 'AllowPrefix' => False ),
- 'hh' => array( 'Group' => 'Energy', 'Unit Name' => 'Horsepower-hour', 'AllowPrefix' => False ),
- 'Wh' => array( 'Group' => 'Energy', 'Unit Name' => 'Watt-hour', 'AllowPrefix' => True ),
- 'wh' => array( 'Group' => 'Energy', 'Unit Name' => 'Watt-hour', 'AllowPrefix' => True ),
- 'flb' => array( 'Group' => 'Energy', 'Unit Name' => 'Foot-pound', 'AllowPrefix' => False ),
- 'BTU' => array( 'Group' => 'Energy', 'Unit Name' => 'BTU', 'AllowPrefix' => False ),
- 'btu' => array( 'Group' => 'Energy', 'Unit Name' => 'BTU', 'AllowPrefix' => False ),
- 'HP' => array( 'Group' => 'Power', 'Unit Name' => 'Horsepower', 'AllowPrefix' => False ),
- 'h' => array( 'Group' => 'Power', 'Unit Name' => 'Horsepower', 'AllowPrefix' => False ),
- 'W' => array( 'Group' => 'Power', 'Unit Name' => 'Watt', 'AllowPrefix' => True ),
- 'w' => array( 'Group' => 'Power', 'Unit Name' => 'Watt', 'AllowPrefix' => True ),
- 'T' => array( 'Group' => 'Magnetism', 'Unit Name' => 'Tesla', 'AllowPrefix' => True ),
- 'ga' => array( 'Group' => 'Magnetism', 'Unit Name' => 'Gauss', 'AllowPrefix' => True ),
- 'C' => array( 'Group' => 'Temperature', 'Unit Name' => 'Celsius', 'AllowPrefix' => False ),
- 'cel' => array( 'Group' => 'Temperature', 'Unit Name' => 'Celsius', 'AllowPrefix' => False ),
- 'F' => array( 'Group' => 'Temperature', 'Unit Name' => 'Fahrenheit', 'AllowPrefix' => False ),
- 'fah' => array( 'Group' => 'Temperature', 'Unit Name' => 'Fahrenheit', 'AllowPrefix' => False ),
- 'K' => array( 'Group' => 'Temperature', 'Unit Name' => 'Kelvin', 'AllowPrefix' => False ),
- 'kel' => array( 'Group' => 'Temperature', 'Unit Name' => 'Kelvin', 'AllowPrefix' => False ),
- 'tsp' => array( 'Group' => 'Liquid', 'Unit Name' => 'Teaspoon', 'AllowPrefix' => False ),
- 'tbs' => array( 'Group' => 'Liquid', 'Unit Name' => 'Tablespoon', 'AllowPrefix' => False ),
- 'oz' => array( 'Group' => 'Liquid', 'Unit Name' => 'Fluid Ounce', 'AllowPrefix' => False ),
- 'cup' => array( 'Group' => 'Liquid', 'Unit Name' => 'Cup', 'AllowPrefix' => False ),
- 'pt' => array( 'Group' => 'Liquid', 'Unit Name' => 'U.S. Pint', 'AllowPrefix' => False ),
- 'us_pt' => array( 'Group' => 'Liquid', 'Unit Name' => 'U.S. Pint', 'AllowPrefix' => False ),
- 'uk_pt' => array( 'Group' => 'Liquid', 'Unit Name' => 'U.K. Pint', 'AllowPrefix' => False ),
- 'qt' => array( 'Group' => 'Liquid', 'Unit Name' => 'Quart', 'AllowPrefix' => False ),
- 'gal' => array( 'Group' => 'Liquid', 'Unit Name' => 'Gallon', 'AllowPrefix' => False ),
- 'l' => array( 'Group' => 'Liquid', 'Unit Name' => 'Litre', 'AllowPrefix' => True ),
- 'lt' => array( 'Group' => 'Liquid', 'Unit Name' => 'Litre', 'AllowPrefix' => True )
- );
-
- /**
- * Details of the Multiplier prefixes that can be used with Units of Measure in CONVERTUOM()
- *
- * @var mixed[]
- */
- private static $_conversionMultipliers = array( 'Y' => array( 'multiplier' => 1E24, 'name' => 'yotta' ),
- 'Z' => array( 'multiplier' => 1E21, 'name' => 'zetta' ),
- 'E' => array( 'multiplier' => 1E18, 'name' => 'exa' ),
- 'P' => array( 'multiplier' => 1E15, 'name' => 'peta' ),
- 'T' => array( 'multiplier' => 1E12, 'name' => 'tera' ),
- 'G' => array( 'multiplier' => 1E9, 'name' => 'giga' ),
- 'M' => array( 'multiplier' => 1E6, 'name' => 'mega' ),
- 'k' => array( 'multiplier' => 1E3, 'name' => 'kilo' ),
- 'h' => array( 'multiplier' => 1E2, 'name' => 'hecto' ),
- 'e' => array( 'multiplier' => 1E1, 'name' => 'deka' ),
- 'd' => array( 'multiplier' => 1E-1, 'name' => 'deci' ),
- 'c' => array( 'multiplier' => 1E-2, 'name' => 'centi' ),
- 'm' => array( 'multiplier' => 1E-3, 'name' => 'milli' ),
- 'u' => array( 'multiplier' => 1E-6, 'name' => 'micro' ),
- 'n' => array( 'multiplier' => 1E-9, 'name' => 'nano' ),
- 'p' => array( 'multiplier' => 1E-12, 'name' => 'pico' ),
- 'f' => array( 'multiplier' => 1E-15, 'name' => 'femto' ),
- 'a' => array( 'multiplier' => 1E-18, 'name' => 'atto' ),
- 'z' => array( 'multiplier' => 1E-21, 'name' => 'zepto' ),
- 'y' => array( 'multiplier' => 1E-24, 'name' => 'yocto' )
- );
-
- /**
- * Details of the Units of measure conversion factors, organised by group
- *
- * @var mixed[]
- */
- private static $_unitConversions = array( 'Mass' => array( 'g' => array( 'g' => 1.0,
- 'sg' => 6.85220500053478E-05,
- 'lbm' => 2.20462291469134E-03,
- 'u' => 6.02217000000000E+23,
- 'ozm' => 3.52739718003627E-02
- ),
- 'sg' => array( 'g' => 1.45938424189287E+04,
- 'sg' => 1.0,
- 'lbm' => 3.21739194101647E+01,
- 'u' => 8.78866000000000E+27,
- 'ozm' => 5.14782785944229E+02
- ),
- 'lbm' => array( 'g' => 4.5359230974881148E+02,
- 'sg' => 3.10810749306493E-02,
- 'lbm' => 1.0,
- 'u' => 2.73161000000000E+26,
- 'ozm' => 1.60000023429410E+01
- ),
- 'u' => array( 'g' => 1.66053100460465E-24,
- 'sg' => 1.13782988532950E-28,
- 'lbm' => 3.66084470330684E-27,
- 'u' => 1.0,
- 'ozm' => 5.85735238300524E-26
- ),
- 'ozm' => array( 'g' => 2.83495152079732E+01,
- 'sg' => 1.94256689870811E-03,
- 'lbm' => 6.24999908478882E-02,
- 'u' => 1.70725600000000E+25,
- 'ozm' => 1.0
- )
- ),
- 'Distance' => array( 'm' => array( 'm' => 1.0,
- 'mi' => 6.21371192237334E-04,
- 'Nmi' => 5.39956803455724E-04,
- 'in' => 3.93700787401575E+01,
- 'ft' => 3.28083989501312E+00,
- 'yd' => 1.09361329797891E+00,
- 'ang' => 1.00000000000000E+10,
- 'Pica' => 2.83464566929116E+03
- ),
- 'mi' => array( 'm' => 1.60934400000000E+03,
- 'mi' => 1.0,
- 'Nmi' => 8.68976241900648E-01,
- 'in' => 6.33600000000000E+04,
- 'ft' => 5.28000000000000E+03,
- 'yd' => 1.76000000000000E+03,
- 'ang' => 1.60934400000000E+13,
- 'Pica' => 4.56191999999971E+06
- ),
- 'Nmi' => array( 'm' => 1.85200000000000E+03,
- 'mi' => 1.15077944802354E+00,
- 'Nmi' => 1.0,
- 'in' => 7.29133858267717E+04,
- 'ft' => 6.07611548556430E+03,
- 'yd' => 2.02537182785694E+03,
- 'ang' => 1.85200000000000E+13,
- 'Pica' => 5.24976377952723E+06
- ),
- 'in' => array( 'm' => 2.54000000000000E-02,
- 'mi' => 1.57828282828283E-05,
- 'Nmi' => 1.37149028077754E-05,
- 'in' => 1.0,
- 'ft' => 8.33333333333333E-02,
- 'yd' => 2.77777777686643E-02,
- 'ang' => 2.54000000000000E+08,
- 'Pica' => 7.19999999999955E+01
- ),
- 'ft' => array( 'm' => 3.04800000000000E-01,
- 'mi' => 1.89393939393939E-04,
- 'Nmi' => 1.64578833693305E-04,
- 'in' => 1.20000000000000E+01,
- 'ft' => 1.0,
- 'yd' => 3.33333333223972E-01,
- 'ang' => 3.04800000000000E+09,
- 'Pica' => 8.63999999999946E+02
- ),
- 'yd' => array( 'm' => 9.14400000300000E-01,
- 'mi' => 5.68181818368230E-04,
- 'Nmi' => 4.93736501241901E-04,
- 'in' => 3.60000000118110E+01,
- 'ft' => 3.00000000000000E+00,
- 'yd' => 1.0,
- 'ang' => 9.14400000300000E+09,
- 'Pica' => 2.59200000085023E+03
- ),
- 'ang' => array( 'm' => 1.00000000000000E-10,
- 'mi' => 6.21371192237334E-14,
- 'Nmi' => 5.39956803455724E-14,
- 'in' => 3.93700787401575E-09,
- 'ft' => 3.28083989501312E-10,
- 'yd' => 1.09361329797891E-10,
- 'ang' => 1.0,
- 'Pica' => 2.83464566929116E-07
- ),
- 'Pica' => array( 'm' => 3.52777777777800E-04,
- 'mi' => 2.19205948372629E-07,
- 'Nmi' => 1.90484761219114E-07,
- 'in' => 1.38888888888898E-02,
- 'ft' => 1.15740740740748E-03,
- 'yd' => 3.85802469009251E-04,
- 'ang' => 3.52777777777800E+06,
- 'Pica' => 1.0
- )
- ),
- 'Time' => array( 'yr' => array( 'yr' => 1.0,
- 'day' => 365.25,
- 'hr' => 8766.0,
- 'mn' => 525960.0,
- 'sec' => 31557600.0
- ),
- 'day' => array( 'yr' => 2.73785078713210E-03,
- 'day' => 1.0,
- 'hr' => 24.0,
- 'mn' => 1440.0,
- 'sec' => 86400.0
- ),
- 'hr' => array( 'yr' => 1.14077116130504E-04,
- 'day' => 4.16666666666667E-02,
- 'hr' => 1.0,
- 'mn' => 60.0,
- 'sec' => 3600.0
- ),
- 'mn' => array( 'yr' => 1.90128526884174E-06,
- 'day' => 6.94444444444444E-04,
- 'hr' => 1.66666666666667E-02,
- 'mn' => 1.0,
- 'sec' => 60.0
- ),
- 'sec' => array( 'yr' => 3.16880878140289E-08,
- 'day' => 1.15740740740741E-05,
- 'hr' => 2.77777777777778E-04,
- 'mn' => 1.66666666666667E-02,
- 'sec' => 1.0
- )
- ),
- 'Pressure' => array( 'Pa' => array( 'Pa' => 1.0,
- 'p' => 1.0,
- 'atm' => 9.86923299998193E-06,
- 'at' => 9.86923299998193E-06,
- 'mmHg' => 7.50061707998627E-03
- ),
- 'p' => array( 'Pa' => 1.0,
- 'p' => 1.0,
- 'atm' => 9.86923299998193E-06,
- 'at' => 9.86923299998193E-06,
- 'mmHg' => 7.50061707998627E-03
- ),
- 'atm' => array( 'Pa' => 1.01324996583000E+05,
- 'p' => 1.01324996583000E+05,
- 'atm' => 1.0,
- 'at' => 1.0,
- 'mmHg' => 760.0
- ),
- 'at' => array( 'Pa' => 1.01324996583000E+05,
- 'p' => 1.01324996583000E+05,
- 'atm' => 1.0,
- 'at' => 1.0,
- 'mmHg' => 760.0
- ),
- 'mmHg' => array( 'Pa' => 1.33322363925000E+02,
- 'p' => 1.33322363925000E+02,
- 'atm' => 1.31578947368421E-03,
- 'at' => 1.31578947368421E-03,
- 'mmHg' => 1.0
- )
- ),
- 'Force' => array( 'N' => array( 'N' => 1.0,
- 'dyn' => 1.0E+5,
- 'dy' => 1.0E+5,
- 'lbf' => 2.24808923655339E-01
- ),
- 'dyn' => array( 'N' => 1.0E-5,
- 'dyn' => 1.0,
- 'dy' => 1.0,
- 'lbf' => 2.24808923655339E-06
- ),
- 'dy' => array( 'N' => 1.0E-5,
- 'dyn' => 1.0,
- 'dy' => 1.0,
- 'lbf' => 2.24808923655339E-06
- ),
- 'lbf' => array( 'N' => 4.448222,
- 'dyn' => 4.448222E+5,
- 'dy' => 4.448222E+5,
- 'lbf' => 1.0
- )
- ),
- 'Energy' => array( 'J' => array( 'J' => 1.0,
- 'e' => 9.99999519343231E+06,
- 'c' => 2.39006249473467E-01,
- 'cal' => 2.38846190642017E-01,
- 'eV' => 6.24145700000000E+18,
- 'ev' => 6.24145700000000E+18,
- 'HPh' => 3.72506430801000E-07,
- 'hh' => 3.72506430801000E-07,
- 'Wh' => 2.77777916238711E-04,
- 'wh' => 2.77777916238711E-04,
- 'flb' => 2.37304222192651E+01,
- 'BTU' => 9.47815067349015E-04,
- 'btu' => 9.47815067349015E-04
- ),
- 'e' => array( 'J' => 1.00000048065700E-07,
- 'e' => 1.0,
- 'c' => 2.39006364353494E-08,
- 'cal' => 2.38846305445111E-08,
- 'eV' => 6.24146000000000E+11,
- 'ev' => 6.24146000000000E+11,
- 'HPh' => 3.72506609848824E-14,
- 'hh' => 3.72506609848824E-14,
- 'Wh' => 2.77778049754611E-11,
- 'wh' => 2.77778049754611E-11,
- 'flb' => 2.37304336254586E-06,
- 'BTU' => 9.47815522922962E-11,
- 'btu' => 9.47815522922962E-11
- ),
- 'c' => array( 'J' => 4.18399101363672E+00,
- 'e' => 4.18398900257312E+07,
- 'c' => 1.0,
- 'cal' => 9.99330315287563E-01,
- 'eV' => 2.61142000000000E+19,
- 'ev' => 2.61142000000000E+19,
- 'HPh' => 1.55856355899327E-06,
- 'hh' => 1.55856355899327E-06,
- 'Wh' => 1.16222030532950E-03,
- 'wh' => 1.16222030532950E-03,
- 'flb' => 9.92878733152102E+01,
- 'BTU' => 3.96564972437776E-03,
- 'btu' => 3.96564972437776E-03
- ),
- 'cal' => array( 'J' => 4.18679484613929E+00,
- 'e' => 4.18679283372801E+07,
- 'c' => 1.00067013349059E+00,
- 'cal' => 1.0,
- 'eV' => 2.61317000000000E+19,
- 'ev' => 2.61317000000000E+19,
- 'HPh' => 1.55960800463137E-06,
- 'hh' => 1.55960800463137E-06,
- 'Wh' => 1.16299914807955E-03,
- 'wh' => 1.16299914807955E-03,
- 'flb' => 9.93544094443283E+01,
- 'BTU' => 3.96830723907002E-03,
- 'btu' => 3.96830723907002E-03
- ),
- 'eV' => array( 'J' => 1.60219000146921E-19,
- 'e' => 1.60218923136574E-12,
- 'c' => 3.82933423195043E-20,
- 'cal' => 3.82676978535648E-20,
- 'eV' => 1.0,
- 'ev' => 1.0,
- 'HPh' => 5.96826078912344E-26,
- 'hh' => 5.96826078912344E-26,
- 'Wh' => 4.45053000026614E-23,
- 'wh' => 4.45053000026614E-23,
- 'flb' => 3.80206452103492E-18,
- 'BTU' => 1.51857982414846E-22,
- 'btu' => 1.51857982414846E-22
- ),
- 'ev' => array( 'J' => 1.60219000146921E-19,
- 'e' => 1.60218923136574E-12,
- 'c' => 3.82933423195043E-20,
- 'cal' => 3.82676978535648E-20,
- 'eV' => 1.0,
- 'ev' => 1.0,
- 'HPh' => 5.96826078912344E-26,
- 'hh' => 5.96826078912344E-26,
- 'Wh' => 4.45053000026614E-23,
- 'wh' => 4.45053000026614E-23,
- 'flb' => 3.80206452103492E-18,
- 'BTU' => 1.51857982414846E-22,
- 'btu' => 1.51857982414846E-22
- ),
- 'HPh' => array( 'J' => 2.68451741316170E+06,
- 'e' => 2.68451612283024E+13,
- 'c' => 6.41616438565991E+05,
- 'cal' => 6.41186757845835E+05,
- 'eV' => 1.67553000000000E+25,
- 'ev' => 1.67553000000000E+25,
- 'HPh' => 1.0,
- 'hh' => 1.0,
- 'Wh' => 7.45699653134593E+02,
- 'wh' => 7.45699653134593E+02,
- 'flb' => 6.37047316692964E+07,
- 'BTU' => 2.54442605275546E+03,
- 'btu' => 2.54442605275546E+03
- ),
- 'hh' => array( 'J' => 2.68451741316170E+06,
- 'e' => 2.68451612283024E+13,
- 'c' => 6.41616438565991E+05,
- 'cal' => 6.41186757845835E+05,
- 'eV' => 1.67553000000000E+25,
- 'ev' => 1.67553000000000E+25,
- 'HPh' => 1.0,
- 'hh' => 1.0,
- 'Wh' => 7.45699653134593E+02,
- 'wh' => 7.45699653134593E+02,
- 'flb' => 6.37047316692964E+07,
- 'BTU' => 2.54442605275546E+03,
- 'btu' => 2.54442605275546E+03
- ),
- 'Wh' => array( 'J' => 3.59999820554720E+03,
- 'e' => 3.59999647518369E+10,
- 'c' => 8.60422069219046E+02,
- 'cal' => 8.59845857713046E+02,
- 'eV' => 2.24692340000000E+22,
- 'ev' => 2.24692340000000E+22,
- 'HPh' => 1.34102248243839E-03,
- 'hh' => 1.34102248243839E-03,
- 'Wh' => 1.0,
- 'wh' => 1.0,
- 'flb' => 8.54294774062316E+04,
- 'BTU' => 3.41213254164705E+00,
- 'btu' => 3.41213254164705E+00
- ),
- 'wh' => array( 'J' => 3.59999820554720E+03,
- 'e' => 3.59999647518369E+10,
- 'c' => 8.60422069219046E+02,
- 'cal' => 8.59845857713046E+02,
- 'eV' => 2.24692340000000E+22,
- 'ev' => 2.24692340000000E+22,
- 'HPh' => 1.34102248243839E-03,
- 'hh' => 1.34102248243839E-03,
- 'Wh' => 1.0,
- 'wh' => 1.0,
- 'flb' => 8.54294774062316E+04,
- 'BTU' => 3.41213254164705E+00,
- 'btu' => 3.41213254164705E+00
- ),
- 'flb' => array( 'J' => 4.21400003236424E-02,
- 'e' => 4.21399800687660E+05,
- 'c' => 1.00717234301644E-02,
- 'cal' => 1.00649785509554E-02,
- 'eV' => 2.63015000000000E+17,
- 'ev' => 2.63015000000000E+17,
- 'HPh' => 1.56974211145130E-08,
- 'hh' => 1.56974211145130E-08,
- 'Wh' => 1.17055614802000E-05,
- 'wh' => 1.17055614802000E-05,
- 'flb' => 1.0,
- 'BTU' => 3.99409272448406E-05,
- 'btu' => 3.99409272448406E-05
- ),
- 'BTU' => array( 'J' => 1.05505813786749E+03,
- 'e' => 1.05505763074665E+10,
- 'c' => 2.52165488508168E+02,
- 'cal' => 2.51996617135510E+02,
- 'eV' => 6.58510000000000E+21,
- 'ev' => 6.58510000000000E+21,
- 'HPh' => 3.93015941224568E-04,
- 'hh' => 3.93015941224568E-04,
- 'Wh' => 2.93071851047526E-01,
- 'wh' => 2.93071851047526E-01,
- 'flb' => 2.50369750774671E+04,
- 'BTU' => 1.0,
- 'btu' => 1.0,
- ),
- 'btu' => array( 'J' => 1.05505813786749E+03,
- 'e' => 1.05505763074665E+10,
- 'c' => 2.52165488508168E+02,
- 'cal' => 2.51996617135510E+02,
- 'eV' => 6.58510000000000E+21,
- 'ev' => 6.58510000000000E+21,
- 'HPh' => 3.93015941224568E-04,
- 'hh' => 3.93015941224568E-04,
- 'Wh' => 2.93071851047526E-01,
- 'wh' => 2.93071851047526E-01,
- 'flb' => 2.50369750774671E+04,
- 'BTU' => 1.0,
- 'btu' => 1.0,
- )
- ),
- 'Power' => array( 'HP' => array( 'HP' => 1.0,
- 'h' => 1.0,
- 'W' => 7.45701000000000E+02,
- 'w' => 7.45701000000000E+02
- ),
- 'h' => array( 'HP' => 1.0,
- 'h' => 1.0,
- 'W' => 7.45701000000000E+02,
- 'w' => 7.45701000000000E+02
- ),
- 'W' => array( 'HP' => 1.34102006031908E-03,
- 'h' => 1.34102006031908E-03,
- 'W' => 1.0,
- 'w' => 1.0
- ),
- 'w' => array( 'HP' => 1.34102006031908E-03,
- 'h' => 1.34102006031908E-03,
- 'W' => 1.0,
- 'w' => 1.0
- )
- ),
- 'Magnetism' => array( 'T' => array( 'T' => 1.0,
- 'ga' => 10000.0
- ),
- 'ga' => array( 'T' => 0.0001,
- 'ga' => 1.0
- )
- ),
- 'Liquid' => array( 'tsp' => array( 'tsp' => 1.0,
- 'tbs' => 3.33333333333333E-01,
- 'oz' => 1.66666666666667E-01,
- 'cup' => 2.08333333333333E-02,
- 'pt' => 1.04166666666667E-02,
- 'us_pt' => 1.04166666666667E-02,
- 'uk_pt' => 8.67558516821960E-03,
- 'qt' => 5.20833333333333E-03,
- 'gal' => 1.30208333333333E-03,
- 'l' => 4.92999408400710E-03,
- 'lt' => 4.92999408400710E-03
- ),
- 'tbs' => array( 'tsp' => 3.00000000000000E+00,
- 'tbs' => 1.0,
- 'oz' => 5.00000000000000E-01,
- 'cup' => 6.25000000000000E-02,
- 'pt' => 3.12500000000000E-02,
- 'us_pt' => 3.12500000000000E-02,
- 'uk_pt' => 2.60267555046588E-02,
- 'qt' => 1.56250000000000E-02,
- 'gal' => 3.90625000000000E-03,
- 'l' => 1.47899822520213E-02,
- 'lt' => 1.47899822520213E-02
- ),
- 'oz' => array( 'tsp' => 6.00000000000000E+00,
- 'tbs' => 2.00000000000000E+00,
- 'oz' => 1.0,
- 'cup' => 1.25000000000000E-01,
- 'pt' => 6.25000000000000E-02,
- 'us_pt' => 6.25000000000000E-02,
- 'uk_pt' => 5.20535110093176E-02,
- 'qt' => 3.12500000000000E-02,
- 'gal' => 7.81250000000000E-03,
- 'l' => 2.95799645040426E-02,
- 'lt' => 2.95799645040426E-02
- ),
- 'cup' => array( 'tsp' => 4.80000000000000E+01,
- 'tbs' => 1.60000000000000E+01,
- 'oz' => 8.00000000000000E+00,
- 'cup' => 1.0,
- 'pt' => 5.00000000000000E-01,
- 'us_pt' => 5.00000000000000E-01,
- 'uk_pt' => 4.16428088074541E-01,
- 'qt' => 2.50000000000000E-01,
- 'gal' => 6.25000000000000E-02,
- 'l' => 2.36639716032341E-01,
- 'lt' => 2.36639716032341E-01
- ),
- 'pt' => array( 'tsp' => 9.60000000000000E+01,
- 'tbs' => 3.20000000000000E+01,
- 'oz' => 1.60000000000000E+01,
- 'cup' => 2.00000000000000E+00,
- 'pt' => 1.0,
- 'us_pt' => 1.0,
- 'uk_pt' => 8.32856176149081E-01,
- 'qt' => 5.00000000000000E-01,
- 'gal' => 1.25000000000000E-01,
- 'l' => 4.73279432064682E-01,
- 'lt' => 4.73279432064682E-01
- ),
- 'us_pt' => array( 'tsp' => 9.60000000000000E+01,
- 'tbs' => 3.20000000000000E+01,
- 'oz' => 1.60000000000000E+01,
- 'cup' => 2.00000000000000E+00,
- 'pt' => 1.0,
- 'us_pt' => 1.0,
- 'uk_pt' => 8.32856176149081E-01,
- 'qt' => 5.00000000000000E-01,
- 'gal' => 1.25000000000000E-01,
- 'l' => 4.73279432064682E-01,
- 'lt' => 4.73279432064682E-01
- ),
- 'uk_pt' => array( 'tsp' => 1.15266000000000E+02,
- 'tbs' => 3.84220000000000E+01,
- 'oz' => 1.92110000000000E+01,
- 'cup' => 2.40137500000000E+00,
- 'pt' => 1.20068750000000E+00,
- 'us_pt' => 1.20068750000000E+00,
- 'uk_pt' => 1.0,
- 'qt' => 6.00343750000000E-01,
- 'gal' => 1.50085937500000E-01,
- 'l' => 5.68260698087162E-01,
- 'lt' => 5.68260698087162E-01
- ),
- 'qt' => array( 'tsp' => 1.92000000000000E+02,
- 'tbs' => 6.40000000000000E+01,
- 'oz' => 3.20000000000000E+01,
- 'cup' => 4.00000000000000E+00,
- 'pt' => 2.00000000000000E+00,
- 'us_pt' => 2.00000000000000E+00,
- 'uk_pt' => 1.66571235229816E+00,
- 'qt' => 1.0,
- 'gal' => 2.50000000000000E-01,
- 'l' => 9.46558864129363E-01,
- 'lt' => 9.46558864129363E-01
- ),
- 'gal' => array( 'tsp' => 7.68000000000000E+02,
- 'tbs' => 2.56000000000000E+02,
- 'oz' => 1.28000000000000E+02,
- 'cup' => 1.60000000000000E+01,
- 'pt' => 8.00000000000000E+00,
- 'us_pt' => 8.00000000000000E+00,
- 'uk_pt' => 6.66284940919265E+00,
- 'qt' => 4.00000000000000E+00,
- 'gal' => 1.0,
- 'l' => 3.78623545651745E+00,
- 'lt' => 3.78623545651745E+00
- ),
- 'l' => array( 'tsp' => 2.02840000000000E+02,
- 'tbs' => 6.76133333333333E+01,
- 'oz' => 3.38066666666667E+01,
- 'cup' => 4.22583333333333E+00,
- 'pt' => 2.11291666666667E+00,
- 'us_pt' => 2.11291666666667E+00,
- 'uk_pt' => 1.75975569552166E+00,
- 'qt' => 1.05645833333333E+00,
- 'gal' => 2.64114583333333E-01,
- 'l' => 1.0,
- 'lt' => 1.0
- ),
- 'lt' => array( 'tsp' => 2.02840000000000E+02,
- 'tbs' => 6.76133333333333E+01,
- 'oz' => 3.38066666666667E+01,
- 'cup' => 4.22583333333333E+00,
- 'pt' => 2.11291666666667E+00,
- 'us_pt' => 2.11291666666667E+00,
- 'uk_pt' => 1.75975569552166E+00,
- 'qt' => 1.05645833333333E+00,
- 'gal' => 2.64114583333333E-01,
- 'l' => 1.0,
- 'lt' => 1.0
- )
- )
- );
-
-
- /**
- * _parseComplex
- *
- * Parses a complex number into its real and imaginary parts, and an I or J suffix
- *
- * @param string $complexNumber The complex number
- * @return string[] Indexed on "real", "imaginary" and "suffix"
- */
- public static function _parseComplex($complexNumber) {
- $workString = (string) $complexNumber;
-
- $realNumber = $imaginary = 0;
- // Extract the suffix, if there is one
- $suffix = substr($workString,-1);
- if (!is_numeric($suffix)) {
- $workString = substr($workString,0,-1);
- } else {
- $suffix = '';
- }
-
- // Split the input into its Real and Imaginary components
- $leadingSign = 0;
- if (strlen($workString) > 0) {
- $leadingSign = (($workString{0} == '+') || ($workString{0} == '-')) ? 1 : 0;
- }
- $power = '';
- $realNumber = strtok($workString, '+-');
- if (strtoupper(substr($realNumber,-1)) == 'E') {
- $power = strtok('+-');
- ++$leadingSign;
- }
-
- $realNumber = substr($workString,0,strlen($realNumber)+strlen($power)+$leadingSign);
-
- if ($suffix != '') {
- $imaginary = substr($workString,strlen($realNumber));
-
- if (($imaginary == '') && (($realNumber == '') || ($realNumber == '+') || ($realNumber == '-'))) {
- $imaginary = $realNumber.'1';
- $realNumber = '0';
- } else if ($imaginary == '') {
- $imaginary = $realNumber;
- $realNumber = '0';
- } elseif (($imaginary == '+') || ($imaginary == '-')) {
- $imaginary .= '1';
- }
- }
-
- return array( 'real' => $realNumber,
- 'imaginary' => $imaginary,
- 'suffix' => $suffix
- );
- } // function _parseComplex()
-
-
- /**
- * Cleans the leading characters in a complex number string
- *
- * @param string $complexNumber The complex number to clean
- * @return string The "cleaned" complex number
- */
- private static function _cleanComplex($complexNumber) {
- if ($complexNumber{0} == '+') $complexNumber = substr($complexNumber,1);
- if ($complexNumber{0} == '0') $complexNumber = substr($complexNumber,1);
- if ($complexNumber{0} == '.') $complexNumber = '0'.$complexNumber;
- if ($complexNumber{0} == '+') $complexNumber = substr($complexNumber,1);
- return $complexNumber;
- }
-
- /**
- * Formats a number base string value with leading zeroes
- *
- * @param string $xVal The "number" to pad
- * @param integer $places The length that we want to pad this value
- * @return string The padded "number"
- */
- private static function _nbrConversionFormat($xVal, $places) {
- if (!is_null($places)) {
- if (strlen($xVal) <= $places) {
- return substr(str_pad($xVal, $places, '0', STR_PAD_LEFT), -10);
- } else {
- return Calculation_Functions::NaN();
- }
- }
-
- return substr($xVal, -10);
- } // function _nbrConversionFormat()
-
- /**
- * BESSELI
- *
- * Returns the modified Bessel function In(x), which is equivalent to the Bessel function evaluated
- * for purely imaginary arguments
- *
- * Excel Function:
- * BESSELI(x,ord)
- *
- * @access public
- * @category Engineering Functions
- * @param float $x The value at which to evaluate the function.
- * If x is nonnumeric, BESSELI returns the #VALUE! error value.
- * @param integer $ord The order of the Bessel function.
- * If ord is not an integer, it is truncated.
- * If $ord is nonnumeric, BESSELI returns the #VALUE! error value.
- * If $ord < 0, BESSELI returns the #NUM! error value.
- * @return float
- *
- */
- public static function BESSELI($x, $ord) {
- $x = (is_null($x)) ? 0.0 : Calculation_Functions::flattenSingleValue($x);
- $ord = (is_null($ord)) ? 0.0 : Calculation_Functions::flattenSingleValue($ord);
-
- if ((is_numeric($x)) && (is_numeric($ord))) {
- $ord = floor($ord);
- if ($ord < 0) {
- return Calculation_Functions::NaN();
- }
-
- if (abs($x) <= 30) {
- $fResult = $fTerm = pow($x / 2, $ord) / Calculation_MathTrig::FACT($ord);
- $ordK = 1;
- $fSqrX = ($x * $x) / 4;
- do {
- $fTerm *= $fSqrX;
- $fTerm /= ($ordK * ($ordK + $ord));
- $fResult += $fTerm;
- } while ((abs($fTerm) > 1e-12) && (++$ordK < 100));
- } else {
- $f_2_PI = 2 * M_PI;
-
- $fXAbs = abs($x);
- $fResult = exp($fXAbs) / sqrt($f_2_PI * $fXAbs);
- if (($ord & 1) && ($x < 0)) {
- $fResult = -$fResult;
- }
- }
- return (is_nan($fResult)) ? Calculation_Functions::NaN() : $fResult;
- }
- return Calculation_Functions::VALUE();
- } // function BESSELI()
-
-
- /**
- * BESSELJ
- *
- * Returns the Bessel function
- *
- * Excel Function:
- * BESSELJ(x,ord)
- *
- * @access public
- * @category Engineering Functions
- * @param float $x The value at which to evaluate the function.
- * If x is nonnumeric, BESSELJ returns the #VALUE! error value.
- * @param integer $ord The order of the Bessel function. If n is not an integer, it is truncated.
- * If $ord is nonnumeric, BESSELJ returns the #VALUE! error value.
- * If $ord < 0, BESSELJ returns the #NUM! error value.
- * @return float
- *
- */
- public static function BESSELJ($x, $ord) {
- $x = (is_null($x)) ? 0.0 : Calculation_Functions::flattenSingleValue($x);
- $ord = (is_null($ord)) ? 0.0 : Calculation_Functions::flattenSingleValue($ord);
-
- if ((is_numeric($x)) && (is_numeric($ord))) {
- $ord = floor($ord);
- if ($ord < 0) {
- return Calculation_Functions::NaN();
- }
-
- $fResult = 0;
- if (abs($x) <= 30) {
- $fResult = $fTerm = pow($x / 2, $ord) / Calculation_MathTrig::FACT($ord);
- $ordK = 1;
- $fSqrX = ($x * $x) / -4;
- do {
- $fTerm *= $fSqrX;
- $fTerm /= ($ordK * ($ordK + $ord));
- $fResult += $fTerm;
- } while ((abs($fTerm) > 1e-12) && (++$ordK < 100));
- } else {
- $f_PI_DIV_2 = M_PI / 2;
- $f_PI_DIV_4 = M_PI / 4;
-
- $fXAbs = abs($x);
- $fResult = sqrt(M_2DIVPI / $fXAbs) * cos($fXAbs - $ord * $f_PI_DIV_2 - $f_PI_DIV_4);
- if (($ord & 1) && ($x < 0)) {
- $fResult = -$fResult;
- }
- }
- return (is_nan($fResult)) ? Calculation_Functions::NaN() : $fResult;
- }
- return Calculation_Functions::VALUE();
- } // function BESSELJ()
-
-
- private static function _Besselk0($fNum) {
- if ($fNum <= 2) {
- $fNum2 = $fNum * 0.5;
- $y = ($fNum2 * $fNum2);
- $fRet = -log($fNum2) * self::BESSELI($fNum, 0) +
- (-0.57721566 + $y * (0.42278420 + $y * (0.23069756 + $y * (0.3488590e-1 + $y * (0.262698e-2 + $y *
- (0.10750e-3 + $y * 0.74e-5))))));
- } else {
- $y = 2 / $fNum;
- $fRet = exp(-$fNum) / sqrt($fNum) *
- (1.25331414 + $y * (-0.7832358e-1 + $y * (0.2189568e-1 + $y * (-0.1062446e-1 + $y *
- (0.587872e-2 + $y * (-0.251540e-2 + $y * 0.53208e-3))))));
- }
- return $fRet;
- } // function _Besselk0()
-
-
- private static function _Besselk1($fNum) {
- if ($fNum <= 2) {
- $fNum2 = $fNum * 0.5;
- $y = ($fNum2 * $fNum2);
- $fRet = log($fNum2) * self::BESSELI($fNum, 1) +
- (1 + $y * (0.15443144 + $y * (-0.67278579 + $y * (-0.18156897 + $y * (-0.1919402e-1 + $y *
- (-0.110404e-2 + $y * (-0.4686e-4))))))) / $fNum;
- } else {
- $y = 2 / $fNum;
- $fRet = exp(-$fNum) / sqrt($fNum) *
- (1.25331414 + $y * (0.23498619 + $y * (-0.3655620e-1 + $y * (0.1504268e-1 + $y * (-0.780353e-2 + $y *
- (0.325614e-2 + $y * (-0.68245e-3)))))));
- }
- return $fRet;
- } // function _Besselk1()
-
-
- /**
- * BESSELK
- *
- * Returns the modified Bessel function Kn(x), which is equivalent to the Bessel functions evaluated
- * for purely imaginary arguments.
- *
- * Excel Function:
- * BESSELK(x,ord)
- *
- * @access public
- * @category Engineering Functions
- * @param float $x The value at which to evaluate the function.
- * If x is nonnumeric, BESSELK returns the #VALUE! error value.
- * @param integer $ord The order of the Bessel function. If n is not an integer, it is truncated.
- * If $ord is nonnumeric, BESSELK returns the #VALUE! error value.
- * If $ord < 0, BESSELK returns the #NUM! error value.
- * @return float
- *
- */
- public static function BESSELK($x, $ord) {
- $x = (is_null($x)) ? 0.0 : Calculation_Functions::flattenSingleValue($x);
- $ord = (is_null($ord)) ? 0.0 : Calculation_Functions::flattenSingleValue($ord);
-
- if ((is_numeric($x)) && (is_numeric($ord))) {
- if (($ord < 0) || ($x == 0.0)) {
- return Calculation_Functions::NaN();
- }
-
- switch(floor($ord)) {
- case 0 : return self::_Besselk0($x);
- break;
- case 1 : return self::_Besselk1($x);
- break;
- default : $fTox = 2 / $x;
- $fBkm = self::_Besselk0($x);
- $fBk = self::_Besselk1($x);
- for ($n = 1; $n < $ord; ++$n) {
- $fBkp = $fBkm + $n * $fTox * $fBk;
- $fBkm = $fBk;
- $fBk = $fBkp;
- }
- }
- return (is_nan($fBk)) ? Calculation_Functions::NaN() : $fBk;
- }
- return Calculation_Functions::VALUE();
- } // function BESSELK()
-
-
- private static function _Bessely0($fNum) {
- if ($fNum < 8.0) {
- $y = ($fNum * $fNum);
- $f1 = -2957821389.0 + $y * (7062834065.0 + $y * (-512359803.6 + $y * (10879881.29 + $y * (-86327.92757 + $y * 228.4622733))));
- $f2 = 40076544269.0 + $y * (745249964.8 + $y * (7189466.438 + $y * (47447.26470 + $y * (226.1030244 + $y))));
- $fRet = $f1 / $f2 + 0.636619772 * self::BESSELJ($fNum, 0) * log($fNum);
- } else {
- $z = 8.0 / $fNum;
- $y = ($z * $z);
- $xx = $fNum - 0.785398164;
- $f1 = 1 + $y * (-0.1098628627e-2 + $y * (0.2734510407e-4 + $y * (-0.2073370639e-5 + $y * 0.2093887211e-6)));
- $f2 = -0.1562499995e-1 + $y * (0.1430488765e-3 + $y * (-0.6911147651e-5 + $y * (0.7621095161e-6 + $y * (-0.934945152e-7))));
- $fRet = sqrt(0.636619772 / $fNum) * (sin($xx) * $f1 + $z * cos($xx) * $f2);
- }
- return $fRet;
- } // function _Bessely0()
-
-
- private static function _Bessely1($fNum) {
- if ($fNum < 8.0) {
- $y = ($fNum * $fNum);
- $f1 = $fNum * (-0.4900604943e13 + $y * (0.1275274390e13 + $y * (-0.5153438139e11 + $y * (0.7349264551e9 + $y *
- (-0.4237922726e7 + $y * 0.8511937935e4)))));
- $f2 = 0.2499580570e14 + $y * (0.4244419664e12 + $y * (0.3733650367e10 + $y * (0.2245904002e8 + $y *
- (0.1020426050e6 + $y * (0.3549632885e3 + $y)))));
- $fRet = $f1 / $f2 + 0.636619772 * ( self::BESSELJ($fNum, 1) * log($fNum) - 1 / $fNum);
- } else {
- $fRet = sqrt(0.636619772 / $fNum) * sin($fNum - 2.356194491);
- }
- return $fRet;
- } // function _Bessely1()
-
-
- /**
- * BESSELY
- *
- * Returns the Bessel function, which is also called the Weber function or the Neumann function.
- *
- * Excel Function:
- * BESSELY(x,ord)
- *
- * @access public
- * @category Engineering Functions
- * @param float $x The value at which to evaluate the function.
- * If x is nonnumeric, BESSELK returns the #VALUE! error value.
- * @param integer $ord The order of the Bessel function. If n is not an integer, it is truncated.
- * If $ord is nonnumeric, BESSELK returns the #VALUE! error value.
- * If $ord < 0, BESSELK returns the #NUM! error value.
- *
- * @return float
- */
- public static function BESSELY($x, $ord) {
- $x = (is_null($x)) ? 0.0 : Calculation_Functions::flattenSingleValue($x);
- $ord = (is_null($ord)) ? 0.0 : Calculation_Functions::flattenSingleValue($ord);
-
- if ((is_numeric($x)) && (is_numeric($ord))) {
- if (($ord < 0) || ($x == 0.0)) {
- return Calculation_Functions::NaN();
- }
-
- switch(floor($ord)) {
- case 0 : return self::_Bessely0($x);
- break;
- case 1 : return self::_Bessely1($x);
- break;
- default: $fTox = 2 / $x;
- $fBym = self::_Bessely0($x);
- $fBy = self::_Bessely1($x);
- for ($n = 1; $n < $ord; ++$n) {
- $fByp = $n * $fTox * $fBy - $fBym;
- $fBym = $fBy;
- $fBy = $fByp;
- }
- }
- return (is_nan($fBy)) ? Calculation_Functions::NaN() : $fBy;
- }
- return Calculation_Functions::VALUE();
- } // function BESSELY()
-
-
- /**
- * BINTODEC
- *
- * Return a binary value as decimal.
- *
- * Excel Function:
- * BIN2DEC(x)
- *
- * @access public
- * @category Engineering Functions
- * @param string $x The binary number (as a string) that you want to convert. The number
- * cannot contain more than 10 characters (10 bits). The most significant
- * bit of number is the sign bit. The remaining 9 bits are magnitude bits.
- * Negative numbers are represented using two's-complement notation.
- * If number is not a valid binary number, or if number contains more than
- * 10 characters (10 bits), BIN2DEC returns the #NUM! error value.
- * @return string
- */
- public static function BINTODEC($x) {
- $x = Calculation_Functions::flattenSingleValue($x);
-
- if (is_bool($x)) {
- if (Calculation_Functions::getCompatibilityMode() == Calculation_Functions::COMPATIBILITY_OPENOFFICE) {
- $x = (int) $x;
- } else {
- return Calculation_Functions::VALUE();
- }
- }
- if (Calculation_Functions::getCompatibilityMode() == Calculation_Functions::COMPATIBILITY_GNUMERIC) {
- $x = floor($x);
- }
- $x = (string) $x;
- if (strlen($x) > preg_match_all('/[01]/',$x,$out)) {
- return Calculation_Functions::NaN();
- }
- if (strlen($x) > 10) {
- return Calculation_Functions::NaN();
- } elseif (strlen($x) == 10) {
- // Two's Complement
- $x = substr($x,-9);
- return '-'.(512-bindec($x));
- }
- return bindec($x);
- } // function BINTODEC()
-
-
- /**
- * BINTOHEX
- *
- * Return a binary value as hex.
- *
- * Excel Function:
- * BIN2HEX(x[,places])
- *
- * @access public
- * @category Engineering Functions
- * @param string $x The binary number (as a string) that you want to convert. The number
- * cannot contain more than 10 characters (10 bits). The most significant
- * bit of number is the sign bit. The remaining 9 bits are magnitude bits.
- * Negative numbers are represented using two's-complement notation.
- * If number is not a valid binary number, or if number contains more than
- * 10 characters (10 bits), BIN2HEX returns the #NUM! error value.
- * @param integer $places The number of characters to use. If places is omitted, BIN2HEX uses the
- * minimum number of characters necessary. Places is useful for padding the
- * return value with leading 0s (zeros).
- * If places is not an integer, it is truncated.
- * If places is nonnumeric, BIN2HEX returns the #VALUE! error value.
- * If places is negative, BIN2HEX returns the #NUM! error value.
- * @return string
- */
- public static function BINTOHEX($x, $places=NULL) {
- $x = Calculation_Functions::flattenSingleValue($x);
- $places = Calculation_Functions::flattenSingleValue($places);
-
- if (is_bool($x)) {
- if (Calculation_Functions::getCompatibilityMode() == Calculation_Functions::COMPATIBILITY_OPENOFFICE) {
- $x = (int) $x;
- } else {
- return Calculation_Functions::VALUE();
- }
- }
- if (Calculation_Functions::getCompatibilityMode() == Calculation_Functions::COMPATIBILITY_GNUMERIC) {
- $x = floor($x);
- }
- $x = (string) $x;
- if (strlen($x) > preg_match_all('/[01]/',$x,$out)) {
- return Calculation_Functions::NaN();
- }
- if (strlen($x) > 10) {
- return Calculation_Functions::NaN();
- } elseif (strlen($x) == 10) {
- // Two's Complement
- return str_repeat('F',8).substr(strtoupper(dechex(bindec(substr($x,-9)))),-2);
- }
- $hexVal = (string) strtoupper(dechex(bindec($x)));
-
- return self::_nbrConversionFormat($hexVal,$places);
- } // function BINTOHEX()
-
-
- /**
- * BINTOOCT
- *
- * Return a binary value as octal.
- *
- * Excel Function:
- * BIN2OCT(x[,places])
- *
- * @access public
- * @category Engineering Functions
- * @param string $x The binary number (as a string) that you want to convert. The number
- * cannot contain more than 10 characters (10 bits). The most significant
- * bit of number is the sign bit. The remaining 9 bits are magnitude bits.
- * Negative numbers are represented using two's-complement notation.
- * If number is not a valid binary number, or if number contains more than
- * 10 characters (10 bits), BIN2OCT returns the #NUM! error value.
- * @param integer $places The number of characters to use. If places is omitted, BIN2OCT uses the
- * minimum number of characters necessary. Places is useful for padding the
- * return value with leading 0s (zeros).
- * If places is not an integer, it is truncated.
- * If places is nonnumeric, BIN2OCT returns the #VALUE! error value.
- * If places is negative, BIN2OCT returns the #NUM! error value.
- * @return string
- */
- public static function BINTOOCT($x, $places=NULL) {
- $x = Calculation_Functions::flattenSingleValue($x);
- $places = Calculation_Functions::flattenSingleValue($places);
-
- if (is_bool($x)) {
- if (Calculation_Functions::getCompatibilityMode() == Calculation_Functions::COMPATIBILITY_OPENOFFICE) {
- $x = (int) $x;
- } else {
- return Calculation_Functions::VALUE();
- }
- }
- if (Calculation_Functions::getCompatibilityMode() == Calculation_Functions::COMPATIBILITY_GNUMERIC) {
- $x = floor($x);
- }
- $x = (string) $x;
- if (strlen($x) > preg_match_all('/[01]/',$x,$out)) {
- return Calculation_Functions::NaN();
- }
- if (strlen($x) > 10) {
- return Calculation_Functions::NaN();
- } elseif (strlen($x) == 10) {
- // Two's Complement
- return str_repeat('7',7).substr(strtoupper(decoct(bindec(substr($x,-9)))),-3);
- }
- $octVal = (string) decoct(bindec($x));
-
- return self::_nbrConversionFormat($octVal,$places);
- } // function BINTOOCT()
-
-
- /**
- * DECTOBIN
- *
- * Return a decimal value as binary.
- *
- * Excel Function:
- * DEC2BIN(x[,places])
- *
- * @access public
- * @category Engineering Functions
- * @param string $x The decimal integer you want to convert. If number is negative,
- * valid place values are ignored and DEC2BIN returns a 10-character
- * (10-bit) binary number in which the most significant bit is the sign
- * bit. The remaining 9 bits are magnitude bits. Negative numbers are
- * represented using two's-complement notation.
- * If number < -512 or if number > 511, DEC2BIN returns the #NUM! error
- * value.
- * If number is nonnumeric, DEC2BIN returns the #VALUE! error value.
- * If DEC2BIN requires more than places characters, it returns the #NUM!
- * error value.
- * @param integer $places The number of characters to use. If places is omitted, DEC2BIN uses
- * the minimum number of characters necessary. Places is useful for
- * padding the return value with leading 0s (zeros).
- * If places is not an integer, it is truncated.
- * If places is nonnumeric, DEC2BIN returns the #VALUE! error value.
- * If places is zero or negative, DEC2BIN returns the #NUM! error value.
- * @return string
- */
- public static function DECTOBIN($x, $places=NULL) {
- $x = Calculation_Functions::flattenSingleValue($x);
- $places = Calculation_Functions::flattenSingleValue($places);
-
- if (is_bool($x)) {
- if (Calculation_Functions::getCompatibilityMode() == Calculation_Functions::COMPATIBILITY_OPENOFFICE) {
- $x = (int) $x;
- } else {
- return Calculation_Functions::VALUE();
- }
- }
- $x = (string) $x;
- if (strlen($x) > preg_match_all('/[-0123456789.]/',$x,$out)) {
- return Calculation_Functions::VALUE();
- }
- $x = (string) floor($x);
- $r = decbin($x);
- if (strlen($r) == 32) {
- // Two's Complement
- $r = substr($r,-10);
- } elseif (strlen($r) > 11) {
- return Calculation_Functions::NaN();
- }
-
- return self::_nbrConversionFormat($r,$places);
- } // function DECTOBIN()
-
-
- /**
- * DECTOHEX
- *
- * Return a decimal value as hex.
- *
- * Excel Function:
- * DEC2HEX(x[,places])
- *
- * @access public
- * @category Engineering Functions
- * @param string $x The decimal integer you want to convert. If number is negative,
- * places is ignored and DEC2HEX returns a 10-character (40-bit)
- * hexadecimal number in which the most significant bit is the sign
- * bit. The remaining 39 bits are magnitude bits. Negative numbers
- * are represented using two's-complement notation.
- * If number < -549,755,813,888 or if number > 549,755,813,887,
- * DEC2HEX returns the #NUM! error value.
- * If number is nonnumeric, DEC2HEX returns the #VALUE! error value.
- * If DEC2HEX requires more than places characters, it returns the
- * #NUM! error value.
- * @param integer $places The number of characters to use. If places is omitted, DEC2HEX uses
- * the minimum number of characters necessary. Places is useful for
- * padding the return value with leading 0s (zeros).
- * If places is not an integer, it is truncated.
- * If places is nonnumeric, DEC2HEX returns the #VALUE! error value.
- * If places is zero or negative, DEC2HEX returns the #NUM! error value.
- * @return string
- */
- public static function DECTOHEX($x, $places=null) {
- $x = Calculation_Functions::flattenSingleValue($x);
- $places = Calculation_Functions::flattenSingleValue($places);
-
- if (is_bool($x)) {
- if (Calculation_Functions::getCompatibilityMode() == Calculation_Functions::COMPATIBILITY_OPENOFFICE) {
- $x = (int) $x;
- } else {
- return Calculation_Functions::VALUE();
- }
- }
- $x = (string) $x;
- if (strlen($x) > preg_match_all('/[-0123456789.]/',$x,$out)) {
- return Calculation_Functions::VALUE();
- }
- $x = (string) floor($x);
- $r = strtoupper(dechex($x));
- if (strlen($r) == 8) {
- // Two's Complement
- $r = 'FF'.$r;
- }
-
- return self::_nbrConversionFormat($r,$places);
- } // function DECTOHEX()
-
-
- /**
- * DECTOOCT
- *
- * Return an decimal value as octal.
- *
- * Excel Function:
- * DEC2OCT(x[,places])
- *
- * @access public
- * @category Engineering Functions
- * @param string $x The decimal integer you want to convert. If number is negative,
- * places is ignored and DEC2OCT returns a 10-character (30-bit)
- * octal number in which the most significant bit is the sign bit.
- * The remaining 29 bits are magnitude bits. Negative numbers are
- * represented using two's-complement notation.
- * If number < -536,870,912 or if number > 536,870,911, DEC2OCT
- * returns the #NUM! error value.
- * If number is nonnumeric, DEC2OCT returns the #VALUE! error value.
- * If DEC2OCT requires more than places characters, it returns the
- * #NUM! error value.
- * @param integer $places The number of characters to use. If places is omitted, DEC2OCT uses
- * the minimum number of characters necessary. Places is useful for
- * padding the return value with leading 0s (zeros).
- * If places is not an integer, it is truncated.
- * If places is nonnumeric, DEC2OCT returns the #VALUE! error value.
- * If places is zero or negative, DEC2OCT returns the #NUM! error value.
- * @return string
- */
- public static function DECTOOCT($x, $places=null) {
- $x = Calculation_Functions::flattenSingleValue($x);
- $places = Calculation_Functions::flattenSingleValue($places);
-
- if (is_bool($x)) {
- if (Calculation_Functions::getCompatibilityMode() == Calculation_Functions::COMPATIBILITY_OPENOFFICE) {
- $x = (int) $x;
- } else {
- return Calculation_Functions::VALUE();
- }
- }
- $x = (string) $x;
- if (strlen($x) > preg_match_all('/[-0123456789.]/',$x,$out)) {
- return Calculation_Functions::VALUE();
- }
- $x = (string) floor($x);
- $r = decoct($x);
- if (strlen($r) == 11) {
- // Two's Complement
- $r = substr($r,-10);
- }
-
- return self::_nbrConversionFormat($r,$places);
- } // function DECTOOCT()
-
-
- /**
- * HEXTOBIN
- *
- * Return a hex value as binary.
- *
- * Excel Function:
- * HEX2BIN(x[,places])
- *
- * @access public
- * @category Engineering Functions
- * @param string $x the hexadecimal number you want to convert. Number cannot
- * contain more than 10 characters. The most significant bit of
- * number is the sign bit (40th bit from the right). The remaining
- * 9 bits are magnitude bits. Negative numbers are represented
- * using two's-complement notation.
- * If number is negative, HEX2BIN ignores places and returns a
- * 10-character binary number.
- * If number is negative, it cannot be less than FFFFFFFE00, and
- * if number is positive, it cannot be greater than 1FF.
- * If number is not a valid hexadecimal number, HEX2BIN returns
- * the #NUM! error value.
- * If HEX2BIN requires more than places characters, it returns
- * the #NUM! error value.
- * @param integer $places The number of characters to use. If places is omitted,
- * HEX2BIN uses the minimum number of characters necessary. Places
- * is useful for padding the return value with leading 0s (zeros).
- * If places is not an integer, it is truncated.
- * If places is nonnumeric, HEX2BIN returns the #VALUE! error value.
- * If places is negative, HEX2BIN returns the #NUM! error value.
- * @return string
- */
- public static function HEXTOBIN($x, $places=null) {
- $x = Calculation_Functions::flattenSingleValue($x);
- $places = Calculation_Functions::flattenSingleValue($places);
-
- if (is_bool($x)) {
- return Calculation_Functions::VALUE();
- }
- $x = (string) $x;
- if (strlen($x) > preg_match_all('/[0123456789ABCDEF]/',strtoupper($x),$out)) {
- return Calculation_Functions::NaN();
- }
- $binVal = decbin(hexdec($x));
-
- return substr(self::_nbrConversionFormat($binVal,$places),-10);
- } // function HEXTOBIN()
-
-
- /**
- * HEXTODEC
- *
- * Return a hex value as decimal.
- *
- * Excel Function:
- * HEX2DEC(x)
- *
- * @access public
- * @category Engineering Functions
- * @param string $x The hexadecimal number you want to convert. This number cannot
- * contain more than 10 characters (40 bits). The most significant
- * bit of number is the sign bit. The remaining 39 bits are magnitude
- * bits. Negative numbers are represented using two's-complement
- * notation.
- * If number is not a valid hexadecimal number, HEX2DEC returns the
- * #NUM! error value.
- * @return string
- */
- public static function HEXTODEC($x) {
- $x = Calculation_Functions::flattenSingleValue($x);
-
- if (is_bool($x)) {
- return Calculation_Functions::VALUE();
- }
- $x = (string) $x;
- if (strlen($x) > preg_match_all('/[0123456789ABCDEF]/',strtoupper($x),$out)) {
- return Calculation_Functions::NaN();
- }
- return hexdec($x);
- } // function HEXTODEC()
-
-
- /**
- * HEXTOOCT
- *
- * Return a hex value as octal.
- *
- * Excel Function:
- * HEX2OCT(x[,places])
- *
- * @access public
- * @category Engineering Functions
- * @param string $x The hexadecimal number you want to convert. Number cannot
- * contain more than 10 characters. The most significant bit of
- * number is the sign bit. The remaining 39 bits are magnitude
- * bits. Negative numbers are represented using two's-complement
- * notation.
- * If number is negative, HEX2OCT ignores places and returns a
- * 10-character octal number.
- * If number is negative, it cannot be less than FFE0000000, and
- * if number is positive, it cannot be greater than 1FFFFFFF.
- * If number is not a valid hexadecimal number, HEX2OCT returns
- * the #NUM! error value.
- * If HEX2OCT requires more than places characters, it returns
- * the #NUM! error value.
- * @param integer $places The number of characters to use. If places is omitted, HEX2OCT
- * uses the minimum number of characters necessary. Places is
- * useful for padding the return value with leading 0s (zeros).
- * If places is not an integer, it is truncated.
- * If places is nonnumeric, HEX2OCT returns the #VALUE! error
- * value.
- * If places is negative, HEX2OCT returns the #NUM! error value.
- * @return string
- */
- public static function HEXTOOCT($x, $places=null) {
- $x = Calculation_Functions::flattenSingleValue($x);
- $places = Calculation_Functions::flattenSingleValue($places);
-
- if (is_bool($x)) {
- return Calculation_Functions::VALUE();
- }
- $x = (string) $x;
- if (strlen($x) > preg_match_all('/[0123456789ABCDEF]/',strtoupper($x),$out)) {
- return Calculation_Functions::NaN();
- }
- $octVal = decoct(hexdec($x));
-
- return self::_nbrConversionFormat($octVal,$places);
- } // function HEXTOOCT()
-
-
- /**
- * OCTTOBIN
- *
- * Return an octal value as binary.
- *
- * Excel Function:
- * OCT2BIN(x[,places])
- *
- * @access public
- * @category Engineering Functions
- * @param string $x The octal number you want to convert. Number may not
- * contain more than 10 characters. The most significant
- * bit of number is the sign bit. The remaining 29 bits
- * are magnitude bits. Negative numbers are represented
- * using two's-complement notation.
- * If number is negative, OCT2BIN ignores places and returns
- * a 10-character binary number.
- * If number is negative, it cannot be less than 7777777000,
- * and if number is positive, it cannot be greater than 777.
- * If number is not a valid octal number, OCT2BIN returns
- * the #NUM! error value.
- * If OCT2BIN requires more than places characters, it
- * returns the #NUM! error value.
- * @param integer $places The number of characters to use. If places is omitted,
- * OCT2BIN uses the minimum number of characters necessary.
- * Places is useful for padding the return value with
- * leading 0s (zeros).
- * If places is not an integer, it is truncated.
- * If places is nonnumeric, OCT2BIN returns the #VALUE!
- * error value.
- * If places is negative, OCT2BIN returns the #NUM! error
- * value.
- * @return string
- */
- public static function OCTTOBIN($x, $places=null) {
- $x = Calculation_Functions::flattenSingleValue($x);
- $places = Calculation_Functions::flattenSingleValue($places);
-
- if (is_bool($x)) {
- return Calculation_Functions::VALUE();
- }
- $x = (string) $x;
- if (preg_match_all('/[01234567]/',$x,$out) != strlen($x)) {
- return Calculation_Functions::NaN();
- }
- $r = decbin(octdec($x));
-
- return self::_nbrConversionFormat($r,$places);
- } // function OCTTOBIN()
-
-
- /**
- * OCTTODEC
- *
- * Return an octal value as decimal.
- *
- * Excel Function:
- * OCT2DEC(x)
- *
- * @access public
- * @category Engineering Functions
- * @param string $x The octal number you want to convert. Number may not contain
- * more than 10 octal characters (30 bits). The most significant
- * bit of number is the sign bit. The remaining 29 bits are
- * magnitude bits. Negative numbers are represented using
- * two's-complement notation.
- * If number is not a valid octal number, OCT2DEC returns the
- * #NUM! error value.
- * @return string
- */
- public static function OCTTODEC($x) {
- $x = Calculation_Functions::flattenSingleValue($x);
-
- if (is_bool($x)) {
- return Calculation_Functions::VALUE();
- }
- $x = (string) $x;
- if (preg_match_all('/[01234567]/',$x,$out) != strlen($x)) {
- return Calculation_Functions::NaN();
- }
- return octdec($x);
- } // function OCTTODEC()
-
-
- /**
- * OCTTOHEX
- *
- * Return an octal value as hex.
- *
- * Excel Function:
- * OCT2HEX(x[,places])
- *
- * @access public
- * @category Engineering Functions
- * @param string $x The octal number you want to convert. Number may not contain
- * more than 10 octal characters (30 bits). The most significant
- * bit of number is the sign bit. The remaining 29 bits are
- * magnitude bits. Negative numbers are represented using
- * two's-complement notation.
- * If number is negative, OCT2HEX ignores places and returns a
- * 10-character hexadecimal number.
- * If number is not a valid octal number, OCT2HEX returns the
- * #NUM! error value.
- * If OCT2HEX requires more than places characters, it returns
- * the #NUM! error value.
- * @param integer $places The number of characters to use. If places is omitted, OCT2HEX
- * uses the minimum number of characters necessary. Places is useful
- * for padding the return value with leading 0s (zeros).
- * If places is not an integer, it is truncated.
- * If places is nonnumeric, OCT2HEX returns the #VALUE! error value.
- * If places is negative, OCT2HEX returns the #NUM! error value.
- * @return string
- */
- public static function OCTTOHEX($x, $places=null) {
- $x = Calculation_Functions::flattenSingleValue($x);
- $places = Calculation_Functions::flattenSingleValue($places);
-
- if (is_bool($x)) {
- return Calculation_Functions::VALUE();
- }
- $x = (string) $x;
- if (preg_match_all('/[01234567]/',$x,$out) != strlen($x)) {
- return Calculation_Functions::NaN();
- }
- $hexVal = strtoupper(dechex(octdec($x)));
-
- return self::_nbrConversionFormat($hexVal,$places);
- } // function OCTTOHEX()
-
-
- /**
- * COMPLEX
- *
- * Converts real and imaginary coefficients into a complex number of the form x + yi or x + yj.
- *
- * Excel Function:
- * COMPLEX(realNumber,imaginary[,places])
- *
- * @access public
- * @category Engineering Functions
- * @param float $realNumber The real coefficient of the complex number.
- * @param float $imaginary The imaginary coefficient of the complex number.
- * @param string $suffix The suffix for the imaginary component of the complex number.
- * If omitted, the suffix is assumed to be "i".
- * @return string
- */
- public static function COMPLEX($realNumber=0.0, $imaginary=0.0, $suffix='i') {
- $realNumber = (is_null($realNumber)) ? 0.0 : Calculation_Functions::flattenSingleValue($realNumber);
- $imaginary = (is_null($imaginary)) ? 0.0 : Calculation_Functions::flattenSingleValue($imaginary);
- $suffix = (is_null($suffix)) ? 'i' : Calculation_Functions::flattenSingleValue($suffix);
-
- if (((is_numeric($realNumber)) && (is_numeric($imaginary))) &&
- (($suffix == 'i') || ($suffix == 'j') || ($suffix == ''))) {
- $realNumber = (float) $realNumber;
- $imaginary = (float) $imaginary;
-
- if ($suffix == '') $suffix = 'i';
- if ($realNumber == 0.0) {
- if ($imaginary == 0.0) {
- return (string) '0';
- } elseif ($imaginary == 1.0) {
- return (string) $suffix;
- } elseif ($imaginary == -1.0) {
- return (string) '-'.$suffix;
- }
- return (string) $imaginary.$suffix;
- } elseif ($imaginary == 0.0) {
- return (string) $realNumber;
- } elseif ($imaginary == 1.0) {
- return (string) $realNumber.'+'.$suffix;
- } elseif ($imaginary == -1.0) {
- return (string) $realNumber.'-'.$suffix;
- }
- if ($imaginary > 0) { $imaginary = (string) '+'.$imaginary; }
- return (string) $realNumber.$imaginary.$suffix;
- }
-
- return Calculation_Functions::VALUE();
- } // function COMPLEX()
-
-
- /**
- * IMAGINARY
- *
- * Returns the imaginary coefficient of a complex number in x + yi or x + yj text format.
- *
- * Excel Function:
- * IMAGINARY(complexNumber)
- *
- * @access public
- * @category Engineering Functions
- * @param string $complexNumber The complex number for which you want the imaginary
- * coefficient.
- * @return float
- */
- public static function IMAGINARY($complexNumber) {
- $complexNumber = Calculation_Functions::flattenSingleValue($complexNumber);
-
- $parsedComplex = self::_parseComplex($complexNumber);
- return $parsedComplex['imaginary'];
- } // function IMAGINARY()
-
-
- /**
- * IMREAL
- *
- * Returns the real coefficient of a complex number in x + yi or x + yj text format.
- *
- * Excel Function:
- * IMREAL(complexNumber)
- *
- * @access public
- * @category Engineering Functions
- * @param string $complexNumber The complex number for which you want the real coefficient.
- * @return float
- */
- public static function IMREAL($complexNumber) {
- $complexNumber = Calculation_Functions::flattenSingleValue($complexNumber);
-
- $parsedComplex = self::_parseComplex($complexNumber);
- return $parsedComplex['real'];
- } // function IMREAL()
-
-
- /**
- * IMABS
- *
- * Returns the absolute value (modulus) of a complex number in x + yi or x + yj text format.
- *
- * Excel Function:
- * IMABS(complexNumber)
- *
- * @param string $complexNumber The complex number for which you want the absolute value.
- * @return float
- */
- public static function IMABS($complexNumber) {
- $complexNumber = Calculation_Functions::flattenSingleValue($complexNumber);
-
- $parsedComplex = self::_parseComplex($complexNumber);
-
- return sqrt(($parsedComplex['real'] * $parsedComplex['real']) + ($parsedComplex['imaginary'] * $parsedComplex['imaginary']));
- } // function IMABS()
-
-
- /**
- * IMARGUMENT
- *
- * Returns the argument theta of a complex number, i.e. the angle in radians from the real
- * axis to the representation of the number in polar coordinates.
- *
- * Excel Function:
- * IMARGUMENT(complexNumber)
- *
- * @param string $complexNumber The complex number for which you want the argument theta.
- * @return float
- */
- public static function IMARGUMENT($complexNumber) {
- $complexNumber = Calculation_Functions::flattenSingleValue($complexNumber);
-
- $parsedComplex = self::_parseComplex($complexNumber);
-
- if ($parsedComplex['real'] == 0.0) {
- if ($parsedComplex['imaginary'] == 0.0) {
- return 0.0;
- } elseif($parsedComplex['imaginary'] < 0.0) {
- return M_PI / -2;
- } else {
- return M_PI / 2;
- }
- } elseif ($parsedComplex['real'] > 0.0) {
- return atan($parsedComplex['imaginary'] / $parsedComplex['real']);
- } elseif ($parsedComplex['imaginary'] < 0.0) {
- return 0 - (M_PI - atan(abs($parsedComplex['imaginary']) / abs($parsedComplex['real'])));
- } else {
- return M_PI - atan($parsedComplex['imaginary'] / abs($parsedComplex['real']));
- }
- } // function IMARGUMENT()
-
-
- /**
- * IMCONJUGATE
- *
- * Returns the complex conjugate of a complex number in x + yi or x + yj text format.
- *
- * Excel Function:
- * IMCONJUGATE(complexNumber)
- *
- * @param string $complexNumber The complex number for which you want the conjugate.
- * @return string
- */
- public static function IMCONJUGATE($complexNumber) {
- $complexNumber = Calculation_Functions::flattenSingleValue($complexNumber);
-
- $parsedComplex = self::_parseComplex($complexNumber);
-
- if ($parsedComplex['imaginary'] == 0.0) {
- return $parsedComplex['real'];
- } else {
- return self::_cleanComplex( self::COMPLEX( $parsedComplex['real'],
- 0 - $parsedComplex['imaginary'],
- $parsedComplex['suffix']
- )
- );
- }
- } // function IMCONJUGATE()
-
-
- /**
- * IMCOS
- *
- * Returns the cosine of a complex number in x + yi or x + yj text format.
- *
- * Excel Function:
- * IMCOS(complexNumber)
- *
- * @param string $complexNumber The complex number for which you want the cosine.
- * @return string|float
- */
- public static function IMCOS($complexNumber) {
- $complexNumber = Calculation_Functions::flattenSingleValue($complexNumber);
-
- $parsedComplex = self::_parseComplex($complexNumber);
-
- if ($parsedComplex['imaginary'] == 0.0) {
- return cos($parsedComplex['real']);
- } else {
- return self::IMCONJUGATE(self::COMPLEX(cos($parsedComplex['real']) * cosh($parsedComplex['imaginary']),sin($parsedComplex['real']) * sinh($parsedComplex['imaginary']),$parsedComplex['suffix']));
- }
- } // function IMCOS()
-
-
- /**
- * IMSIN
- *
- * Returns the sine of a complex number in x + yi or x + yj text format.
- *
- * Excel Function:
- * IMSIN(complexNumber)
- *
- * @param string $complexNumber The complex number for which you want the sine.
- * @return string|float
- */
- public static function IMSIN($complexNumber) {
- $complexNumber = Calculation_Functions::flattenSingleValue($complexNumber);
-
- $parsedComplex = self::_parseComplex($complexNumber);
-
- if ($parsedComplex['imaginary'] == 0.0) {
- return sin($parsedComplex['real']);
- } else {
- return self::COMPLEX(sin($parsedComplex['real']) * cosh($parsedComplex['imaginary']),cos($parsedComplex['real']) * sinh($parsedComplex['imaginary']),$parsedComplex['suffix']);
- }
- } // function IMSIN()
-
-
- /**
- * IMSQRT
- *
- * Returns the square root of a complex number in x + yi or x + yj text format.
- *
- * Excel Function:
- * IMSQRT(complexNumber)
- *
- * @param string $complexNumber The complex number for which you want the square root.
- * @return string
- */
- public static function IMSQRT($complexNumber) {
- $complexNumber = Calculation_Functions::flattenSingleValue($complexNumber);
-
- $parsedComplex = self::_parseComplex($complexNumber);
-
- $theta = self::IMARGUMENT($complexNumber);
- $d1 = cos($theta / 2);
- $d2 = sin($theta / 2);
- $r = sqrt(sqrt(($parsedComplex['real'] * $parsedComplex['real']) + ($parsedComplex['imaginary'] * $parsedComplex['imaginary'])));
-
- if ($parsedComplex['suffix'] == '') {
- return self::COMPLEX($d1 * $r,$d2 * $r);
- } else {
- return self::COMPLEX($d1 * $r,$d2 * $r,$parsedComplex['suffix']);
- }
- } // function IMSQRT()
-
-
- /**
- * IMLN
- *
- * Returns the natural logarithm of a complex number in x + yi or x + yj text format.
- *
- * Excel Function:
- * IMLN(complexNumber)
- *
- * @param string $complexNumber The complex number for which you want the natural logarithm.
- * @return string
- */
- public static function IMLN($complexNumber) {
- $complexNumber = Calculation_Functions::flattenSingleValue($complexNumber);
-
- $parsedComplex = self::_parseComplex($complexNumber);
-
- if (($parsedComplex['real'] == 0.0) && ($parsedComplex['imaginary'] == 0.0)) {
- return Calculation_Functions::NaN();
- }
-
- $logR = log(sqrt(($parsedComplex['real'] * $parsedComplex['real']) + ($parsedComplex['imaginary'] * $parsedComplex['imaginary'])));
- $t = self::IMARGUMENT($complexNumber);
-
- if ($parsedComplex['suffix'] == '') {
- return self::COMPLEX($logR,$t);
- } else {
- return self::COMPLEX($logR,$t,$parsedComplex['suffix']);
- }
- } // function IMLN()
-
-
- /**
- * IMLOG10
- *
- * Returns the common logarithm (base 10) of a complex number in x + yi or x + yj text format.
- *
- * Excel Function:
- * IMLOG10(complexNumber)
- *
- * @param string $complexNumber The complex number for which you want the common logarithm.
- * @return string
- */
- public static function IMLOG10($complexNumber) {
- $complexNumber = Calculation_Functions::flattenSingleValue($complexNumber);
-
- $parsedComplex = self::_parseComplex($complexNumber);
-
- if (($parsedComplex['real'] == 0.0) && ($parsedComplex['imaginary'] == 0.0)) {
- return Calculation_Functions::NaN();
- } elseif (($parsedComplex['real'] > 0.0) && ($parsedComplex['imaginary'] == 0.0)) {
- return log10($parsedComplex['real']);
- }
-
- return self::IMPRODUCT(log10(EULER),self::IMLN($complexNumber));
- } // function IMLOG10()
-
-
- /**
- * IMLOG2
- *
- * Returns the base-2 logarithm of a complex number in x + yi or x + yj text format.
- *
- * Excel Function:
- * IMLOG2(complexNumber)
- *
- * @param string $complexNumber The complex number for which you want the base-2 logarithm.
- * @return string
- */
- public static function IMLOG2($complexNumber) {
- $complexNumber = Calculation_Functions::flattenSingleValue($complexNumber);
-
- $parsedComplex = self::_parseComplex($complexNumber);
-
- if (($parsedComplex['real'] == 0.0) && ($parsedComplex['imaginary'] == 0.0)) {
- return Calculation_Functions::NaN();
- } elseif (($parsedComplex['real'] > 0.0) && ($parsedComplex['imaginary'] == 0.0)) {
- return log($parsedComplex['real'],2);
- }
-
- return self::IMPRODUCT(log(EULER,2),self::IMLN($complexNumber));
- } // function IMLOG2()
-
-
- /**
- * IMEXP
- *
- * Returns the exponential of a complex number in x + yi or x + yj text format.
- *
- * Excel Function:
- * IMEXP(complexNumber)
- *
- * @param string $complexNumber The complex number for which you want the exponential.
- * @return string
- */
- public static function IMEXP($complexNumber) {
- $complexNumber = Calculation_Functions::flattenSingleValue($complexNumber);
-
- $parsedComplex = self::_parseComplex($complexNumber);
-
- if (($parsedComplex['real'] == 0.0) && ($parsedComplex['imaginary'] == 0.0)) {
- return '1';
- }
-
- $e = exp($parsedComplex['real']);
- $eX = $e * cos($parsedComplex['imaginary']);
- $eY = $e * sin($parsedComplex['imaginary']);
-
- if ($parsedComplex['suffix'] == '') {
- return self::COMPLEX($eX,$eY);
- } else {
- return self::COMPLEX($eX,$eY,$parsedComplex['suffix']);
- }
- } // function IMEXP()
-
-
- /**
- * IMPOWER
- *
- * Returns a complex number in x + yi or x + yj text format raised to a power.
- *
- * Excel Function:
- * IMPOWER(complexNumber,realNumber)
- *
- * @param string $complexNumber The complex number you want to raise to a power.
- * @param float $realNumber The power to which you want to raise the complex number.
- * @return string
- */
- public static function IMPOWER($complexNumber,$realNumber) {
- $complexNumber = Calculation_Functions::flattenSingleValue($complexNumber);
- $realNumber = Calculation_Functions::flattenSingleValue($realNumber);
-
- if (!is_numeric($realNumber)) {
- return Calculation_Functions::VALUE();
- }
-
- $parsedComplex = self::_parseComplex($complexNumber);
-
- $r = sqrt(($parsedComplex['real'] * $parsedComplex['real']) + ($parsedComplex['imaginary'] * $parsedComplex['imaginary']));
- $rPower = pow($r,$realNumber);
- $theta = self::IMARGUMENT($complexNumber) * $realNumber;
- if ($theta == 0) {
- return 1;
- } elseif ($parsedComplex['imaginary'] == 0.0) {
- return self::COMPLEX($rPower * cos($theta),$rPower * sin($theta),$parsedComplex['suffix']);
- } else {
- return self::COMPLEX($rPower * cos($theta),$rPower * sin($theta),$parsedComplex['suffix']);
- }
- } // function IMPOWER()
-
-
- /**
- * IMDIV
- *
- * Returns the quotient of two complex numbers in x + yi or x + yj text format.
- *
- * Excel Function:
- * IMDIV(complexDividend,complexDivisor)
- *
- * @param string $complexDividend The complex numerator or dividend.
- * @param string $complexDivisor The complex denominator or divisor.
- * @return string
- */
- public static function IMDIV($complexDividend,$complexDivisor) {
- $complexDividend = Calculation_Functions::flattenSingleValue($complexDividend);
- $complexDivisor = Calculation_Functions::flattenSingleValue($complexDivisor);
-
- $parsedComplexDividend = self::_parseComplex($complexDividend);
- $parsedComplexDivisor = self::_parseComplex($complexDivisor);
-
- if (($parsedComplexDividend['suffix'] != '') && ($parsedComplexDivisor['suffix'] != '') &&
- ($parsedComplexDividend['suffix'] != $parsedComplexDivisor['suffix'])) {
- return Calculation_Functions::NaN();
- }
- if (($parsedComplexDividend['suffix'] != '') && ($parsedComplexDivisor['suffix'] == '')) {
- $parsedComplexDivisor['suffix'] = $parsedComplexDividend['suffix'];
- }
-
- $d1 = ($parsedComplexDividend['real'] * $parsedComplexDivisor['real']) + ($parsedComplexDividend['imaginary'] * $parsedComplexDivisor['imaginary']);
- $d2 = ($parsedComplexDividend['imaginary'] * $parsedComplexDivisor['real']) - ($parsedComplexDividend['real'] * $parsedComplexDivisor['imaginary']);
- $d3 = ($parsedComplexDivisor['real'] * $parsedComplexDivisor['real']) + ($parsedComplexDivisor['imaginary'] * $parsedComplexDivisor['imaginary']);
-
- $r = $d1/$d3;
- $i = $d2/$d3;
-
- if ($i > 0.0) {
- return self::_cleanComplex($r.'+'.$i.$parsedComplexDivisor['suffix']);
- } elseif ($i < 0.0) {
- return self::_cleanComplex($r.$i.$parsedComplexDivisor['suffix']);
- } else {
- return $r;
- }
- } // function IMDIV()
-
-
- /**
- * IMSUB
- *
- * Returns the difference of two complex numbers in x + yi or x + yj text format.
- *
- * Excel Function:
- * IMSUB(complexNumber1,complexNumber2)
- *
- * @param string $complexNumber1 The complex number from which to subtract complexNumber2.
- * @param string $complexNumber2 The complex number to subtract from complexNumber1.
- * @return string
- */
- public static function IMSUB($complexNumber1,$complexNumber2) {
- $complexNumber1 = Calculation_Functions::flattenSingleValue($complexNumber1);
- $complexNumber2 = Calculation_Functions::flattenSingleValue($complexNumber2);
-
- $parsedComplex1 = self::_parseComplex($complexNumber1);
- $parsedComplex2 = self::_parseComplex($complexNumber2);
-
- if ((($parsedComplex1['suffix'] != '') && ($parsedComplex2['suffix'] != '')) &&
- ($parsedComplex1['suffix'] != $parsedComplex2['suffix'])) {
- return Calculation_Functions::NaN();
- } elseif (($parsedComplex1['suffix'] == '') && ($parsedComplex2['suffix'] != '')) {
- $parsedComplex1['suffix'] = $parsedComplex2['suffix'];
- }
-
- $d1 = $parsedComplex1['real'] - $parsedComplex2['real'];
- $d2 = $parsedComplex1['imaginary'] - $parsedComplex2['imaginary'];
-
- return self::COMPLEX($d1,$d2,$parsedComplex1['suffix']);
- } // function IMSUB()
-
-
- /**
- * IMSUM
- *
- * Returns the sum of two or more complex numbers in x + yi or x + yj text format.
- *
- * Excel Function:
- * IMSUM(complexNumber[,complexNumber[,...]])
- *
- * @param string $complexNumber,... Series of complex numbers to add
- * @return string
- */
- public static function IMSUM() {
- // Return value
- $returnValue = self::_parseComplex('0');
- $activeSuffix = '';
-
- // Loop through the arguments
- $aArgs = Calculation_Functions::flattenArray(func_get_args());
- foreach ($aArgs as $arg) {
- $parsedComplex = self::_parseComplex($arg);
-
- if ($activeSuffix == '') {
- $activeSuffix = $parsedComplex['suffix'];
- } elseif (($parsedComplex['suffix'] != '') && ($activeSuffix != $parsedComplex['suffix'])) {
- return Calculation_Functions::VALUE();
- }
-
- $returnValue['real'] += $parsedComplex['real'];
- $returnValue['imaginary'] += $parsedComplex['imaginary'];
- }
-
- if ($returnValue['imaginary'] == 0.0) { $activeSuffix = ''; }
- return self::COMPLEX($returnValue['real'],$returnValue['imaginary'],$activeSuffix);
- } // function IMSUM()
-
-
- /**
- * IMPRODUCT
- *
- * Returns the product of two or more complex numbers in x + yi or x + yj text format.
- *
- * Excel Function:
- * IMPRODUCT(complexNumber[,complexNumber[,...]])
- *
- * @param string $complexNumber,... Series of complex numbers to multiply
- * @return string
- */
- public static function IMPRODUCT() {
- // Return value
- $returnValue = self::_parseComplex('1');
- $activeSuffix = '';
-
- // Loop through the arguments
- $aArgs = Calculation_Functions::flattenArray(func_get_args());
- foreach ($aArgs as $arg) {
- $parsedComplex = self::_parseComplex($arg);
-
- $workValue = $returnValue;
- if (($parsedComplex['suffix'] != '') && ($activeSuffix == '')) {
- $activeSuffix = $parsedComplex['suffix'];
- } elseif (($parsedComplex['suffix'] != '') && ($activeSuffix != $parsedComplex['suffix'])) {
- return Calculation_Functions::NaN();
- }
- $returnValue['real'] = ($workValue['real'] * $parsedComplex['real']) - ($workValue['imaginary'] * $parsedComplex['imaginary']);
- $returnValue['imaginary'] = ($workValue['real'] * $parsedComplex['imaginary']) + ($workValue['imaginary'] * $parsedComplex['real']);
- }
-
- if ($returnValue['imaginary'] == 0.0) { $activeSuffix = ''; }
- return self::COMPLEX($returnValue['real'],$returnValue['imaginary'],$activeSuffix);
- } // function IMPRODUCT()
-
-
- /**
- * DELTA
- *
- * Tests whether two values are equal. Returns 1 if number1 = number2; returns 0 otherwise.
- * Use this function to filter a set of values. For example, by summing several DELTA
- * functions you calculate the count of equal pairs. This function is also known as the
- * Kronecker Delta function.
- *
- * Excel Function:
- * DELTA(a[,b])
- *
- * @param float $a The first number.
- * @param float $b The second number. If omitted, b is assumed to be zero.
- * @return int
- */
- public static function DELTA($a, $b=0) {
- $a = Calculation_Functions::flattenSingleValue($a);
- $b = Calculation_Functions::flattenSingleValue($b);
-
- return (int) ($a == $b);
- } // function DELTA()
-
-
- /**
- * GESTEP
- *
- * Excel Function:
- * GESTEP(number[,step])
- *
- * Returns 1 if number >= step; returns 0 (zero) otherwise
- * Use this function to filter a set of values. For example, by summing several GESTEP
- * functions you calculate the count of values that exceed a threshold.
- *
- * @param float $number The value to test against step.
- * @param float $step The threshold value.
- * If you omit a value for step, GESTEP uses zero.
- * @return int
- */
- public static function GESTEP($number, $step=0) {
- $number = Calculation_Functions::flattenSingleValue($number);
- $step = Calculation_Functions::flattenSingleValue($step);
-
- return (int) ($number >= $step);
- } // function GESTEP()
-
-
- //
- // Private method to calculate the erf value
- //
- private static $_two_sqrtpi = 1.128379167095512574;
-
- public static function _erfVal($x) {
- if (abs($x) > 2.2) {
- return 1 - self::_erfcVal($x);
- }
- $sum = $term = $x;
- $xsqr = ($x * $x);
- $j = 1;
- do {
- $term *= $xsqr / $j;
- $sum -= $term / (2 * $j + 1);
- ++$j;
- $term *= $xsqr / $j;
- $sum += $term / (2 * $j + 1);
- ++$j;
- if ($sum == 0.0) {
- break;
- }
- } while (abs($term / $sum) > PRECISION);
- return self::$_two_sqrtpi * $sum;
- } // function _erfVal()
-
-
- /**
- * ERF
- *
- * Returns the error function integrated between the lower and upper bound arguments.
- *
- * Note: In Excel 2007 or earlier, if you input a negative value for the upper or lower bound arguments,
- * the function would return a #NUM! error. However, in Excel 2010, the function algorithm was
- * improved, so that it can now calculate the function for both positive and negative ranges.
- * PHPExcel follows Excel 2010 behaviour, and accepts nagative arguments.
- *
- * Excel Function:
- * ERF(lower[,upper])
- *
- * @param float $lower lower bound for integrating ERF
- * @param float $upper upper bound for integrating ERF.
- * If omitted, ERF integrates between zero and lower_limit
- * @return float
- */
- public static function ERF($lower, $upper = NULL) {
- $lower = Calculation_Functions::flattenSingleValue($lower);
- $upper = Calculation_Functions::flattenSingleValue($upper);
-
- if (is_numeric($lower)) {
- if (is_null($upper)) {
- return self::_erfVal($lower);
- }
- if (is_numeric($upper)) {
- return self::_erfVal($upper) - self::_erfVal($lower);
- }
- }
- return Calculation_Functions::VALUE();
- } // function ERF()
-
-
- //
- // Private method to calculate the erfc value
- //
- private static $_one_sqrtpi = 0.564189583547756287;
-
- private static function _erfcVal($x) {
- if (abs($x) < 2.2) {
- return 1 - self::_erfVal($x);
- }
- if ($x < 0) {
- return 2 - self::ERFC(-$x);
- }
- $a = $n = 1;
- $b = $c = $x;
- $d = ($x * $x) + 0.5;
- $q1 = $q2 = $b / $d;
- $t = 0;
- do {
- $t = $a * $n + $b * $x;
- $a = $b;
- $b = $t;
- $t = $c * $n + $d * $x;
- $c = $d;
- $d = $t;
- $n += 0.5;
- $q1 = $q2;
- $q2 = $b / $d;
- } while ((abs($q1 - $q2) / $q2) > PRECISION);
- return self::$_one_sqrtpi * exp(-$x * $x) * $q2;
- } // function _erfcVal()
-
-
- /**
- * ERFC
- *
- * Returns the complementary ERF function integrated between x and infinity
- *
- * Note: In Excel 2007 or earlier, if you input a negative value for the lower bound argument,
- * the function would return a #NUM! error. However, in Excel 2010, the function algorithm was
- * improved, so that it can now calculate the function for both positive and negative x values.
- * PHPExcel follows Excel 2010 behaviour, and accepts nagative arguments.
- *
- * Excel Function:
- * ERFC(x)
- *
- * @param float $x The lower bound for integrating ERFC
- * @return float
- */
- public static function ERFC($x) {
- $x = Calculation_Functions::flattenSingleValue($x);
-
- if (is_numeric($x)) {
- return self::_erfcVal($x);
- }
- return Calculation_Functions::VALUE();
- } // function ERFC()
-
-
- /**
- * getConversionGroups
- * Returns a list of the different conversion groups for UOM conversions
- *
- * @return array
- */
- public static function getConversionGroups() {
- $conversionGroups = array();
- foreach(self::$_conversionUnits as $conversionUnit) {
- $conversionGroups[] = $conversionUnit['Group'];
- }
- return array_merge(array_unique($conversionGroups));
- } // function getConversionGroups()
-
-
- /**
- * getConversionGroupUnits
- * Returns an array of units of measure, for a specified conversion group, or for all groups
- *
- * @param string $group The group whose units of measure you want to retrieve
- * @return array
- */
- public static function getConversionGroupUnits($group = NULL) {
- $conversionGroups = array();
- foreach(self::$_conversionUnits as $conversionUnit => $conversionGroup) {
- if ((is_null($group)) || ($conversionGroup['Group'] == $group)) {
- $conversionGroups[$conversionGroup['Group']][] = $conversionUnit;
- }
- }
- return $conversionGroups;
- } // function getConversionGroupUnits()
-
-
- /**
- * getConversionGroupUnitDetails
- *
- * @param string $group The group whose units of measure you want to retrieve
- * @return array
- */
- public static function getConversionGroupUnitDetails($group = NULL) {
- $conversionGroups = array();
- foreach(self::$_conversionUnits as $conversionUnit => $conversionGroup) {
- if ((is_null($group)) || ($conversionGroup['Group'] == $group)) {
- $conversionGroups[$conversionGroup['Group']][] = array( 'unit' => $conversionUnit,
- 'description' => $conversionGroup['Unit Name']
- );
- }
- }
- return $conversionGroups;
- } // function getConversionGroupUnitDetails()
-
-
- /**
- * getConversionMultipliers
- * Returns an array of the Multiplier prefixes that can be used with Units of Measure in CONVERTUOM()
- *
- * @return array of mixed
- */
- public static function getConversionMultipliers() {
- return self::$_conversionMultipliers;
- } // function getConversionGroups()
-
-
- /**
- * CONVERTUOM
- *
- * Converts a number from one measurement system to another.
- * For example, CONVERT can translate a table of distances in miles to a table of distances
- * in kilometers.
- *
- * Excel Function:
- * CONVERT(value,fromUOM,toUOM)
- *
- * @param float $value The value in fromUOM to convert.
- * @param string $fromUOM The units for value.
- * @param string $toUOM The units for the result.
- *
- * @return float
- */
- public static function CONVERTUOM($value, $fromUOM, $toUOM) {
- $value = Calculation_Functions::flattenSingleValue($value);
- $fromUOM = Calculation_Functions::flattenSingleValue($fromUOM);
- $toUOM = Calculation_Functions::flattenSingleValue($toUOM);
-
- if (!is_numeric($value)) {
- return Calculation_Functions::VALUE();
- }
- $fromMultiplier = 1.0;
- if (isset(self::$_conversionUnits[$fromUOM])) {
- $unitGroup1 = self::$_conversionUnits[$fromUOM]['Group'];
- } else {
- $fromMultiplier = substr($fromUOM,0,1);
- $fromUOM = substr($fromUOM,1);
- if (isset(self::$_conversionMultipliers[$fromMultiplier])) {
- $fromMultiplier = self::$_conversionMultipliers[$fromMultiplier]['multiplier'];
- } else {
- return Calculation_Functions::NA();
- }
- if ((isset(self::$_conversionUnits[$fromUOM])) && (self::$_conversionUnits[$fromUOM]['AllowPrefix'])) {
- $unitGroup1 = self::$_conversionUnits[$fromUOM]['Group'];
- } else {
- return Calculation_Functions::NA();
- }
- }
- $value *= $fromMultiplier;
-
- $toMultiplier = 1.0;
- if (isset(self::$_conversionUnits[$toUOM])) {
- $unitGroup2 = self::$_conversionUnits[$toUOM]['Group'];
- } else {
- $toMultiplier = substr($toUOM,0,1);
- $toUOM = substr($toUOM,1);
- if (isset(self::$_conversionMultipliers[$toMultiplier])) {
- $toMultiplier = self::$_conversionMultipliers[$toMultiplier]['multiplier'];
- } else {
- return Calculation_Functions::NA();
- }
- if ((isset(self::$_conversionUnits[$toUOM])) && (self::$_conversionUnits[$toUOM]['AllowPrefix'])) {
- $unitGroup2 = self::$_conversionUnits[$toUOM]['Group'];
- } else {
- return Calculation_Functions::NA();
- }
- }
- if ($unitGroup1 != $unitGroup2) {
- return Calculation_Functions::NA();
- }
-
- if (($fromUOM == $toUOM) && ($fromMultiplier == $toMultiplier)) {
- // We've already factored $fromMultiplier into the value, so we need
- // to reverse it again
- return $value / $fromMultiplier;
- } elseif ($unitGroup1 == 'Temperature') {
- if (($fromUOM == 'F') || ($fromUOM == 'fah')) {
- if (($toUOM == 'F') || ($toUOM == 'fah')) {
- return $value;
- } else {
- $value = (($value - 32) / 1.8);
- if (($toUOM == 'K') || ($toUOM == 'kel')) {
- $value += 273.15;
- }
- return $value;
- }
- } elseif ((($fromUOM == 'K') || ($fromUOM == 'kel')) &&
- (($toUOM == 'K') || ($toUOM == 'kel'))) {
- return $value;
- } elseif ((($fromUOM == 'C') || ($fromUOM == 'cel')) &&
- (($toUOM == 'C') || ($toUOM == 'cel'))) {
- return $value;
- }
- if (($toUOM == 'F') || ($toUOM == 'fah')) {
- if (($fromUOM == 'K') || ($fromUOM == 'kel')) {
- $value -= 273.15;
- }
- return ($value * 1.8) + 32;
- }
- if (($toUOM == 'C') || ($toUOM == 'cel')) {
- return $value - 273.15;
- }
- return $value + 273.15;
- }
- return ($value * self::$_unitConversions[$unitGroup1][$fromUOM][$toUOM]) / $toMultiplier;
- } // function CONVERTUOM()
-
+ /**
+ * Details of the Units of measure that can be used in CONVERTUOM()
+ *
+ * @var mixed[]
+ */
+ private static $_conversionUnits = array( 'g' => array( 'Group' => 'Mass', 'Unit Name' => 'Gram', 'AllowPrefix' => True ),
+ 'sg' => array( 'Group' => 'Mass', 'Unit Name' => 'Slug', 'AllowPrefix' => False ),
+ 'lbm' => array( 'Group' => 'Mass', 'Unit Name' => 'Pound mass (avoirdupois)', 'AllowPrefix' => False ),
+ 'u' => array( 'Group' => 'Mass', 'Unit Name' => 'U (atomic mass unit)', 'AllowPrefix' => True ),
+ 'ozm' => array( 'Group' => 'Mass', 'Unit Name' => 'Ounce mass (avoirdupois)', 'AllowPrefix' => False ),
+ 'm' => array( 'Group' => 'Distance', 'Unit Name' => 'Meter', 'AllowPrefix' => True ),
+ 'mi' => array( 'Group' => 'Distance', 'Unit Name' => 'Statute mile', 'AllowPrefix' => False ),
+ 'Nmi' => array( 'Group' => 'Distance', 'Unit Name' => 'Nautical mile', 'AllowPrefix' => False ),
+ 'in' => array( 'Group' => 'Distance', 'Unit Name' => 'Inch', 'AllowPrefix' => False ),
+ 'ft' => array( 'Group' => 'Distance', 'Unit Name' => 'Foot', 'AllowPrefix' => False ),
+ 'yd' => array( 'Group' => 'Distance', 'Unit Name' => 'Yard', 'AllowPrefix' => False ),
+ 'ang' => array( 'Group' => 'Distance', 'Unit Name' => 'Angstrom', 'AllowPrefix' => True ),
+ 'Pica' => array( 'Group' => 'Distance', 'Unit Name' => 'Pica (1/72 in)', 'AllowPrefix' => False ),
+ 'yr' => array( 'Group' => 'Time', 'Unit Name' => 'Year', 'AllowPrefix' => False ),
+ 'day' => array( 'Group' => 'Time', 'Unit Name' => 'Day', 'AllowPrefix' => False ),
+ 'hr' => array( 'Group' => 'Time', 'Unit Name' => 'Hour', 'AllowPrefix' => False ),
+ 'mn' => array( 'Group' => 'Time', 'Unit Name' => 'Minute', 'AllowPrefix' => False ),
+ 'sec' => array( 'Group' => 'Time', 'Unit Name' => 'Second', 'AllowPrefix' => True ),
+ 'Pa' => array( 'Group' => 'Pressure', 'Unit Name' => 'Pascal', 'AllowPrefix' => True ),
+ 'p' => array( 'Group' => 'Pressure', 'Unit Name' => 'Pascal', 'AllowPrefix' => True ),
+ 'atm' => array( 'Group' => 'Pressure', 'Unit Name' => 'Atmosphere', 'AllowPrefix' => True ),
+ 'at' => array( 'Group' => 'Pressure', 'Unit Name' => 'Atmosphere', 'AllowPrefix' => True ),
+ 'mmHg' => array( 'Group' => 'Pressure', 'Unit Name' => 'mm of Mercury', 'AllowPrefix' => True ),
+ 'N' => array( 'Group' => 'Force', 'Unit Name' => 'Newton', 'AllowPrefix' => True ),
+ 'dyn' => array( 'Group' => 'Force', 'Unit Name' => 'Dyne', 'AllowPrefix' => True ),
+ 'dy' => array( 'Group' => 'Force', 'Unit Name' => 'Dyne', 'AllowPrefix' => True ),
+ 'lbf' => array( 'Group' => 'Force', 'Unit Name' => 'Pound force', 'AllowPrefix' => False ),
+ 'J' => array( 'Group' => 'Energy', 'Unit Name' => 'Joule', 'AllowPrefix' => True ),
+ 'e' => array( 'Group' => 'Energy', 'Unit Name' => 'Erg', 'AllowPrefix' => True ),
+ 'c' => array( 'Group' => 'Energy', 'Unit Name' => 'Thermodynamic calorie', 'AllowPrefix' => True ),
+ 'cal' => array( 'Group' => 'Energy', 'Unit Name' => 'IT calorie', 'AllowPrefix' => True ),
+ 'eV' => array( 'Group' => 'Energy', 'Unit Name' => 'Electron volt', 'AllowPrefix' => True ),
+ 'ev' => array( 'Group' => 'Energy', 'Unit Name' => 'Electron volt', 'AllowPrefix' => True ),
+ 'HPh' => array( 'Group' => 'Energy', 'Unit Name' => 'Horsepower-hour', 'AllowPrefix' => False ),
+ 'hh' => array( 'Group' => 'Energy', 'Unit Name' => 'Horsepower-hour', 'AllowPrefix' => False ),
+ 'Wh' => array( 'Group' => 'Energy', 'Unit Name' => 'Watt-hour', 'AllowPrefix' => True ),
+ 'wh' => array( 'Group' => 'Energy', 'Unit Name' => 'Watt-hour', 'AllowPrefix' => True ),
+ 'flb' => array( 'Group' => 'Energy', 'Unit Name' => 'Foot-pound', 'AllowPrefix' => False ),
+ 'BTU' => array( 'Group' => 'Energy', 'Unit Name' => 'BTU', 'AllowPrefix' => False ),
+ 'btu' => array( 'Group' => 'Energy', 'Unit Name' => 'BTU', 'AllowPrefix' => False ),
+ 'HP' => array( 'Group' => 'Power', 'Unit Name' => 'Horsepower', 'AllowPrefix' => False ),
+ 'h' => array( 'Group' => 'Power', 'Unit Name' => 'Horsepower', 'AllowPrefix' => False ),
+ 'W' => array( 'Group' => 'Power', 'Unit Name' => 'Watt', 'AllowPrefix' => True ),
+ 'w' => array( 'Group' => 'Power', 'Unit Name' => 'Watt', 'AllowPrefix' => True ),
+ 'T' => array( 'Group' => 'Magnetism', 'Unit Name' => 'Tesla', 'AllowPrefix' => True ),
+ 'ga' => array( 'Group' => 'Magnetism', 'Unit Name' => 'Gauss', 'AllowPrefix' => True ),
+ 'C' => array( 'Group' => 'Temperature', 'Unit Name' => 'Celsius', 'AllowPrefix' => False ),
+ 'cel' => array( 'Group' => 'Temperature', 'Unit Name' => 'Celsius', 'AllowPrefix' => False ),
+ 'F' => array( 'Group' => 'Temperature', 'Unit Name' => 'Fahrenheit', 'AllowPrefix' => False ),
+ 'fah' => array( 'Group' => 'Temperature', 'Unit Name' => 'Fahrenheit', 'AllowPrefix' => False ),
+ 'K' => array( 'Group' => 'Temperature', 'Unit Name' => 'Kelvin', 'AllowPrefix' => False ),
+ 'kel' => array( 'Group' => 'Temperature', 'Unit Name' => 'Kelvin', 'AllowPrefix' => False ),
+ 'tsp' => array( 'Group' => 'Liquid', 'Unit Name' => 'Teaspoon', 'AllowPrefix' => False ),
+ 'tbs' => array( 'Group' => 'Liquid', 'Unit Name' => 'Tablespoon', 'AllowPrefix' => False ),
+ 'oz' => array( 'Group' => 'Liquid', 'Unit Name' => 'Fluid Ounce', 'AllowPrefix' => False ),
+ 'cup' => array( 'Group' => 'Liquid', 'Unit Name' => 'Cup', 'AllowPrefix' => False ),
+ 'pt' => array( 'Group' => 'Liquid', 'Unit Name' => 'U.S. Pint', 'AllowPrefix' => False ),
+ 'us_pt' => array( 'Group' => 'Liquid', 'Unit Name' => 'U.S. Pint', 'AllowPrefix' => False ),
+ 'uk_pt' => array( 'Group' => 'Liquid', 'Unit Name' => 'U.K. Pint', 'AllowPrefix' => False ),
+ 'qt' => array( 'Group' => 'Liquid', 'Unit Name' => 'Quart', 'AllowPrefix' => False ),
+ 'gal' => array( 'Group' => 'Liquid', 'Unit Name' => 'Gallon', 'AllowPrefix' => False ),
+ 'l' => array( 'Group' => 'Liquid', 'Unit Name' => 'Litre', 'AllowPrefix' => True ),
+ 'lt' => array( 'Group' => 'Liquid', 'Unit Name' => 'Litre', 'AllowPrefix' => True )
+ );
+
+ /**
+ * Details of the Multiplier prefixes that can be used with Units of Measure in CONVERTUOM()
+ *
+ * @var mixed[]
+ */
+ private static $_conversionMultipliers = array( 'Y' => array( 'multiplier' => 1E24, 'name' => 'yotta' ),
+ 'Z' => array( 'multiplier' => 1E21, 'name' => 'zetta' ),
+ 'E' => array( 'multiplier' => 1E18, 'name' => 'exa' ),
+ 'P' => array( 'multiplier' => 1E15, 'name' => 'peta' ),
+ 'T' => array( 'multiplier' => 1E12, 'name' => 'tera' ),
+ 'G' => array( 'multiplier' => 1E9, 'name' => 'giga' ),
+ 'M' => array( 'multiplier' => 1E6, 'name' => 'mega' ),
+ 'k' => array( 'multiplier' => 1E3, 'name' => 'kilo' ),
+ 'h' => array( 'multiplier' => 1E2, 'name' => 'hecto' ),
+ 'e' => array( 'multiplier' => 1E1, 'name' => 'deka' ),
+ 'd' => array( 'multiplier' => 1E-1, 'name' => 'deci' ),
+ 'c' => array( 'multiplier' => 1E-2, 'name' => 'centi' ),
+ 'm' => array( 'multiplier' => 1E-3, 'name' => 'milli' ),
+ 'u' => array( 'multiplier' => 1E-6, 'name' => 'micro' ),
+ 'n' => array( 'multiplier' => 1E-9, 'name' => 'nano' ),
+ 'p' => array( 'multiplier' => 1E-12, 'name' => 'pico' ),
+ 'f' => array( 'multiplier' => 1E-15, 'name' => 'femto' ),
+ 'a' => array( 'multiplier' => 1E-18, 'name' => 'atto' ),
+ 'z' => array( 'multiplier' => 1E-21, 'name' => 'zepto' ),
+ 'y' => array( 'multiplier' => 1E-24, 'name' => 'yocto' )
+ );
+
+ /**
+ * Details of the Units of measure conversion factors, organised by group
+ *
+ * @var mixed[]
+ */
+ private static $_unitConversions = array( 'Mass' => array( 'g' => array( 'g' => 1.0,
+ 'sg' => 6.85220500053478E-05,
+ 'lbm' => 2.20462291469134E-03,
+ 'u' => 6.02217000000000E+23,
+ 'ozm' => 3.52739718003627E-02
+ ),
+ 'sg' => array( 'g' => 1.45938424189287E+04,
+ 'sg' => 1.0,
+ 'lbm' => 3.21739194101647E+01,
+ 'u' => 8.78866000000000E+27,
+ 'ozm' => 5.14782785944229E+02
+ ),
+ 'lbm' => array( 'g' => 4.5359230974881148E+02,
+ 'sg' => 3.10810749306493E-02,
+ 'lbm' => 1.0,
+ 'u' => 2.73161000000000E+26,
+ 'ozm' => 1.60000023429410E+01
+ ),
+ 'u' => array( 'g' => 1.66053100460465E-24,
+ 'sg' => 1.13782988532950E-28,
+ 'lbm' => 3.66084470330684E-27,
+ 'u' => 1.0,
+ 'ozm' => 5.85735238300524E-26
+ ),
+ 'ozm' => array( 'g' => 2.83495152079732E+01,
+ 'sg' => 1.94256689870811E-03,
+ 'lbm' => 6.24999908478882E-02,
+ 'u' => 1.70725600000000E+25,
+ 'ozm' => 1.0
+ )
+ ),
+ 'Distance' => array( 'm' => array( 'm' => 1.0,
+ 'mi' => 6.21371192237334E-04,
+ 'Nmi' => 5.39956803455724E-04,
+ 'in' => 3.93700787401575E+01,
+ 'ft' => 3.28083989501312E+00,
+ 'yd' => 1.09361329797891E+00,
+ 'ang' => 1.00000000000000E+10,
+ 'Pica' => 2.83464566929116E+03
+ ),
+ 'mi' => array( 'm' => 1.60934400000000E+03,
+ 'mi' => 1.0,
+ 'Nmi' => 8.68976241900648E-01,
+ 'in' => 6.33600000000000E+04,
+ 'ft' => 5.28000000000000E+03,
+ 'yd' => 1.76000000000000E+03,
+ 'ang' => 1.60934400000000E+13,
+ 'Pica' => 4.56191999999971E+06
+ ),
+ 'Nmi' => array( 'm' => 1.85200000000000E+03,
+ 'mi' => 1.15077944802354E+00,
+ 'Nmi' => 1.0,
+ 'in' => 7.29133858267717E+04,
+ 'ft' => 6.07611548556430E+03,
+ 'yd' => 2.02537182785694E+03,
+ 'ang' => 1.85200000000000E+13,
+ 'Pica' => 5.24976377952723E+06
+ ),
+ 'in' => array( 'm' => 2.54000000000000E-02,
+ 'mi' => 1.57828282828283E-05,
+ 'Nmi' => 1.37149028077754E-05,
+ 'in' => 1.0,
+ 'ft' => 8.33333333333333E-02,
+ 'yd' => 2.77777777686643E-02,
+ 'ang' => 2.54000000000000E+08,
+ 'Pica' => 7.19999999999955E+01
+ ),
+ 'ft' => array( 'm' => 3.04800000000000E-01,
+ 'mi' => 1.89393939393939E-04,
+ 'Nmi' => 1.64578833693305E-04,
+ 'in' => 1.20000000000000E+01,
+ 'ft' => 1.0,
+ 'yd' => 3.33333333223972E-01,
+ 'ang' => 3.04800000000000E+09,
+ 'Pica' => 8.63999999999946E+02
+ ),
+ 'yd' => array( 'm' => 9.14400000300000E-01,
+ 'mi' => 5.68181818368230E-04,
+ 'Nmi' => 4.93736501241901E-04,
+ 'in' => 3.60000000118110E+01,
+ 'ft' => 3.00000000000000E+00,
+ 'yd' => 1.0,
+ 'ang' => 9.14400000300000E+09,
+ 'Pica' => 2.59200000085023E+03
+ ),
+ 'ang' => array( 'm' => 1.00000000000000E-10,
+ 'mi' => 6.21371192237334E-14,
+ 'Nmi' => 5.39956803455724E-14,
+ 'in' => 3.93700787401575E-09,
+ 'ft' => 3.28083989501312E-10,
+ 'yd' => 1.09361329797891E-10,
+ 'ang' => 1.0,
+ 'Pica' => 2.83464566929116E-07
+ ),
+ 'Pica' => array( 'm' => 3.52777777777800E-04,
+ 'mi' => 2.19205948372629E-07,
+ 'Nmi' => 1.90484761219114E-07,
+ 'in' => 1.38888888888898E-02,
+ 'ft' => 1.15740740740748E-03,
+ 'yd' => 3.85802469009251E-04,
+ 'ang' => 3.52777777777800E+06,
+ 'Pica' => 1.0
+ )
+ ),
+ 'Time' => array( 'yr' => array( 'yr' => 1.0,
+ 'day' => 365.25,
+ 'hr' => 8766.0,
+ 'mn' => 525960.0,
+ 'sec' => 31557600.0
+ ),
+ 'day' => array( 'yr' => 2.73785078713210E-03,
+ 'day' => 1.0,
+ 'hr' => 24.0,
+ 'mn' => 1440.0,
+ 'sec' => 86400.0
+ ),
+ 'hr' => array( 'yr' => 1.14077116130504E-04,
+ 'day' => 4.16666666666667E-02,
+ 'hr' => 1.0,
+ 'mn' => 60.0,
+ 'sec' => 3600.0
+ ),
+ 'mn' => array( 'yr' => 1.90128526884174E-06,
+ 'day' => 6.94444444444444E-04,
+ 'hr' => 1.66666666666667E-02,
+ 'mn' => 1.0,
+ 'sec' => 60.0
+ ),
+ 'sec' => array( 'yr' => 3.16880878140289E-08,
+ 'day' => 1.15740740740741E-05,
+ 'hr' => 2.77777777777778E-04,
+ 'mn' => 1.66666666666667E-02,
+ 'sec' => 1.0
+ )
+ ),
+ 'Pressure' => array( 'Pa' => array( 'Pa' => 1.0,
+ 'p' => 1.0,
+ 'atm' => 9.86923299998193E-06,
+ 'at' => 9.86923299998193E-06,
+ 'mmHg' => 7.50061707998627E-03
+ ),
+ 'p' => array( 'Pa' => 1.0,
+ 'p' => 1.0,
+ 'atm' => 9.86923299998193E-06,
+ 'at' => 9.86923299998193E-06,
+ 'mmHg' => 7.50061707998627E-03
+ ),
+ 'atm' => array( 'Pa' => 1.01324996583000E+05,
+ 'p' => 1.01324996583000E+05,
+ 'atm' => 1.0,
+ 'at' => 1.0,
+ 'mmHg' => 760.0
+ ),
+ 'at' => array( 'Pa' => 1.01324996583000E+05,
+ 'p' => 1.01324996583000E+05,
+ 'atm' => 1.0,
+ 'at' => 1.0,
+ 'mmHg' => 760.0
+ ),
+ 'mmHg' => array( 'Pa' => 1.33322363925000E+02,
+ 'p' => 1.33322363925000E+02,
+ 'atm' => 1.31578947368421E-03,
+ 'at' => 1.31578947368421E-03,
+ 'mmHg' => 1.0
+ )
+ ),
+ 'Force' => array( 'N' => array( 'N' => 1.0,
+ 'dyn' => 1.0E+5,
+ 'dy' => 1.0E+5,
+ 'lbf' => 2.24808923655339E-01
+ ),
+ 'dyn' => array( 'N' => 1.0E-5,
+ 'dyn' => 1.0,
+ 'dy' => 1.0,
+ 'lbf' => 2.24808923655339E-06
+ ),
+ 'dy' => array( 'N' => 1.0E-5,
+ 'dyn' => 1.0,
+ 'dy' => 1.0,
+ 'lbf' => 2.24808923655339E-06
+ ),
+ 'lbf' => array( 'N' => 4.448222,
+ 'dyn' => 4.448222E+5,
+ 'dy' => 4.448222E+5,
+ 'lbf' => 1.0
+ )
+ ),
+ 'Energy' => array( 'J' => array( 'J' => 1.0,
+ 'e' => 9.99999519343231E+06,
+ 'c' => 2.39006249473467E-01,
+ 'cal' => 2.38846190642017E-01,
+ 'eV' => 6.24145700000000E+18,
+ 'ev' => 6.24145700000000E+18,
+ 'HPh' => 3.72506430801000E-07,
+ 'hh' => 3.72506430801000E-07,
+ 'Wh' => 2.77777916238711E-04,
+ 'wh' => 2.77777916238711E-04,
+ 'flb' => 2.37304222192651E+01,
+ 'BTU' => 9.47815067349015E-04,
+ 'btu' => 9.47815067349015E-04
+ ),
+ 'e' => array( 'J' => 1.00000048065700E-07,
+ 'e' => 1.0,
+ 'c' => 2.39006364353494E-08,
+ 'cal' => 2.38846305445111E-08,
+ 'eV' => 6.24146000000000E+11,
+ 'ev' => 6.24146000000000E+11,
+ 'HPh' => 3.72506609848824E-14,
+ 'hh' => 3.72506609848824E-14,
+ 'Wh' => 2.77778049754611E-11,
+ 'wh' => 2.77778049754611E-11,
+ 'flb' => 2.37304336254586E-06,
+ 'BTU' => 9.47815522922962E-11,
+ 'btu' => 9.47815522922962E-11
+ ),
+ 'c' => array( 'J' => 4.18399101363672E+00,
+ 'e' => 4.18398900257312E+07,
+ 'c' => 1.0,
+ 'cal' => 9.99330315287563E-01,
+ 'eV' => 2.61142000000000E+19,
+ 'ev' => 2.61142000000000E+19,
+ 'HPh' => 1.55856355899327E-06,
+ 'hh' => 1.55856355899327E-06,
+ 'Wh' => 1.16222030532950E-03,
+ 'wh' => 1.16222030532950E-03,
+ 'flb' => 9.92878733152102E+01,
+ 'BTU' => 3.96564972437776E-03,
+ 'btu' => 3.96564972437776E-03
+ ),
+ 'cal' => array( 'J' => 4.18679484613929E+00,
+ 'e' => 4.18679283372801E+07,
+ 'c' => 1.00067013349059E+00,
+ 'cal' => 1.0,
+ 'eV' => 2.61317000000000E+19,
+ 'ev' => 2.61317000000000E+19,
+ 'HPh' => 1.55960800463137E-06,
+ 'hh' => 1.55960800463137E-06,
+ 'Wh' => 1.16299914807955E-03,
+ 'wh' => 1.16299914807955E-03,
+ 'flb' => 9.93544094443283E+01,
+ 'BTU' => 3.96830723907002E-03,
+ 'btu' => 3.96830723907002E-03
+ ),
+ 'eV' => array( 'J' => 1.60219000146921E-19,
+ 'e' => 1.60218923136574E-12,
+ 'c' => 3.82933423195043E-20,
+ 'cal' => 3.82676978535648E-20,
+ 'eV' => 1.0,
+ 'ev' => 1.0,
+ 'HPh' => 5.96826078912344E-26,
+ 'hh' => 5.96826078912344E-26,
+ 'Wh' => 4.45053000026614E-23,
+ 'wh' => 4.45053000026614E-23,
+ 'flb' => 3.80206452103492E-18,
+ 'BTU' => 1.51857982414846E-22,
+ 'btu' => 1.51857982414846E-22
+ ),
+ 'ev' => array( 'J' => 1.60219000146921E-19,
+ 'e' => 1.60218923136574E-12,
+ 'c' => 3.82933423195043E-20,
+ 'cal' => 3.82676978535648E-20,
+ 'eV' => 1.0,
+ 'ev' => 1.0,
+ 'HPh' => 5.96826078912344E-26,
+ 'hh' => 5.96826078912344E-26,
+ 'Wh' => 4.45053000026614E-23,
+ 'wh' => 4.45053000026614E-23,
+ 'flb' => 3.80206452103492E-18,
+ 'BTU' => 1.51857982414846E-22,
+ 'btu' => 1.51857982414846E-22
+ ),
+ 'HPh' => array( 'J' => 2.68451741316170E+06,
+ 'e' => 2.68451612283024E+13,
+ 'c' => 6.41616438565991E+05,
+ 'cal' => 6.41186757845835E+05,
+ 'eV' => 1.67553000000000E+25,
+ 'ev' => 1.67553000000000E+25,
+ 'HPh' => 1.0,
+ 'hh' => 1.0,
+ 'Wh' => 7.45699653134593E+02,
+ 'wh' => 7.45699653134593E+02,
+ 'flb' => 6.37047316692964E+07,
+ 'BTU' => 2.54442605275546E+03,
+ 'btu' => 2.54442605275546E+03
+ ),
+ 'hh' => array( 'J' => 2.68451741316170E+06,
+ 'e' => 2.68451612283024E+13,
+ 'c' => 6.41616438565991E+05,
+ 'cal' => 6.41186757845835E+05,
+ 'eV' => 1.67553000000000E+25,
+ 'ev' => 1.67553000000000E+25,
+ 'HPh' => 1.0,
+ 'hh' => 1.0,
+ 'Wh' => 7.45699653134593E+02,
+ 'wh' => 7.45699653134593E+02,
+ 'flb' => 6.37047316692964E+07,
+ 'BTU' => 2.54442605275546E+03,
+ 'btu' => 2.54442605275546E+03
+ ),
+ 'Wh' => array( 'J' => 3.59999820554720E+03,
+ 'e' => 3.59999647518369E+10,
+ 'c' => 8.60422069219046E+02,
+ 'cal' => 8.59845857713046E+02,
+ 'eV' => 2.24692340000000E+22,
+ 'ev' => 2.24692340000000E+22,
+ 'HPh' => 1.34102248243839E-03,
+ 'hh' => 1.34102248243839E-03,
+ 'Wh' => 1.0,
+ 'wh' => 1.0,
+ 'flb' => 8.54294774062316E+04,
+ 'BTU' => 3.41213254164705E+00,
+ 'btu' => 3.41213254164705E+00
+ ),
+ 'wh' => array( 'J' => 3.59999820554720E+03,
+ 'e' => 3.59999647518369E+10,
+ 'c' => 8.60422069219046E+02,
+ 'cal' => 8.59845857713046E+02,
+ 'eV' => 2.24692340000000E+22,
+ 'ev' => 2.24692340000000E+22,
+ 'HPh' => 1.34102248243839E-03,
+ 'hh' => 1.34102248243839E-03,
+ 'Wh' => 1.0,
+ 'wh' => 1.0,
+ 'flb' => 8.54294774062316E+04,
+ 'BTU' => 3.41213254164705E+00,
+ 'btu' => 3.41213254164705E+00
+ ),
+ 'flb' => array( 'J' => 4.21400003236424E-02,
+ 'e' => 4.21399800687660E+05,
+ 'c' => 1.00717234301644E-02,
+ 'cal' => 1.00649785509554E-02,
+ 'eV' => 2.63015000000000E+17,
+ 'ev' => 2.63015000000000E+17,
+ 'HPh' => 1.56974211145130E-08,
+ 'hh' => 1.56974211145130E-08,
+ 'Wh' => 1.17055614802000E-05,
+ 'wh' => 1.17055614802000E-05,
+ 'flb' => 1.0,
+ 'BTU' => 3.99409272448406E-05,
+ 'btu' => 3.99409272448406E-05
+ ),
+ 'BTU' => array( 'J' => 1.05505813786749E+03,
+ 'e' => 1.05505763074665E+10,
+ 'c' => 2.52165488508168E+02,
+ 'cal' => 2.51996617135510E+02,
+ 'eV' => 6.58510000000000E+21,
+ 'ev' => 6.58510000000000E+21,
+ 'HPh' => 3.93015941224568E-04,
+ 'hh' => 3.93015941224568E-04,
+ 'Wh' => 2.93071851047526E-01,
+ 'wh' => 2.93071851047526E-01,
+ 'flb' => 2.50369750774671E+04,
+ 'BTU' => 1.0,
+ 'btu' => 1.0,
+ ),
+ 'btu' => array( 'J' => 1.05505813786749E+03,
+ 'e' => 1.05505763074665E+10,
+ 'c' => 2.52165488508168E+02,
+ 'cal' => 2.51996617135510E+02,
+ 'eV' => 6.58510000000000E+21,
+ 'ev' => 6.58510000000000E+21,
+ 'HPh' => 3.93015941224568E-04,
+ 'hh' => 3.93015941224568E-04,
+ 'Wh' => 2.93071851047526E-01,
+ 'wh' => 2.93071851047526E-01,
+ 'flb' => 2.50369750774671E+04,
+ 'BTU' => 1.0,
+ 'btu' => 1.0,
+ )
+ ),
+ 'Power' => array( 'HP' => array( 'HP' => 1.0,
+ 'h' => 1.0,
+ 'W' => 7.45701000000000E+02,
+ 'w' => 7.45701000000000E+02
+ ),
+ 'h' => array( 'HP' => 1.0,
+ 'h' => 1.0,
+ 'W' => 7.45701000000000E+02,
+ 'w' => 7.45701000000000E+02
+ ),
+ 'W' => array( 'HP' => 1.34102006031908E-03,
+ 'h' => 1.34102006031908E-03,
+ 'W' => 1.0,
+ 'w' => 1.0
+ ),
+ 'w' => array( 'HP' => 1.34102006031908E-03,
+ 'h' => 1.34102006031908E-03,
+ 'W' => 1.0,
+ 'w' => 1.0
+ )
+ ),
+ 'Magnetism' => array( 'T' => array( 'T' => 1.0,
+ 'ga' => 10000.0
+ ),
+ 'ga' => array( 'T' => 0.0001,
+ 'ga' => 1.0
+ )
+ ),
+ 'Liquid' => array( 'tsp' => array( 'tsp' => 1.0,
+ 'tbs' => 3.33333333333333E-01,
+ 'oz' => 1.66666666666667E-01,
+ 'cup' => 2.08333333333333E-02,
+ 'pt' => 1.04166666666667E-02,
+ 'us_pt' => 1.04166666666667E-02,
+ 'uk_pt' => 8.67558516821960E-03,
+ 'qt' => 5.20833333333333E-03,
+ 'gal' => 1.30208333333333E-03,
+ 'l' => 4.92999408400710E-03,
+ 'lt' => 4.92999408400710E-03
+ ),
+ 'tbs' => array( 'tsp' => 3.00000000000000E+00,
+ 'tbs' => 1.0,
+ 'oz' => 5.00000000000000E-01,
+ 'cup' => 6.25000000000000E-02,
+ 'pt' => 3.12500000000000E-02,
+ 'us_pt' => 3.12500000000000E-02,
+ 'uk_pt' => 2.60267555046588E-02,
+ 'qt' => 1.56250000000000E-02,
+ 'gal' => 3.90625000000000E-03,
+ 'l' => 1.47899822520213E-02,
+ 'lt' => 1.47899822520213E-02
+ ),
+ 'oz' => array( 'tsp' => 6.00000000000000E+00,
+ 'tbs' => 2.00000000000000E+00,
+ 'oz' => 1.0,
+ 'cup' => 1.25000000000000E-01,
+ 'pt' => 6.25000000000000E-02,
+ 'us_pt' => 6.25000000000000E-02,
+ 'uk_pt' => 5.20535110093176E-02,
+ 'qt' => 3.12500000000000E-02,
+ 'gal' => 7.81250000000000E-03,
+ 'l' => 2.95799645040426E-02,
+ 'lt' => 2.95799645040426E-02
+ ),
+ 'cup' => array( 'tsp' => 4.80000000000000E+01,
+ 'tbs' => 1.60000000000000E+01,
+ 'oz' => 8.00000000000000E+00,
+ 'cup' => 1.0,
+ 'pt' => 5.00000000000000E-01,
+ 'us_pt' => 5.00000000000000E-01,
+ 'uk_pt' => 4.16428088074541E-01,
+ 'qt' => 2.50000000000000E-01,
+ 'gal' => 6.25000000000000E-02,
+ 'l' => 2.36639716032341E-01,
+ 'lt' => 2.36639716032341E-01
+ ),
+ 'pt' => array( 'tsp' => 9.60000000000000E+01,
+ 'tbs' => 3.20000000000000E+01,
+ 'oz' => 1.60000000000000E+01,
+ 'cup' => 2.00000000000000E+00,
+ 'pt' => 1.0,
+ 'us_pt' => 1.0,
+ 'uk_pt' => 8.32856176149081E-01,
+ 'qt' => 5.00000000000000E-01,
+ 'gal' => 1.25000000000000E-01,
+ 'l' => 4.73279432064682E-01,
+ 'lt' => 4.73279432064682E-01
+ ),
+ 'us_pt' => array( 'tsp' => 9.60000000000000E+01,
+ 'tbs' => 3.20000000000000E+01,
+ 'oz' => 1.60000000000000E+01,
+ 'cup' => 2.00000000000000E+00,
+ 'pt' => 1.0,
+ 'us_pt' => 1.0,
+ 'uk_pt' => 8.32856176149081E-01,
+ 'qt' => 5.00000000000000E-01,
+ 'gal' => 1.25000000000000E-01,
+ 'l' => 4.73279432064682E-01,
+ 'lt' => 4.73279432064682E-01
+ ),
+ 'uk_pt' => array( 'tsp' => 1.15266000000000E+02,
+ 'tbs' => 3.84220000000000E+01,
+ 'oz' => 1.92110000000000E+01,
+ 'cup' => 2.40137500000000E+00,
+ 'pt' => 1.20068750000000E+00,
+ 'us_pt' => 1.20068750000000E+00,
+ 'uk_pt' => 1.0,
+ 'qt' => 6.00343750000000E-01,
+ 'gal' => 1.50085937500000E-01,
+ 'l' => 5.68260698087162E-01,
+ 'lt' => 5.68260698087162E-01
+ ),
+ 'qt' => array( 'tsp' => 1.92000000000000E+02,
+ 'tbs' => 6.40000000000000E+01,
+ 'oz' => 3.20000000000000E+01,
+ 'cup' => 4.00000000000000E+00,
+ 'pt' => 2.00000000000000E+00,
+ 'us_pt' => 2.00000000000000E+00,
+ 'uk_pt' => 1.66571235229816E+00,
+ 'qt' => 1.0,
+ 'gal' => 2.50000000000000E-01,
+ 'l' => 9.46558864129363E-01,
+ 'lt' => 9.46558864129363E-01
+ ),
+ 'gal' => array( 'tsp' => 7.68000000000000E+02,
+ 'tbs' => 2.56000000000000E+02,
+ 'oz' => 1.28000000000000E+02,
+ 'cup' => 1.60000000000000E+01,
+ 'pt' => 8.00000000000000E+00,
+ 'us_pt' => 8.00000000000000E+00,
+ 'uk_pt' => 6.66284940919265E+00,
+ 'qt' => 4.00000000000000E+00,
+ 'gal' => 1.0,
+ 'l' => 3.78623545651745E+00,
+ 'lt' => 3.78623545651745E+00
+ ),
+ 'l' => array( 'tsp' => 2.02840000000000E+02,
+ 'tbs' => 6.76133333333333E+01,
+ 'oz' => 3.38066666666667E+01,
+ 'cup' => 4.22583333333333E+00,
+ 'pt' => 2.11291666666667E+00,
+ 'us_pt' => 2.11291666666667E+00,
+ 'uk_pt' => 1.75975569552166E+00,
+ 'qt' => 1.05645833333333E+00,
+ 'gal' => 2.64114583333333E-01,
+ 'l' => 1.0,
+ 'lt' => 1.0
+ ),
+ 'lt' => array( 'tsp' => 2.02840000000000E+02,
+ 'tbs' => 6.76133333333333E+01,
+ 'oz' => 3.38066666666667E+01,
+ 'cup' => 4.22583333333333E+00,
+ 'pt' => 2.11291666666667E+00,
+ 'us_pt' => 2.11291666666667E+00,
+ 'uk_pt' => 1.75975569552166E+00,
+ 'qt' => 1.05645833333333E+00,
+ 'gal' => 2.64114583333333E-01,
+ 'l' => 1.0,
+ 'lt' => 1.0
+ )
+ )
+ );
+
+
+ /**
+ * _parseComplex
+ *
+ * Parses a complex number into its real and imaginary parts, and an I or J suffix
+ *
+ * @param string $complexNumber The complex number
+ * @return string[] Indexed on "real", "imaginary" and "suffix"
+ */
+ public static function _parseComplex($complexNumber) {
+ $workString = (string) $complexNumber;
+
+ $realNumber = $imaginary = 0;
+ // Extract the suffix, if there is one
+ $suffix = substr($workString,-1);
+ if (!is_numeric($suffix)) {
+ $workString = substr($workString,0,-1);
+ } else {
+ $suffix = '';
+ }
+
+ // Split the input into its Real and Imaginary components
+ $leadingSign = 0;
+ if (strlen($workString) > 0) {
+ $leadingSign = (($workString{0} == '+') || ($workString{0} == '-')) ? 1 : 0;
+ }
+ $power = '';
+ $realNumber = strtok($workString, '+-');
+ if (strtoupper(substr($realNumber,-1)) == 'E') {
+ $power = strtok('+-');
+ ++$leadingSign;
+ }
+
+ $realNumber = substr($workString,0,strlen($realNumber)+strlen($power)+$leadingSign);
+
+ if ($suffix != '') {
+ $imaginary = substr($workString,strlen($realNumber));
+
+ if (($imaginary == '') && (($realNumber == '') || ($realNumber == '+') || ($realNumber == '-'))) {
+ $imaginary = $realNumber.'1';
+ $realNumber = '0';
+ } else if ($imaginary == '') {
+ $imaginary = $realNumber;
+ $realNumber = '0';
+ } elseif (($imaginary == '+') || ($imaginary == '-')) {
+ $imaginary .= '1';
+ }
+ }
+
+ return array( 'real' => $realNumber,
+ 'imaginary' => $imaginary,
+ 'suffix' => $suffix
+ );
+ } // function _parseComplex()
+
+
+ /**
+ * Cleans the leading characters in a complex number string
+ *
+ * @param string $complexNumber The complex number to clean
+ * @return string The "cleaned" complex number
+ */
+ private static function _cleanComplex($complexNumber) {
+ if ($complexNumber{0} == '+') $complexNumber = substr($complexNumber,1);
+ if ($complexNumber{0} == '0') $complexNumber = substr($complexNumber,1);
+ if ($complexNumber{0} == '.') $complexNumber = '0'.$complexNumber;
+ if ($complexNumber{0} == '+') $complexNumber = substr($complexNumber,1);
+ return $complexNumber;
+ }
+
+ /**
+ * Formats a number base string value with leading zeroes
+ *
+ * @param string $xVal The "number" to pad
+ * @param integer $places The length that we want to pad this value
+ * @return string The padded "number"
+ */
+ private static function _nbrConversionFormat($xVal, $places) {
+ if (!is_null($places)) {
+ if (strlen($xVal) <= $places) {
+ return substr(str_pad($xVal, $places, '0', STR_PAD_LEFT), -10);
+ } else {
+ return Calculation_Functions::NaN();
+ }
+ }
+
+ return substr($xVal, -10);
+ } // function _nbrConversionFormat()
+
+ /**
+ * BESSELI
+ *
+ * Returns the modified Bessel function In(x), which is equivalent to the Bessel function evaluated
+ * for purely imaginary arguments
+ *
+ * Excel Function:
+ * BESSELI(x,ord)
+ *
+ * @access public
+ * @category Engineering Functions
+ * @param float $x The value at which to evaluate the function.
+ * If x is nonnumeric, BESSELI returns the #VALUE! error value.
+ * @param integer $ord The order of the Bessel function.
+ * If ord is not an integer, it is truncated.
+ * If $ord is nonnumeric, BESSELI returns the #VALUE! error value.
+ * If $ord < 0, BESSELI returns the #NUM! error value.
+ * @return float
+ *
+ */
+ public static function BESSELI($x, $ord) {
+ $x = (is_null($x)) ? 0.0 : Calculation_Functions::flattenSingleValue($x);
+ $ord = (is_null($ord)) ? 0.0 : Calculation_Functions::flattenSingleValue($ord);
+
+ if ((is_numeric($x)) && (is_numeric($ord))) {
+ $ord = floor($ord);
+ if ($ord < 0) {
+ return Calculation_Functions::NaN();
+ }
+
+ if (abs($x) <= 30) {
+ $fResult = $fTerm = pow($x / 2, $ord) / Calculation_MathTrig::FACT($ord);
+ $ordK = 1;
+ $fSqrX = ($x * $x) / 4;
+ do {
+ $fTerm *= $fSqrX;
+ $fTerm /= ($ordK * ($ordK + $ord));
+ $fResult += $fTerm;
+ } while ((abs($fTerm) > 1e-12) && (++$ordK < 100));
+ } else {
+ $f_2_PI = 2 * M_PI;
+
+ $fXAbs = abs($x);
+ $fResult = exp($fXAbs) / sqrt($f_2_PI * $fXAbs);
+ if (($ord & 1) && ($x < 0)) {
+ $fResult = -$fResult;
+ }
+ }
+ return (is_nan($fResult)) ? Calculation_Functions::NaN() : $fResult;
+ }
+ return Calculation_Functions::VALUE();
+ } // function BESSELI()
+
+
+ /**
+ * BESSELJ
+ *
+ * Returns the Bessel function
+ *
+ * Excel Function:
+ * BESSELJ(x,ord)
+ *
+ * @access public
+ * @category Engineering Functions
+ * @param float $x The value at which to evaluate the function.
+ * If x is nonnumeric, BESSELJ returns the #VALUE! error value.
+ * @param integer $ord The order of the Bessel function. If n is not an integer, it is truncated.
+ * If $ord is nonnumeric, BESSELJ returns the #VALUE! error value.
+ * If $ord < 0, BESSELJ returns the #NUM! error value.
+ * @return float
+ *
+ */
+ public static function BESSELJ($x, $ord) {
+ $x = (is_null($x)) ? 0.0 : Calculation_Functions::flattenSingleValue($x);
+ $ord = (is_null($ord)) ? 0.0 : Calculation_Functions::flattenSingleValue($ord);
+
+ if ((is_numeric($x)) && (is_numeric($ord))) {
+ $ord = floor($ord);
+ if ($ord < 0) {
+ return Calculation_Functions::NaN();
+ }
+
+ $fResult = 0;
+ if (abs($x) <= 30) {
+ $fResult = $fTerm = pow($x / 2, $ord) / Calculation_MathTrig::FACT($ord);
+ $ordK = 1;
+ $fSqrX = ($x * $x) / -4;
+ do {
+ $fTerm *= $fSqrX;
+ $fTerm /= ($ordK * ($ordK + $ord));
+ $fResult += $fTerm;
+ } while ((abs($fTerm) > 1e-12) && (++$ordK < 100));
+ } else {
+ $f_PI_DIV_2 = M_PI / 2;
+ $f_PI_DIV_4 = M_PI / 4;
+
+ $fXAbs = abs($x);
+ $fResult = sqrt(M_2DIVPI / $fXAbs) * cos($fXAbs - $ord * $f_PI_DIV_2 - $f_PI_DIV_4);
+ if (($ord & 1) && ($x < 0)) {
+ $fResult = -$fResult;
+ }
+ }
+ return (is_nan($fResult)) ? Calculation_Functions::NaN() : $fResult;
+ }
+ return Calculation_Functions::VALUE();
+ } // function BESSELJ()
+
+
+ private static function _Besselk0($fNum) {
+ if ($fNum <= 2) {
+ $fNum2 = $fNum * 0.5;
+ $y = ($fNum2 * $fNum2);
+ $fRet = -log($fNum2) * self::BESSELI($fNum, 0) +
+ (-0.57721566 + $y * (0.42278420 + $y * (0.23069756 + $y * (0.3488590e-1 + $y * (0.262698e-2 + $y *
+ (0.10750e-3 + $y * 0.74e-5))))));
+ } else {
+ $y = 2 / $fNum;
+ $fRet = exp(-$fNum) / sqrt($fNum) *
+ (1.25331414 + $y * (-0.7832358e-1 + $y * (0.2189568e-1 + $y * (-0.1062446e-1 + $y *
+ (0.587872e-2 + $y * (-0.251540e-2 + $y * 0.53208e-3))))));
+ }
+ return $fRet;
+ } // function _Besselk0()
+
+
+ private static function _Besselk1($fNum) {
+ if ($fNum <= 2) {
+ $fNum2 = $fNum * 0.5;
+ $y = ($fNum2 * $fNum2);
+ $fRet = log($fNum2) * self::BESSELI($fNum, 1) +
+ (1 + $y * (0.15443144 + $y * (-0.67278579 + $y * (-0.18156897 + $y * (-0.1919402e-1 + $y *
+ (-0.110404e-2 + $y * (-0.4686e-4))))))) / $fNum;
+ } else {
+ $y = 2 / $fNum;
+ $fRet = exp(-$fNum) / sqrt($fNum) *
+ (1.25331414 + $y * (0.23498619 + $y * (-0.3655620e-1 + $y * (0.1504268e-1 + $y * (-0.780353e-2 + $y *
+ (0.325614e-2 + $y * (-0.68245e-3)))))));
+ }
+ return $fRet;
+ } // function _Besselk1()
+
+
+ /**
+ * BESSELK
+ *
+ * Returns the modified Bessel function Kn(x), which is equivalent to the Bessel functions evaluated
+ * for purely imaginary arguments.
+ *
+ * Excel Function:
+ * BESSELK(x,ord)
+ *
+ * @access public
+ * @category Engineering Functions
+ * @param float $x The value at which to evaluate the function.
+ * If x is nonnumeric, BESSELK returns the #VALUE! error value.
+ * @param integer $ord The order of the Bessel function. If n is not an integer, it is truncated.
+ * If $ord is nonnumeric, BESSELK returns the #VALUE! error value.
+ * If $ord < 0, BESSELK returns the #NUM! error value.
+ * @return float
+ *
+ */
+ public static function BESSELK($x, $ord) {
+ $x = (is_null($x)) ? 0.0 : Calculation_Functions::flattenSingleValue($x);
+ $ord = (is_null($ord)) ? 0.0 : Calculation_Functions::flattenSingleValue($ord);
+
+ if ((is_numeric($x)) && (is_numeric($ord))) {
+ if (($ord < 0) || ($x == 0.0)) {
+ return Calculation_Functions::NaN();
+ }
+
+ switch(floor($ord)) {
+ case 0 : return self::_Besselk0($x);
+ break;
+ case 1 : return self::_Besselk1($x);
+ break;
+ default : $fTox = 2 / $x;
+ $fBkm = self::_Besselk0($x);
+ $fBk = self::_Besselk1($x);
+ for ($n = 1; $n < $ord; ++$n) {
+ $fBkp = $fBkm + $n * $fTox * $fBk;
+ $fBkm = $fBk;
+ $fBk = $fBkp;
+ }
+ }
+ return (is_nan($fBk)) ? Calculation_Functions::NaN() : $fBk;
+ }
+ return Calculation_Functions::VALUE();
+ } // function BESSELK()
+
+
+ private static function _Bessely0($fNum) {
+ if ($fNum < 8.0) {
+ $y = ($fNum * $fNum);
+ $f1 = -2957821389.0 + $y * (7062834065.0 + $y * (-512359803.6 + $y * (10879881.29 + $y * (-86327.92757 + $y * 228.4622733))));
+ $f2 = 40076544269.0 + $y * (745249964.8 + $y * (7189466.438 + $y * (47447.26470 + $y * (226.1030244 + $y))));
+ $fRet = $f1 / $f2 + 0.636619772 * self::BESSELJ($fNum, 0) * log($fNum);
+ } else {
+ $z = 8.0 / $fNum;
+ $y = ($z * $z);
+ $xx = $fNum - 0.785398164;
+ $f1 = 1 + $y * (-0.1098628627e-2 + $y * (0.2734510407e-4 + $y * (-0.2073370639e-5 + $y * 0.2093887211e-6)));
+ $f2 = -0.1562499995e-1 + $y * (0.1430488765e-3 + $y * (-0.6911147651e-5 + $y * (0.7621095161e-6 + $y * (-0.934945152e-7))));
+ $fRet = sqrt(0.636619772 / $fNum) * (sin($xx) * $f1 + $z * cos($xx) * $f2);
+ }
+ return $fRet;
+ } // function _Bessely0()
+
+
+ private static function _Bessely1($fNum) {
+ if ($fNum < 8.0) {
+ $y = ($fNum * $fNum);
+ $f1 = $fNum * (-0.4900604943e13 + $y * (0.1275274390e13 + $y * (-0.5153438139e11 + $y * (0.7349264551e9 + $y *
+ (-0.4237922726e7 + $y * 0.8511937935e4)))));
+ $f2 = 0.2499580570e14 + $y * (0.4244419664e12 + $y * (0.3733650367e10 + $y * (0.2245904002e8 + $y *
+ (0.1020426050e6 + $y * (0.3549632885e3 + $y)))));
+ $fRet = $f1 / $f2 + 0.636619772 * ( self::BESSELJ($fNum, 1) * log($fNum) - 1 / $fNum);
+ } else {
+ $fRet = sqrt(0.636619772 / $fNum) * sin($fNum - 2.356194491);
+ }
+ return $fRet;
+ } // function _Bessely1()
+
+
+ /**
+ * BESSELY
+ *
+ * Returns the Bessel function, which is also called the Weber function or the Neumann function.
+ *
+ * Excel Function:
+ * BESSELY(x,ord)
+ *
+ * @access public
+ * @category Engineering Functions
+ * @param float $x The value at which to evaluate the function.
+ * If x is nonnumeric, BESSELK returns the #VALUE! error value.
+ * @param integer $ord The order of the Bessel function. If n is not an integer, it is truncated.
+ * If $ord is nonnumeric, BESSELK returns the #VALUE! error value.
+ * If $ord < 0, BESSELK returns the #NUM! error value.
+ *
+ * @return float
+ */
+ public static function BESSELY($x, $ord) {
+ $x = (is_null($x)) ? 0.0 : Calculation_Functions::flattenSingleValue($x);
+ $ord = (is_null($ord)) ? 0.0 : Calculation_Functions::flattenSingleValue($ord);
+
+ if ((is_numeric($x)) && (is_numeric($ord))) {
+ if (($ord < 0) || ($x == 0.0)) {
+ return Calculation_Functions::NaN();
+ }
+
+ switch(floor($ord)) {
+ case 0 : return self::_Bessely0($x);
+ break;
+ case 1 : return self::_Bessely1($x);
+ break;
+ default: $fTox = 2 / $x;
+ $fBym = self::_Bessely0($x);
+ $fBy = self::_Bessely1($x);
+ for ($n = 1; $n < $ord; ++$n) {
+ $fByp = $n * $fTox * $fBy - $fBym;
+ $fBym = $fBy;
+ $fBy = $fByp;
+ }
+ }
+ return (is_nan($fBy)) ? Calculation_Functions::NaN() : $fBy;
+ }
+ return Calculation_Functions::VALUE();
+ } // function BESSELY()
+
+
+ /**
+ * BINTODEC
+ *
+ * Return a binary value as decimal.
+ *
+ * Excel Function:
+ * BIN2DEC(x)
+ *
+ * @access public
+ * @category Engineering Functions
+ * @param string $x The binary number (as a string) that you want to convert. The number
+ * cannot contain more than 10 characters (10 bits). The most significant
+ * bit of number is the sign bit. The remaining 9 bits are magnitude bits.
+ * Negative numbers are represented using two's-complement notation.
+ * If number is not a valid binary number, or if number contains more than
+ * 10 characters (10 bits), BIN2DEC returns the #NUM! error value.
+ * @return string
+ */
+ public static function BINTODEC($x) {
+ $x = Calculation_Functions::flattenSingleValue($x);
+
+ if (is_bool($x)) {
+ if (Calculation_Functions::getCompatibilityMode() == Calculation_Functions::COMPATIBILITY_OPENOFFICE) {
+ $x = (int) $x;
+ } else {
+ return Calculation_Functions::VALUE();
+ }
+ }
+ if (Calculation_Functions::getCompatibilityMode() == Calculation_Functions::COMPATIBILITY_GNUMERIC) {
+ $x = floor($x);
+ }
+ $x = (string) $x;
+ if (strlen($x) > preg_match_all('/[01]/',$x,$out)) {
+ return Calculation_Functions::NaN();
+ }
+ if (strlen($x) > 10) {
+ return Calculation_Functions::NaN();
+ } elseif (strlen($x) == 10) {
+ // Two's Complement
+ $x = substr($x,-9);
+ return '-'.(512-bindec($x));
+ }
+ return bindec($x);
+ } // function BINTODEC()
+
+
+ /**
+ * BINTOHEX
+ *
+ * Return a binary value as hex.
+ *
+ * Excel Function:
+ * BIN2HEX(x[,places])
+ *
+ * @access public
+ * @category Engineering Functions
+ * @param string $x The binary number (as a string) that you want to convert. The number
+ * cannot contain more than 10 characters (10 bits). The most significant
+ * bit of number is the sign bit. The remaining 9 bits are magnitude bits.
+ * Negative numbers are represented using two's-complement notation.
+ * If number is not a valid binary number, or if number contains more than
+ * 10 characters (10 bits), BIN2HEX returns the #NUM! error value.
+ * @param integer $places The number of characters to use. If places is omitted, BIN2HEX uses the
+ * minimum number of characters necessary. Places is useful for padding the
+ * return value with leading 0s (zeros).
+ * If places is not an integer, it is truncated.
+ * If places is nonnumeric, BIN2HEX returns the #VALUE! error value.
+ * If places is negative, BIN2HEX returns the #NUM! error value.
+ * @return string
+ */
+ public static function BINTOHEX($x, $places=null) {
+ $x = Calculation_Functions::flattenSingleValue($x);
+ $places = Calculation_Functions::flattenSingleValue($places);
+
+ if (is_bool($x)) {
+ if (Calculation_Functions::getCompatibilityMode() == Calculation_Functions::COMPATIBILITY_OPENOFFICE) {
+ $x = (int) $x;
+ } else {
+ return Calculation_Functions::VALUE();
+ }
+ }
+ if (Calculation_Functions::getCompatibilityMode() == Calculation_Functions::COMPATIBILITY_GNUMERIC) {
+ $x = floor($x);
+ }
+ $x = (string) $x;
+ if (strlen($x) > preg_match_all('/[01]/',$x,$out)) {
+ return Calculation_Functions::NaN();
+ }
+ if (strlen($x) > 10) {
+ return Calculation_Functions::NaN();
+ } elseif (strlen($x) == 10) {
+ // Two's Complement
+ return str_repeat('F',8).substr(strtoupper(dechex(bindec(substr($x,-9)))),-2);
+ }
+ $hexVal = (string) strtoupper(dechex(bindec($x)));
+
+ return self::_nbrConversionFormat($hexVal,$places);
+ } // function BINTOHEX()
+
+
+ /**
+ * BINTOOCT
+ *
+ * Return a binary value as octal.
+ *
+ * Excel Function:
+ * BIN2OCT(x[,places])
+ *
+ * @access public
+ * @category Engineering Functions
+ * @param string $x The binary number (as a string) that you want to convert. The number
+ * cannot contain more than 10 characters (10 bits). The most significant
+ * bit of number is the sign bit. The remaining 9 bits are magnitude bits.
+ * Negative numbers are represented using two's-complement notation.
+ * If number is not a valid binary number, or if number contains more than
+ * 10 characters (10 bits), BIN2OCT returns the #NUM! error value.
+ * @param integer $places The number of characters to use. If places is omitted, BIN2OCT uses the
+ * minimum number of characters necessary. Places is useful for padding the
+ * return value with leading 0s (zeros).
+ * If places is not an integer, it is truncated.
+ * If places is nonnumeric, BIN2OCT returns the #VALUE! error value.
+ * If places is negative, BIN2OCT returns the #NUM! error value.
+ * @return string
+ */
+ public static function BINTOOCT($x, $places=null) {
+ $x = Calculation_Functions::flattenSingleValue($x);
+ $places = Calculation_Functions::flattenSingleValue($places);
+
+ if (is_bool($x)) {
+ if (Calculation_Functions::getCompatibilityMode() == Calculation_Functions::COMPATIBILITY_OPENOFFICE) {
+ $x = (int) $x;
+ } else {
+ return Calculation_Functions::VALUE();
+ }
+ }
+ if (Calculation_Functions::getCompatibilityMode() == Calculation_Functions::COMPATIBILITY_GNUMERIC) {
+ $x = floor($x);
+ }
+ $x = (string) $x;
+ if (strlen($x) > preg_match_all('/[01]/',$x,$out)) {
+ return Calculation_Functions::NaN();
+ }
+ if (strlen($x) > 10) {
+ return Calculation_Functions::NaN();
+ } elseif (strlen($x) == 10) {
+ // Two's Complement
+ return str_repeat('7',7).substr(strtoupper(decoct(bindec(substr($x,-9)))),-3);
+ }
+ $octVal = (string) decoct(bindec($x));
+
+ return self::_nbrConversionFormat($octVal,$places);
+ } // function BINTOOCT()
+
+
+ /**
+ * DECTOBIN
+ *
+ * Return a decimal value as binary.
+ *
+ * Excel Function:
+ * DEC2BIN(x[,places])
+ *
+ * @access public
+ * @category Engineering Functions
+ * @param string $x The decimal integer you want to convert. If number is negative,
+ * valid place values are ignored and DEC2BIN returns a 10-character
+ * (10-bit) binary number in which the most significant bit is the sign
+ * bit. The remaining 9 bits are magnitude bits. Negative numbers are
+ * represented using two's-complement notation.
+ * If number < -512 or if number > 511, DEC2BIN returns the #NUM! error
+ * value.
+ * If number is nonnumeric, DEC2BIN returns the #VALUE! error value.
+ * If DEC2BIN requires more than places characters, it returns the #NUM!
+ * error value.
+ * @param integer $places The number of characters to use. If places is omitted, DEC2BIN uses
+ * the minimum number of characters necessary. Places is useful for
+ * padding the return value with leading 0s (zeros).
+ * If places is not an integer, it is truncated.
+ * If places is nonnumeric, DEC2BIN returns the #VALUE! error value.
+ * If places is zero or negative, DEC2BIN returns the #NUM! error value.
+ * @return string
+ */
+ public static function DECTOBIN($x, $places=null) {
+ $x = Calculation_Functions::flattenSingleValue($x);
+ $places = Calculation_Functions::flattenSingleValue($places);
+
+ if (is_bool($x)) {
+ if (Calculation_Functions::getCompatibilityMode() == Calculation_Functions::COMPATIBILITY_OPENOFFICE) {
+ $x = (int) $x;
+ } else {
+ return Calculation_Functions::VALUE();
+ }
+ }
+ $x = (string) $x;
+ if (strlen($x) > preg_match_all('/[-0123456789.]/',$x,$out)) {
+ return Calculation_Functions::VALUE();
+ }
+ $x = (string) floor($x);
+ $r = decbin($x);
+ if (strlen($r) == 32) {
+ // Two's Complement
+ $r = substr($r,-10);
+ } elseif (strlen($r) > 11) {
+ return Calculation_Functions::NaN();
+ }
+
+ return self::_nbrConversionFormat($r,$places);
+ } // function DECTOBIN()
+
+
+ /**
+ * DECTOHEX
+ *
+ * Return a decimal value as hex.
+ *
+ * Excel Function:
+ * DEC2HEX(x[,places])
+ *
+ * @access public
+ * @category Engineering Functions
+ * @param string $x The decimal integer you want to convert. If number is negative,
+ * places is ignored and DEC2HEX returns a 10-character (40-bit)
+ * hexadecimal number in which the most significant bit is the sign
+ * bit. The remaining 39 bits are magnitude bits. Negative numbers
+ * are represented using two's-complement notation.
+ * If number < -549,755,813,888 or if number > 549,755,813,887,
+ * DEC2HEX returns the #NUM! error value.
+ * If number is nonnumeric, DEC2HEX returns the #VALUE! error value.
+ * If DEC2HEX requires more than places characters, it returns the
+ * #NUM! error value.
+ * @param integer $places The number of characters to use. If places is omitted, DEC2HEX uses
+ * the minimum number of characters necessary. Places is useful for
+ * padding the return value with leading 0s (zeros).
+ * If places is not an integer, it is truncated.
+ * If places is nonnumeric, DEC2HEX returns the #VALUE! error value.
+ * If places is zero or negative, DEC2HEX returns the #NUM! error value.
+ * @return string
+ */
+ public static function DECTOHEX($x, $places=null) {
+ $x = Calculation_Functions::flattenSingleValue($x);
+ $places = Calculation_Functions::flattenSingleValue($places);
+
+ if (is_bool($x)) {
+ if (Calculation_Functions::getCompatibilityMode() == Calculation_Functions::COMPATIBILITY_OPENOFFICE) {
+ $x = (int) $x;
+ } else {
+ return Calculation_Functions::VALUE();
+ }
+ }
+ $x = (string) $x;
+ if (strlen($x) > preg_match_all('/[-0123456789.]/',$x,$out)) {
+ return Calculation_Functions::VALUE();
+ }
+ $x = (string) floor($x);
+ $r = strtoupper(dechex($x));
+ if (strlen($r) == 8) {
+ // Two's Complement
+ $r = 'FF'.$r;
+ }
+
+ return self::_nbrConversionFormat($r,$places);
+ } // function DECTOHEX()
+
+
+ /**
+ * DECTOOCT
+ *
+ * Return an decimal value as octal.
+ *
+ * Excel Function:
+ * DEC2OCT(x[,places])
+ *
+ * @access public
+ * @category Engineering Functions
+ * @param string $x The decimal integer you want to convert. If number is negative,
+ * places is ignored and DEC2OCT returns a 10-character (30-bit)
+ * octal number in which the most significant bit is the sign bit.
+ * The remaining 29 bits are magnitude bits. Negative numbers are
+ * represented using two's-complement notation.
+ * If number < -536,870,912 or if number > 536,870,911, DEC2OCT
+ * returns the #NUM! error value.
+ * If number is nonnumeric, DEC2OCT returns the #VALUE! error value.
+ * If DEC2OCT requires more than places characters, it returns the
+ * #NUM! error value.
+ * @param integer $places The number of characters to use. If places is omitted, DEC2OCT uses
+ * the minimum number of characters necessary. Places is useful for
+ * padding the return value with leading 0s (zeros).
+ * If places is not an integer, it is truncated.
+ * If places is nonnumeric, DEC2OCT returns the #VALUE! error value.
+ * If places is zero or negative, DEC2OCT returns the #NUM! error value.
+ * @return string
+ */
+ public static function DECTOOCT($x, $places=null) {
+ $x = Calculation_Functions::flattenSingleValue($x);
+ $places = Calculation_Functions::flattenSingleValue($places);
+
+ if (is_bool($x)) {
+ if (Calculation_Functions::getCompatibilityMode() == Calculation_Functions::COMPATIBILITY_OPENOFFICE) {
+ $x = (int) $x;
+ } else {
+ return Calculation_Functions::VALUE();
+ }
+ }
+ $x = (string) $x;
+ if (strlen($x) > preg_match_all('/[-0123456789.]/',$x,$out)) {
+ return Calculation_Functions::VALUE();
+ }
+ $x = (string) floor($x);
+ $r = decoct($x);
+ if (strlen($r) == 11) {
+ // Two's Complement
+ $r = substr($r,-10);
+ }
+
+ return self::_nbrConversionFormat($r,$places);
+ } // function DECTOOCT()
+
+
+ /**
+ * HEXTOBIN
+ *
+ * Return a hex value as binary.
+ *
+ * Excel Function:
+ * HEX2BIN(x[,places])
+ *
+ * @access public
+ * @category Engineering Functions
+ * @param string $x the hexadecimal number you want to convert. Number cannot
+ * contain more than 10 characters. The most significant bit of
+ * number is the sign bit (40th bit from the right). The remaining
+ * 9 bits are magnitude bits. Negative numbers are represented
+ * using two's-complement notation.
+ * If number is negative, HEX2BIN ignores places and returns a
+ * 10-character binary number.
+ * If number is negative, it cannot be less than FFFFFFFE00, and
+ * if number is positive, it cannot be greater than 1FF.
+ * If number is not a valid hexadecimal number, HEX2BIN returns
+ * the #NUM! error value.
+ * If HEX2BIN requires more than places characters, it returns
+ * the #NUM! error value.
+ * @param integer $places The number of characters to use. If places is omitted,
+ * HEX2BIN uses the minimum number of characters necessary. Places
+ * is useful for padding the return value with leading 0s (zeros).
+ * If places is not an integer, it is truncated.
+ * If places is nonnumeric, HEX2BIN returns the #VALUE! error value.
+ * If places is negative, HEX2BIN returns the #NUM! error value.
+ * @return string
+ */
+ public static function HEXTOBIN($x, $places=null) {
+ $x = Calculation_Functions::flattenSingleValue($x);
+ $places = Calculation_Functions::flattenSingleValue($places);
+
+ if (is_bool($x)) {
+ return Calculation_Functions::VALUE();
+ }
+ $x = (string) $x;
+ if (strlen($x) > preg_match_all('/[0123456789ABCDEF]/',strtoupper($x),$out)) {
+ return Calculation_Functions::NaN();
+ }
+ $binVal = decbin(hexdec($x));
+
+ return substr(self::_nbrConversionFormat($binVal,$places),-10);
+ } // function HEXTOBIN()
+
+
+ /**
+ * HEXTODEC
+ *
+ * Return a hex value as decimal.
+ *
+ * Excel Function:
+ * HEX2DEC(x)
+ *
+ * @access public
+ * @category Engineering Functions
+ * @param string $x The hexadecimal number you want to convert. This number cannot
+ * contain more than 10 characters (40 bits). The most significant
+ * bit of number is the sign bit. The remaining 39 bits are magnitude
+ * bits. Negative numbers are represented using two's-complement
+ * notation.
+ * If number is not a valid hexadecimal number, HEX2DEC returns the
+ * #NUM! error value.
+ * @return string
+ */
+ public static function HEXTODEC($x) {
+ $x = Calculation_Functions::flattenSingleValue($x);
+
+ if (is_bool($x)) {
+ return Calculation_Functions::VALUE();
+ }
+ $x = (string) $x;
+ if (strlen($x) > preg_match_all('/[0123456789ABCDEF]/',strtoupper($x),$out)) {
+ return Calculation_Functions::NaN();
+ }
+ return hexdec($x);
+ } // function HEXTODEC()
+
+
+ /**
+ * HEXTOOCT
+ *
+ * Return a hex value as octal.
+ *
+ * Excel Function:
+ * HEX2OCT(x[,places])
+ *
+ * @access public
+ * @category Engineering Functions
+ * @param string $x The hexadecimal number you want to convert. Number cannot
+ * contain more than 10 characters. The most significant bit of
+ * number is the sign bit. The remaining 39 bits are magnitude
+ * bits. Negative numbers are represented using two's-complement
+ * notation.
+ * If number is negative, HEX2OCT ignores places and returns a
+ * 10-character octal number.
+ * If number is negative, it cannot be less than FFE0000000, and
+ * if number is positive, it cannot be greater than 1FFFFFFF.
+ * If number is not a valid hexadecimal number, HEX2OCT returns
+ * the #NUM! error value.
+ * If HEX2OCT requires more than places characters, it returns
+ * the #NUM! error value.
+ * @param integer $places The number of characters to use. If places is omitted, HEX2OCT
+ * uses the minimum number of characters necessary. Places is
+ * useful for padding the return value with leading 0s (zeros).
+ * If places is not an integer, it is truncated.
+ * If places is nonnumeric, HEX2OCT returns the #VALUE! error
+ * value.
+ * If places is negative, HEX2OCT returns the #NUM! error value.
+ * @return string
+ */
+ public static function HEXTOOCT($x, $places=null) {
+ $x = Calculation_Functions::flattenSingleValue($x);
+ $places = Calculation_Functions::flattenSingleValue($places);
+
+ if (is_bool($x)) {
+ return Calculation_Functions::VALUE();
+ }
+ $x = (string) $x;
+ if (strlen($x) > preg_match_all('/[0123456789ABCDEF]/',strtoupper($x),$out)) {
+ return Calculation_Functions::NaN();
+ }
+ $octVal = decoct(hexdec($x));
+
+ return self::_nbrConversionFormat($octVal,$places);
+ } // function HEXTOOCT()
+
+
+ /**
+ * OCTTOBIN
+ *
+ * Return an octal value as binary.
+ *
+ * Excel Function:
+ * OCT2BIN(x[,places])
+ *
+ * @access public
+ * @category Engineering Functions
+ * @param string $x The octal number you want to convert. Number may not
+ * contain more than 10 characters. The most significant
+ * bit of number is the sign bit. The remaining 29 bits
+ * are magnitude bits. Negative numbers are represented
+ * using two's-complement notation.
+ * If number is negative, OCT2BIN ignores places and returns
+ * a 10-character binary number.
+ * If number is negative, it cannot be less than 7777777000,
+ * and if number is positive, it cannot be greater than 777.
+ * If number is not a valid octal number, OCT2BIN returns
+ * the #NUM! error value.
+ * If OCT2BIN requires more than places characters, it
+ * returns the #NUM! error value.
+ * @param integer $places The number of characters to use. If places is omitted,
+ * OCT2BIN uses the minimum number of characters necessary.
+ * Places is useful for padding the return value with
+ * leading 0s (zeros).
+ * If places is not an integer, it is truncated.
+ * If places is nonnumeric, OCT2BIN returns the #VALUE!
+ * error value.
+ * If places is negative, OCT2BIN returns the #NUM! error
+ * value.
+ * @return string
+ */
+ public static function OCTTOBIN($x, $places=null) {
+ $x = Calculation_Functions::flattenSingleValue($x);
+ $places = Calculation_Functions::flattenSingleValue($places);
+
+ if (is_bool($x)) {
+ return Calculation_Functions::VALUE();
+ }
+ $x = (string) $x;
+ if (preg_match_all('/[01234567]/',$x,$out) != strlen($x)) {
+ return Calculation_Functions::NaN();
+ }
+ $r = decbin(octdec($x));
+
+ return self::_nbrConversionFormat($r,$places);
+ } // function OCTTOBIN()
+
+
+ /**
+ * OCTTODEC
+ *
+ * Return an octal value as decimal.
+ *
+ * Excel Function:
+ * OCT2DEC(x)
+ *
+ * @access public
+ * @category Engineering Functions
+ * @param string $x The octal number you want to convert. Number may not contain
+ * more than 10 octal characters (30 bits). The most significant
+ * bit of number is the sign bit. The remaining 29 bits are
+ * magnitude bits. Negative numbers are represented using
+ * two's-complement notation.
+ * If number is not a valid octal number, OCT2DEC returns the
+ * #NUM! error value.
+ * @return string
+ */
+ public static function OCTTODEC($x) {
+ $x = Calculation_Functions::flattenSingleValue($x);
+
+ if (is_bool($x)) {
+ return Calculation_Functions::VALUE();
+ }
+ $x = (string) $x;
+ if (preg_match_all('/[01234567]/',$x,$out) != strlen($x)) {
+ return Calculation_Functions::NaN();
+ }
+ return octdec($x);
+ } // function OCTTODEC()
+
+
+ /**
+ * OCTTOHEX
+ *
+ * Return an octal value as hex.
+ *
+ * Excel Function:
+ * OCT2HEX(x[,places])
+ *
+ * @access public
+ * @category Engineering Functions
+ * @param string $x The octal number you want to convert. Number may not contain
+ * more than 10 octal characters (30 bits). The most significant
+ * bit of number is the sign bit. The remaining 29 bits are
+ * magnitude bits. Negative numbers are represented using
+ * two's-complement notation.
+ * If number is negative, OCT2HEX ignores places and returns a
+ * 10-character hexadecimal number.
+ * If number is not a valid octal number, OCT2HEX returns the
+ * #NUM! error value.
+ * If OCT2HEX requires more than places characters, it returns
+ * the #NUM! error value.
+ * @param integer $places The number of characters to use. If places is omitted, OCT2HEX
+ * uses the minimum number of characters necessary. Places is useful
+ * for padding the return value with leading 0s (zeros).
+ * If places is not an integer, it is truncated.
+ * If places is nonnumeric, OCT2HEX returns the #VALUE! error value.
+ * If places is negative, OCT2HEX returns the #NUM! error value.
+ * @return string
+ */
+ public static function OCTTOHEX($x, $places=null) {
+ $x = Calculation_Functions::flattenSingleValue($x);
+ $places = Calculation_Functions::flattenSingleValue($places);
+
+ if (is_bool($x)) {
+ return Calculation_Functions::VALUE();
+ }
+ $x = (string) $x;
+ if (preg_match_all('/[01234567]/',$x,$out) != strlen($x)) {
+ return Calculation_Functions::NaN();
+ }
+ $hexVal = strtoupper(dechex(octdec($x)));
+
+ return self::_nbrConversionFormat($hexVal,$places);
+ } // function OCTTOHEX()
+
+
+ /**
+ * COMPLEX
+ *
+ * Converts real and imaginary coefficients into a complex number of the form x + yi or x + yj.
+ *
+ * Excel Function:
+ * COMPLEX(realNumber,imaginary[,places])
+ *
+ * @access public
+ * @category Engineering Functions
+ * @param float $realNumber The real coefficient of the complex number.
+ * @param float $imaginary The imaginary coefficient of the complex number.
+ * @param string $suffix The suffix for the imaginary component of the complex number.
+ * If omitted, the suffix is assumed to be "i".
+ * @return string
+ */
+ public static function COMPLEX($realNumber=0.0, $imaginary=0.0, $suffix='i') {
+ $realNumber = (is_null($realNumber)) ? 0.0 : Calculation_Functions::flattenSingleValue($realNumber);
+ $imaginary = (is_null($imaginary)) ? 0.0 : Calculation_Functions::flattenSingleValue($imaginary);
+ $suffix = (is_null($suffix)) ? 'i' : Calculation_Functions::flattenSingleValue($suffix);
+
+ if (((is_numeric($realNumber)) && (is_numeric($imaginary))) &&
+ (($suffix == 'i') || ($suffix == 'j') || ($suffix == ''))) {
+ $realNumber = (float) $realNumber;
+ $imaginary = (float) $imaginary;
+
+ if ($suffix == '') $suffix = 'i';
+ if ($realNumber == 0.0) {
+ if ($imaginary == 0.0) {
+ return (string) '0';
+ } elseif ($imaginary == 1.0) {
+ return (string) $suffix;
+ } elseif ($imaginary == -1.0) {
+ return (string) '-'.$suffix;
+ }
+ return (string) $imaginary.$suffix;
+ } elseif ($imaginary == 0.0) {
+ return (string) $realNumber;
+ } elseif ($imaginary == 1.0) {
+ return (string) $realNumber.'+'.$suffix;
+ } elseif ($imaginary == -1.0) {
+ return (string) $realNumber.'-'.$suffix;
+ }
+ if ($imaginary > 0) { $imaginary = (string) '+'.$imaginary; }
+ return (string) $realNumber.$imaginary.$suffix;
+ }
+
+ return Calculation_Functions::VALUE();
+ } // function COMPLEX()
+
+
+ /**
+ * IMAGINARY
+ *
+ * Returns the imaginary coefficient of a complex number in x + yi or x + yj text format.
+ *
+ * Excel Function:
+ * IMAGINARY(complexNumber)
+ *
+ * @access public
+ * @category Engineering Functions
+ * @param string $complexNumber The complex number for which you want the imaginary
+ * coefficient.
+ * @return float
+ */
+ public static function IMAGINARY($complexNumber) {
+ $complexNumber = Calculation_Functions::flattenSingleValue($complexNumber);
+
+ $parsedComplex = self::_parseComplex($complexNumber);
+ return $parsedComplex['imaginary'];
+ } // function IMAGINARY()
+
+
+ /**
+ * IMREAL
+ *
+ * Returns the real coefficient of a complex number in x + yi or x + yj text format.
+ *
+ * Excel Function:
+ * IMREAL(complexNumber)
+ *
+ * @access public
+ * @category Engineering Functions
+ * @param string $complexNumber The complex number for which you want the real coefficient.
+ * @return float
+ */
+ public static function IMREAL($complexNumber) {
+ $complexNumber = Calculation_Functions::flattenSingleValue($complexNumber);
+
+ $parsedComplex = self::_parseComplex($complexNumber);
+ return $parsedComplex['real'];
+ } // function IMREAL()
+
+
+ /**
+ * IMABS
+ *
+ * Returns the absolute value (modulus) of a complex number in x + yi or x + yj text format.
+ *
+ * Excel Function:
+ * IMABS(complexNumber)
+ *
+ * @param string $complexNumber The complex number for which you want the absolute value.
+ * @return float
+ */
+ public static function IMABS($complexNumber) {
+ $complexNumber = Calculation_Functions::flattenSingleValue($complexNumber);
+
+ $parsedComplex = self::_parseComplex($complexNumber);
+
+ return sqrt(($parsedComplex['real'] * $parsedComplex['real']) + ($parsedComplex['imaginary'] * $parsedComplex['imaginary']));
+ } // function IMABS()
+
+
+ /**
+ * IMARGUMENT
+ *
+ * Returns the argument theta of a complex number, i.e. the angle in radians from the real
+ * axis to the representation of the number in polar coordinates.
+ *
+ * Excel Function:
+ * IMARGUMENT(complexNumber)
+ *
+ * @param string $complexNumber The complex number for which you want the argument theta.
+ * @return float
+ */
+ public static function IMARGUMENT($complexNumber) {
+ $complexNumber = Calculation_Functions::flattenSingleValue($complexNumber);
+
+ $parsedComplex = self::_parseComplex($complexNumber);
+
+ if ($parsedComplex['real'] == 0.0) {
+ if ($parsedComplex['imaginary'] == 0.0) {
+ return 0.0;
+ } elseif($parsedComplex['imaginary'] < 0.0) {
+ return M_PI / -2;
+ } else {
+ return M_PI / 2;
+ }
+ } elseif ($parsedComplex['real'] > 0.0) {
+ return atan($parsedComplex['imaginary'] / $parsedComplex['real']);
+ } elseif ($parsedComplex['imaginary'] < 0.0) {
+ return 0 - (M_PI - atan(abs($parsedComplex['imaginary']) / abs($parsedComplex['real'])));
+ } else {
+ return M_PI - atan($parsedComplex['imaginary'] / abs($parsedComplex['real']));
+ }
+ } // function IMARGUMENT()
+
+
+ /**
+ * IMCONJUGATE
+ *
+ * Returns the complex conjugate of a complex number in x + yi or x + yj text format.
+ *
+ * Excel Function:
+ * IMCONJUGATE(complexNumber)
+ *
+ * @param string $complexNumber The complex number for which you want the conjugate.
+ * @return string
+ */
+ public static function IMCONJUGATE($complexNumber) {
+ $complexNumber = Calculation_Functions::flattenSingleValue($complexNumber);
+
+ $parsedComplex = self::_parseComplex($complexNumber);
+
+ if ($parsedComplex['imaginary'] == 0.0) {
+ return $parsedComplex['real'];
+ } else {
+ return self::_cleanComplex( self::COMPLEX( $parsedComplex['real'],
+ 0 - $parsedComplex['imaginary'],
+ $parsedComplex['suffix']
+ )
+ );
+ }
+ } // function IMCONJUGATE()
+
+
+ /**
+ * IMCOS
+ *
+ * Returns the cosine of a complex number in x + yi or x + yj text format.
+ *
+ * Excel Function:
+ * IMCOS(complexNumber)
+ *
+ * @param string $complexNumber The complex number for which you want the cosine.
+ * @return string|float
+ */
+ public static function IMCOS($complexNumber) {
+ $complexNumber = Calculation_Functions::flattenSingleValue($complexNumber);
+
+ $parsedComplex = self::_parseComplex($complexNumber);
+
+ if ($parsedComplex['imaginary'] == 0.0) {
+ return cos($parsedComplex['real']);
+ } else {
+ return self::IMCONJUGATE(self::COMPLEX(cos($parsedComplex['real']) * cosh($parsedComplex['imaginary']),sin($parsedComplex['real']) * sinh($parsedComplex['imaginary']),$parsedComplex['suffix']));
+ }
+ } // function IMCOS()
+
+
+ /**
+ * IMSIN
+ *
+ * Returns the sine of a complex number in x + yi or x + yj text format.
+ *
+ * Excel Function:
+ * IMSIN(complexNumber)
+ *
+ * @param string $complexNumber The complex number for which you want the sine.
+ * @return string|float
+ */
+ public static function IMSIN($complexNumber) {
+ $complexNumber = Calculation_Functions::flattenSingleValue($complexNumber);
+
+ $parsedComplex = self::_parseComplex($complexNumber);
+
+ if ($parsedComplex['imaginary'] == 0.0) {
+ return sin($parsedComplex['real']);
+ } else {
+ return self::COMPLEX(sin($parsedComplex['real']) * cosh($parsedComplex['imaginary']),cos($parsedComplex['real']) * sinh($parsedComplex['imaginary']),$parsedComplex['suffix']);
+ }
+ } // function IMSIN()
+
+
+ /**
+ * IMSQRT
+ *
+ * Returns the square root of a complex number in x + yi or x + yj text format.
+ *
+ * Excel Function:
+ * IMSQRT(complexNumber)
+ *
+ * @param string $complexNumber The complex number for which you want the square root.
+ * @return string
+ */
+ public static function IMSQRT($complexNumber) {
+ $complexNumber = Calculation_Functions::flattenSingleValue($complexNumber);
+
+ $parsedComplex = self::_parseComplex($complexNumber);
+
+ $theta = self::IMARGUMENT($complexNumber);
+ $d1 = cos($theta / 2);
+ $d2 = sin($theta / 2);
+ $r = sqrt(sqrt(($parsedComplex['real'] * $parsedComplex['real']) + ($parsedComplex['imaginary'] * $parsedComplex['imaginary'])));
+
+ if ($parsedComplex['suffix'] == '') {
+ return self::COMPLEX($d1 * $r,$d2 * $r);
+ } else {
+ return self::COMPLEX($d1 * $r,$d2 * $r,$parsedComplex['suffix']);
+ }
+ } // function IMSQRT()
+
+
+ /**
+ * IMLN
+ *
+ * Returns the natural logarithm of a complex number in x + yi or x + yj text format.
+ *
+ * Excel Function:
+ * IMLN(complexNumber)
+ *
+ * @param string $complexNumber The complex number for which you want the natural logarithm.
+ * @return string
+ */
+ public static function IMLN($complexNumber) {
+ $complexNumber = Calculation_Functions::flattenSingleValue($complexNumber);
+
+ $parsedComplex = self::_parseComplex($complexNumber);
+
+ if (($parsedComplex['real'] == 0.0) && ($parsedComplex['imaginary'] == 0.0)) {
+ return Calculation_Functions::NaN();
+ }
+
+ $logR = log(sqrt(($parsedComplex['real'] * $parsedComplex['real']) + ($parsedComplex['imaginary'] * $parsedComplex['imaginary'])));
+ $t = self::IMARGUMENT($complexNumber);
+
+ if ($parsedComplex['suffix'] == '') {
+ return self::COMPLEX($logR,$t);
+ } else {
+ return self::COMPLEX($logR,$t,$parsedComplex['suffix']);
+ }
+ } // function IMLN()
+
+
+ /**
+ * IMLOG10
+ *
+ * Returns the common logarithm (base 10) of a complex number in x + yi or x + yj text format.
+ *
+ * Excel Function:
+ * IMLOG10(complexNumber)
+ *
+ * @param string $complexNumber The complex number for which you want the common logarithm.
+ * @return string
+ */
+ public static function IMLOG10($complexNumber) {
+ $complexNumber = Calculation_Functions::flattenSingleValue($complexNumber);
+
+ $parsedComplex = self::_parseComplex($complexNumber);
+
+ if (($parsedComplex['real'] == 0.0) && ($parsedComplex['imaginary'] == 0.0)) {
+ return Calculation_Functions::NaN();
+ } elseif (($parsedComplex['real'] > 0.0) && ($parsedComplex['imaginary'] == 0.0)) {
+ return log10($parsedComplex['real']);
+ }
+
+ return self::IMPRODUCT(log10(EULER),self::IMLN($complexNumber));
+ } // function IMLOG10()
+
+
+ /**
+ * IMLOG2
+ *
+ * Returns the base-2 logarithm of a complex number in x + yi or x + yj text format.
+ *
+ * Excel Function:
+ * IMLOG2(complexNumber)
+ *
+ * @param string $complexNumber The complex number for which you want the base-2 logarithm.
+ * @return string
+ */
+ public static function IMLOG2($complexNumber) {
+ $complexNumber = Calculation_Functions::flattenSingleValue($complexNumber);
+
+ $parsedComplex = self::_parseComplex($complexNumber);
+
+ if (($parsedComplex['real'] == 0.0) && ($parsedComplex['imaginary'] == 0.0)) {
+ return Calculation_Functions::NaN();
+ } elseif (($parsedComplex['real'] > 0.0) && ($parsedComplex['imaginary'] == 0.0)) {
+ return log($parsedComplex['real'],2);
+ }
+
+ return self::IMPRODUCT(log(EULER,2),self::IMLN($complexNumber));
+ } // function IMLOG2()
+
+
+ /**
+ * IMEXP
+ *
+ * Returns the exponential of a complex number in x + yi or x + yj text format.
+ *
+ * Excel Function:
+ * IMEXP(complexNumber)
+ *
+ * @param string $complexNumber The complex number for which you want the exponential.
+ * @return string
+ */
+ public static function IMEXP($complexNumber) {
+ $complexNumber = Calculation_Functions::flattenSingleValue($complexNumber);
+
+ $parsedComplex = self::_parseComplex($complexNumber);
+
+ if (($parsedComplex['real'] == 0.0) && ($parsedComplex['imaginary'] == 0.0)) {
+ return '1';
+ }
+
+ $e = exp($parsedComplex['real']);
+ $eX = $e * cos($parsedComplex['imaginary']);
+ $eY = $e * sin($parsedComplex['imaginary']);
+
+ if ($parsedComplex['suffix'] == '') {
+ return self::COMPLEX($eX,$eY);
+ } else {
+ return self::COMPLEX($eX,$eY,$parsedComplex['suffix']);
+ }
+ } // function IMEXP()
+
+
+ /**
+ * IMPOWER
+ *
+ * Returns a complex number in x + yi or x + yj text format raised to a power.
+ *
+ * Excel Function:
+ * IMPOWER(complexNumber,realNumber)
+ *
+ * @param string $complexNumber The complex number you want to raise to a power.
+ * @param float $realNumber The power to which you want to raise the complex number.
+ * @return string
+ */
+ public static function IMPOWER($complexNumber,$realNumber) {
+ $complexNumber = Calculation_Functions::flattenSingleValue($complexNumber);
+ $realNumber = Calculation_Functions::flattenSingleValue($realNumber);
+
+ if (!is_numeric($realNumber)) {
+ return Calculation_Functions::VALUE();
+ }
+
+ $parsedComplex = self::_parseComplex($complexNumber);
+
+ $r = sqrt(($parsedComplex['real'] * $parsedComplex['real']) + ($parsedComplex['imaginary'] * $parsedComplex['imaginary']));
+ $rPower = pow($r,$realNumber);
+ $theta = self::IMARGUMENT($complexNumber) * $realNumber;
+ if ($theta == 0) {
+ return 1;
+ } elseif ($parsedComplex['imaginary'] == 0.0) {
+ return self::COMPLEX($rPower * cos($theta),$rPower * sin($theta),$parsedComplex['suffix']);
+ } else {
+ return self::COMPLEX($rPower * cos($theta),$rPower * sin($theta),$parsedComplex['suffix']);
+ }
+ } // function IMPOWER()
+
+
+ /**
+ * IMDIV
+ *
+ * Returns the quotient of two complex numbers in x + yi or x + yj text format.
+ *
+ * Excel Function:
+ * IMDIV(complexDividend,complexDivisor)
+ *
+ * @param string $complexDividend The complex numerator or dividend.
+ * @param string $complexDivisor The complex denominator or divisor.
+ * @return string
+ */
+ public static function IMDIV($complexDividend,$complexDivisor) {
+ $complexDividend = Calculation_Functions::flattenSingleValue($complexDividend);
+ $complexDivisor = Calculation_Functions::flattenSingleValue($complexDivisor);
+
+ $parsedComplexDividend = self::_parseComplex($complexDividend);
+ $parsedComplexDivisor = self::_parseComplex($complexDivisor);
+
+ if (($parsedComplexDividend['suffix'] != '') && ($parsedComplexDivisor['suffix'] != '') &&
+ ($parsedComplexDividend['suffix'] != $parsedComplexDivisor['suffix'])) {
+ return Calculation_Functions::NaN();
+ }
+ if (($parsedComplexDividend['suffix'] != '') && ($parsedComplexDivisor['suffix'] == '')) {
+ $parsedComplexDivisor['suffix'] = $parsedComplexDividend['suffix'];
+ }
+
+ $d1 = ($parsedComplexDividend['real'] * $parsedComplexDivisor['real']) + ($parsedComplexDividend['imaginary'] * $parsedComplexDivisor['imaginary']);
+ $d2 = ($parsedComplexDividend['imaginary'] * $parsedComplexDivisor['real']) - ($parsedComplexDividend['real'] * $parsedComplexDivisor['imaginary']);
+ $d3 = ($parsedComplexDivisor['real'] * $parsedComplexDivisor['real']) + ($parsedComplexDivisor['imaginary'] * $parsedComplexDivisor['imaginary']);
+
+ $r = $d1/$d3;
+ $i = $d2/$d3;
+
+ if ($i > 0.0) {
+ return self::_cleanComplex($r.'+'.$i.$parsedComplexDivisor['suffix']);
+ } elseif ($i < 0.0) {
+ return self::_cleanComplex($r.$i.$parsedComplexDivisor['suffix']);
+ } else {
+ return $r;
+ }
+ } // function IMDIV()
+
+
+ /**
+ * IMSUB
+ *
+ * Returns the difference of two complex numbers in x + yi or x + yj text format.
+ *
+ * Excel Function:
+ * IMSUB(complexNumber1,complexNumber2)
+ *
+ * @param string $complexNumber1 The complex number from which to subtract complexNumber2.
+ * @param string $complexNumber2 The complex number to subtract from complexNumber1.
+ * @return string
+ */
+ public static function IMSUB($complexNumber1,$complexNumber2) {
+ $complexNumber1 = Calculation_Functions::flattenSingleValue($complexNumber1);
+ $complexNumber2 = Calculation_Functions::flattenSingleValue($complexNumber2);
+
+ $parsedComplex1 = self::_parseComplex($complexNumber1);
+ $parsedComplex2 = self::_parseComplex($complexNumber2);
+
+ if ((($parsedComplex1['suffix'] != '') && ($parsedComplex2['suffix'] != '')) &&
+ ($parsedComplex1['suffix'] != $parsedComplex2['suffix'])) {
+ return Calculation_Functions::NaN();
+ } elseif (($parsedComplex1['suffix'] == '') && ($parsedComplex2['suffix'] != '')) {
+ $parsedComplex1['suffix'] = $parsedComplex2['suffix'];
+ }
+
+ $d1 = $parsedComplex1['real'] - $parsedComplex2['real'];
+ $d2 = $parsedComplex1['imaginary'] - $parsedComplex2['imaginary'];
+
+ return self::COMPLEX($d1,$d2,$parsedComplex1['suffix']);
+ } // function IMSUB()
+
+
+ /**
+ * IMSUM
+ *
+ * Returns the sum of two or more complex numbers in x + yi or x + yj text format.
+ *
+ * Excel Function:
+ * IMSUM(complexNumber[,complexNumber[,...]])
+ *
+ * @param string $complexNumber,... Series of complex numbers to add
+ * @return string
+ */
+ public static function IMSUM() {
+ // Return value
+ $returnValue = self::_parseComplex('0');
+ $activeSuffix = '';
+
+ // Loop through the arguments
+ $aArgs = Calculation_Functions::flattenArray(func_get_args());
+ foreach ($aArgs as $arg) {
+ $parsedComplex = self::_parseComplex($arg);
+
+ if ($activeSuffix == '') {
+ $activeSuffix = $parsedComplex['suffix'];
+ } elseif (($parsedComplex['suffix'] != '') && ($activeSuffix != $parsedComplex['suffix'])) {
+ return Calculation_Functions::VALUE();
+ }
+
+ $returnValue['real'] += $parsedComplex['real'];
+ $returnValue['imaginary'] += $parsedComplex['imaginary'];
+ }
+
+ if ($returnValue['imaginary'] == 0.0) { $activeSuffix = ''; }
+ return self::COMPLEX($returnValue['real'],$returnValue['imaginary'],$activeSuffix);
+ } // function IMSUM()
+
+
+ /**
+ * IMPRODUCT
+ *
+ * Returns the product of two or more complex numbers in x + yi or x + yj text format.
+ *
+ * Excel Function:
+ * IMPRODUCT(complexNumber[,complexNumber[,...]])
+ *
+ * @param string $complexNumber,... Series of complex numbers to multiply
+ * @return string
+ */
+ public static function IMPRODUCT() {
+ // Return value
+ $returnValue = self::_parseComplex('1');
+ $activeSuffix = '';
+
+ // Loop through the arguments
+ $aArgs = Calculation_Functions::flattenArray(func_get_args());
+ foreach ($aArgs as $arg) {
+ $parsedComplex = self::_parseComplex($arg);
+
+ $workValue = $returnValue;
+ if (($parsedComplex['suffix'] != '') && ($activeSuffix == '')) {
+ $activeSuffix = $parsedComplex['suffix'];
+ } elseif (($parsedComplex['suffix'] != '') && ($activeSuffix != $parsedComplex['suffix'])) {
+ return Calculation_Functions::NaN();
+ }
+ $returnValue['real'] = ($workValue['real'] * $parsedComplex['real']) - ($workValue['imaginary'] * $parsedComplex['imaginary']);
+ $returnValue['imaginary'] = ($workValue['real'] * $parsedComplex['imaginary']) + ($workValue['imaginary'] * $parsedComplex['real']);
+ }
+
+ if ($returnValue['imaginary'] == 0.0) { $activeSuffix = ''; }
+ return self::COMPLEX($returnValue['real'],$returnValue['imaginary'],$activeSuffix);
+ } // function IMPRODUCT()
+
+
+ /**
+ * DELTA
+ *
+ * Tests whether two values are equal. Returns 1 if number1 = number2; returns 0 otherwise.
+ * Use this function to filter a set of values. For example, by summing several DELTA
+ * functions you calculate the count of equal pairs. This function is also known as the
+ * Kronecker Delta function.
+ *
+ * Excel Function:
+ * DELTA(a[,b])
+ *
+ * @param float $a The first number.
+ * @param float $b The second number. If omitted, b is assumed to be zero.
+ * @return int
+ */
+ public static function DELTA($a, $b=0) {
+ $a = Calculation_Functions::flattenSingleValue($a);
+ $b = Calculation_Functions::flattenSingleValue($b);
+
+ return (int) ($a == $b);
+ } // function DELTA()
+
+
+ /**
+ * GESTEP
+ *
+ * Excel Function:
+ * GESTEP(number[,step])
+ *
+ * Returns 1 if number >= step; returns 0 (zero) otherwise
+ * Use this function to filter a set of values. For example, by summing several GESTEP
+ * functions you calculate the count of values that exceed a threshold.
+ *
+ * @param float $number The value to test against step.
+ * @param float $step The threshold value.
+ * If you omit a value for step, GESTEP uses zero.
+ * @return int
+ */
+ public static function GESTEP($number, $step=0) {
+ $number = Calculation_Functions::flattenSingleValue($number);
+ $step = Calculation_Functions::flattenSingleValue($step);
+
+ return (int) ($number >= $step);
+ } // function GESTEP()
+
+
+ //
+ // Private method to calculate the erf value
+ //
+ private static $_two_sqrtpi = 1.128379167095512574;
+
+ public static function _erfVal($x) {
+ if (abs($x) > 2.2) {
+ return 1 - self::_erfcVal($x);
+ }
+ $sum = $term = $x;
+ $xsqr = ($x * $x);
+ $j = 1;
+ do {
+ $term *= $xsqr / $j;
+ $sum -= $term / (2 * $j + 1);
+ ++$j;
+ $term *= $xsqr / $j;
+ $sum += $term / (2 * $j + 1);
+ ++$j;
+ if ($sum == 0.0) {
+ break;
+ }
+ } while (abs($term / $sum) > PRECISION);
+ return self::$_two_sqrtpi * $sum;
+ } // function _erfVal()
+
+
+ /**
+ * ERF
+ *
+ * Returns the error function integrated between the lower and upper bound arguments.
+ *
+ * Note: In Excel 2007 or earlier, if you input a negative value for the upper or lower bound arguments,
+ * the function would return a #NUM! error. However, in Excel 2010, the function algorithm was
+ * improved, so that it can now calculate the function for both positive and negative ranges.
+ * PHPExcel follows Excel 2010 behaviour, and accepts nagative arguments.
+ *
+ * Excel Function:
+ * ERF(lower[,upper])
+ *
+ * @param float $lower lower bound for integrating ERF
+ * @param float $upper upper bound for integrating ERF.
+ * If omitted, ERF integrates between zero and lower_limit
+ * @return float
+ */
+ public static function ERF($lower, $upper = null) {
+ $lower = Calculation_Functions::flattenSingleValue($lower);
+ $upper = Calculation_Functions::flattenSingleValue($upper);
+
+ if (is_numeric($lower)) {
+ if (is_null($upper)) {
+ return self::_erfVal($lower);
+ }
+ if (is_numeric($upper)) {
+ return self::_erfVal($upper) - self::_erfVal($lower);
+ }
+ }
+ return Calculation_Functions::VALUE();
+ } // function ERF()
+
+
+ //
+ // Private method to calculate the erfc value
+ //
+ private static $_one_sqrtpi = 0.564189583547756287;
+
+ private static function _erfcVal($x) {
+ if (abs($x) < 2.2) {
+ return 1 - self::_erfVal($x);
+ }
+ if ($x < 0) {
+ return 2 - self::ERFC(-$x);
+ }
+ $a = $n = 1;
+ $b = $c = $x;
+ $d = ($x * $x) + 0.5;
+ $q1 = $q2 = $b / $d;
+ $t = 0;
+ do {
+ $t = $a * $n + $b * $x;
+ $a = $b;
+ $b = $t;
+ $t = $c * $n + $d * $x;
+ $c = $d;
+ $d = $t;
+ $n += 0.5;
+ $q1 = $q2;
+ $q2 = $b / $d;
+ } while ((abs($q1 - $q2) / $q2) > PRECISION);
+ return self::$_one_sqrtpi * exp(-$x * $x) * $q2;
+ } // function _erfcVal()
+
+
+ /**
+ * ERFC
+ *
+ * Returns the complementary ERF function integrated between x and infinity
+ *
+ * Note: In Excel 2007 or earlier, if you input a negative value for the lower bound argument,
+ * the function would return a #NUM! error. However, in Excel 2010, the function algorithm was
+ * improved, so that it can now calculate the function for both positive and negative x values.
+ * PHPExcel follows Excel 2010 behaviour, and accepts nagative arguments.
+ *
+ * Excel Function:
+ * ERFC(x)
+ *
+ * @param float $x The lower bound for integrating ERFC
+ * @return float
+ */
+ public static function ERFC($x) {
+ $x = Calculation_Functions::flattenSingleValue($x);
+
+ if (is_numeric($x)) {
+ return self::_erfcVal($x);
+ }
+ return Calculation_Functions::VALUE();
+ } // function ERFC()
+
+
+ /**
+ * getConversionGroups
+ * Returns a list of the different conversion groups for UOM conversions
+ *
+ * @return array
+ */
+ public static function getConversionGroups() {
+ $conversionGroups = array();
+ foreach(self::$_conversionUnits as $conversionUnit) {
+ $conversionGroups[] = $conversionUnit['Group'];
+ }
+ return array_merge(array_unique($conversionGroups));
+ } // function getConversionGroups()
+
+
+ /**
+ * getConversionGroupUnits
+ * Returns an array of units of measure, for a specified conversion group, or for all groups
+ *
+ * @param string $group The group whose units of measure you want to retrieve
+ * @return array
+ */
+ public static function getConversionGroupUnits($group = null) {
+ $conversionGroups = array();
+ foreach(self::$_conversionUnits as $conversionUnit => $conversionGroup) {
+ if ((is_null($group)) || ($conversionGroup['Group'] == $group)) {
+ $conversionGroups[$conversionGroup['Group']][] = $conversionUnit;
+ }
+ }
+ return $conversionGroups;
+ } // function getConversionGroupUnits()
+
+
+ /**
+ * getConversionGroupUnitDetails
+ *
+ * @param string $group The group whose units of measure you want to retrieve
+ * @return array
+ */
+ public static function getConversionGroupUnitDetails($group = null) {
+ $conversionGroups = array();
+ foreach(self::$_conversionUnits as $conversionUnit => $conversionGroup) {
+ if ((is_null($group)) || ($conversionGroup['Group'] == $group)) {
+ $conversionGroups[$conversionGroup['Group']][] = array( 'unit' => $conversionUnit,
+ 'description' => $conversionGroup['Unit Name']
+ );
+ }
+ }
+ return $conversionGroups;
+ } // function getConversionGroupUnitDetails()
+
+
+ /**
+ * getConversionMultipliers
+ * Returns an array of the Multiplier prefixes that can be used with Units of Measure in CONVERTUOM()
+ *
+ * @return array of mixed
+ */
+ public static function getConversionMultipliers() {
+ return self::$_conversionMultipliers;
+ } // function getConversionGroups()
+
+
+ /**
+ * CONVERTUOM
+ *
+ * Converts a number from one measurement system to another.
+ * For example, CONVERT can translate a table of distances in miles to a table of distances
+ * in kilometers.
+ *
+ * Excel Function:
+ * CONVERT(value,fromUOM,toUOM)
+ *
+ * @param float $value The value in fromUOM to convert.
+ * @param string $fromUOM The units for value.
+ * @param string $toUOM The units for the result.
+ *
+ * @return float
+ */
+ public static function CONVERTUOM($value, $fromUOM, $toUOM) {
+ $value = Calculation_Functions::flattenSingleValue($value);
+ $fromUOM = Calculation_Functions::flattenSingleValue($fromUOM);
+ $toUOM = Calculation_Functions::flattenSingleValue($toUOM);
+
+ if (!is_numeric($value)) {
+ return Calculation_Functions::VALUE();
+ }
+ $fromMultiplier = 1.0;
+ if (isset(self::$_conversionUnits[$fromUOM])) {
+ $unitGroup1 = self::$_conversionUnits[$fromUOM]['Group'];
+ } else {
+ $fromMultiplier = substr($fromUOM,0,1);
+ $fromUOM = substr($fromUOM,1);
+ if (isset(self::$_conversionMultipliers[$fromMultiplier])) {
+ $fromMultiplier = self::$_conversionMultipliers[$fromMultiplier]['multiplier'];
+ } else {
+ return Calculation_Functions::NA();
+ }
+ if ((isset(self::$_conversionUnits[$fromUOM])) && (self::$_conversionUnits[$fromUOM]['AllowPrefix'])) {
+ $unitGroup1 = self::$_conversionUnits[$fromUOM]['Group'];
+ } else {
+ return Calculation_Functions::NA();
+ }
+ }
+ $value *= $fromMultiplier;
+
+ $toMultiplier = 1.0;
+ if (isset(self::$_conversionUnits[$toUOM])) {
+ $unitGroup2 = self::$_conversionUnits[$toUOM]['Group'];
+ } else {
+ $toMultiplier = substr($toUOM,0,1);
+ $toUOM = substr($toUOM,1);
+ if (isset(self::$_conversionMultipliers[$toMultiplier])) {
+ $toMultiplier = self::$_conversionMultipliers[$toMultiplier]['multiplier'];
+ } else {
+ return Calculation_Functions::NA();
+ }
+ if ((isset(self::$_conversionUnits[$toUOM])) && (self::$_conversionUnits[$toUOM]['AllowPrefix'])) {
+ $unitGroup2 = self::$_conversionUnits[$toUOM]['Group'];
+ } else {
+ return Calculation_Functions::NA();
+ }
+ }
+ if ($unitGroup1 != $unitGroup2) {
+ return Calculation_Functions::NA();
+ }
+
+ if (($fromUOM == $toUOM) && ($fromMultiplier == $toMultiplier)) {
+ // We've already factored $fromMultiplier into the value, so we need
+ // to reverse it again
+ return $value / $fromMultiplier;
+ } elseif ($unitGroup1 == 'Temperature') {
+ if (($fromUOM == 'F') || ($fromUOM == 'fah')) {
+ if (($toUOM == 'F') || ($toUOM == 'fah')) {
+ return $value;
+ } else {
+ $value = (($value - 32) / 1.8);
+ if (($toUOM == 'K') || ($toUOM == 'kel')) {
+ $value += 273.15;
+ }
+ return $value;
+ }
+ } elseif ((($fromUOM == 'K') || ($fromUOM == 'kel')) &&
+ (($toUOM == 'K') || ($toUOM == 'kel'))) {
+ return $value;
+ } elseif ((($fromUOM == 'C') || ($fromUOM == 'cel')) &&
+ (($toUOM == 'C') || ($toUOM == 'cel'))) {
+ return $value;
+ }
+ if (($toUOM == 'F') || ($toUOM == 'fah')) {
+ if (($fromUOM == 'K') || ($fromUOM == 'kel')) {
+ $value -= 273.15;
+ }
+ return ($value * 1.8) + 32;
+ }
+ if (($toUOM == 'C') || ($toUOM == 'cel')) {
+ return $value - 273.15;
+ }
+ return $value + 273.15;
+ }
+ return ($value * self::$_unitConversions[$unitGroup1][$fromUOM][$toUOM]) / $toMultiplier;
+ } // function CONVERTUOM()
}
diff --git a/Classes/PHPExcel/Calculation/Exception.php b/Classes/PHPExcel/Calculation/Exception.php
index 50e28d4..76e57c8 100644
--- a/Classes/PHPExcel/Calculation/Exception.php
+++ b/Classes/PHPExcel/Calculation/Exception.php
@@ -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;
+ }
}
diff --git a/Classes/PHPExcel/Calculation/ExceptionHandler.php b/Classes/PHPExcel/Calculation/ExceptionHandler.php
index 0858ea1..0ab908b 100644
--- a/Classes/PHPExcel/Calculation/ExceptionHandler.php
+++ b/Classes/PHPExcel/Calculation/ExceptionHandler.php
@@ -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();
+ }
}
diff --git a/Classes/PHPExcel/Calculation/Financial.php b/Classes/PHPExcel/Calculation/Financial.php
index 14d5be3..050ee22 100644
--- a/Classes/PHPExcel/Calculation/Financial.php
+++ b/Classes/PHPExcel/Calculation/Financial.php
@@ -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##
*/
@@ -38,2247 +38,2246 @@ define('FINANCIAL_PRECISION', 1.0e-08);
/**
* PHPExcel\Calculation_Financial
*
- * @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_Financial {
- /**
- * _lastDayOfMonth
- *
- * Returns a boolean TRUE/FALSE indicating if this date is the last date of the month
- *
- * @param DateTime $testDate The date for testing
- * @return boolean
- */
- private static function _lastDayOfMonth($testDate)
- {
- return ($testDate->format('d') == $testDate->format('t'));
- } // function _lastDayOfMonth()
+ /**
+ * _lastDayOfMonth
+ *
+ * Returns a boolean TRUE/FALSE indicating if this date is the last date of the month
+ *
+ * @param DateTime $testDate The date for testing
+ * @return boolean
+ */
+ private static function _lastDayOfMonth($testDate)
+ {
+ return ($testDate->format('d') == $testDate->format('t'));
+ } // function _lastDayOfMonth()
- /**
- * _firstDayOfMonth
- *
- * Returns a boolean TRUE/FALSE indicating if this date is the first date of the month
- *
- * @param DateTime $testDate The date for testing
- * @return boolean
- */
- private static function _firstDayOfMonth($testDate)
- {
- return ($testDate->format('d') == 1);
- } // function _firstDayOfMonth()
+ /**
+ * _firstDayOfMonth
+ *
+ * Returns a boolean TRUE/FALSE indicating if this date is the first date of the month
+ *
+ * @param DateTime $testDate The date for testing
+ * @return boolean
+ */
+ private static function _firstDayOfMonth($testDate)
+ {
+ return ($testDate->format('d') == 1);
+ } // function _firstDayOfMonth()
- private static function _coupFirstPeriodDate($settlement, $maturity, $frequency, $next)
- {
- $months = 12 / $frequency;
+ private static function _coupFirstPeriodDate($settlement, $maturity, $frequency, $next)
+ {
+ $months = 12 / $frequency;
- $result = Shared_Date::ExcelToPHPObject($maturity);
- $eom = self::_lastDayOfMonth($result);
+ $result = Shared_Date::ExcelToPHPObject($maturity);
+ $eom = self::_lastDayOfMonth($result);
- while ($settlement < Shared_Date::PHPToExcel($result)) {
- $result->modify('-'.$months.' months');
- }
- if ($next) {
- $result->modify('+'.$months.' months');
- }
+ while ($settlement < Shared_Date::PHPToExcel($result)) {
+ $result->modify('-'.$months.' months');
+ }
+ if ($next) {
+ $result->modify('+'.$months.' months');
+ }
- if ($eom) {
- $result->modify('-1 day');
- }
+ if ($eom) {
+ $result->modify('-1 day');
+ }
- return Shared_Date::PHPToExcel($result);
- } // function _coupFirstPeriodDate()
+ return Shared_Date::PHPToExcel($result);
+ } // function _coupFirstPeriodDate()
- private static function _validFrequency($frequency)
- {
- if (($frequency == 1) || ($frequency == 2) || ($frequency == 4)) {
- return true;
- }
- if ((Calculation_Functions::getCompatibilityMode() == Calculation_Functions::COMPATIBILITY_GNUMERIC) &&
- (($frequency == 6) || ($frequency == 12))) {
- return true;
- }
- return false;
- } // function _validFrequency()
+ private static function _validFrequency($frequency)
+ {
+ if (($frequency == 1) || ($frequency == 2) || ($frequency == 4)) {
+ return true;
+ }
+ if ((Calculation_Functions::getCompatibilityMode() == Calculation_Functions::COMPATIBILITY_GNUMERIC) &&
+ (($frequency == 6) || ($frequency == 12))) {
+ return true;
+ }
+ return false;
+ } // function _validFrequency()
- /**
- * _daysPerYear
- *
- * Returns the number of days in a specified year, as defined by the "basis" value
- *
- * @param integer $year The year against which we're testing
- * @param integer $basis The type of day count:
- * 0 or omitted US (NASD) 360
- * 1 Actual (365 or 366 in a leap year)
- * 2 360
- * 3 365
- * 4 European 360
- * @return integer
- */
- private static function _daysPerYear($year, $basis=0)
- {
- switch ($basis) {
- case 0 :
- case 2 :
- case 4 :
- $daysPerYear = 360;
- break;
- case 3 :
- $daysPerYear = 365;
- break;
- case 1 :
- $daysPerYear = (Calculation_DateTime::_isLeapYear($year)) ? 366 : 365;
- break;
- default :
- return Calculation_Functions::NaN();
- }
- return $daysPerYear;
- } // function _daysPerYear()
+ /**
+ * _daysPerYear
+ *
+ * Returns the number of days in a specified year, as defined by the "basis" value
+ *
+ * @param integer $year The year against which we're testing
+ * @param integer $basis The type of day count:
+ * 0 or omitted US (NASD) 360
+ * 1 Actual (365 or 366 in a leap year)
+ * 2 360
+ * 3 365
+ * 4 European 360
+ * @return integer
+ */
+ private static function _daysPerYear($year, $basis=0)
+ {
+ switch ($basis) {
+ case 0 :
+ case 2 :
+ case 4 :
+ $daysPerYear = 360;
+ break;
+ case 3 :
+ $daysPerYear = 365;
+ break;
+ case 1 :
+ $daysPerYear = (Calculation_DateTime::_isLeapYear($year)) ? 366 : 365;
+ break;
+ default :
+ return Calculation_Functions::NaN();
+ }
+ return $daysPerYear;
+ } // function _daysPerYear()
- private static function _interestAndPrincipal($rate=0, $per=0, $nper=0, $pv=0, $fv=0, $type=0)
- {
- $pmt = self::PMT($rate, $nper, $pv, $fv, $type);
- $capital = $pv;
- for ($i = 1; $i<= $per; ++$i) {
- $interest = ($type && $i == 1) ? 0 : -$capital * $rate;
- $principal = $pmt - $interest;
- $capital += $principal;
- }
- return array($interest, $principal);
- } // function _interestAndPrincipal()
+ private static function _interestAndPrincipal($rate=0, $per=0, $nper=0, $pv=0, $fv=0, $type=0)
+ {
+ $pmt = self::PMT($rate, $nper, $pv, $fv, $type);
+ $capital = $pv;
+ for ($i = 1; $i<= $per; ++$i) {
+ $interest = ($type && $i == 1) ? 0 : -$capital * $rate;
+ $principal = $pmt - $interest;
+ $capital += $principal;
+ }
+ return array($interest, $principal);
+ } // function _interestAndPrincipal()
- /**
- * ACCRINT
- *
- * Returns the accrued interest for a security that pays periodic interest.
- *
- * Excel Function:
- * ACCRINT(issue,firstinterest,settlement,rate,par,frequency[,basis])
- *
- * @access public
- * @category Financial Functions
- * @param mixed $issue The security's issue date.
- * @param mixed $firstinterest The security's first interest date.
- * @param mixed $settlement The security's settlement date.
- * The security settlement date is the date after the issue date
- * when the security is traded to the buyer.
- * @param float $rate The security's annual coupon rate.
- * @param float $par The security's par value.
- * If you omit par, ACCRINT uses $1,000.
- * @param integer $frequency the number of coupon payments per year.
- * Valid frequency values are:
- * 1 Annual
- * 2 Semi-Annual
- * 4 Quarterly
- * If working in Gnumeric Mode, the following frequency options are
- * also available
- * 6 Bimonthly
- * 12 Monthly
- * @param integer $basis The type of day count to use.
- * 0 or omitted US (NASD) 30/360
- * 1 Actual/actual
- * 2 Actual/360
- * 3 Actual/365
- * 4 European 30/360
- * @return float
- */
- public static function ACCRINT($issue, $firstinterest, $settlement, $rate, $par=1000, $frequency=1, $basis=0)
- {
- $issue = Calculation_Functions::flattenSingleValue($issue);
- $firstinterest = Calculation_Functions::flattenSingleValue($firstinterest);
- $settlement = Calculation_Functions::flattenSingleValue($settlement);
- $rate = Calculation_Functions::flattenSingleValue($rate);
- $par = (is_null($par)) ? 1000 : Calculation_Functions::flattenSingleValue($par);
- $frequency = (is_null($frequency)) ? 1 : Calculation_Functions::flattenSingleValue($frequency);
- $basis = (is_null($basis)) ? 0 : Calculation_Functions::flattenSingleValue($basis);
+ /**
+ * ACCRINT
+ *
+ * Returns the accrued interest for a security that pays periodic interest.
+ *
+ * Excel Function:
+ * ACCRINT(issue,firstinterest,settlement,rate,par,frequency[,basis])
+ *
+ * @access public
+ * @category Financial Functions
+ * @param mixed $issue The security's issue date.
+ * @param mixed $firstinterest The security's first interest date.
+ * @param mixed $settlement The security's settlement date.
+ * The security settlement date is the date after the issue date
+ * when the security is traded to the buyer.
+ * @param float $rate The security's annual coupon rate.
+ * @param float $par The security's par value.
+ * If you omit par, ACCRINT uses $1,000.
+ * @param integer $frequency the number of coupon payments per year.
+ * Valid frequency values are:
+ * 1 Annual
+ * 2 Semi-Annual
+ * 4 Quarterly
+ * If working in Gnumeric Mode, the following frequency options are
+ * also available
+ * 6 Bimonthly
+ * 12 Monthly
+ * @param integer $basis The type of day count to use.
+ * 0 or omitted US (NASD) 30/360
+ * 1 Actual/actual
+ * 2 Actual/360
+ * 3 Actual/365
+ * 4 European 30/360
+ * @return float
+ */
+ public static function ACCRINT($issue, $firstinterest, $settlement, $rate, $par=1000, $frequency=1, $basis=0)
+ {
+ $issue = Calculation_Functions::flattenSingleValue($issue);
+ $firstinterest = Calculation_Functions::flattenSingleValue($firstinterest);
+ $settlement = Calculation_Functions::flattenSingleValue($settlement);
+ $rate = Calculation_Functions::flattenSingleValue($rate);
+ $par = (is_null($par)) ? 1000 : Calculation_Functions::flattenSingleValue($par);
+ $frequency = (is_null($frequency)) ? 1 : Calculation_Functions::flattenSingleValue($frequency);
+ $basis = (is_null($basis)) ? 0 : Calculation_Functions::flattenSingleValue($basis);
- // Validate
- if ((is_numeric($rate)) && (is_numeric($par))) {
- $rate = (float) $rate;
- $par = (float) $par;
- if (($rate <= 0) || ($par <= 0)) {
- return Calculation_Functions::NaN();
- }
- $daysBetweenIssueAndSettlement = Calculation_DateTime::YEARFRAC($issue, $settlement, $basis);
- if (!is_numeric($daysBetweenIssueAndSettlement)) {
- // return date error
- return $daysBetweenIssueAndSettlement;
- }
+ // Validate
+ if ((is_numeric($rate)) && (is_numeric($par))) {
+ $rate = (float) $rate;
+ $par = (float) $par;
+ if (($rate <= 0) || ($par <= 0)) {
+ return Calculation_Functions::NaN();
+ }
+ $daysBetweenIssueAndSettlement = Calculation_DateTime::YEARFRAC($issue, $settlement, $basis);
+ if (!is_numeric($daysBetweenIssueAndSettlement)) {
+ // return date error
+ return $daysBetweenIssueAndSettlement;
+ }
- return $par * $rate * $daysBetweenIssueAndSettlement;
- }
- return Calculation_Functions::VALUE();
- } // function ACCRINT()
+ return $par * $rate * $daysBetweenIssueAndSettlement;
+ }
+ return Calculation_Functions::VALUE();
+ } // function ACCRINT()
- /**
- * ACCRINTM
- *
- * Returns the accrued interest for a security that pays interest at maturity.
- *
- * Excel Function:
- * ACCRINTM(issue,settlement,rate[,par[,basis]])
- *
- * @access public
- * @category Financial Functions
- * @param mixed issue The security's issue date.
- * @param mixed settlement The security's settlement (or maturity) date.
- * @param float rate The security's annual coupon rate.
- * @param float par The security's par value.
- * If you omit par, ACCRINT uses $1,000.
- * @param integer basis The type of day count to use.
- * 0 or omitted US (NASD) 30/360
- * 1 Actual/actual
- * 2 Actual/360
- * 3 Actual/365
- * 4 European 30/360
- * @return float
- */
- public static function ACCRINTM($issue, $settlement, $rate, $par=1000, $basis=0) {
- $issue = Calculation_Functions::flattenSingleValue($issue);
- $settlement = Calculation_Functions::flattenSingleValue($settlement);
- $rate = Calculation_Functions::flattenSingleValue($rate);
- $par = (is_null($par)) ? 1000 : Calculation_Functions::flattenSingleValue($par);
- $basis = (is_null($basis)) ? 0 : Calculation_Functions::flattenSingleValue($basis);
+ /**
+ * ACCRINTM
+ *
+ * Returns the accrued interest for a security that pays interest at maturity.
+ *
+ * Excel Function:
+ * ACCRINTM(issue,settlement,rate[,par[,basis]])
+ *
+ * @access public
+ * @category Financial Functions
+ * @param mixed issue The security's issue date.
+ * @param mixed settlement The security's settlement (or maturity) date.
+ * @param float rate The security's annual coupon rate.
+ * @param float par The security's par value.
+ * If you omit par, ACCRINT uses $1,000.
+ * @param integer basis The type of day count to use.
+ * 0 or omitted US (NASD) 30/360
+ * 1 Actual/actual
+ * 2 Actual/360
+ * 3 Actual/365
+ * 4 European 30/360
+ * @return float
+ */
+ public static function ACCRINTM($issue, $settlement, $rate, $par=1000, $basis=0) {
+ $issue = Calculation_Functions::flattenSingleValue($issue);
+ $settlement = Calculation_Functions::flattenSingleValue($settlement);
+ $rate = Calculation_Functions::flattenSingleValue($rate);
+ $par = (is_null($par)) ? 1000 : Calculation_Functions::flattenSingleValue($par);
+ $basis = (is_null($basis)) ? 0 : Calculation_Functions::flattenSingleValue($basis);
- // Validate
- if ((is_numeric($rate)) && (is_numeric($par))) {
- $rate = (float) $rate;
- $par = (float) $par;
- if (($rate <= 0) || ($par <= 0)) {
- return Calculation_Functions::NaN();
- }
- $daysBetweenIssueAndSettlement = Calculation_DateTime::YEARFRAC($issue, $settlement, $basis);
- if (!is_numeric($daysBetweenIssueAndSettlement)) {
- // return date error
- return $daysBetweenIssueAndSettlement;
- }
- return $par * $rate * $daysBetweenIssueAndSettlement;
- }
- return Calculation_Functions::VALUE();
- } // function ACCRINTM()
+ // Validate
+ if ((is_numeric($rate)) && (is_numeric($par))) {
+ $rate = (float) $rate;
+ $par = (float) $par;
+ if (($rate <= 0) || ($par <= 0)) {
+ return Calculation_Functions::NaN();
+ }
+ $daysBetweenIssueAndSettlement = Calculation_DateTime::YEARFRAC($issue, $settlement, $basis);
+ if (!is_numeric($daysBetweenIssueAndSettlement)) {
+ // return date error
+ return $daysBetweenIssueAndSettlement;
+ }
+ return $par * $rate * $daysBetweenIssueAndSettlement;
+ }
+ return Calculation_Functions::VALUE();
+ } // function ACCRINTM()
- /**
- * AMORDEGRC
- *
- * Returns the depreciation for each accounting period.
- * This function is provided for the French accounting system. If an asset is purchased in
- * the middle of the accounting period, the prorated depreciation is taken into account.
- * The function is similar to AMORLINC, except that a depreciation coefficient is applied in
- * the calculation depending on the life of the assets.
- * This function will return the depreciation until the last period of the life of the assets
- * or until the cumulated value of depreciation is greater than the cost of the assets minus
- * the salvage value.
- *
- * Excel Function:
- * AMORDEGRC(cost,purchased,firstPeriod,salvage,period,rate[,basis])
- *
- * @access public
- * @category Financial Functions
- * @param float cost The cost of the asset.
- * @param mixed purchased Date of the purchase of the asset.
- * @param mixed firstPeriod Date of the end of the first period.
- * @param mixed salvage The salvage value at the end of the life of the asset.
- * @param float period The period.
- * @param float rate Rate of depreciation.
- * @param integer basis The type of day count to use.
- * 0 or omitted US (NASD) 30/360
- * 1 Actual/actual
- * 2 Actual/360
- * 3 Actual/365
- * 4 European 30/360
- * @return float
- */
- public static function AMORDEGRC($cost, $purchased, $firstPeriod, $salvage, $period, $rate, $basis=0) {
- $cost = Calculation_Functions::flattenSingleValue($cost);
- $purchased = Calculation_Functions::flattenSingleValue($purchased);
- $firstPeriod = Calculation_Functions::flattenSingleValue($firstPeriod);
- $salvage = Calculation_Functions::flattenSingleValue($salvage);
- $period = floor(Calculation_Functions::flattenSingleValue($period));
- $rate = Calculation_Functions::flattenSingleValue($rate);
- $basis = (is_null($basis)) ? 0 : (int) Calculation_Functions::flattenSingleValue($basis);
+ /**
+ * AMORDEGRC
+ *
+ * Returns the depreciation for each accounting period.
+ * This function is provided for the French accounting system. If an asset is purchased in
+ * the middle of the accounting period, the prorated depreciation is taken into account.
+ * The function is similar to AMORLINC, except that a depreciation coefficient is applied in
+ * the calculation depending on the life of the assets.
+ * This function will return the depreciation until the last period of the life of the assets
+ * or until the cumulated value of depreciation is greater than the cost of the assets minus
+ * the salvage value.
+ *
+ * Excel Function:
+ * AMORDEGRC(cost,purchased,firstPeriod,salvage,period,rate[,basis])
+ *
+ * @access public
+ * @category Financial Functions
+ * @param float cost The cost of the asset.
+ * @param mixed purchased Date of the purchase of the asset.
+ * @param mixed firstPeriod Date of the end of the first period.
+ * @param mixed salvage The salvage value at the end of the life of the asset.
+ * @param float period The period.
+ * @param float rate Rate of depreciation.
+ * @param integer basis The type of day count to use.
+ * 0 or omitted US (NASD) 30/360
+ * 1 Actual/actual
+ * 2 Actual/360
+ * 3 Actual/365
+ * 4 European 30/360
+ * @return float
+ */
+ public static function AMORDEGRC($cost, $purchased, $firstPeriod, $salvage, $period, $rate, $basis=0) {
+ $cost = Calculation_Functions::flattenSingleValue($cost);
+ $purchased = Calculation_Functions::flattenSingleValue($purchased);
+ $firstPeriod = Calculation_Functions::flattenSingleValue($firstPeriod);
+ $salvage = Calculation_Functions::flattenSingleValue($salvage);
+ $period = floor(Calculation_Functions::flattenSingleValue($period));
+ $rate = Calculation_Functions::flattenSingleValue($rate);
+ $basis = (is_null($basis)) ? 0 : (int) Calculation_Functions::flattenSingleValue($basis);
- // The depreciation coefficients are:
- // Life of assets (1/rate) Depreciation coefficient
- // Less than 3 years 1
- // Between 3 and 4 years 1.5
- // Between 5 and 6 years 2
- // More than 6 years 2.5
- $fUsePer = 1.0 / $rate;
- if ($fUsePer < 3.0) {
- $amortiseCoeff = 1.0;
- } elseif ($fUsePer < 5.0) {
- $amortiseCoeff = 1.5;
- } elseif ($fUsePer <= 6.0) {
- $amortiseCoeff = 2.0;
- } else {
- $amortiseCoeff = 2.5;
- }
+ // The depreciation coefficients are:
+ // Life of assets (1/rate) Depreciation coefficient
+ // Less than 3 years 1
+ // Between 3 and 4 years 1.5
+ // Between 5 and 6 years 2
+ // More than 6 years 2.5
+ $fUsePer = 1.0 / $rate;
+ if ($fUsePer < 3.0) {
+ $amortiseCoeff = 1.0;
+ } elseif ($fUsePer < 5.0) {
+ $amortiseCoeff = 1.5;
+ } elseif ($fUsePer <= 6.0) {
+ $amortiseCoeff = 2.0;
+ } else {
+ $amortiseCoeff = 2.5;
+ }
- $rate *= $amortiseCoeff;
- $fNRate = round(Calculation_DateTime::YEARFRAC($purchased, $firstPeriod, $basis) * $rate * $cost,0);
- $cost -= $fNRate;
- $fRest = $cost - $salvage;
+ $rate *= $amortiseCoeff;
+ $fNRate = round(Calculation_DateTime::YEARFRAC($purchased, $firstPeriod, $basis) * $rate * $cost,0);
+ $cost -= $fNRate;
+ $fRest = $cost - $salvage;
- for ($n = 0; $n < $period; ++$n) {
- $fNRate = round($rate * $cost,0);
- $fRest -= $fNRate;
+ for ($n = 0; $n < $period; ++$n) {
+ $fNRate = round($rate * $cost,0);
+ $fRest -= $fNRate;
- if ($fRest < 0.0) {
- switch ($period - $n) {
- case 0 :
- case 1 : return round($cost * 0.5, 0);
- break;
- default : return 0.0;
- break;
- }
- }
- $cost -= $fNRate;
- }
- return $fNRate;
- } // function AMORDEGRC()
+ if ($fRest < 0.0) {
+ switch ($period - $n) {
+ case 0 :
+ case 1 : return round($cost * 0.5, 0);
+ break;
+ default : return 0.0;
+ break;
+ }
+ }
+ $cost -= $fNRate;
+ }
+ return $fNRate;
+ } // function AMORDEGRC()
- /**
- * AMORLINC
- *
- * Returns the depreciation for each accounting period.
- * This function is provided for the French accounting system. If an asset is purchased in
- * the middle of the accounting period, the prorated depreciation is taken into account.
- *
- * Excel Function:
- * AMORLINC(cost,purchased,firstPeriod,salvage,period,rate[,basis])
- *
- * @access public
- * @category Financial Functions
- * @param float cost The cost of the asset.
- * @param mixed purchased Date of the purchase of the asset.
- * @param mixed firstPeriod Date of the end of the first period.
- * @param mixed salvage The salvage value at the end of the life of the asset.
- * @param float period The period.
- * @param float rate Rate of depreciation.
- * @param integer basis The type of day count to use.
- * 0 or omitted US (NASD) 30/360
- * 1 Actual/actual
- * 2 Actual/360
- * 3 Actual/365
- * 4 European 30/360
- * @return float
- */
- public static function AMORLINC($cost, $purchased, $firstPeriod, $salvage, $period, $rate, $basis=0) {
- $cost = Calculation_Functions::flattenSingleValue($cost);
- $purchased = Calculation_Functions::flattenSingleValue($purchased);
- $firstPeriod = Calculation_Functions::flattenSingleValue($firstPeriod);
- $salvage = Calculation_Functions::flattenSingleValue($salvage);
- $period = Calculation_Functions::flattenSingleValue($period);
- $rate = Calculation_Functions::flattenSingleValue($rate);
- $basis = (is_null($basis)) ? 0 : (int) Calculation_Functions::flattenSingleValue($basis);
+ /**
+ * AMORLINC
+ *
+ * Returns the depreciation for each accounting period.
+ * This function is provided for the French accounting system. If an asset is purchased in
+ * the middle of the accounting period, the prorated depreciation is taken into account.
+ *
+ * Excel Function:
+ * AMORLINC(cost,purchased,firstPeriod,salvage,period,rate[,basis])
+ *
+ * @access public
+ * @category Financial Functions
+ * @param float cost The cost of the asset.
+ * @param mixed purchased Date of the purchase of the asset.
+ * @param mixed firstPeriod Date of the end of the first period.
+ * @param mixed salvage The salvage value at the end of the life of the asset.
+ * @param float period The period.
+ * @param float rate Rate of depreciation.
+ * @param integer basis The type of day count to use.
+ * 0 or omitted US (NASD) 30/360
+ * 1 Actual/actual
+ * 2 Actual/360
+ * 3 Actual/365
+ * 4 European 30/360
+ * @return float
+ */
+ public static function AMORLINC($cost, $purchased, $firstPeriod, $salvage, $period, $rate, $basis=0) {
+ $cost = Calculation_Functions::flattenSingleValue($cost);
+ $purchased = Calculation_Functions::flattenSingleValue($purchased);
+ $firstPeriod = Calculation_Functions::flattenSingleValue($firstPeriod);
+ $salvage = Calculation_Functions::flattenSingleValue($salvage);
+ $period = Calculation_Functions::flattenSingleValue($period);
+ $rate = Calculation_Functions::flattenSingleValue($rate);
+ $basis = (is_null($basis)) ? 0 : (int) Calculation_Functions::flattenSingleValue($basis);
- $fOneRate = $cost * $rate;
- $fCostDelta = $cost - $salvage;
- // Note, quirky variation for leap years on the YEARFRAC for this function
- $purchasedYear = Calculation_DateTime::YEAR($purchased);
- $yearFrac = Calculation_DateTime::YEARFRAC($purchased, $firstPeriod, $basis);
+ $fOneRate = $cost * $rate;
+ $fCostDelta = $cost - $salvage;
+ // Note, quirky variation for leap years on the YEARFRAC for this function
+ $purchasedYear = Calculation_DateTime::YEAR($purchased);
+ $yearFrac = Calculation_DateTime::YEARFRAC($purchased, $firstPeriod, $basis);
- if (($basis == 1) && ($yearFrac < 1) && (Calculation_DateTime::_isLeapYear($purchasedYear))) {
- $yearFrac *= 365 / 366;
- }
+ if (($basis == 1) && ($yearFrac < 1) && (Calculation_DateTime::_isLeapYear($purchasedYear))) {
+ $yearFrac *= 365 / 366;
+ }
- $f0Rate = $yearFrac * $rate * $cost;
- $nNumOfFullPeriods = intval(($cost - $salvage - $f0Rate) / $fOneRate);
+ $f0Rate = $yearFrac * $rate * $cost;
+ $nNumOfFullPeriods = intval(($cost - $salvage - $f0Rate) / $fOneRate);
- if ($period == 0) {
- return $f0Rate;
- } elseif ($period <= $nNumOfFullPeriods) {
- return $fOneRate;
- } elseif ($period == ($nNumOfFullPeriods + 1)) {
+ if ($period == 0) {
+ return $f0Rate;
+ } elseif ($period <= $nNumOfFullPeriods) {
+ return $fOneRate;
+ } elseif ($period == ($nNumOfFullPeriods + 1)) {
return ($fCostDelta - $fOneRate * $nNumOfFullPeriods - $f0Rate);
- } else {
- return 0.0;
- }
- } // function AMORLINC()
-
-
- /**
- * COUPDAYBS
- *
- * Returns the number of days from the beginning of the coupon period to the settlement date.
- *
- * Excel Function:
- * COUPDAYBS(settlement,maturity,frequency[,basis])
- *
- * @access public
- * @category Financial Functions
- * @param mixed settlement The security's settlement date.
- * The security settlement date is the date after the issue
- * date when the security is traded to the buyer.
- * @param mixed maturity The security's maturity date.
- * The maturity date is the date when the security expires.
- * @param mixed frequency the number of coupon payments per year.
- * Valid frequency values are:
- * 1 Annual
- * 2 Semi-Annual
- * 4 Quarterly
- * If working in Gnumeric Mode, the following frequency options are
- * also available
- * 6 Bimonthly
- * 12 Monthly
- * @param integer basis The type of day count to use.
- * 0 or omitted US (NASD) 30/360
- * 1 Actual/actual
- * 2 Actual/360
- * 3 Actual/365
- * 4 European 30/360
- * @return float
- */
- public static function COUPDAYBS($settlement, $maturity, $frequency, $basis=0) {
- $settlement = Calculation_Functions::flattenSingleValue($settlement);
- $maturity = Calculation_Functions::flattenSingleValue($maturity);
- $frequency = (int) Calculation_Functions::flattenSingleValue($frequency);
- $basis = (is_null($basis)) ? 0 : (int) Calculation_Functions::flattenSingleValue($basis);
-
- if (is_string($settlement = Calculation_DateTime::_getDateValue($settlement))) {
- return Calculation_Functions::VALUE();
- }
- if (is_string($maturity = Calculation_DateTime::_getDateValue($maturity))) {
- return Calculation_Functions::VALUE();
- }
-
- if (($settlement > $maturity) ||
- (!self::_validFrequency($frequency)) ||
- (($basis < 0) || ($basis > 4))) {
- return Calculation_Functions::NaN();
- }
-
- $daysPerYear = self::_daysPerYear(Calculation_DateTime::YEAR($settlement),$basis);
- $prev = self::_coupFirstPeriodDate($settlement, $maturity, $frequency, False);
-
- return Calculation_DateTime::YEARFRAC($prev, $settlement, $basis) * $daysPerYear;
- } // function COUPDAYBS()
-
-
- /**
- * COUPDAYS
- *
- * Returns the number of days in the coupon period that contains the settlement date.
- *
- * Excel Function:
- * COUPDAYS(settlement,maturity,frequency[,basis])
- *
- * @access public
- * @category Financial Functions
- * @param mixed settlement The security's settlement date.
- * The security settlement date is the date after the issue
- * date when the security is traded to the buyer.
- * @param mixed maturity The security's maturity date.
- * The maturity date is the date when the security expires.
- * @param mixed frequency the number of coupon payments per year.
- * Valid frequency values are:
- * 1 Annual
- * 2 Semi-Annual
- * 4 Quarterly
- * If working in Gnumeric Mode, the following frequency options are
- * also available
- * 6 Bimonthly
- * 12 Monthly
- * @param integer basis The type of day count to use.
- * 0 or omitted US (NASD) 30/360
- * 1 Actual/actual
- * 2 Actual/360
- * 3 Actual/365
- * 4 European 30/360
- * @return float
- */
- public static function COUPDAYS($settlement, $maturity, $frequency, $basis=0) {
- $settlement = Calculation_Functions::flattenSingleValue($settlement);
- $maturity = Calculation_Functions::flattenSingleValue($maturity);
- $frequency = (int) Calculation_Functions::flattenSingleValue($frequency);
- $basis = (is_null($basis)) ? 0 : (int) Calculation_Functions::flattenSingleValue($basis);
-
- if (is_string($settlement = Calculation_DateTime::_getDateValue($settlement))) {
- return Calculation_Functions::VALUE();
- }
- if (is_string($maturity = Calculation_DateTime::_getDateValue($maturity))) {
- return Calculation_Functions::VALUE();
- }
-
- if (($settlement > $maturity) ||
- (!self::_validFrequency($frequency)) ||
- (($basis < 0) || ($basis > 4))) {
- return Calculation_Functions::NaN();
- }
-
- switch ($basis) {
- case 3: // Actual/365
- return 365 / $frequency;
- case 1: // Actual/actual
- if ($frequency == 1) {
- $daysPerYear = self::_daysPerYear(Calculation_DateTime::YEAR($maturity),$basis);
- return ($daysPerYear / $frequency);
- } else {
- $prev = self::_coupFirstPeriodDate($settlement, $maturity, $frequency, False);
- $next = self::_coupFirstPeriodDate($settlement, $maturity, $frequency, True);
- return ($next - $prev);
- }
- default: // US (NASD) 30/360, Actual/360 or European 30/360
- return 360 / $frequency;
- }
- return Calculation_Functions::VALUE();
- } // function COUPDAYS()
-
-
- /**
- * COUPDAYSNC
- *
- * Returns the number of days from the settlement date to the next coupon date.
- *
- * Excel Function:
- * COUPDAYSNC(settlement,maturity,frequency[,basis])
- *
- * @access public
- * @category Financial Functions
- * @param mixed settlement The security's settlement date.
- * The security settlement date is the date after the issue
- * date when the security is traded to the buyer.
- * @param mixed maturity The security's maturity date.
- * The maturity date is the date when the security expires.
- * @param mixed frequency the number of coupon payments per year.
- * Valid frequency values are:
- * 1 Annual
- * 2 Semi-Annual
- * 4 Quarterly
- * If working in Gnumeric Mode, the following frequency options are
- * also available
- * 6 Bimonthly
- * 12 Monthly
- * @param integer basis The type of day count to use.
- * 0 or omitted US (NASD) 30/360
- * 1 Actual/actual
- * 2 Actual/360
- * 3 Actual/365
- * 4 European 30/360
- * @return float
- */
- public static function COUPDAYSNC($settlement, $maturity, $frequency, $basis=0) {
- $settlement = Calculation_Functions::flattenSingleValue($settlement);
- $maturity = Calculation_Functions::flattenSingleValue($maturity);
- $frequency = (int) Calculation_Functions::flattenSingleValue($frequency);
- $basis = (is_null($basis)) ? 0 : (int) Calculation_Functions::flattenSingleValue($basis);
-
- if (is_string($settlement = Calculation_DateTime::_getDateValue($settlement))) {
- return Calculation_Functions::VALUE();
- }
- if (is_string($maturity = Calculation_DateTime::_getDateValue($maturity))) {
- return Calculation_Functions::VALUE();
- }
-
- if (($settlement > $maturity) ||
- (!self::_validFrequency($frequency)) ||
- (($basis < 0) || ($basis > 4))) {
- return Calculation_Functions::NaN();
- }
-
- $daysPerYear = self::_daysPerYear(Calculation_DateTime::YEAR($settlement),$basis);
- $next = self::_coupFirstPeriodDate($settlement, $maturity, $frequency, True);
-
- return Calculation_DateTime::YEARFRAC($settlement, $next, $basis) * $daysPerYear;
- } // function COUPDAYSNC()
-
-
- /**
- * COUPNCD
- *
- * Returns the next coupon date after the settlement date.
- *
- * Excel Function:
- * COUPNCD(settlement,maturity,frequency[,basis])
- *
- * @access public
- * @category Financial Functions
- * @param mixed settlement The security's settlement date.
- * The security settlement date is the date after the issue
- * date when the security is traded to the buyer.
- * @param mixed maturity The security's maturity date.
- * The maturity date is the date when the security expires.
- * @param mixed frequency the number of coupon payments per year.
- * Valid frequency values are:
- * 1 Annual
- * 2 Semi-Annual
- * 4 Quarterly
- * If working in Gnumeric Mode, the following frequency options are
- * also available
- * 6 Bimonthly
- * 12 Monthly
- * @param integer basis The type of day count to use.
- * 0 or omitted US (NASD) 30/360
- * 1 Actual/actual
- * 2 Actual/360
- * 3 Actual/365
- * 4 European 30/360
- * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
- * depending on the value of the ReturnDateType flag
- */
- public static function COUPNCD($settlement, $maturity, $frequency, $basis=0) {
- $settlement = Calculation_Functions::flattenSingleValue($settlement);
- $maturity = Calculation_Functions::flattenSingleValue($maturity);
- $frequency = (int) Calculation_Functions::flattenSingleValue($frequency);
- $basis = (is_null($basis)) ? 0 : (int) Calculation_Functions::flattenSingleValue($basis);
-
- if (is_string($settlement = Calculation_DateTime::_getDateValue($settlement))) {
- return Calculation_Functions::VALUE();
- }
- if (is_string($maturity = Calculation_DateTime::_getDateValue($maturity))) {
- return Calculation_Functions::VALUE();
- }
-
- if (($settlement > $maturity) ||
- (!self::_validFrequency($frequency)) ||
- (($basis < 0) || ($basis > 4))) {
- return Calculation_Functions::NaN();
- }
-
- return self::_coupFirstPeriodDate($settlement, $maturity, $frequency, True);
- } // function COUPNCD()
-
-
- /**
- * COUPNUM
- *
- * Returns the number of coupons payable between the settlement date and maturity date,
- * rounded up to the nearest whole coupon.
- *
- * Excel Function:
- * COUPNUM(settlement,maturity,frequency[,basis])
- *
- * @access public
- * @category Financial Functions
- * @param mixed settlement The security's settlement date.
- * The security settlement date is the date after the issue
- * date when the security is traded to the buyer.
- * @param mixed maturity The security's maturity date.
- * The maturity date is the date when the security expires.
- * @param mixed frequency the number of coupon payments per year.
- * Valid frequency values are:
- * 1 Annual
- * 2 Semi-Annual
- * 4 Quarterly
- * If working in Gnumeric Mode, the following frequency options are
- * also available
- * 6 Bimonthly
- * 12 Monthly
- * @param integer basis The type of day count to use.
- * 0 or omitted US (NASD) 30/360
- * 1 Actual/actual
- * 2 Actual/360
- * 3 Actual/365
- * 4 European 30/360
- * @return integer
- */
- public static function COUPNUM($settlement, $maturity, $frequency, $basis=0) {
- $settlement = Calculation_Functions::flattenSingleValue($settlement);
- $maturity = Calculation_Functions::flattenSingleValue($maturity);
- $frequency = (int) Calculation_Functions::flattenSingleValue($frequency);
- $basis = (is_null($basis)) ? 0 : (int) Calculation_Functions::flattenSingleValue($basis);
-
- if (is_string($settlement = Calculation_DateTime::_getDateValue($settlement))) {
- return Calculation_Functions::VALUE();
- }
- if (is_string($maturity = Calculation_DateTime::_getDateValue($maturity))) {
- return Calculation_Functions::VALUE();
- }
-
- if (($settlement > $maturity) ||
- (!self::_validFrequency($frequency)) ||
- (($basis < 0) || ($basis > 4))) {
- return Calculation_Functions::NaN();
- }
-
- $settlement = self::_coupFirstPeriodDate($settlement, $maturity, $frequency, True);
- $daysBetweenSettlementAndMaturity = Calculation_DateTime::YEARFRAC($settlement, $maturity, $basis) * 365;
-
- switch ($frequency) {
- case 1: // annual payments
- return ceil($daysBetweenSettlementAndMaturity / 360);
- case 2: // half-yearly
- return ceil($daysBetweenSettlementAndMaturity / 180);
- case 4: // quarterly
- return ceil($daysBetweenSettlementAndMaturity / 90);
- case 6: // bimonthly
- return ceil($daysBetweenSettlementAndMaturity / 60);
- case 12: // monthly
- return ceil($daysBetweenSettlementAndMaturity / 30);
- }
- return Calculation_Functions::VALUE();
- } // function COUPNUM()
-
-
- /**
- * COUPPCD
- *
- * Returns the previous coupon date before the settlement date.
- *
- * Excel Function:
- * COUPPCD(settlement,maturity,frequency[,basis])
- *
- * @access public
- * @category Financial Functions
- * @param mixed settlement The security's settlement date.
- * The security settlement date is the date after the issue
- * date when the security is traded to the buyer.
- * @param mixed maturity The security's maturity date.
- * The maturity date is the date when the security expires.
- * @param mixed frequency the number of coupon payments per year.
- * Valid frequency values are:
- * 1 Annual
- * 2 Semi-Annual
- * 4 Quarterly
- * If working in Gnumeric Mode, the following frequency options are
- * also available
- * 6 Bimonthly
- * 12 Monthly
- * @param integer basis The type of day count to use.
- * 0 or omitted US (NASD) 30/360
- * 1 Actual/actual
- * 2 Actual/360
- * 3 Actual/365
- * 4 European 30/360
- * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
- * depending on the value of the ReturnDateType flag
- */
- public static function COUPPCD($settlement, $maturity, $frequency, $basis=0) {
- $settlement = Calculation_Functions::flattenSingleValue($settlement);
- $maturity = Calculation_Functions::flattenSingleValue($maturity);
- $frequency = (int) Calculation_Functions::flattenSingleValue($frequency);
- $basis = (is_null($basis)) ? 0 : (int) Calculation_Functions::flattenSingleValue($basis);
-
- if (is_string($settlement = Calculation_DateTime::_getDateValue($settlement))) {
- return Calculation_Functions::VALUE();
- }
- if (is_string($maturity = Calculation_DateTime::_getDateValue($maturity))) {
- return Calculation_Functions::VALUE();
- }
-
- if (($settlement > $maturity) ||
- (!self::_validFrequency($frequency)) ||
- (($basis < 0) || ($basis > 4))) {
- return Calculation_Functions::NaN();
- }
-
- return self::_coupFirstPeriodDate($settlement, $maturity, $frequency, False);
- } // function COUPPCD()
-
-
- /**
- * CUMIPMT
- *
- * Returns the cumulative interest paid on a loan between the start and end periods.
- *
- * Excel Function:
- * CUMIPMT(rate,nper,pv,start,end[,type])
- *
- * @access public
- * @category Financial Functions
- * @param float $rate The Interest rate
- * @param integer $nper The total number of payment periods
- * @param float $pv Present Value
- * @param integer $start The first period in the calculation.
- * Payment periods are numbered beginning with 1.
- * @param integer $end The last period in the calculation.
- * @param integer $type A number 0 or 1 and indicates when payments are due:
- * 0 or omitted At the end of the period.
- * 1 At the beginning of the period.
- * @return float
- */
- public static function CUMIPMT($rate, $nper, $pv, $start, $end, $type = 0) {
- $rate = Calculation_Functions::flattenSingleValue($rate);
- $nper = (int) Calculation_Functions::flattenSingleValue($nper);
- $pv = Calculation_Functions::flattenSingleValue($pv);
- $start = (int) Calculation_Functions::flattenSingleValue($start);
- $end = (int) Calculation_Functions::flattenSingleValue($end);
- $type = (int) Calculation_Functions::flattenSingleValue($type);
-
- // Validate parameters
- if ($type != 0 && $type != 1) {
- return Calculation_Functions::NaN();
- }
- if ($start < 1 || $start > $end) {
- return Calculation_Functions::VALUE();
- }
-
- // Calculate
- $interest = 0;
- for ($per = $start; $per <= $end; ++$per) {
- $interest += self::IPMT($rate, $per, $nper, $pv, 0, $type);
- }
-
- return $interest;
- } // function CUMIPMT()
-
-
- /**
- * CUMPRINC
- *
- * Returns the cumulative principal paid on a loan between the start and end periods.
- *
- * Excel Function:
- * CUMPRINC(rate,nper,pv,start,end[,type])
- *
- * @access public
- * @category Financial Functions
- * @param float $rate The Interest rate
- * @param integer $nper The total number of payment periods
- * @param float $pv Present Value
- * @param integer $start The first period in the calculation.
- * Payment periods are numbered beginning with 1.
- * @param integer $end The last period in the calculation.
- * @param integer $type A number 0 or 1 and indicates when payments are due:
- * 0 or omitted At the end of the period.
- * 1 At the beginning of the period.
- * @return float
- */
- public static function CUMPRINC($rate, $nper, $pv, $start, $end, $type = 0) {
- $rate = Calculation_Functions::flattenSingleValue($rate);
- $nper = (int) Calculation_Functions::flattenSingleValue($nper);
- $pv = Calculation_Functions::flattenSingleValue($pv);
- $start = (int) Calculation_Functions::flattenSingleValue($start);
- $end = (int) Calculation_Functions::flattenSingleValue($end);
- $type = (int) Calculation_Functions::flattenSingleValue($type);
-
- // Validate parameters
- if ($type != 0 && $type != 1) {
- return Calculation_Functions::NaN();
- }
- if ($start < 1 || $start > $end) {
- return Calculation_Functions::VALUE();
- }
-
- // Calculate
- $principal = 0;
- for ($per = $start; $per <= $end; ++$per) {
- $principal += self::PPMT($rate, $per, $nper, $pv, 0, $type);
- }
-
- return $principal;
- } // function CUMPRINC()
-
-
- /**
- * DB
- *
- * Returns the depreciation of an asset for a specified period using the
- * fixed-declining balance method.
- * This form of depreciation is used if you want to get a higher depreciation value
- * at the beginning of the depreciation (as opposed to linear depreciation). The
- * depreciation value is reduced with every depreciation period by the depreciation
- * already deducted from the initial cost.
- *
- * Excel Function:
- * DB(cost,salvage,life,period[,month])
- *
- * @access public
- * @category Financial Functions
- * @param float cost Initial cost of the asset.
- * @param float salvage Value at the end of the depreciation.
- * (Sometimes called the salvage value of the asset)
- * @param integer life Number of periods over which the asset is depreciated.
- * (Sometimes called the useful life of the asset)
- * @param integer period The period for which you want to calculate the
- * depreciation. Period must use the same units as life.
- * @param integer month Number of months in the first year. If month is omitted,
- * it defaults to 12.
- * @return float
- */
- public static function DB($cost, $salvage, $life, $period, $month=12) {
- $cost = Calculation_Functions::flattenSingleValue($cost);
- $salvage = Calculation_Functions::flattenSingleValue($salvage);
- $life = Calculation_Functions::flattenSingleValue($life);
- $period = Calculation_Functions::flattenSingleValue($period);
- $month = Calculation_Functions::flattenSingleValue($month);
-
- // Validate
- if ((is_numeric($cost)) && (is_numeric($salvage)) && (is_numeric($life)) && (is_numeric($period)) && (is_numeric($month))) {
- $cost = (float) $cost;
- $salvage = (float) $salvage;
- $life = (int) $life;
- $period = (int) $period;
- $month = (int) $month;
- if ($cost == 0) {
- return 0.0;
- } elseif (($cost < 0) || (($salvage / $cost) < 0) || ($life <= 0) || ($period < 1) || ($month < 1)) {
- return Calculation_Functions::NaN();
- }
- // Set Fixed Depreciation Rate
- $fixedDepreciationRate = 1 - pow(($salvage / $cost), (1 / $life));
- $fixedDepreciationRate = round($fixedDepreciationRate, 3);
-
- // Loop through each period calculating the depreciation
- $previousDepreciation = 0;
- for ($per = 1; $per <= $period; ++$per) {
- if ($per == 1) {
- $depreciation = $cost * $fixedDepreciationRate * $month / 12;
- } elseif ($per == ($life + 1)) {
- $depreciation = ($cost - $previousDepreciation) * $fixedDepreciationRate * (12 - $month) / 12;
- } else {
- $depreciation = ($cost - $previousDepreciation) * $fixedDepreciationRate;
- }
- $previousDepreciation += $depreciation;
- }
- if (Calculation_Functions::getCompatibilityMode() == Calculation_Functions::COMPATIBILITY_GNUMERIC) {
- $depreciation = round($depreciation,2);
- }
- return $depreciation;
- }
- return Calculation_Functions::VALUE();
- } // function DB()
-
-
- /**
- * DDB
- *
- * Returns the depreciation of an asset for a specified period using the
- * double-declining balance method or some other method you specify.
- *
- * Excel Function:
- * DDB(cost,salvage,life,period[,factor])
- *
- * @access public
- * @category Financial Functions
- * @param float cost Initial cost of the asset.
- * @param float salvage Value at the end of the depreciation.
- * (Sometimes called the salvage value of the asset)
- * @param integer life Number of periods over which the asset is depreciated.
- * (Sometimes called the useful life of the asset)
- * @param integer period The period for which you want to calculate the
- * depreciation. Period must use the same units as life.
- * @param float factor The rate at which the balance declines.
- * If factor is omitted, it is assumed to be 2 (the
- * double-declining balance method).
- * @return float
- */
- public static function DDB($cost, $salvage, $life, $period, $factor=2.0) {
- $cost = Calculation_Functions::flattenSingleValue($cost);
- $salvage = Calculation_Functions::flattenSingleValue($salvage);
- $life = Calculation_Functions::flattenSingleValue($life);
- $period = Calculation_Functions::flattenSingleValue($period);
- $factor = Calculation_Functions::flattenSingleValue($factor);
-
- // Validate
- if ((is_numeric($cost)) && (is_numeric($salvage)) && (is_numeric($life)) && (is_numeric($period)) && (is_numeric($factor))) {
- $cost = (float) $cost;
- $salvage = (float) $salvage;
- $life = (int) $life;
- $period = (int) $period;
- $factor = (float) $factor;
- if (($cost <= 0) || (($salvage / $cost) < 0) || ($life <= 0) || ($period < 1) || ($factor <= 0.0) || ($period > $life)) {
- return Calculation_Functions::NaN();
- }
- // Set Fixed Depreciation Rate
- $fixedDepreciationRate = 1 - pow(($salvage / $cost), (1 / $life));
- $fixedDepreciationRate = round($fixedDepreciationRate, 3);
-
- // Loop through each period calculating the depreciation
- $previousDepreciation = 0;
- for ($per = 1; $per <= $period; ++$per) {
- $depreciation = min( ($cost - $previousDepreciation) * ($factor / $life), ($cost - $salvage - $previousDepreciation) );
- $previousDepreciation += $depreciation;
- }
- if (Calculation_Functions::getCompatibilityMode() == Calculation_Functions::COMPATIBILITY_GNUMERIC) {
- $depreciation = round($depreciation,2);
- }
- return $depreciation;
- }
- return Calculation_Functions::VALUE();
- } // function DDB()
-
-
- /**
- * DISC
- *
- * Returns the discount rate for a security.
- *
- * Excel Function:
- * DISC(settlement,maturity,price,redemption[,basis])
- *
- * @access public
- * @category Financial Functions
- * @param mixed settlement The security's settlement date.
- * The security settlement date is the date after the issue
- * date when the security is traded to the buyer.
- * @param mixed maturity The security's maturity date.
- * The maturity date is the date when the security expires.
- * @param integer price The security's price per $100 face value.
- * @param integer redemption The security's redemption value per $100 face value.
- * @param integer basis The type of day count to use.
- * 0 or omitted US (NASD) 30/360
- * 1 Actual/actual
- * 2 Actual/360
- * 3 Actual/365
- * 4 European 30/360
- * @return float
- */
- public static function DISC($settlement, $maturity, $price, $redemption, $basis=0) {
- $settlement = Calculation_Functions::flattenSingleValue($settlement);
- $maturity = Calculation_Functions::flattenSingleValue($maturity);
- $price = Calculation_Functions::flattenSingleValue($price);
- $redemption = Calculation_Functions::flattenSingleValue($redemption);
- $basis = Calculation_Functions::flattenSingleValue($basis);
-
- // Validate
- if ((is_numeric($price)) && (is_numeric($redemption)) && (is_numeric($basis))) {
- $price = (float) $price;
- $redemption = (float) $redemption;
- $basis = (int) $basis;
- if (($price <= 0) || ($redemption <= 0)) {
- return Calculation_Functions::NaN();
- }
- $daysBetweenSettlementAndMaturity = Calculation_DateTime::YEARFRAC($settlement, $maturity, $basis);
- if (!is_numeric($daysBetweenSettlementAndMaturity)) {
- // return date error
- return $daysBetweenSettlementAndMaturity;
- }
-
- return ((1 - $price / $redemption) / $daysBetweenSettlementAndMaturity);
- }
- return Calculation_Functions::VALUE();
- } // function DISC()
-
-
- /**
- * DOLLARDE
- *
- * Converts a dollar price expressed as an integer part and a fraction
- * part into a dollar price expressed as a decimal number.
- * Fractional dollar numbers are sometimes used for security prices.
- *
- * Excel Function:
- * DOLLARDE(fractional_dollar,fraction)
- *
- * @access public
- * @category Financial Functions
- * @param float $fractional_dollar Fractional Dollar
- * @param integer $fraction Fraction
- * @return float
- */
- public static function DOLLARDE($fractional_dollar = Null, $fraction = 0) {
- $fractional_dollar = Calculation_Functions::flattenSingleValue($fractional_dollar);
- $fraction = (int)Calculation_Functions::flattenSingleValue($fraction);
-
- // Validate parameters
- if (is_null($fractional_dollar) || $fraction < 0) {
- return Calculation_Functions::NaN();
- }
- if ($fraction == 0) {
- return Calculation_Functions::DIV0();
- }
-
- $dollars = floor($fractional_dollar);
- $cents = fmod($fractional_dollar,1);
- $cents /= $fraction;
- $cents *= pow(10,ceil(log10($fraction)));
- return $dollars + $cents;
- } // function DOLLARDE()
-
-
- /**
- * DOLLARFR
- *
- * Converts a dollar price expressed as a decimal number into a dollar price
- * expressed as a fraction.
- * Fractional dollar numbers are sometimes used for security prices.
- *
- * Excel Function:
- * DOLLARFR(decimal_dollar,fraction)
- *
- * @access public
- * @category Financial Functions
- * @param float $decimal_dollar Decimal Dollar
- * @param integer $fraction Fraction
- * @return float
- */
- public static function DOLLARFR($decimal_dollar = Null, $fraction = 0) {
- $decimal_dollar = Calculation_Functions::flattenSingleValue($decimal_dollar);
- $fraction = (int)Calculation_Functions::flattenSingleValue($fraction);
-
- // Validate parameters
- if (is_null($decimal_dollar) || $fraction < 0) {
- return Calculation_Functions::NaN();
- }
- if ($fraction == 0) {
- return Calculation_Functions::DIV0();
- }
-
- $dollars = floor($decimal_dollar);
- $cents = fmod($decimal_dollar,1);
- $cents *= $fraction;
- $cents *= pow(10,-ceil(log10($fraction)));
- return $dollars + $cents;
- } // function DOLLARFR()
-
-
- /**
- * EFFECT
- *
- * Returns the effective interest rate given the nominal rate and the number of
- * compounding payments per year.
- *
- * Excel Function:
- * EFFECT(nominal_rate,npery)
- *
- * @access public
- * @category Financial Functions
- * @param float $nominal_rate Nominal interest rate
- * @param integer $npery Number of compounding payments per year
- * @return float
- */
- public static function EFFECT($nominal_rate = 0, $npery = 0) {
- $nominal_rate = Calculation_Functions::flattenSingleValue($nominal_rate);
- $npery = (int)Calculation_Functions::flattenSingleValue($npery);
-
- // Validate parameters
- if ($nominal_rate <= 0 || $npery < 1) {
- return Calculation_Functions::NaN();
- }
-
- return pow((1 + $nominal_rate / $npery), $npery) - 1;
- } // function EFFECT()
-
-
- /**
- * FV
- *
- * Returns the Future Value of a cash flow with constant payments and interest rate (annuities).
- *
- * Excel Function:
- * FV(rate,nper,pmt[,pv[,type]])
- *
- * @access public
- * @category Financial Functions
- * @param float $rate The interest rate per period
- * @param int $nper Total number of payment periods in an annuity
- * @param float $pmt The payment made each period: it cannot change over the
- * life of the annuity. Typically, pmt contains principal
- * and interest but no other fees or taxes.
- * @param float $pv Present Value, or the lump-sum amount that a series of
- * future payments is worth right now.
- * @param integer $type A number 0 or 1 and indicates when payments are due:
- * 0 or omitted At the end of the period.
- * 1 At the beginning of the period.
- * @return float
- */
- public static function FV($rate = 0, $nper = 0, $pmt = 0, $pv = 0, $type = 0) {
- $rate = Calculation_Functions::flattenSingleValue($rate);
- $nper = Calculation_Functions::flattenSingleValue($nper);
- $pmt = Calculation_Functions::flattenSingleValue($pmt);
- $pv = Calculation_Functions::flattenSingleValue($pv);
- $type = Calculation_Functions::flattenSingleValue($type);
-
- // Validate parameters
- if ($type != 0 && $type != 1) {
- return Calculation_Functions::NaN();
- }
-
- // Calculate
- if (!is_null($rate) && $rate != 0) {
- return -$pv * pow(1 + $rate, $nper) - $pmt * (1 + $rate * $type) * (pow(1 + $rate, $nper) - 1) / $rate;
- } else {
- return -$pv - $pmt * $nper;
- }
- } // function FV()
-
-
- /**
- * FVSCHEDULE
- *
- * Returns the future value of an initial principal after applying a series of compound interest rates.
- * Use FVSCHEDULE to calculate the future value of an investment with a variable or adjustable rate.
- *
- * Excel Function:
- * FVSCHEDULE(principal,schedule)
- *
- * @param float $principal The present value.
- * @param float[] $schedule An array of interest rates to apply.
- * @return float
- */
- public static function FVSCHEDULE($principal, $schedule) {
- $principal = Calculation_Functions::flattenSingleValue($principal);
- $schedule = Calculation_Functions::flattenArray($schedule);
-
- foreach($schedule as $rate) {
- $principal *= 1 + $rate;
- }
-
- return $principal;
- } // function FVSCHEDULE()
-
-
- /**
- * INTRATE
- *
- * Returns the interest rate for a fully invested security.
- *
- * Excel Function:
- * INTRATE(settlement,maturity,investment,redemption[,basis])
- *
- * @param mixed $settlement The security's settlement date.
- * The security settlement date is the date after the issue date when the security is traded to the buyer.
- * @param mixed $maturity The security's maturity date.
- * The maturity date is the date when the security expires.
- * @param integer $investment The amount invested in the security.
- * @param integer $redemption The amount to be received at maturity.
- * @param integer $basis The type of day count to use.
- * 0 or omitted US (NASD) 30/360
- * 1 Actual/actual
- * 2 Actual/360
- * 3 Actual/365
- * 4 European 30/360
- * @return float
- */
- public static function INTRATE($settlement, $maturity, $investment, $redemption, $basis=0) {
- $settlement = Calculation_Functions::flattenSingleValue($settlement);
- $maturity = Calculation_Functions::flattenSingleValue($maturity);
- $investment = Calculation_Functions::flattenSingleValue($investment);
- $redemption = Calculation_Functions::flattenSingleValue($redemption);
- $basis = Calculation_Functions::flattenSingleValue($basis);
-
- // Validate
- if ((is_numeric($investment)) && (is_numeric($redemption)) && (is_numeric($basis))) {
- $investment = (float) $investment;
- $redemption = (float) $redemption;
- $basis = (int) $basis;
- if (($investment <= 0) || ($redemption <= 0)) {
- return Calculation_Functions::NaN();
- }
- $daysBetweenSettlementAndMaturity = Calculation_DateTime::YEARFRAC($settlement, $maturity, $basis);
- if (!is_numeric($daysBetweenSettlementAndMaturity)) {
- // return date error
- return $daysBetweenSettlementAndMaturity;
- }
-
- return (($redemption / $investment) - 1) / ($daysBetweenSettlementAndMaturity);
- }
- return Calculation_Functions::VALUE();
- } // function INTRATE()
-
-
- /**
- * IPMT
- *
- * Returns the interest payment for a given period for an investment based on periodic, constant payments and a constant interest rate.
- *
- * Excel Function:
- * IPMT(rate,per,nper,pv[,fv][,type])
- *
- * @param float $rate Interest rate per period
- * @param int $per Period for which we want to find the interest
- * @param int $nper Number of periods
- * @param float $pv Present Value
- * @param float $fv Future Value
- * @param int $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period
- * @return float
- */
- public static function IPMT($rate, $per, $nper, $pv, $fv = 0, $type = 0) {
- $rate = Calculation_Functions::flattenSingleValue($rate);
- $per = (int) Calculation_Functions::flattenSingleValue($per);
- $nper = (int) Calculation_Functions::flattenSingleValue($nper);
- $pv = Calculation_Functions::flattenSingleValue($pv);
- $fv = Calculation_Functions::flattenSingleValue($fv);
- $type = (int) Calculation_Functions::flattenSingleValue($type);
-
- // Validate parameters
- if ($type != 0 && $type != 1) {
- return Calculation_Functions::NaN();
- }
- if ($per <= 0 || $per > $nper) {
- return Calculation_Functions::VALUE();
- }
-
- // Calculate
- $interestAndPrincipal = self::_interestAndPrincipal($rate, $per, $nper, $pv, $fv, $type);
- return $interestAndPrincipal[0];
- } // function IPMT()
-
- /**
- * IRR
- *
- * Returns the internal rate of return for a series of cash flows represented by the numbers in values.
- * These cash flows do not have to be even, as they would be for an annuity. However, the cash flows must occur
- * at regular intervals, such as monthly or annually. The internal rate of return is the interest rate received
- * for an investment consisting of payments (negative values) and income (positive values) that occur at regular
- * periods.
- *
- * Excel Function:
- * IRR(values[,guess])
- *
- * @param float[] $values An array or a reference to cells that contain numbers for which you want
- * to calculate the internal rate of return.
- * Values must contain at least one positive value and one negative value to
- * calculate the internal rate of return.
- * @param float $guess A number that you guess is close to the result of IRR
- * @return float
- */
- public static function IRR($values, $guess = 0.1) {
- if (!is_array($values)) return Calculation_Functions::VALUE();
- $values = Calculation_Functions::flattenArray($values);
- $guess = Calculation_Functions::flattenSingleValue($guess);
-
- // create an initial range, with a root somewhere between 0 and guess
- $x1 = 0.0;
- $x2 = $guess;
- $f1 = self::NPV($x1, $values);
- $f2 = self::NPV($x2, $values);
- for ($i = 0; $i < FINANCIAL_MAX_ITERATIONS; ++$i) {
- if (($f1 * $f2) < 0.0) break;
- if (abs($f1) < abs($f2)) {
- $f1 = self::NPV($x1 += 1.6 * ($x1 - $x2), $values);
- } else {
- $f2 = self::NPV($x2 += 1.6 * ($x2 - $x1), $values);
- }
- }
- if (($f1 * $f2) > 0.0) return Calculation_Functions::VALUE();
-
- $f = self::NPV($x1, $values);
- if ($f < 0.0) {
- $rtb = $x1;
- $dx = $x2 - $x1;
- } else {
- $rtb = $x2;
- $dx = $x1 - $x2;
- }
-
- for ($i = 0; $i < FINANCIAL_MAX_ITERATIONS; ++$i) {
- $dx *= 0.5;
- $x_mid = $rtb + $dx;
- $f_mid = self::NPV($x_mid, $values);
- if ($f_mid <= 0.0)
- $rtb = $x_mid;
- if ((abs($f_mid) < FINANCIAL_PRECISION) || (abs($dx) < FINANCIAL_PRECISION))
- return $x_mid;
- }
- return Calculation_Functions::VALUE();
- } // function IRR()
-
-
- /**
- * ISPMT
- *
- * Returns the interest payment for an investment based on an interest rate and a constant payment schedule.
- *
- * Excel Function:
- * =ISPMT(interest_rate, period, number_payments, PV)
- *
- * interest_rate is the interest rate for the investment
- *
- * period is the period to calculate the interest rate. It must be betweeen 1 and number_payments.
- *
- * number_payments is the number of payments for the annuity
- *
- * PV is the loan amount or present value of the payments
- */
- public static function ISPMT() {
- // Return value
- $returnValue = 0;
-
- // Get the parameters
- $aArgs = Calculation_Functions::flattenArray(func_get_args());
- $interestRate = array_shift($aArgs);
- $period = array_shift($aArgs);
- $numberPeriods = array_shift($aArgs);
- $principleRemaining = array_shift($aArgs);
-
- // Calculate
- $principlePayment = ($principleRemaining * 1.0) / ($numberPeriods * 1.0);
- for($i=0; $i <= $period; ++$i) {
- $returnValue = $interestRate * $principleRemaining * -1;
- $principleRemaining -= $principlePayment;
- // principle needs to be 0 after the last payment, don't let floating point screw it up
- if($i == $numberPeriods) {
- $returnValue = 0;
- }
- }
- return($returnValue);
- } // function ISPMT()
-
-
- /**
- * MIRR
- *
- * Returns the modified internal rate of return for a series of periodic cash flows. MIRR considers both
- * the cost of the investment and the interest received on reinvestment of cash.
- *
- * Excel Function:
- * MIRR(values,finance_rate, reinvestment_rate)
- *
- * @param float[] $values An array or a reference to cells that contain a series of payments and
- * income occurring at regular intervals.
- * Payments are negative value, income is positive values.
- * @param float $finance_rate The interest rate you pay on the money used in the cash flows
- * @param float $reinvestment_rate The interest rate you receive on the cash flows as you reinvest them
- * @return float
- */
- public static function MIRR($values, $finance_rate, $reinvestment_rate) {
- if (!is_array($values)) return Calculation_Functions::VALUE();
- $values = Calculation_Functions::flattenArray($values);
- $finance_rate = Calculation_Functions::flattenSingleValue($finance_rate);
- $reinvestment_rate = Calculation_Functions::flattenSingleValue($reinvestment_rate);
- $n = count($values);
-
- $rr = 1.0 + $reinvestment_rate;
- $fr = 1.0 + $finance_rate;
-
- $npv_pos = $npv_neg = 0.0;
- foreach($values as $i => $v) {
- if ($v >= 0) {
- $npv_pos += $v / pow($rr, $i);
- } else {
- $npv_neg += $v / pow($fr, $i);
- }
- }
-
- if (($npv_neg == 0) || ($npv_pos == 0) || ($reinvestment_rate <= -1)) {
- return Calculation_Functions::VALUE();
- }
-
- $mirr = pow((-$npv_pos * pow($rr, $n))
- / ($npv_neg * ($rr)), (1.0 / ($n - 1))) - 1.0;
-
- return (is_finite($mirr) ? $mirr : Calculation_Functions::VALUE());
- } // function MIRR()
-
-
- /**
- * NOMINAL
- *
- * Returns the nominal interest rate given the effective rate and the number of compounding payments per year.
- *
- * @param float $effect_rate Effective interest rate
- * @param int $npery Number of compounding payments per year
- * @return float
- */
- public static function NOMINAL($effect_rate = 0, $npery = 0) {
- $effect_rate = Calculation_Functions::flattenSingleValue($effect_rate);
- $npery = (int)Calculation_Functions::flattenSingleValue($npery);
-
- // Validate parameters
- if ($effect_rate <= 0 || $npery < 1) {
- return Calculation_Functions::NaN();
- }
-
- // Calculate
- return $npery * (pow($effect_rate + 1, 1 / $npery) - 1);
- } // function NOMINAL()
-
-
- /**
- * NPER
- *
- * Returns the number of periods for a cash flow with constant periodic payments (annuities), and interest rate.
- *
- * @param float $rate Interest rate per period
- * @param int $pmt Periodic payment (annuity)
- * @param float $pv Present Value
- * @param float $fv Future Value
- * @param int $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period
- * @return float
- */
- public static function NPER($rate = 0, $pmt = 0, $pv = 0, $fv = 0, $type = 0) {
- $rate = Calculation_Functions::flattenSingleValue($rate);
- $pmt = Calculation_Functions::flattenSingleValue($pmt);
- $pv = Calculation_Functions::flattenSingleValue($pv);
- $fv = Calculation_Functions::flattenSingleValue($fv);
- $type = Calculation_Functions::flattenSingleValue($type);
-
- // Validate parameters
- if ($type != 0 && $type != 1) {
- return Calculation_Functions::NaN();
- }
-
- // Calculate
- if (!is_null($rate) && $rate != 0) {
- if ($pmt == 0 && $pv == 0) {
- return Calculation_Functions::NaN();
- }
- return log(($pmt * (1 + $rate * $type) / $rate - $fv) / ($pv + $pmt * (1 + $rate * $type) / $rate)) / log(1 + $rate);
- } else {
- if ($pmt == 0) {
- return Calculation_Functions::NaN();
- }
- return (-$pv -$fv) / $pmt;
- }
- } // function NPER()
-
- /**
- * NPV
- *
- * Returns the Net Present Value of a cash flow series given a discount rate.
- *
- * @return float
- */
- public static function NPV() {
- // Return value
- $returnValue = 0;
-
- // Loop through arguments
- $aArgs = Calculation_Functions::flattenArray(func_get_args());
-
- // Calculate
- $rate = array_shift($aArgs);
- for ($i = 1; $i <= count($aArgs); ++$i) {
- // Is it a numeric value?
- if (is_numeric($aArgs[$i - 1])) {
- $returnValue += $aArgs[$i - 1] / pow(1 + $rate, $i);
- }
- }
-
- // Return
- return $returnValue;
- } // function NPV()
-
- /**
- * PMT
- *
- * Returns the constant payment (annuity) for a cash flow with a constant interest rate.
- *
- * @param float $rate Interest rate per period
- * @param int $nper Number of periods
- * @param float $pv Present Value
- * @param float $fv Future Value
- * @param int $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period
- * @return float
- */
- public static function PMT($rate = 0, $nper = 0, $pv = 0, $fv = 0, $type = 0) {
- $rate = Calculation_Functions::flattenSingleValue($rate);
- $nper = Calculation_Functions::flattenSingleValue($nper);
- $pv = Calculation_Functions::flattenSingleValue($pv);
- $fv = Calculation_Functions::flattenSingleValue($fv);
- $type = Calculation_Functions::flattenSingleValue($type);
-
- // Validate parameters
- if ($type != 0 && $type != 1) {
- return Calculation_Functions::NaN();
- }
-
- // Calculate
- if (!is_null($rate) && $rate != 0) {
- return (-$fv - $pv * pow(1 + $rate, $nper)) / (1 + $rate * $type) / ((pow(1 + $rate, $nper) - 1) / $rate);
- } else {
- return (-$pv - $fv) / $nper;
- }
- } // function PMT()
-
-
- /**
- * PPMT
- *
- * Returns the interest payment for a given period for an investment based on periodic, constant payments and a constant interest rate.
- *
- * @param float $rate Interest rate per period
- * @param int $per Period for which we want to find the interest
- * @param int $nper Number of periods
- * @param float $pv Present Value
- * @param float $fv Future Value
- * @param int $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period
- * @return float
- */
- public static function PPMT($rate, $per, $nper, $pv, $fv = 0, $type = 0) {
- $rate = Calculation_Functions::flattenSingleValue($rate);
- $per = (int) Calculation_Functions::flattenSingleValue($per);
- $nper = (int) Calculation_Functions::flattenSingleValue($nper);
- $pv = Calculation_Functions::flattenSingleValue($pv);
- $fv = Calculation_Functions::flattenSingleValue($fv);
- $type = (int) Calculation_Functions::flattenSingleValue($type);
-
- // Validate parameters
- if ($type != 0 && $type != 1) {
- return Calculation_Functions::NaN();
- }
- if ($per <= 0 || $per > $nper) {
- return Calculation_Functions::VALUE();
- }
-
- // Calculate
- $interestAndPrincipal = self::_interestAndPrincipal($rate, $per, $nper, $pv, $fv, $type);
- return $interestAndPrincipal[1];
- } // function PPMT()
-
-
- public static function PRICE($settlement, $maturity, $rate, $yield, $redemption, $frequency, $basis=0) {
- $settlement = Calculation_Functions::flattenSingleValue($settlement);
- $maturity = Calculation_Functions::flattenSingleValue($maturity);
- $rate = (float) Calculation_Functions::flattenSingleValue($rate);
- $yield = (float) Calculation_Functions::flattenSingleValue($yield);
- $redemption = (float) Calculation_Functions::flattenSingleValue($redemption);
- $frequency = (int) Calculation_Functions::flattenSingleValue($frequency);
- $basis = (is_null($basis)) ? 0 : (int) Calculation_Functions::flattenSingleValue($basis);
-
- if (is_string($settlement = Calculation_DateTime::_getDateValue($settlement))) {
- return Calculation_Functions::VALUE();
- }
- if (is_string($maturity = Calculation_DateTime::_getDateValue($maturity))) {
- return Calculation_Functions::VALUE();
- }
-
- if (($settlement > $maturity) ||
- (!self::_validFrequency($frequency)) ||
- (($basis < 0) || ($basis > 4))) {
- return Calculation_Functions::NaN();
- }
-
- $dsc = self::COUPDAYSNC($settlement, $maturity, $frequency, $basis);
- $e = self::COUPDAYS($settlement, $maturity, $frequency, $basis);
- $n = self::COUPNUM($settlement, $maturity, $frequency, $basis);
- $a = self::COUPDAYBS($settlement, $maturity, $frequency, $basis);
-
- $baseYF = 1.0 + ($yield / $frequency);
- $rfp = 100 * ($rate / $frequency);
- $de = $dsc / $e;
-
- $result = $redemption / pow($baseYF, (--$n + $de));
- for($k = 0; $k <= $n; ++$k) {
- $result += $rfp / (pow($baseYF, ($k + $de)));
- }
- $result -= $rfp * ($a / $e);
-
- return $result;
- } // function PRICE()
-
-
- /**
- * PRICEDISC
- *
- * Returns the price per $100 face value of a discounted security.
- *
- * @param mixed settlement The security's settlement date.
- * The security settlement date is the date after the issue date when the security is traded to the buyer.
- * @param mixed maturity The security's maturity date.
- * The maturity date is the date when the security expires.
- * @param int discount The security's discount rate.
- * @param int redemption The security's redemption value per $100 face value.
- * @param int basis The type of day count to use.
- * 0 or omitted US (NASD) 30/360
- * 1 Actual/actual
- * 2 Actual/360
- * 3 Actual/365
- * 4 European 30/360
- * @return float
- */
- public static function PRICEDISC($settlement, $maturity, $discount, $redemption, $basis=0) {
- $settlement = Calculation_Functions::flattenSingleValue($settlement);
- $maturity = Calculation_Functions::flattenSingleValue($maturity);
- $discount = (float) Calculation_Functions::flattenSingleValue($discount);
- $redemption = (float) Calculation_Functions::flattenSingleValue($redemption);
- $basis = (int) Calculation_Functions::flattenSingleValue($basis);
-
- // Validate
- if ((is_numeric($discount)) && (is_numeric($redemption)) && (is_numeric($basis))) {
- if (($discount <= 0) || ($redemption <= 0)) {
- return Calculation_Functions::NaN();
- }
- $daysBetweenSettlementAndMaturity = Calculation_DateTime::YEARFRAC($settlement, $maturity, $basis);
- if (!is_numeric($daysBetweenSettlementAndMaturity)) {
- // return date error
- return $daysBetweenSettlementAndMaturity;
- }
-
- return $redemption * (1 - $discount * $daysBetweenSettlementAndMaturity);
- }
- return Calculation_Functions::VALUE();
- } // function PRICEDISC()
-
-
- /**
- * PRICEMAT
- *
- * Returns the price per $100 face value of a security that pays interest at maturity.
- *
- * @param mixed settlement The security's settlement date.
- * The security's settlement date is the date after the issue date when the security is traded to the buyer.
- * @param mixed maturity The security's maturity date.
- * The maturity date is the date when the security expires.
- * @param mixed issue The security's issue date.
- * @param int rate The security's interest rate at date of issue.
- * @param int yield The security's annual yield.
- * @param int basis The type of day count to use.
- * 0 or omitted US (NASD) 30/360
- * 1 Actual/actual
- * 2 Actual/360
- * 3 Actual/365
- * 4 European 30/360
- * @return float
- */
- public static function PRICEMAT($settlement, $maturity, $issue, $rate, $yield, $basis=0) {
- $settlement = Calculation_Functions::flattenSingleValue($settlement);
- $maturity = Calculation_Functions::flattenSingleValue($maturity);
- $issue = Calculation_Functions::flattenSingleValue($issue);
- $rate = Calculation_Functions::flattenSingleValue($rate);
- $yield = Calculation_Functions::flattenSingleValue($yield);
- $basis = (int) Calculation_Functions::flattenSingleValue($basis);
-
- // Validate
- if (is_numeric($rate) && is_numeric($yield)) {
- if (($rate <= 0) || ($yield <= 0)) {
- return Calculation_Functions::NaN();
- }
- $daysPerYear = self::_daysPerYear(Calculation_DateTime::YEAR($settlement),$basis);
- if (!is_numeric($daysPerYear)) {
- return $daysPerYear;
- }
- $daysBetweenIssueAndSettlement = Calculation_DateTime::YEARFRAC($issue, $settlement, $basis);
- if (!is_numeric($daysBetweenIssueAndSettlement)) {
- // return date error
- return $daysBetweenIssueAndSettlement;
- }
- $daysBetweenIssueAndSettlement *= $daysPerYear;
- $daysBetweenIssueAndMaturity = Calculation_DateTime::YEARFRAC($issue, $maturity, $basis);
- if (!is_numeric($daysBetweenIssueAndMaturity)) {
- // return date error
- return $daysBetweenIssueAndMaturity;
- }
- $daysBetweenIssueAndMaturity *= $daysPerYear;
- $daysBetweenSettlementAndMaturity = Calculation_DateTime::YEARFRAC($settlement, $maturity, $basis);
- if (!is_numeric($daysBetweenSettlementAndMaturity)) {
- // return date error
- return $daysBetweenSettlementAndMaturity;
- }
- $daysBetweenSettlementAndMaturity *= $daysPerYear;
-
- return ((100 + (($daysBetweenIssueAndMaturity / $daysPerYear) * $rate * 100)) /
- (1 + (($daysBetweenSettlementAndMaturity / $daysPerYear) * $yield)) -
- (($daysBetweenIssueAndSettlement / $daysPerYear) * $rate * 100));
- }
- return Calculation_Functions::VALUE();
- } // function PRICEMAT()
-
-
- /**
- * PV
- *
- * Returns the Present Value of a cash flow with constant payments and interest rate (annuities).
- *
- * @param float $rate Interest rate per period
- * @param int $nper Number of periods
- * @param float $pmt Periodic payment (annuity)
- * @param float $fv Future Value
- * @param int $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period
- * @return float
- */
- public static function PV($rate = 0, $nper = 0, $pmt = 0, $fv = 0, $type = 0) {
- $rate = Calculation_Functions::flattenSingleValue($rate);
- $nper = Calculation_Functions::flattenSingleValue($nper);
- $pmt = Calculation_Functions::flattenSingleValue($pmt);
- $fv = Calculation_Functions::flattenSingleValue($fv);
- $type = Calculation_Functions::flattenSingleValue($type);
-
- // Validate parameters
- if ($type != 0 && $type != 1) {
- return Calculation_Functions::NaN();
- }
-
- // Calculate
- if (!is_null($rate) && $rate != 0) {
- return (-$pmt * (1 + $rate * $type) * ((pow(1 + $rate, $nper) - 1) / $rate) - $fv) / pow(1 + $rate, $nper);
- } else {
- return -$fv - $pmt * $nper;
- }
- } // function PV()
-
-
- /**
- * RATE
- *
- * Returns the interest rate per period of an annuity.
- * RATE is calculated by iteration and can have zero or more solutions.
- * If the successive results of RATE do not converge to within 0.0000001 after 20 iterations,
- * RATE returns the #NUM! error value.
- *
- * Excel Function:
- * RATE(nper,pmt,pv[,fv[,type[,guess]]])
- *
- * @access public
- * @category Financial Functions
- * @param float nper The total number of payment periods in an annuity.
- * @param float pmt The payment made each period and cannot change over the life
- * of the annuity.
- * Typically, pmt includes principal and interest but no other
- * fees or taxes.
- * @param float pv The present value - the total amount that a series of future
- * payments is worth now.
- * @param float fv The future value, or a cash balance you want to attain after
- * the last payment is made. If fv is omitted, it is assumed
- * to be 0 (the future value of a loan, for example, is 0).
- * @param integer type A number 0 or 1 and indicates when payments are due:
- * 0 or omitted At the end of the period.
- * 1 At the beginning of the period.
- * @param float guess Your guess for what the rate will be.
- * If you omit guess, it is assumed to be 10 percent.
- * @return float
- **/
- public static function RATE($nper, $pmt, $pv, $fv = 0.0, $type = 0, $guess = 0.1) {
- $nper = (int) Calculation_Functions::flattenSingleValue($nper);
- $pmt = Calculation_Functions::flattenSingleValue($pmt);
- $pv = Calculation_Functions::flattenSingleValue($pv);
- $fv = (is_null($fv)) ? 0.0 : Calculation_Functions::flattenSingleValue($fv);
- $type = (is_null($type)) ? 0 : (int) Calculation_Functions::flattenSingleValue($type);
- $guess = (is_null($guess)) ? 0.1 : Calculation_Functions::flattenSingleValue($guess);
-
- $rate = $guess;
- if (abs($rate) < FINANCIAL_PRECISION) {
- $y = $pv * (1 + $nper * $rate) + $pmt * (1 + $rate * $type) * $nper + $fv;
- } else {
- $f = exp($nper * log(1 + $rate));
- $y = $pv * $f + $pmt * (1 / $rate + $type) * ($f - 1) + $fv;
- }
- $y0 = $pv + $pmt * $nper + $fv;
- $y1 = $pv * $f + $pmt * (1 / $rate + $type) * ($f - 1) + $fv;
-
- // find root by secant method
- $i = $x0 = 0.0;
- $x1 = $rate;
- while ((abs($y0 - $y1) > FINANCIAL_PRECISION) && ($i < FINANCIAL_MAX_ITERATIONS)) {
- $rate = ($y1 * $x0 - $y0 * $x1) / ($y1 - $y0);
- $x0 = $x1;
- $x1 = $rate;
- if (($nper * abs($pmt)) > ($pv - $fv))
- $x1 = abs($x1);
-
- if (abs($rate) < FINANCIAL_PRECISION) {
- $y = $pv * (1 + $nper * $rate) + $pmt * (1 + $rate * $type) * $nper + $fv;
- } else {
- $f = exp($nper * log(1 + $rate));
- $y = $pv * $f + $pmt * (1 / $rate + $type) * ($f - 1) + $fv;
- }
-
- $y0 = $y1;
- $y1 = $y;
- ++$i;
- }
- return $rate;
- } // function RATE()
-
-
- /**
- * RECEIVED
- *
- * Returns the price per $100 face value of a discounted security.
- *
- * @param mixed settlement The security's settlement date.
- * The security settlement date is the date after the issue date when the security is traded to the buyer.
- * @param mixed maturity The security's maturity date.
- * The maturity date is the date when the security expires.
- * @param int investment The amount invested in the security.
- * @param int discount The security's discount rate.
- * @param int basis The type of day count to use.
- * 0 or omitted US (NASD) 30/360
- * 1 Actual/actual
- * 2 Actual/360
- * 3 Actual/365
- * 4 European 30/360
- * @return float
- */
- public static function RECEIVED($settlement, $maturity, $investment, $discount, $basis=0) {
- $settlement = Calculation_Functions::flattenSingleValue($settlement);
- $maturity = Calculation_Functions::flattenSingleValue($maturity);
- $investment = (float) Calculation_Functions::flattenSingleValue($investment);
- $discount = (float) Calculation_Functions::flattenSingleValue($discount);
- $basis = (int) Calculation_Functions::flattenSingleValue($basis);
-
- // Validate
- if ((is_numeric($investment)) && (is_numeric($discount)) && (is_numeric($basis))) {
- if (($investment <= 0) || ($discount <= 0)) {
- return Calculation_Functions::NaN();
- }
- $daysBetweenSettlementAndMaturity = Calculation_DateTime::YEARFRAC($settlement, $maturity, $basis);
- if (!is_numeric($daysBetweenSettlementAndMaturity)) {
- // return date error
- return $daysBetweenSettlementAndMaturity;
- }
-
- return $investment / ( 1 - ($discount * $daysBetweenSettlementAndMaturity));
- }
- return Calculation_Functions::VALUE();
- } // function RECEIVED()
-
-
- /**
- * SLN
- *
- * Returns the straight-line depreciation of an asset for one period
- *
- * @param cost Initial cost of the asset
- * @param salvage Value at the end of the depreciation
- * @param life Number of periods over which the asset is depreciated
- * @return float
- */
- public static function SLN($cost, $salvage, $life) {
- $cost = Calculation_Functions::flattenSingleValue($cost);
- $salvage = Calculation_Functions::flattenSingleValue($salvage);
- $life = Calculation_Functions::flattenSingleValue($life);
-
- // Calculate
- if ((is_numeric($cost)) && (is_numeric($salvage)) && (is_numeric($life))) {
- if ($life < 0) {
- return Calculation_Functions::NaN();
- }
- return ($cost - $salvage) / $life;
- }
- return Calculation_Functions::VALUE();
- } // function SLN()
-
-
- /**
- * SYD
- *
- * Returns the sum-of-years' digits depreciation of an asset for a specified period.
- *
- * @param cost Initial cost of the asset
- * @param salvage Value at the end of the depreciation
- * @param life Number of periods over which the asset is depreciated
- * @param period Period
- * @return float
- */
- public static function SYD($cost, $salvage, $life, $period) {
- $cost = Calculation_Functions::flattenSingleValue($cost);
- $salvage = Calculation_Functions::flattenSingleValue($salvage);
- $life = Calculation_Functions::flattenSingleValue($life);
- $period = Calculation_Functions::flattenSingleValue($period);
-
- // Calculate
- if ((is_numeric($cost)) && (is_numeric($salvage)) && (is_numeric($life)) && (is_numeric($period))) {
- if (($life < 1) || ($period > $life)) {
- return Calculation_Functions::NaN();
- }
- return (($cost - $salvage) * ($life - $period + 1) * 2) / ($life * ($life + 1));
- }
- return Calculation_Functions::VALUE();
- } // function SYD()
-
-
- /**
- * TBILLEQ
- *
- * Returns the bond-equivalent yield for a Treasury bill.
- *
- * @param mixed settlement The Treasury bill's settlement date.
- * The Treasury bill's settlement date is the date after the issue date when the Treasury bill is traded to the buyer.
- * @param mixed maturity The Treasury bill's maturity date.
- * The maturity date is the date when the Treasury bill expires.
- * @param int discount The Treasury bill's discount rate.
- * @return float
- */
- public static function TBILLEQ($settlement, $maturity, $discount) {
- $settlement = Calculation_Functions::flattenSingleValue($settlement);
- $maturity = Calculation_Functions::flattenSingleValue($maturity);
- $discount = Calculation_Functions::flattenSingleValue($discount);
-
- // Use TBILLPRICE for validation
- $testValue = self::TBILLPRICE($settlement, $maturity, $discount);
- if (is_string($testValue)) {
- return $testValue;
- }
-
- if (is_string($maturity = Calculation_DateTime::_getDateValue($maturity))) {
- return Calculation_Functions::VALUE();
- }
-
- if (Calculation_Functions::getCompatibilityMode() == Calculation_Functions::COMPATIBILITY_OPENOFFICE) {
- ++$maturity;
- $daysBetweenSettlementAndMaturity = Calculation_DateTime::YEARFRAC($settlement, $maturity) * 360;
- } else {
- $daysBetweenSettlementAndMaturity = (Calculation_DateTime::_getDateValue($maturity) - Calculation_DateTime::_getDateValue($settlement));
- }
-
- return (365 * $discount) / (360 - $discount * $daysBetweenSettlementAndMaturity);
- } // function TBILLEQ()
-
-
- /**
- * TBILLPRICE
- *
- * Returns the yield for a Treasury bill.
- *
- * @param mixed settlement The Treasury bill's settlement date.
- * The Treasury bill's settlement date is the date after the issue date when the Treasury bill is traded to the buyer.
- * @param mixed maturity The Treasury bill's maturity date.
- * The maturity date is the date when the Treasury bill expires.
- * @param int discount The Treasury bill's discount rate.
- * @return float
- */
- public static function TBILLPRICE($settlement, $maturity, $discount) {
- $settlement = Calculation_Functions::flattenSingleValue($settlement);
- $maturity = Calculation_Functions::flattenSingleValue($maturity);
- $discount = Calculation_Functions::flattenSingleValue($discount);
-
- if (is_string($maturity = Calculation_DateTime::_getDateValue($maturity))) {
- return Calculation_Functions::VALUE();
- }
-
- // Validate
- if (is_numeric($discount)) {
- if ($discount <= 0) {
- return Calculation_Functions::NaN();
- }
-
- if (Calculation_Functions::getCompatibilityMode() == Calculation_Functions::COMPATIBILITY_OPENOFFICE) {
- ++$maturity;
- $daysBetweenSettlementAndMaturity = Calculation_DateTime::YEARFRAC($settlement, $maturity) * 360;
- if (!is_numeric($daysBetweenSettlementAndMaturity)) {
- // return date error
- return $daysBetweenSettlementAndMaturity;
- }
- } else {
- $daysBetweenSettlementAndMaturity = (Calculation_DateTime::_getDateValue($maturity) - Calculation_DateTime::_getDateValue($settlement));
- }
-
- if ($daysBetweenSettlementAndMaturity > 360) {
- return Calculation_Functions::NaN();
- }
-
- $price = 100 * (1 - (($discount * $daysBetweenSettlementAndMaturity) / 360));
- if ($price <= 0) {
- return Calculation_Functions::NaN();
- }
- return $price;
- }
- return Calculation_Functions::VALUE();
- } // function TBILLPRICE()
-
-
- /**
- * TBILLYIELD
- *
- * Returns the yield for a Treasury bill.
- *
- * @param mixed settlement The Treasury bill's settlement date.
- * The Treasury bill's settlement date is the date after the issue date when the Treasury bill is traded to the buyer.
- * @param mixed maturity The Treasury bill's maturity date.
- * The maturity date is the date when the Treasury bill expires.
- * @param int price The Treasury bill's price per $100 face value.
- * @return float
- */
- public static function TBILLYIELD($settlement, $maturity, $price) {
- $settlement = Calculation_Functions::flattenSingleValue($settlement);
- $maturity = Calculation_Functions::flattenSingleValue($maturity);
- $price = Calculation_Functions::flattenSingleValue($price);
-
- // Validate
- if (is_numeric($price)) {
- if ($price <= 0) {
- return Calculation_Functions::NaN();
- }
-
- if (Calculation_Functions::getCompatibilityMode() == Calculation_Functions::COMPATIBILITY_OPENOFFICE) {
- ++$maturity;
- $daysBetweenSettlementAndMaturity = Calculation_DateTime::YEARFRAC($settlement, $maturity) * 360;
- if (!is_numeric($daysBetweenSettlementAndMaturity)) {
- // return date error
- return $daysBetweenSettlementAndMaturity;
- }
- } else {
- $daysBetweenSettlementAndMaturity = (Calculation_DateTime::_getDateValue($maturity) - Calculation_DateTime::_getDateValue($settlement));
- }
-
- if ($daysBetweenSettlementAndMaturity > 360) {
- return Calculation_Functions::NaN();
- }
-
- return ((100 - $price) / $price) * (360 / $daysBetweenSettlementAndMaturity);
- }
- return Calculation_Functions::VALUE();
- } // function TBILLYIELD()
-
-
- public static function XIRR($values, $dates, $guess = 0.1) {
- if ((!is_array($values)) && (!is_array($dates))) return Calculation_Functions::VALUE();
- $values = Calculation_Functions::flattenArray($values);
- $dates = Calculation_Functions::flattenArray($dates);
- $guess = Calculation_Functions::flattenSingleValue($guess);
- if (count($values) != count($dates)) return Calculation_Functions::NaN();
-
- // create an initial range, with a root somewhere between 0 and guess
- $x1 = 0.0;
- $x2 = $guess;
- $f1 = self::XNPV($x1, $values, $dates);
- $f2 = self::XNPV($x2, $values, $dates);
- for ($i = 0; $i < FINANCIAL_MAX_ITERATIONS; ++$i) {
- if (($f1 * $f2) < 0.0) break;
- if (abs($f1) < abs($f2)) {
- $f1 = self::XNPV($x1 += 1.6 * ($x1 - $x2), $values, $dates);
- } else {
- $f2 = self::XNPV($x2 += 1.6 * ($x2 - $x1), $values, $dates);
- }
- }
- if (($f1 * $f2) > 0.0) return Calculation_Functions::VALUE();
-
- $f = self::XNPV($x1, $values, $dates);
- if ($f < 0.0) {
- $rtb = $x1;
- $dx = $x2 - $x1;
- } else {
- $rtb = $x2;
- $dx = $x1 - $x2;
- }
-
- for ($i = 0; $i < FINANCIAL_MAX_ITERATIONS; ++$i) {
- $dx *= 0.5;
- $x_mid = $rtb + $dx;
- $f_mid = self::XNPV($x_mid, $values, $dates);
- if ($f_mid <= 0.0) $rtb = $x_mid;
- if ((abs($f_mid) < FINANCIAL_PRECISION) || (abs($dx) < FINANCIAL_PRECISION)) return $x_mid;
- }
- return Calculation_Functions::VALUE();
- }
-
-
- /**
- * XNPV
- *
- * Returns the net present value for a schedule of cash flows that is not necessarily periodic.
- * To calculate the net present value for a series of cash flows that is periodic, use the NPV function.
- *
- * Excel Function:
- * =XNPV(rate,values,dates)
- *
- * @param float $rate The discount rate to apply to the cash flows.
- * @param array of float $values A series of cash flows that corresponds to a schedule of payments in dates. The first payment is optional and corresponds to a cost or payment that occurs at the beginning of the investment. If the first value is a cost or payment, it must be a negative value. All succeeding payments are discounted based on a 365-day year. The series of values must contain at least one positive value and one negative value.
- * @param array of mixed $dates A schedule of payment dates that corresponds to the cash flow payments. The first payment date indicates the beginning of the schedule of payments. All other dates must be later than this date, but they may occur in any order.
- * @return float
- */
- public static function XNPV($rate, $values, $dates) {
- $rate = Calculation_Functions::flattenSingleValue($rate);
- if (!is_numeric($rate)) return Calculation_Functions::VALUE();
- if ((!is_array($values)) || (!is_array($dates))) return Calculation_Functions::VALUE();
- $values = Calculation_Functions::flattenArray($values);
- $dates = Calculation_Functions::flattenArray($dates);
- $valCount = count($values);
- if ($valCount != count($dates)) return Calculation_Functions::NaN();
- if ((min($values) > 0) || (max($values) < 0)) return Calculation_Functions::VALUE();
-
- $xnpv = 0.0;
- for ($i = 0; $i < $valCount; ++$i) {
- if (!is_numeric($values[$i])) return Calculation_Functions::VALUE();
- $xnpv += $values[$i] / pow(1 + $rate, Calculation_DateTime::DATEDIF($dates[0],$dates[$i],'d') / 365);
- }
- return (is_finite($xnpv)) ? $xnpv : Calculation_Functions::VALUE();
- } // function XNPV()
-
-
- /**
- * YIELDDISC
- *
- * Returns the annual yield of a security that pays interest at maturity.
- *
- * @param mixed settlement The security's settlement date.
- * The security's settlement date is the date after the issue date when the security is traded to the buyer.
- * @param mixed maturity The security's maturity date.
- * The maturity date is the date when the security expires.
- * @param int price The security's price per $100 face value.
- * @param int redemption The security's redemption value per $100 face value.
- * @param int basis The type of day count to use.
- * 0 or omitted US (NASD) 30/360
- * 1 Actual/actual
- * 2 Actual/360
- * 3 Actual/365
- * 4 European 30/360
- * @return float
- */
- public static function YIELDDISC($settlement, $maturity, $price, $redemption, $basis=0) {
- $settlement = Calculation_Functions::flattenSingleValue($settlement);
- $maturity = Calculation_Functions::flattenSingleValue($maturity);
- $price = Calculation_Functions::flattenSingleValue($price);
- $redemption = Calculation_Functions::flattenSingleValue($redemption);
- $basis = (int) Calculation_Functions::flattenSingleValue($basis);
-
- // Validate
- if (is_numeric($price) && is_numeric($redemption)) {
- if (($price <= 0) || ($redemption <= 0)) {
- return Calculation_Functions::NaN();
- }
- $daysPerYear = self::_daysPerYear(Calculation_DateTime::YEAR($settlement),$basis);
- if (!is_numeric($daysPerYear)) {
- return $daysPerYear;
- }
- $daysBetweenSettlementAndMaturity = Calculation_DateTime::YEARFRAC($settlement, $maturity,$basis);
- if (!is_numeric($daysBetweenSettlementAndMaturity)) {
- // return date error
- return $daysBetweenSettlementAndMaturity;
- }
- $daysBetweenSettlementAndMaturity *= $daysPerYear;
-
- return (($redemption - $price) / $price) * ($daysPerYear / $daysBetweenSettlementAndMaturity);
- }
- return Calculation_Functions::VALUE();
- } // function YIELDDISC()
-
-
- /**
- * YIELDMAT
- *
- * Returns the annual yield of a security that pays interest at maturity.
- *
- * @param mixed settlement The security's settlement date.
- * The security's settlement date is the date after the issue date when the security is traded to the buyer.
- * @param mixed maturity The security's maturity date.
- * The maturity date is the date when the security expires.
- * @param mixed issue The security's issue date.
- * @param int rate The security's interest rate at date of issue.
- * @param int price The security's price per $100 face value.
- * @param int basis The type of day count to use.
- * 0 or omitted US (NASD) 30/360
- * 1 Actual/actual
- * 2 Actual/360
- * 3 Actual/365
- * 4 European 30/360
- * @return float
- */
- public static function YIELDMAT($settlement, $maturity, $issue, $rate, $price, $basis=0) {
- $settlement = Calculation_Functions::flattenSingleValue($settlement);
- $maturity = Calculation_Functions::flattenSingleValue($maturity);
- $issue = Calculation_Functions::flattenSingleValue($issue);
- $rate = Calculation_Functions::flattenSingleValue($rate);
- $price = Calculation_Functions::flattenSingleValue($price);
- $basis = (int) Calculation_Functions::flattenSingleValue($basis);
-
- // Validate
- if (is_numeric($rate) && is_numeric($price)) {
- if (($rate <= 0) || ($price <= 0)) {
- return Calculation_Functions::NaN();
- }
- $daysPerYear = self::_daysPerYear(Calculation_DateTime::YEAR($settlement),$basis);
- if (!is_numeric($daysPerYear)) {
- return $daysPerYear;
- }
- $daysBetweenIssueAndSettlement = Calculation_DateTime::YEARFRAC($issue, $settlement, $basis);
- if (!is_numeric($daysBetweenIssueAndSettlement)) {
- // return date error
- return $daysBetweenIssueAndSettlement;
- }
- $daysBetweenIssueAndSettlement *= $daysPerYear;
- $daysBetweenIssueAndMaturity = Calculation_DateTime::YEARFRAC($issue, $maturity, $basis);
- if (!is_numeric($daysBetweenIssueAndMaturity)) {
- // return date error
- return $daysBetweenIssueAndMaturity;
- }
- $daysBetweenIssueAndMaturity *= $daysPerYear;
- $daysBetweenSettlementAndMaturity = Calculation_DateTime::YEARFRAC($settlement, $maturity, $basis);
- if (!is_numeric($daysBetweenSettlementAndMaturity)) {
- // return date error
- return $daysBetweenSettlementAndMaturity;
- }
- $daysBetweenSettlementAndMaturity *= $daysPerYear;
-
- return ((1 + (($daysBetweenIssueAndMaturity / $daysPerYear) * $rate) - (($price / 100) + (($daysBetweenIssueAndSettlement / $daysPerYear) * $rate))) /
- (($price / 100) + (($daysBetweenIssueAndSettlement / $daysPerYear) * $rate))) *
- ($daysPerYear / $daysBetweenSettlementAndMaturity);
- }
- return Calculation_Functions::VALUE();
- } // function YIELDMAT()
-
+ } else {
+ return 0.0;
+ }
+ } // function AMORLINC()
+
+
+ /**
+ * COUPDAYBS
+ *
+ * Returns the number of days from the beginning of the coupon period to the settlement date.
+ *
+ * Excel Function:
+ * COUPDAYBS(settlement,maturity,frequency[,basis])
+ *
+ * @access public
+ * @category Financial Functions
+ * @param mixed settlement The security's settlement date.
+ * The security settlement date is the date after the issue
+ * date when the security is traded to the buyer.
+ * @param mixed maturity The security's maturity date.
+ * The maturity date is the date when the security expires.
+ * @param mixed frequency the number of coupon payments per year.
+ * Valid frequency values are:
+ * 1 Annual
+ * 2 Semi-Annual
+ * 4 Quarterly
+ * If working in Gnumeric Mode, the following frequency options are
+ * also available
+ * 6 Bimonthly
+ * 12 Monthly
+ * @param integer basis The type of day count to use.
+ * 0 or omitted US (NASD) 30/360
+ * 1 Actual/actual
+ * 2 Actual/360
+ * 3 Actual/365
+ * 4 European 30/360
+ * @return float
+ */
+ public static function COUPDAYBS($settlement, $maturity, $frequency, $basis=0) {
+ $settlement = Calculation_Functions::flattenSingleValue($settlement);
+ $maturity = Calculation_Functions::flattenSingleValue($maturity);
+ $frequency = (int) Calculation_Functions::flattenSingleValue($frequency);
+ $basis = (is_null($basis)) ? 0 : (int) Calculation_Functions::flattenSingleValue($basis);
+
+ if (is_string($settlement = Calculation_DateTime::_getDateValue($settlement))) {
+ return Calculation_Functions::VALUE();
+ }
+ if (is_string($maturity = Calculation_DateTime::_getDateValue($maturity))) {
+ return Calculation_Functions::VALUE();
+ }
+
+ if (($settlement > $maturity) ||
+ (!self::_validFrequency($frequency)) ||
+ (($basis < 0) || ($basis > 4))) {
+ return Calculation_Functions::NaN();
+ }
+
+ $daysPerYear = self::_daysPerYear(Calculation_DateTime::YEAR($settlement),$basis);
+ $prev = self::_coupFirstPeriodDate($settlement, $maturity, $frequency, False);
+
+ return Calculation_DateTime::YEARFRAC($prev, $settlement, $basis) * $daysPerYear;
+ } // function COUPDAYBS()
+
+
+ /**
+ * COUPDAYS
+ *
+ * Returns the number of days in the coupon period that contains the settlement date.
+ *
+ * Excel Function:
+ * COUPDAYS(settlement,maturity,frequency[,basis])
+ *
+ * @access public
+ * @category Financial Functions
+ * @param mixed settlement The security's settlement date.
+ * The security settlement date is the date after the issue
+ * date when the security is traded to the buyer.
+ * @param mixed maturity The security's maturity date.
+ * The maturity date is the date when the security expires.
+ * @param mixed frequency the number of coupon payments per year.
+ * Valid frequency values are:
+ * 1 Annual
+ * 2 Semi-Annual
+ * 4 Quarterly
+ * If working in Gnumeric Mode, the following frequency options are
+ * also available
+ * 6 Bimonthly
+ * 12 Monthly
+ * @param integer basis The type of day count to use.
+ * 0 or omitted US (NASD) 30/360
+ * 1 Actual/actual
+ * 2 Actual/360
+ * 3 Actual/365
+ * 4 European 30/360
+ * @return float
+ */
+ public static function COUPDAYS($settlement, $maturity, $frequency, $basis=0) {
+ $settlement = Calculation_Functions::flattenSingleValue($settlement);
+ $maturity = Calculation_Functions::flattenSingleValue($maturity);
+ $frequency = (int) Calculation_Functions::flattenSingleValue($frequency);
+ $basis = (is_null($basis)) ? 0 : (int) Calculation_Functions::flattenSingleValue($basis);
+
+ if (is_string($settlement = Calculation_DateTime::_getDateValue($settlement))) {
+ return Calculation_Functions::VALUE();
+ }
+ if (is_string($maturity = Calculation_DateTime::_getDateValue($maturity))) {
+ return Calculation_Functions::VALUE();
+ }
+
+ if (($settlement > $maturity) ||
+ (!self::_validFrequency($frequency)) ||
+ (($basis < 0) || ($basis > 4))) {
+ return Calculation_Functions::NaN();
+ }
+
+ switch ($basis) {
+ case 3: // Actual/365
+ return 365 / $frequency;
+ case 1: // Actual/actual
+ if ($frequency == 1) {
+ $daysPerYear = self::_daysPerYear(Calculation_DateTime::YEAR($maturity),$basis);
+ return ($daysPerYear / $frequency);
+ } else {
+ $prev = self::_coupFirstPeriodDate($settlement, $maturity, $frequency, False);
+ $next = self::_coupFirstPeriodDate($settlement, $maturity, $frequency, True);
+ return ($next - $prev);
+ }
+ default: // US (NASD) 30/360, Actual/360 or European 30/360
+ return 360 / $frequency;
+ }
+ return Calculation_Functions::VALUE();
+ } // function COUPDAYS()
+
+
+ /**
+ * COUPDAYSNC
+ *
+ * Returns the number of days from the settlement date to the next coupon date.
+ *
+ * Excel Function:
+ * COUPDAYSNC(settlement,maturity,frequency[,basis])
+ *
+ * @access public
+ * @category Financial Functions
+ * @param mixed settlement The security's settlement date.
+ * The security settlement date is the date after the issue
+ * date when the security is traded to the buyer.
+ * @param mixed maturity The security's maturity date.
+ * The maturity date is the date when the security expires.
+ * @param mixed frequency the number of coupon payments per year.
+ * Valid frequency values are:
+ * 1 Annual
+ * 2 Semi-Annual
+ * 4 Quarterly
+ * If working in Gnumeric Mode, the following frequency options are
+ * also available
+ * 6 Bimonthly
+ * 12 Monthly
+ * @param integer basis The type of day count to use.
+ * 0 or omitted US (NASD) 30/360
+ * 1 Actual/actual
+ * 2 Actual/360
+ * 3 Actual/365
+ * 4 European 30/360
+ * @return float
+ */
+ public static function COUPDAYSNC($settlement, $maturity, $frequency, $basis=0) {
+ $settlement = Calculation_Functions::flattenSingleValue($settlement);
+ $maturity = Calculation_Functions::flattenSingleValue($maturity);
+ $frequency = (int) Calculation_Functions::flattenSingleValue($frequency);
+ $basis = (is_null($basis)) ? 0 : (int) Calculation_Functions::flattenSingleValue($basis);
+
+ if (is_string($settlement = Calculation_DateTime::_getDateValue($settlement))) {
+ return Calculation_Functions::VALUE();
+ }
+ if (is_string($maturity = Calculation_DateTime::_getDateValue($maturity))) {
+ return Calculation_Functions::VALUE();
+ }
+
+ if (($settlement > $maturity) ||
+ (!self::_validFrequency($frequency)) ||
+ (($basis < 0) || ($basis > 4))) {
+ return Calculation_Functions::NaN();
+ }
+
+ $daysPerYear = self::_daysPerYear(Calculation_DateTime::YEAR($settlement),$basis);
+ $next = self::_coupFirstPeriodDate($settlement, $maturity, $frequency, True);
+
+ return Calculation_DateTime::YEARFRAC($settlement, $next, $basis) * $daysPerYear;
+ } // function COUPDAYSNC()
+
+
+ /**
+ * COUPNCD
+ *
+ * Returns the next coupon date after the settlement date.
+ *
+ * Excel Function:
+ * COUPNCD(settlement,maturity,frequency[,basis])
+ *
+ * @access public
+ * @category Financial Functions
+ * @param mixed settlement The security's settlement date.
+ * The security settlement date is the date after the issue
+ * date when the security is traded to the buyer.
+ * @param mixed maturity The security's maturity date.
+ * The maturity date is the date when the security expires.
+ * @param mixed frequency the number of coupon payments per year.
+ * Valid frequency values are:
+ * 1 Annual
+ * 2 Semi-Annual
+ * 4 Quarterly
+ * If working in Gnumeric Mode, the following frequency options are
+ * also available
+ * 6 Bimonthly
+ * 12 Monthly
+ * @param integer basis The type of day count to use.
+ * 0 or omitted US (NASD) 30/360
+ * 1 Actual/actual
+ * 2 Actual/360
+ * 3 Actual/365
+ * 4 European 30/360
+ * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
+ * depending on the value of the ReturnDateType flag
+ */
+ public static function COUPNCD($settlement, $maturity, $frequency, $basis=0) {
+ $settlement = Calculation_Functions::flattenSingleValue($settlement);
+ $maturity = Calculation_Functions::flattenSingleValue($maturity);
+ $frequency = (int) Calculation_Functions::flattenSingleValue($frequency);
+ $basis = (is_null($basis)) ? 0 : (int) Calculation_Functions::flattenSingleValue($basis);
+
+ if (is_string($settlement = Calculation_DateTime::_getDateValue($settlement))) {
+ return Calculation_Functions::VALUE();
+ }
+ if (is_string($maturity = Calculation_DateTime::_getDateValue($maturity))) {
+ return Calculation_Functions::VALUE();
+ }
+
+ if (($settlement > $maturity) ||
+ (!self::_validFrequency($frequency)) ||
+ (($basis < 0) || ($basis > 4))) {
+ return Calculation_Functions::NaN();
+ }
+
+ return self::_coupFirstPeriodDate($settlement, $maturity, $frequency, True);
+ } // function COUPNCD()
+
+
+ /**
+ * COUPNUM
+ *
+ * Returns the number of coupons payable between the settlement date and maturity date,
+ * rounded up to the nearest whole coupon.
+ *
+ * Excel Function:
+ * COUPNUM(settlement,maturity,frequency[,basis])
+ *
+ * @access public
+ * @category Financial Functions
+ * @param mixed settlement The security's settlement date.
+ * The security settlement date is the date after the issue
+ * date when the security is traded to the buyer.
+ * @param mixed maturity The security's maturity date.
+ * The maturity date is the date when the security expires.
+ * @param mixed frequency the number of coupon payments per year.
+ * Valid frequency values are:
+ * 1 Annual
+ * 2 Semi-Annual
+ * 4 Quarterly
+ * If working in Gnumeric Mode, the following frequency options are
+ * also available
+ * 6 Bimonthly
+ * 12 Monthly
+ * @param integer basis The type of day count to use.
+ * 0 or omitted US (NASD) 30/360
+ * 1 Actual/actual
+ * 2 Actual/360
+ * 3 Actual/365
+ * 4 European 30/360
+ * @return integer
+ */
+ public static function COUPNUM($settlement, $maturity, $frequency, $basis=0) {
+ $settlement = Calculation_Functions::flattenSingleValue($settlement);
+ $maturity = Calculation_Functions::flattenSingleValue($maturity);
+ $frequency = (int) Calculation_Functions::flattenSingleValue($frequency);
+ $basis = (is_null($basis)) ? 0 : (int) Calculation_Functions::flattenSingleValue($basis);
+
+ if (is_string($settlement = Calculation_DateTime::_getDateValue($settlement))) {
+ return Calculation_Functions::VALUE();
+ }
+ if (is_string($maturity = Calculation_DateTime::_getDateValue($maturity))) {
+ return Calculation_Functions::VALUE();
+ }
+
+ if (($settlement > $maturity) ||
+ (!self::_validFrequency($frequency)) ||
+ (($basis < 0) || ($basis > 4))) {
+ return Calculation_Functions::NaN();
+ }
+
+ $settlement = self::_coupFirstPeriodDate($settlement, $maturity, $frequency, True);
+ $daysBetweenSettlementAndMaturity = Calculation_DateTime::YEARFRAC($settlement, $maturity, $basis) * 365;
+
+ switch ($frequency) {
+ case 1: // annual payments
+ return ceil($daysBetweenSettlementAndMaturity / 360);
+ case 2: // half-yearly
+ return ceil($daysBetweenSettlementAndMaturity / 180);
+ case 4: // quarterly
+ return ceil($daysBetweenSettlementAndMaturity / 90);
+ case 6: // bimonthly
+ return ceil($daysBetweenSettlementAndMaturity / 60);
+ case 12: // monthly
+ return ceil($daysBetweenSettlementAndMaturity / 30);
+ }
+ return Calculation_Functions::VALUE();
+ } // function COUPNUM()
+
+
+ /**
+ * COUPPCD
+ *
+ * Returns the previous coupon date before the settlement date.
+ *
+ * Excel Function:
+ * COUPPCD(settlement,maturity,frequency[,basis])
+ *
+ * @access public
+ * @category Financial Functions
+ * @param mixed settlement The security's settlement date.
+ * The security settlement date is the date after the issue
+ * date when the security is traded to the buyer.
+ * @param mixed maturity The security's maturity date.
+ * The maturity date is the date when the security expires.
+ * @param mixed frequency the number of coupon payments per year.
+ * Valid frequency values are:
+ * 1 Annual
+ * 2 Semi-Annual
+ * 4 Quarterly
+ * If working in Gnumeric Mode, the following frequency options are
+ * also available
+ * 6 Bimonthly
+ * 12 Monthly
+ * @param integer basis The type of day count to use.
+ * 0 or omitted US (NASD) 30/360
+ * 1 Actual/actual
+ * 2 Actual/360
+ * 3 Actual/365
+ * 4 European 30/360
+ * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
+ * depending on the value of the ReturnDateType flag
+ */
+ public static function COUPPCD($settlement, $maturity, $frequency, $basis=0) {
+ $settlement = Calculation_Functions::flattenSingleValue($settlement);
+ $maturity = Calculation_Functions::flattenSingleValue($maturity);
+ $frequency = (int) Calculation_Functions::flattenSingleValue($frequency);
+ $basis = (is_null($basis)) ? 0 : (int) Calculation_Functions::flattenSingleValue($basis);
+
+ if (is_string($settlement = Calculation_DateTime::_getDateValue($settlement))) {
+ return Calculation_Functions::VALUE();
+ }
+ if (is_string($maturity = Calculation_DateTime::_getDateValue($maturity))) {
+ return Calculation_Functions::VALUE();
+ }
+
+ if (($settlement > $maturity) ||
+ (!self::_validFrequency($frequency)) ||
+ (($basis < 0) || ($basis > 4))) {
+ return Calculation_Functions::NaN();
+ }
+
+ return self::_coupFirstPeriodDate($settlement, $maturity, $frequency, False);
+ } // function COUPPCD()
+
+
+ /**
+ * CUMIPMT
+ *
+ * Returns the cumulative interest paid on a loan between the start and end periods.
+ *
+ * Excel Function:
+ * CUMIPMT(rate,nper,pv,start,end[,type])
+ *
+ * @access public
+ * @category Financial Functions
+ * @param float $rate The Interest rate
+ * @param integer $nper The total number of payment periods
+ * @param float $pv Present Value
+ * @param integer $start The first period in the calculation.
+ * Payment periods are numbered beginning with 1.
+ * @param integer $end The last period in the calculation.
+ * @param integer $type A number 0 or 1 and indicates when payments are due:
+ * 0 or omitted At the end of the period.
+ * 1 At the beginning of the period.
+ * @return float
+ */
+ public static function CUMIPMT($rate, $nper, $pv, $start, $end, $type = 0) {
+ $rate = Calculation_Functions::flattenSingleValue($rate);
+ $nper = (int) Calculation_Functions::flattenSingleValue($nper);
+ $pv = Calculation_Functions::flattenSingleValue($pv);
+ $start = (int) Calculation_Functions::flattenSingleValue($start);
+ $end = (int) Calculation_Functions::flattenSingleValue($end);
+ $type = (int) Calculation_Functions::flattenSingleValue($type);
+
+ // Validate parameters
+ if ($type != 0 && $type != 1) {
+ return Calculation_Functions::NaN();
+ }
+ if ($start < 1 || $start > $end) {
+ return Calculation_Functions::VALUE();
+ }
+
+ // Calculate
+ $interest = 0;
+ for ($per = $start; $per <= $end; ++$per) {
+ $interest += self::IPMT($rate, $per, $nper, $pv, 0, $type);
+ }
+
+ return $interest;
+ } // function CUMIPMT()
+
+
+ /**
+ * CUMPRINC
+ *
+ * Returns the cumulative principal paid on a loan between the start and end periods.
+ *
+ * Excel Function:
+ * CUMPRINC(rate,nper,pv,start,end[,type])
+ *
+ * @access public
+ * @category Financial Functions
+ * @param float $rate The Interest rate
+ * @param integer $nper The total number of payment periods
+ * @param float $pv Present Value
+ * @param integer $start The first period in the calculation.
+ * Payment periods are numbered beginning with 1.
+ * @param integer $end The last period in the calculation.
+ * @param integer $type A number 0 or 1 and indicates when payments are due:
+ * 0 or omitted At the end of the period.
+ * 1 At the beginning of the period.
+ * @return float
+ */
+ public static function CUMPRINC($rate, $nper, $pv, $start, $end, $type = 0) {
+ $rate = Calculation_Functions::flattenSingleValue($rate);
+ $nper = (int) Calculation_Functions::flattenSingleValue($nper);
+ $pv = Calculation_Functions::flattenSingleValue($pv);
+ $start = (int) Calculation_Functions::flattenSingleValue($start);
+ $end = (int) Calculation_Functions::flattenSingleValue($end);
+ $type = (int) Calculation_Functions::flattenSingleValue($type);
+
+ // Validate parameters
+ if ($type != 0 && $type != 1) {
+ return Calculation_Functions::NaN();
+ }
+ if ($start < 1 || $start > $end) {
+ return Calculation_Functions::VALUE();
+ }
+
+ // Calculate
+ $principal = 0;
+ for ($per = $start; $per <= $end; ++$per) {
+ $principal += self::PPMT($rate, $per, $nper, $pv, 0, $type);
+ }
+
+ return $principal;
+ } // function CUMPRINC()
+
+
+ /**
+ * DB
+ *
+ * Returns the depreciation of an asset for a specified period using the
+ * fixed-declining balance method.
+ * This form of depreciation is used if you want to get a higher depreciation value
+ * at the beginning of the depreciation (as opposed to linear depreciation). The
+ * depreciation value is reduced with every depreciation period by the depreciation
+ * already deducted from the initial cost.
+ *
+ * Excel Function:
+ * DB(cost,salvage,life,period[,month])
+ *
+ * @access public
+ * @category Financial Functions
+ * @param float cost Initial cost of the asset.
+ * @param float salvage Value at the end of the depreciation.
+ * (Sometimes called the salvage value of the asset)
+ * @param integer life Number of periods over which the asset is depreciated.
+ * (Sometimes called the useful life of the asset)
+ * @param integer period The period for which you want to calculate the
+ * depreciation. Period must use the same units as life.
+ * @param integer month Number of months in the first year. If month is omitted,
+ * it defaults to 12.
+ * @return float
+ */
+ public static function DB($cost, $salvage, $life, $period, $month=12) {
+ $cost = Calculation_Functions::flattenSingleValue($cost);
+ $salvage = Calculation_Functions::flattenSingleValue($salvage);
+ $life = Calculation_Functions::flattenSingleValue($life);
+ $period = Calculation_Functions::flattenSingleValue($period);
+ $month = Calculation_Functions::flattenSingleValue($month);
+
+ // Validate
+ if ((is_numeric($cost)) && (is_numeric($salvage)) && (is_numeric($life)) && (is_numeric($period)) && (is_numeric($month))) {
+ $cost = (float) $cost;
+ $salvage = (float) $salvage;
+ $life = (int) $life;
+ $period = (int) $period;
+ $month = (int) $month;
+ if ($cost == 0) {
+ return 0.0;
+ } elseif (($cost < 0) || (($salvage / $cost) < 0) || ($life <= 0) || ($period < 1) || ($month < 1)) {
+ return Calculation_Functions::NaN();
+ }
+ // Set Fixed Depreciation Rate
+ $fixedDepreciationRate = 1 - pow(($salvage / $cost), (1 / $life));
+ $fixedDepreciationRate = round($fixedDepreciationRate, 3);
+
+ // Loop through each period calculating the depreciation
+ $previousDepreciation = 0;
+ for ($per = 1; $per <= $period; ++$per) {
+ if ($per == 1) {
+ $depreciation = $cost * $fixedDepreciationRate * $month / 12;
+ } elseif ($per == ($life + 1)) {
+ $depreciation = ($cost - $previousDepreciation) * $fixedDepreciationRate * (12 - $month) / 12;
+ } else {
+ $depreciation = ($cost - $previousDepreciation) * $fixedDepreciationRate;
+ }
+ $previousDepreciation += $depreciation;
+ }
+ if (Calculation_Functions::getCompatibilityMode() == Calculation_Functions::COMPATIBILITY_GNUMERIC) {
+ $depreciation = round($depreciation,2);
+ }
+ return $depreciation;
+ }
+ return Calculation_Functions::VALUE();
+ } // function DB()
+
+
+ /**
+ * DDB
+ *
+ * Returns the depreciation of an asset for a specified period using the
+ * double-declining balance method or some other method you specify.
+ *
+ * Excel Function:
+ * DDB(cost,salvage,life,period[,factor])
+ *
+ * @access public
+ * @category Financial Functions
+ * @param float cost Initial cost of the asset.
+ * @param float salvage Value at the end of the depreciation.
+ * (Sometimes called the salvage value of the asset)
+ * @param integer life Number of periods over which the asset is depreciated.
+ * (Sometimes called the useful life of the asset)
+ * @param integer period The period for which you want to calculate the
+ * depreciation. Period must use the same units as life.
+ * @param float factor The rate at which the balance declines.
+ * If factor is omitted, it is assumed to be 2 (the
+ * double-declining balance method).
+ * @return float
+ */
+ public static function DDB($cost, $salvage, $life, $period, $factor=2.0) {
+ $cost = Calculation_Functions::flattenSingleValue($cost);
+ $salvage = Calculation_Functions::flattenSingleValue($salvage);
+ $life = Calculation_Functions::flattenSingleValue($life);
+ $period = Calculation_Functions::flattenSingleValue($period);
+ $factor = Calculation_Functions::flattenSingleValue($factor);
+
+ // Validate
+ if ((is_numeric($cost)) && (is_numeric($salvage)) && (is_numeric($life)) && (is_numeric($period)) && (is_numeric($factor))) {
+ $cost = (float) $cost;
+ $salvage = (float) $salvage;
+ $life = (int) $life;
+ $period = (int) $period;
+ $factor = (float) $factor;
+ if (($cost <= 0) || (($salvage / $cost) < 0) || ($life <= 0) || ($period < 1) || ($factor <= 0.0) || ($period > $life)) {
+ return Calculation_Functions::NaN();
+ }
+ // Set Fixed Depreciation Rate
+ $fixedDepreciationRate = 1 - pow(($salvage / $cost), (1 / $life));
+ $fixedDepreciationRate = round($fixedDepreciationRate, 3);
+
+ // Loop through each period calculating the depreciation
+ $previousDepreciation = 0;
+ for ($per = 1; $per <= $period; ++$per) {
+ $depreciation = min( ($cost - $previousDepreciation) * ($factor / $life), ($cost - $salvage - $previousDepreciation) );
+ $previousDepreciation += $depreciation;
+ }
+ if (Calculation_Functions::getCompatibilityMode() == Calculation_Functions::COMPATIBILITY_GNUMERIC) {
+ $depreciation = round($depreciation,2);
+ }
+ return $depreciation;
+ }
+ return Calculation_Functions::VALUE();
+ } // function DDB()
+
+
+ /**
+ * DISC
+ *
+ * Returns the discount rate for a security.
+ *
+ * Excel Function:
+ * DISC(settlement,maturity,price,redemption[,basis])
+ *
+ * @access public
+ * @category Financial Functions
+ * @param mixed settlement The security's settlement date.
+ * The security settlement date is the date after the issue
+ * date when the security is traded to the buyer.
+ * @param mixed maturity The security's maturity date.
+ * The maturity date is the date when the security expires.
+ * @param integer price The security's price per $100 face value.
+ * @param integer redemption The security's redemption value per $100 face value.
+ * @param integer basis The type of day count to use.
+ * 0 or omitted US (NASD) 30/360
+ * 1 Actual/actual
+ * 2 Actual/360
+ * 3 Actual/365
+ * 4 European 30/360
+ * @return float
+ */
+ public static function DISC($settlement, $maturity, $price, $redemption, $basis=0) {
+ $settlement = Calculation_Functions::flattenSingleValue($settlement);
+ $maturity = Calculation_Functions::flattenSingleValue($maturity);
+ $price = Calculation_Functions::flattenSingleValue($price);
+ $redemption = Calculation_Functions::flattenSingleValue($redemption);
+ $basis = Calculation_Functions::flattenSingleValue($basis);
+
+ // Validate
+ if ((is_numeric($price)) && (is_numeric($redemption)) && (is_numeric($basis))) {
+ $price = (float) $price;
+ $redemption = (float) $redemption;
+ $basis = (int) $basis;
+ if (($price <= 0) || ($redemption <= 0)) {
+ return Calculation_Functions::NaN();
+ }
+ $daysBetweenSettlementAndMaturity = Calculation_DateTime::YEARFRAC($settlement, $maturity, $basis);
+ if (!is_numeric($daysBetweenSettlementAndMaturity)) {
+ // return date error
+ return $daysBetweenSettlementAndMaturity;
+ }
+
+ return ((1 - $price / $redemption) / $daysBetweenSettlementAndMaturity);
+ }
+ return Calculation_Functions::VALUE();
+ } // function DISC()
+
+
+ /**
+ * DOLLARDE
+ *
+ * Converts a dollar price expressed as an integer part and a fraction
+ * part into a dollar price expressed as a decimal number.
+ * Fractional dollar numbers are sometimes used for security prices.
+ *
+ * Excel Function:
+ * DOLLARDE(fractional_dollar,fraction)
+ *
+ * @access public
+ * @category Financial Functions
+ * @param float $fractional_dollar Fractional Dollar
+ * @param integer $fraction Fraction
+ * @return float
+ */
+ public static function DOLLARDE($fractional_dollar = Null, $fraction = 0) {
+ $fractional_dollar = Calculation_Functions::flattenSingleValue($fractional_dollar);
+ $fraction = (int)Calculation_Functions::flattenSingleValue($fraction);
+
+ // Validate parameters
+ if (is_null($fractional_dollar) || $fraction < 0) {
+ return Calculation_Functions::NaN();
+ }
+ if ($fraction == 0) {
+ return Calculation_Functions::DIV0();
+ }
+
+ $dollars = floor($fractional_dollar);
+ $cents = fmod($fractional_dollar,1);
+ $cents /= $fraction;
+ $cents *= pow(10,ceil(log10($fraction)));
+ return $dollars + $cents;
+ } // function DOLLARDE()
+
+
+ /**
+ * DOLLARFR
+ *
+ * Converts a dollar price expressed as a decimal number into a dollar price
+ * expressed as a fraction.
+ * Fractional dollar numbers are sometimes used for security prices.
+ *
+ * Excel Function:
+ * DOLLARFR(decimal_dollar,fraction)
+ *
+ * @access public
+ * @category Financial Functions
+ * @param float $decimal_dollar Decimal Dollar
+ * @param integer $fraction Fraction
+ * @return float
+ */
+ public static function DOLLARFR($decimal_dollar = Null, $fraction = 0) {
+ $decimal_dollar = Calculation_Functions::flattenSingleValue($decimal_dollar);
+ $fraction = (int)Calculation_Functions::flattenSingleValue($fraction);
+
+ // Validate parameters
+ if (is_null($decimal_dollar) || $fraction < 0) {
+ return Calculation_Functions::NaN();
+ }
+ if ($fraction == 0) {
+ return Calculation_Functions::DIV0();
+ }
+
+ $dollars = floor($decimal_dollar);
+ $cents = fmod($decimal_dollar,1);
+ $cents *= $fraction;
+ $cents *= pow(10,-ceil(log10($fraction)));
+ return $dollars + $cents;
+ } // function DOLLARFR()
+
+
+ /**
+ * EFFECT
+ *
+ * Returns the effective interest rate given the nominal rate and the number of
+ * compounding payments per year.
+ *
+ * Excel Function:
+ * EFFECT(nominal_rate,npery)
+ *
+ * @access public
+ * @category Financial Functions
+ * @param float $nominal_rate Nominal interest rate
+ * @param integer $npery Number of compounding payments per year
+ * @return float
+ */
+ public static function EFFECT($nominal_rate = 0, $npery = 0) {
+ $nominal_rate = Calculation_Functions::flattenSingleValue($nominal_rate);
+ $npery = (int)Calculation_Functions::flattenSingleValue($npery);
+
+ // Validate parameters
+ if ($nominal_rate <= 0 || $npery < 1) {
+ return Calculation_Functions::NaN();
+ }
+
+ return pow((1 + $nominal_rate / $npery), $npery) - 1;
+ } // function EFFECT()
+
+
+ /**
+ * FV
+ *
+ * Returns the Future Value of a cash flow with constant payments and interest rate (annuities).
+ *
+ * Excel Function:
+ * FV(rate,nper,pmt[,pv[,type]])
+ *
+ * @access public
+ * @category Financial Functions
+ * @param float $rate The interest rate per period
+ * @param int $nper Total number of payment periods in an annuity
+ * @param float $pmt The payment made each period: it cannot change over the
+ * life of the annuity. Typically, pmt contains principal
+ * and interest but no other fees or taxes.
+ * @param float $pv Present Value, or the lump-sum amount that a series of
+ * future payments is worth right now.
+ * @param integer $type A number 0 or 1 and indicates when payments are due:
+ * 0 or omitted At the end of the period.
+ * 1 At the beginning of the period.
+ * @return float
+ */
+ public static function FV($rate = 0, $nper = 0, $pmt = 0, $pv = 0, $type = 0) {
+ $rate = Calculation_Functions::flattenSingleValue($rate);
+ $nper = Calculation_Functions::flattenSingleValue($nper);
+ $pmt = Calculation_Functions::flattenSingleValue($pmt);
+ $pv = Calculation_Functions::flattenSingleValue($pv);
+ $type = Calculation_Functions::flattenSingleValue($type);
+
+ // Validate parameters
+ if ($type != 0 && $type != 1) {
+ return Calculation_Functions::NaN();
+ }
+
+ // Calculate
+ if (!is_null($rate) && $rate != 0) {
+ return -$pv * pow(1 + $rate, $nper) - $pmt * (1 + $rate * $type) * (pow(1 + $rate, $nper) - 1) / $rate;
+ } else {
+ return -$pv - $pmt * $nper;
+ }
+ } // function FV()
+
+
+ /**
+ * FVSCHEDULE
+ *
+ * Returns the future value of an initial principal after applying a series of compound interest rates.
+ * Use FVSCHEDULE to calculate the future value of an investment with a variable or adjustable rate.
+ *
+ * Excel Function:
+ * FVSCHEDULE(principal,schedule)
+ *
+ * @param float $principal The present value.
+ * @param float[] $schedule An array of interest rates to apply.
+ * @return float
+ */
+ public static function FVSCHEDULE($principal, $schedule) {
+ $principal = Calculation_Functions::flattenSingleValue($principal);
+ $schedule = Calculation_Functions::flattenArray($schedule);
+
+ foreach($schedule as $rate) {
+ $principal *= 1 + $rate;
+ }
+
+ return $principal;
+ } // function FVSCHEDULE()
+
+
+ /**
+ * INTRATE
+ *
+ * Returns the interest rate for a fully invested security.
+ *
+ * Excel Function:
+ * INTRATE(settlement,maturity,investment,redemption[,basis])
+ *
+ * @param mixed $settlement The security's settlement date.
+ * The security settlement date is the date after the issue date when the security is traded to the buyer.
+ * @param mixed $maturity The security's maturity date.
+ * The maturity date is the date when the security expires.
+ * @param integer $investment The amount invested in the security.
+ * @param integer $redemption The amount to be received at maturity.
+ * @param integer $basis The type of day count to use.
+ * 0 or omitted US (NASD) 30/360
+ * 1 Actual/actual
+ * 2 Actual/360
+ * 3 Actual/365
+ * 4 European 30/360
+ * @return float
+ */
+ public static function INTRATE($settlement, $maturity, $investment, $redemption, $basis=0) {
+ $settlement = Calculation_Functions::flattenSingleValue($settlement);
+ $maturity = Calculation_Functions::flattenSingleValue($maturity);
+ $investment = Calculation_Functions::flattenSingleValue($investment);
+ $redemption = Calculation_Functions::flattenSingleValue($redemption);
+ $basis = Calculation_Functions::flattenSingleValue($basis);
+
+ // Validate
+ if ((is_numeric($investment)) && (is_numeric($redemption)) && (is_numeric($basis))) {
+ $investment = (float) $investment;
+ $redemption = (float) $redemption;
+ $basis = (int) $basis;
+ if (($investment <= 0) || ($redemption <= 0)) {
+ return Calculation_Functions::NaN();
+ }
+ $daysBetweenSettlementAndMaturity = Calculation_DateTime::YEARFRAC($settlement, $maturity, $basis);
+ if (!is_numeric($daysBetweenSettlementAndMaturity)) {
+ // return date error
+ return $daysBetweenSettlementAndMaturity;
+ }
+
+ return (($redemption / $investment) - 1) / ($daysBetweenSettlementAndMaturity);
+ }
+ return Calculation_Functions::VALUE();
+ } // function INTRATE()
+
+
+ /**
+ * IPMT
+ *
+ * Returns the interest payment for a given period for an investment based on periodic, constant payments and a constant interest rate.
+ *
+ * Excel Function:
+ * IPMT(rate,per,nper,pv[,fv][,type])
+ *
+ * @param float $rate Interest rate per period
+ * @param int $per Period for which we want to find the interest
+ * @param int $nper Number of periods
+ * @param float $pv Present Value
+ * @param float $fv Future Value
+ * @param int $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period
+ * @return float
+ */
+ public static function IPMT($rate, $per, $nper, $pv, $fv = 0, $type = 0) {
+ $rate = Calculation_Functions::flattenSingleValue($rate);
+ $per = (int) Calculation_Functions::flattenSingleValue($per);
+ $nper = (int) Calculation_Functions::flattenSingleValue($nper);
+ $pv = Calculation_Functions::flattenSingleValue($pv);
+ $fv = Calculation_Functions::flattenSingleValue($fv);
+ $type = (int) Calculation_Functions::flattenSingleValue($type);
+
+ // Validate parameters
+ if ($type != 0 && $type != 1) {
+ return Calculation_Functions::NaN();
+ }
+ if ($per <= 0 || $per > $nper) {
+ return Calculation_Functions::VALUE();
+ }
+
+ // Calculate
+ $interestAndPrincipal = self::_interestAndPrincipal($rate, $per, $nper, $pv, $fv, $type);
+ return $interestAndPrincipal[0];
+ } // function IPMT()
+
+ /**
+ * IRR
+ *
+ * Returns the internal rate of return for a series of cash flows represented by the numbers in values.
+ * These cash flows do not have to be even, as they would be for an annuity. However, the cash flows must occur
+ * at regular intervals, such as monthly or annually. The internal rate of return is the interest rate received
+ * for an investment consisting of payments (negative values) and income (positive values) that occur at regular
+ * periods.
+ *
+ * Excel Function:
+ * IRR(values[,guess])
+ *
+ * @param float[] $values An array or a reference to cells that contain numbers for which you want
+ * to calculate the internal rate of return.
+ * Values must contain at least one positive value and one negative value to
+ * calculate the internal rate of return.
+ * @param float $guess A number that you guess is close to the result of IRR
+ * @return float
+ */
+ public static function IRR($values, $guess = 0.1) {
+ if (!is_array($values)) return Calculation_Functions::VALUE();
+ $values = Calculation_Functions::flattenArray($values);
+ $guess = Calculation_Functions::flattenSingleValue($guess);
+
+ // create an initial range, with a root somewhere between 0 and guess
+ $x1 = 0.0;
+ $x2 = $guess;
+ $f1 = self::NPV($x1, $values);
+ $f2 = self::NPV($x2, $values);
+ for ($i = 0; $i < FINANCIAL_MAX_ITERATIONS; ++$i) {
+ if (($f1 * $f2) < 0.0) break;
+ if (abs($f1) < abs($f2)) {
+ $f1 = self::NPV($x1 += 1.6 * ($x1 - $x2), $values);
+ } else {
+ $f2 = self::NPV($x2 += 1.6 * ($x2 - $x1), $values);
+ }
+ }
+ if (($f1 * $f2) > 0.0) return Calculation_Functions::VALUE();
+
+ $f = self::NPV($x1, $values);
+ if ($f < 0.0) {
+ $rtb = $x1;
+ $dx = $x2 - $x1;
+ } else {
+ $rtb = $x2;
+ $dx = $x1 - $x2;
+ }
+
+ for ($i = 0; $i < FINANCIAL_MAX_ITERATIONS; ++$i) {
+ $dx *= 0.5;
+ $x_mid = $rtb + $dx;
+ $f_mid = self::NPV($x_mid, $values);
+ if ($f_mid <= 0.0)
+ $rtb = $x_mid;
+ if ((abs($f_mid) < FINANCIAL_PRECISION) || (abs($dx) < FINANCIAL_PRECISION))
+ return $x_mid;
+ }
+ return Calculation_Functions::VALUE();
+ } // function IRR()
+
+
+ /**
+ * ISPMT
+ *
+ * Returns the interest payment for an investment based on an interest rate and a constant payment schedule.
+ *
+ * Excel Function:
+ * =ISPMT(interest_rate, period, number_payments, PV)
+ *
+ * interest_rate is the interest rate for the investment
+ *
+ * period is the period to calculate the interest rate. It must be betweeen 1 and number_payments.
+ *
+ * number_payments is the number of payments for the annuity
+ *
+ * PV is the loan amount or present value of the payments
+ */
+ public static function ISPMT() {
+ // Return value
+ $returnValue = 0;
+
+ // Get the parameters
+ $aArgs = Calculation_Functions::flattenArray(func_get_args());
+ $interestRate = array_shift($aArgs);
+ $period = array_shift($aArgs);
+ $numberPeriods = array_shift($aArgs);
+ $principleRemaining = array_shift($aArgs);
+
+ // Calculate
+ $principlePayment = ($principleRemaining * 1.0) / ($numberPeriods * 1.0);
+ for($i=0; $i <= $period; ++$i) {
+ $returnValue = $interestRate * $principleRemaining * -1;
+ $principleRemaining -= $principlePayment;
+ // principle needs to be 0 after the last payment, don't let floating point screw it up
+ if($i == $numberPeriods) {
+ $returnValue = 0;
+ }
+ }
+ return($returnValue);
+ } // function ISPMT()
+
+
+ /**
+ * MIRR
+ *
+ * Returns the modified internal rate of return for a series of periodic cash flows. MIRR considers both
+ * the cost of the investment and the interest received on reinvestment of cash.
+ *
+ * Excel Function:
+ * MIRR(values,finance_rate, reinvestment_rate)
+ *
+ * @param float[] $values An array or a reference to cells that contain a series of payments and
+ * income occurring at regular intervals.
+ * Payments are negative value, income is positive values.
+ * @param float $finance_rate The interest rate you pay on the money used in the cash flows
+ * @param float $reinvestment_rate The interest rate you receive on the cash flows as you reinvest them
+ * @return float
+ */
+ public static function MIRR($values, $finance_rate, $reinvestment_rate) {
+ if (!is_array($values)) return Calculation_Functions::VALUE();
+ $values = Calculation_Functions::flattenArray($values);
+ $finance_rate = Calculation_Functions::flattenSingleValue($finance_rate);
+ $reinvestment_rate = Calculation_Functions::flattenSingleValue($reinvestment_rate);
+ $n = count($values);
+
+ $rr = 1.0 + $reinvestment_rate;
+ $fr = 1.0 + $finance_rate;
+
+ $npv_pos = $npv_neg = 0.0;
+ foreach($values as $i => $v) {
+ if ($v >= 0) {
+ $npv_pos += $v / pow($rr, $i);
+ } else {
+ $npv_neg += $v / pow($fr, $i);
+ }
+ }
+
+ if (($npv_neg == 0) || ($npv_pos == 0) || ($reinvestment_rate <= -1)) {
+ return Calculation_Functions::VALUE();
+ }
+
+ $mirr = pow((-$npv_pos * pow($rr, $n))
+ / ($npv_neg * ($rr)), (1.0 / ($n - 1))) - 1.0;
+
+ return (is_finite($mirr) ? $mirr : Calculation_Functions::VALUE());
+ } // function MIRR()
+
+
+ /**
+ * NOMINAL
+ *
+ * Returns the nominal interest rate given the effective rate and the number of compounding payments per year.
+ *
+ * @param float $effect_rate Effective interest rate
+ * @param int $npery Number of compounding payments per year
+ * @return float
+ */
+ public static function NOMINAL($effect_rate = 0, $npery = 0) {
+ $effect_rate = Calculation_Functions::flattenSingleValue($effect_rate);
+ $npery = (int)Calculation_Functions::flattenSingleValue($npery);
+
+ // Validate parameters
+ if ($effect_rate <= 0 || $npery < 1) {
+ return Calculation_Functions::NaN();
+ }
+
+ // Calculate
+ return $npery * (pow($effect_rate + 1, 1 / $npery) - 1);
+ } // function NOMINAL()
+
+
+ /**
+ * NPER
+ *
+ * Returns the number of periods for a cash flow with constant periodic payments (annuities), and interest rate.
+ *
+ * @param float $rate Interest rate per period
+ * @param int $pmt Periodic payment (annuity)
+ * @param float $pv Present Value
+ * @param float $fv Future Value
+ * @param int $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period
+ * @return float
+ */
+ public static function NPER($rate = 0, $pmt = 0, $pv = 0, $fv = 0, $type = 0) {
+ $rate = Calculation_Functions::flattenSingleValue($rate);
+ $pmt = Calculation_Functions::flattenSingleValue($pmt);
+ $pv = Calculation_Functions::flattenSingleValue($pv);
+ $fv = Calculation_Functions::flattenSingleValue($fv);
+ $type = Calculation_Functions::flattenSingleValue($type);
+
+ // Validate parameters
+ if ($type != 0 && $type != 1) {
+ return Calculation_Functions::NaN();
+ }
+
+ // Calculate
+ if (!is_null($rate) && $rate != 0) {
+ if ($pmt == 0 && $pv == 0) {
+ return Calculation_Functions::NaN();
+ }
+ return log(($pmt * (1 + $rate * $type) / $rate - $fv) / ($pv + $pmt * (1 + $rate * $type) / $rate)) / log(1 + $rate);
+ } else {
+ if ($pmt == 0) {
+ return Calculation_Functions::NaN();
+ }
+ return (-$pv -$fv) / $pmt;
+ }
+ } // function NPER()
+
+ /**
+ * NPV
+ *
+ * Returns the Net Present Value of a cash flow series given a discount rate.
+ *
+ * @return float
+ */
+ public static function NPV() {
+ // Return value
+ $returnValue = 0;
+
+ // Loop through arguments
+ $aArgs = Calculation_Functions::flattenArray(func_get_args());
+
+ // Calculate
+ $rate = array_shift($aArgs);
+ for ($i = 1; $i <= count($aArgs); ++$i) {
+ // Is it a numeric value?
+ if (is_numeric($aArgs[$i - 1])) {
+ $returnValue += $aArgs[$i - 1] / pow(1 + $rate, $i);
+ }
+ }
+
+ // Return
+ return $returnValue;
+ } // function NPV()
+
+ /**
+ * PMT
+ *
+ * Returns the constant payment (annuity) for a cash flow with a constant interest rate.
+ *
+ * @param float $rate Interest rate per period
+ * @param int $nper Number of periods
+ * @param float $pv Present Value
+ * @param float $fv Future Value
+ * @param int $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period
+ * @return float
+ */
+ public static function PMT($rate = 0, $nper = 0, $pv = 0, $fv = 0, $type = 0) {
+ $rate = Calculation_Functions::flattenSingleValue($rate);
+ $nper = Calculation_Functions::flattenSingleValue($nper);
+ $pv = Calculation_Functions::flattenSingleValue($pv);
+ $fv = Calculation_Functions::flattenSingleValue($fv);
+ $type = Calculation_Functions::flattenSingleValue($type);
+
+ // Validate parameters
+ if ($type != 0 && $type != 1) {
+ return Calculation_Functions::NaN();
+ }
+
+ // Calculate
+ if (!is_null($rate) && $rate != 0) {
+ return (-$fv - $pv * pow(1 + $rate, $nper)) / (1 + $rate * $type) / ((pow(1 + $rate, $nper) - 1) / $rate);
+ } else {
+ return (-$pv - $fv) / $nper;
+ }
+ } // function PMT()
+
+
+ /**
+ * PPMT
+ *
+ * Returns the interest payment for a given period for an investment based on periodic, constant payments and a constant interest rate.
+ *
+ * @param float $rate Interest rate per period
+ * @param int $per Period for which we want to find the interest
+ * @param int $nper Number of periods
+ * @param float $pv Present Value
+ * @param float $fv Future Value
+ * @param int $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period
+ * @return float
+ */
+ public static function PPMT($rate, $per, $nper, $pv, $fv = 0, $type = 0) {
+ $rate = Calculation_Functions::flattenSingleValue($rate);
+ $per = (int) Calculation_Functions::flattenSingleValue($per);
+ $nper = (int) Calculation_Functions::flattenSingleValue($nper);
+ $pv = Calculation_Functions::flattenSingleValue($pv);
+ $fv = Calculation_Functions::flattenSingleValue($fv);
+ $type = (int) Calculation_Functions::flattenSingleValue($type);
+
+ // Validate parameters
+ if ($type != 0 && $type != 1) {
+ return Calculation_Functions::NaN();
+ }
+ if ($per <= 0 || $per > $nper) {
+ return Calculation_Functions::VALUE();
+ }
+
+ // Calculate
+ $interestAndPrincipal = self::_interestAndPrincipal($rate, $per, $nper, $pv, $fv, $type);
+ return $interestAndPrincipal[1];
+ } // function PPMT()
+
+
+ public static function PRICE($settlement, $maturity, $rate, $yield, $redemption, $frequency, $basis=0) {
+ $settlement = Calculation_Functions::flattenSingleValue($settlement);
+ $maturity = Calculation_Functions::flattenSingleValue($maturity);
+ $rate = (float) Calculation_Functions::flattenSingleValue($rate);
+ $yield = (float) Calculation_Functions::flattenSingleValue($yield);
+ $redemption = (float) Calculation_Functions::flattenSingleValue($redemption);
+ $frequency = (int) Calculation_Functions::flattenSingleValue($frequency);
+ $basis = (is_null($basis)) ? 0 : (int) Calculation_Functions::flattenSingleValue($basis);
+
+ if (is_string($settlement = Calculation_DateTime::_getDateValue($settlement))) {
+ return Calculation_Functions::VALUE();
+ }
+ if (is_string($maturity = Calculation_DateTime::_getDateValue($maturity))) {
+ return Calculation_Functions::VALUE();
+ }
+
+ if (($settlement > $maturity) ||
+ (!self::_validFrequency($frequency)) ||
+ (($basis < 0) || ($basis > 4))) {
+ return Calculation_Functions::NaN();
+ }
+
+ $dsc = self::COUPDAYSNC($settlement, $maturity, $frequency, $basis);
+ $e = self::COUPDAYS($settlement, $maturity, $frequency, $basis);
+ $n = self::COUPNUM($settlement, $maturity, $frequency, $basis);
+ $a = self::COUPDAYBS($settlement, $maturity, $frequency, $basis);
+
+ $baseYF = 1.0 + ($yield / $frequency);
+ $rfp = 100 * ($rate / $frequency);
+ $de = $dsc / $e;
+
+ $result = $redemption / pow($baseYF, (--$n + $de));
+ for($k = 0; $k <= $n; ++$k) {
+ $result += $rfp / (pow($baseYF, ($k + $de)));
+ }
+ $result -= $rfp * ($a / $e);
+
+ return $result;
+ } // function PRICE()
+
+
+ /**
+ * PRICEDISC
+ *
+ * Returns the price per $100 face value of a discounted security.
+ *
+ * @param mixed settlement The security's settlement date.
+ * The security settlement date is the date after the issue date when the security is traded to the buyer.
+ * @param mixed maturity The security's maturity date.
+ * The maturity date is the date when the security expires.
+ * @param int discount The security's discount rate.
+ * @param int redemption The security's redemption value per $100 face value.
+ * @param int basis The type of day count to use.
+ * 0 or omitted US (NASD) 30/360
+ * 1 Actual/actual
+ * 2 Actual/360
+ * 3 Actual/365
+ * 4 European 30/360
+ * @return float
+ */
+ public static function PRICEDISC($settlement, $maturity, $discount, $redemption, $basis=0) {
+ $settlement = Calculation_Functions::flattenSingleValue($settlement);
+ $maturity = Calculation_Functions::flattenSingleValue($maturity);
+ $discount = (float) Calculation_Functions::flattenSingleValue($discount);
+ $redemption = (float) Calculation_Functions::flattenSingleValue($redemption);
+ $basis = (int) Calculation_Functions::flattenSingleValue($basis);
+
+ // Validate
+ if ((is_numeric($discount)) && (is_numeric($redemption)) && (is_numeric($basis))) {
+ if (($discount <= 0) || ($redemption <= 0)) {
+ return Calculation_Functions::NaN();
+ }
+ $daysBetweenSettlementAndMaturity = Calculation_DateTime::YEARFRAC($settlement, $maturity, $basis);
+ if (!is_numeric($daysBetweenSettlementAndMaturity)) {
+ // return date error
+ return $daysBetweenSettlementAndMaturity;
+ }
+
+ return $redemption * (1 - $discount * $daysBetweenSettlementAndMaturity);
+ }
+ return Calculation_Functions::VALUE();
+ } // function PRICEDISC()
+
+
+ /**
+ * PRICEMAT
+ *
+ * Returns the price per $100 face value of a security that pays interest at maturity.
+ *
+ * @param mixed settlement The security's settlement date.
+ * The security's settlement date is the date after the issue date when the security is traded to the buyer.
+ * @param mixed maturity The security's maturity date.
+ * The maturity date is the date when the security expires.
+ * @param mixed issue The security's issue date.
+ * @param int rate The security's interest rate at date of issue.
+ * @param int yield The security's annual yield.
+ * @param int basis The type of day count to use.
+ * 0 or omitted US (NASD) 30/360
+ * 1 Actual/actual
+ * 2 Actual/360
+ * 3 Actual/365
+ * 4 European 30/360
+ * @return float
+ */
+ public static function PRICEMAT($settlement, $maturity, $issue, $rate, $yield, $basis=0) {
+ $settlement = Calculation_Functions::flattenSingleValue($settlement);
+ $maturity = Calculation_Functions::flattenSingleValue($maturity);
+ $issue = Calculation_Functions::flattenSingleValue($issue);
+ $rate = Calculation_Functions::flattenSingleValue($rate);
+ $yield = Calculation_Functions::flattenSingleValue($yield);
+ $basis = (int) Calculation_Functions::flattenSingleValue($basis);
+
+ // Validate
+ if (is_numeric($rate) && is_numeric($yield)) {
+ if (($rate <= 0) || ($yield <= 0)) {
+ return Calculation_Functions::NaN();
+ }
+ $daysPerYear = self::_daysPerYear(Calculation_DateTime::YEAR($settlement),$basis);
+ if (!is_numeric($daysPerYear)) {
+ return $daysPerYear;
+ }
+ $daysBetweenIssueAndSettlement = Calculation_DateTime::YEARFRAC($issue, $settlement, $basis);
+ if (!is_numeric($daysBetweenIssueAndSettlement)) {
+ // return date error
+ return $daysBetweenIssueAndSettlement;
+ }
+ $daysBetweenIssueAndSettlement *= $daysPerYear;
+ $daysBetweenIssueAndMaturity = Calculation_DateTime::YEARFRAC($issue, $maturity, $basis);
+ if (!is_numeric($daysBetweenIssueAndMaturity)) {
+ // return date error
+ return $daysBetweenIssueAndMaturity;
+ }
+ $daysBetweenIssueAndMaturity *= $daysPerYear;
+ $daysBetweenSettlementAndMaturity = Calculation_DateTime::YEARFRAC($settlement, $maturity, $basis);
+ if (!is_numeric($daysBetweenSettlementAndMaturity)) {
+ // return date error
+ return $daysBetweenSettlementAndMaturity;
+ }
+ $daysBetweenSettlementAndMaturity *= $daysPerYear;
+
+ return ((100 + (($daysBetweenIssueAndMaturity / $daysPerYear) * $rate * 100)) /
+ (1 + (($daysBetweenSettlementAndMaturity / $daysPerYear) * $yield)) -
+ (($daysBetweenIssueAndSettlement / $daysPerYear) * $rate * 100));
+ }
+ return Calculation_Functions::VALUE();
+ } // function PRICEMAT()
+
+
+ /**
+ * PV
+ *
+ * Returns the Present Value of a cash flow with constant payments and interest rate (annuities).
+ *
+ * @param float $rate Interest rate per period
+ * @param int $nper Number of periods
+ * @param float $pmt Periodic payment (annuity)
+ * @param float $fv Future Value
+ * @param int $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period
+ * @return float
+ */
+ public static function PV($rate = 0, $nper = 0, $pmt = 0, $fv = 0, $type = 0) {
+ $rate = Calculation_Functions::flattenSingleValue($rate);
+ $nper = Calculation_Functions::flattenSingleValue($nper);
+ $pmt = Calculation_Functions::flattenSingleValue($pmt);
+ $fv = Calculation_Functions::flattenSingleValue($fv);
+ $type = Calculation_Functions::flattenSingleValue($type);
+
+ // Validate parameters
+ if ($type != 0 && $type != 1) {
+ return Calculation_Functions::NaN();
+ }
+
+ // Calculate
+ if (!is_null($rate) && $rate != 0) {
+ return (-$pmt * (1 + $rate * $type) * ((pow(1 + $rate, $nper) - 1) / $rate) - $fv) / pow(1 + $rate, $nper);
+ } else {
+ return -$fv - $pmt * $nper;
+ }
+ } // function PV()
+
+
+ /**
+ * RATE
+ *
+ * Returns the interest rate per period of an annuity.
+ * RATE is calculated by iteration and can have zero or more solutions.
+ * If the successive results of RATE do not converge to within 0.0000001 after 20 iterations,
+ * RATE returns the #NUM! error value.
+ *
+ * Excel Function:
+ * RATE(nper,pmt,pv[,fv[,type[,guess]]])
+ *
+ * @access public
+ * @category Financial Functions
+ * @param float nper The total number of payment periods in an annuity.
+ * @param float pmt The payment made each period and cannot change over the life
+ * of the annuity.
+ * Typically, pmt includes principal and interest but no other
+ * fees or taxes.
+ * @param float pv The present value - the total amount that a series of future
+ * payments is worth now.
+ * @param float fv The future value, or a cash balance you want to attain after
+ * the last payment is made. If fv is omitted, it is assumed
+ * to be 0 (the future value of a loan, for example, is 0).
+ * @param integer type A number 0 or 1 and indicates when payments are due:
+ * 0 or omitted At the end of the period.
+ * 1 At the beginning of the period.
+ * @param float guess Your guess for what the rate will be.
+ * If you omit guess, it is assumed to be 10 percent.
+ * @return float
+ **/
+ public static function RATE($nper, $pmt, $pv, $fv = 0.0, $type = 0, $guess = 0.1) {
+ $nper = (int) Calculation_Functions::flattenSingleValue($nper);
+ $pmt = Calculation_Functions::flattenSingleValue($pmt);
+ $pv = Calculation_Functions::flattenSingleValue($pv);
+ $fv = (is_null($fv)) ? 0.0 : Calculation_Functions::flattenSingleValue($fv);
+ $type = (is_null($type)) ? 0 : (int) Calculation_Functions::flattenSingleValue($type);
+ $guess = (is_null($guess)) ? 0.1 : Calculation_Functions::flattenSingleValue($guess);
+
+ $rate = $guess;
+ if (abs($rate) < FINANCIAL_PRECISION) {
+ $y = $pv * (1 + $nper * $rate) + $pmt * (1 + $rate * $type) * $nper + $fv;
+ } else {
+ $f = exp($nper * log(1 + $rate));
+ $y = $pv * $f + $pmt * (1 / $rate + $type) * ($f - 1) + $fv;
+ }
+ $y0 = $pv + $pmt * $nper + $fv;
+ $y1 = $pv * $f + $pmt * (1 / $rate + $type) * ($f - 1) + $fv;
+
+ // find root by secant method
+ $i = $x0 = 0.0;
+ $x1 = $rate;
+ while ((abs($y0 - $y1) > FINANCIAL_PRECISION) && ($i < FINANCIAL_MAX_ITERATIONS)) {
+ $rate = ($y1 * $x0 - $y0 * $x1) / ($y1 - $y0);
+ $x0 = $x1;
+ $x1 = $rate;
+ if (($nper * abs($pmt)) > ($pv - $fv))
+ $x1 = abs($x1);
+
+ if (abs($rate) < FINANCIAL_PRECISION) {
+ $y = $pv * (1 + $nper * $rate) + $pmt * (1 + $rate * $type) * $nper + $fv;
+ } else {
+ $f = exp($nper * log(1 + $rate));
+ $y = $pv * $f + $pmt * (1 / $rate + $type) * ($f - 1) + $fv;
+ }
+
+ $y0 = $y1;
+ $y1 = $y;
+ ++$i;
+ }
+ return $rate;
+ } // function RATE()
+
+
+ /**
+ * RECEIVED
+ *
+ * Returns the price per $100 face value of a discounted security.
+ *
+ * @param mixed settlement The security's settlement date.
+ * The security settlement date is the date after the issue date when the security is traded to the buyer.
+ * @param mixed maturity The security's maturity date.
+ * The maturity date is the date when the security expires.
+ * @param int investment The amount invested in the security.
+ * @param int discount The security's discount rate.
+ * @param int basis The type of day count to use.
+ * 0 or omitted US (NASD) 30/360
+ * 1 Actual/actual
+ * 2 Actual/360
+ * 3 Actual/365
+ * 4 European 30/360
+ * @return float
+ */
+ public static function RECEIVED($settlement, $maturity, $investment, $discount, $basis=0) {
+ $settlement = Calculation_Functions::flattenSingleValue($settlement);
+ $maturity = Calculation_Functions::flattenSingleValue($maturity);
+ $investment = (float) Calculation_Functions::flattenSingleValue($investment);
+ $discount = (float) Calculation_Functions::flattenSingleValue($discount);
+ $basis = (int) Calculation_Functions::flattenSingleValue($basis);
+
+ // Validate
+ if ((is_numeric($investment)) && (is_numeric($discount)) && (is_numeric($basis))) {
+ if (($investment <= 0) || ($discount <= 0)) {
+ return Calculation_Functions::NaN();
+ }
+ $daysBetweenSettlementAndMaturity = Calculation_DateTime::YEARFRAC($settlement, $maturity, $basis);
+ if (!is_numeric($daysBetweenSettlementAndMaturity)) {
+ // return date error
+ return $daysBetweenSettlementAndMaturity;
+ }
+
+ return $investment / ( 1 - ($discount * $daysBetweenSettlementAndMaturity));
+ }
+ return Calculation_Functions::VALUE();
+ } // function RECEIVED()
+
+
+ /**
+ * SLN
+ *
+ * Returns the straight-line depreciation of an asset for one period
+ *
+ * @param cost Initial cost of the asset
+ * @param salvage Value at the end of the depreciation
+ * @param life Number of periods over which the asset is depreciated
+ * @return float
+ */
+ public static function SLN($cost, $salvage, $life) {
+ $cost = Calculation_Functions::flattenSingleValue($cost);
+ $salvage = Calculation_Functions::flattenSingleValue($salvage);
+ $life = Calculation_Functions::flattenSingleValue($life);
+
+ // Calculate
+ if ((is_numeric($cost)) && (is_numeric($salvage)) && (is_numeric($life))) {
+ if ($life < 0) {
+ return Calculation_Functions::NaN();
+ }
+ return ($cost - $salvage) / $life;
+ }
+ return Calculation_Functions::VALUE();
+ } // function SLN()
+
+
+ /**
+ * SYD
+ *
+ * Returns the sum-of-years' digits depreciation of an asset for a specified period.
+ *
+ * @param cost Initial cost of the asset
+ * @param salvage Value at the end of the depreciation
+ * @param life Number of periods over which the asset is depreciated
+ * @param period Period
+ * @return float
+ */
+ public static function SYD($cost, $salvage, $life, $period) {
+ $cost = Calculation_Functions::flattenSingleValue($cost);
+ $salvage = Calculation_Functions::flattenSingleValue($salvage);
+ $life = Calculation_Functions::flattenSingleValue($life);
+ $period = Calculation_Functions::flattenSingleValue($period);
+
+ // Calculate
+ if ((is_numeric($cost)) && (is_numeric($salvage)) && (is_numeric($life)) && (is_numeric($period))) {
+ if (($life < 1) || ($period > $life)) {
+ return Calculation_Functions::NaN();
+ }
+ return (($cost - $salvage) * ($life - $period + 1) * 2) / ($life * ($life + 1));
+ }
+ return Calculation_Functions::VALUE();
+ } // function SYD()
+
+
+ /**
+ * TBILLEQ
+ *
+ * Returns the bond-equivalent yield for a Treasury bill.
+ *
+ * @param mixed settlement The Treasury bill's settlement date.
+ * The Treasury bill's settlement date is the date after the issue date when the Treasury bill is traded to the buyer.
+ * @param mixed maturity The Treasury bill's maturity date.
+ * The maturity date is the date when the Treasury bill expires.
+ * @param int discount The Treasury bill's discount rate.
+ * @return float
+ */
+ public static function TBILLEQ($settlement, $maturity, $discount) {
+ $settlement = Calculation_Functions::flattenSingleValue($settlement);
+ $maturity = Calculation_Functions::flattenSingleValue($maturity);
+ $discount = Calculation_Functions::flattenSingleValue($discount);
+
+ // Use TBILLPRICE for validation
+ $testValue = self::TBILLPRICE($settlement, $maturity, $discount);
+ if (is_string($testValue)) {
+ return $testValue;
+ }
+
+ if (is_string($maturity = Calculation_DateTime::_getDateValue($maturity))) {
+ return Calculation_Functions::VALUE();
+ }
+
+ if (Calculation_Functions::getCompatibilityMode() == Calculation_Functions::COMPATIBILITY_OPENOFFICE) {
+ ++$maturity;
+ $daysBetweenSettlementAndMaturity = Calculation_DateTime::YEARFRAC($settlement, $maturity) * 360;
+ } else {
+ $daysBetweenSettlementAndMaturity = (Calculation_DateTime::_getDateValue($maturity) - Calculation_DateTime::_getDateValue($settlement));
+ }
+
+ return (365 * $discount) / (360 - $discount * $daysBetweenSettlementAndMaturity);
+ } // function TBILLEQ()
+
+
+ /**
+ * TBILLPRICE
+ *
+ * Returns the yield for a Treasury bill.
+ *
+ * @param mixed settlement The Treasury bill's settlement date.
+ * The Treasury bill's settlement date is the date after the issue date when the Treasury bill is traded to the buyer.
+ * @param mixed maturity The Treasury bill's maturity date.
+ * The maturity date is the date when the Treasury bill expires.
+ * @param int discount The Treasury bill's discount rate.
+ * @return float
+ */
+ public static function TBILLPRICE($settlement, $maturity, $discount) {
+ $settlement = Calculation_Functions::flattenSingleValue($settlement);
+ $maturity = Calculation_Functions::flattenSingleValue($maturity);
+ $discount = Calculation_Functions::flattenSingleValue($discount);
+
+ if (is_string($maturity = Calculation_DateTime::_getDateValue($maturity))) {
+ return Calculation_Functions::VALUE();
+ }
+
+ // Validate
+ if (is_numeric($discount)) {
+ if ($discount <= 0) {
+ return Calculation_Functions::NaN();
+ }
+
+ if (Calculation_Functions::getCompatibilityMode() == Calculation_Functions::COMPATIBILITY_OPENOFFICE) {
+ ++$maturity;
+ $daysBetweenSettlementAndMaturity = Calculation_DateTime::YEARFRAC($settlement, $maturity) * 360;
+ if (!is_numeric($daysBetweenSettlementAndMaturity)) {
+ // return date error
+ return $daysBetweenSettlementAndMaturity;
+ }
+ } else {
+ $daysBetweenSettlementAndMaturity = (Calculation_DateTime::_getDateValue($maturity) - Calculation_DateTime::_getDateValue($settlement));
+ }
+
+ if ($daysBetweenSettlementAndMaturity > 360) {
+ return Calculation_Functions::NaN();
+ }
+
+ $price = 100 * (1 - (($discount * $daysBetweenSettlementAndMaturity) / 360));
+ if ($price <= 0) {
+ return Calculation_Functions::NaN();
+ }
+ return $price;
+ }
+ return Calculation_Functions::VALUE();
+ } // function TBILLPRICE()
+
+
+ /**
+ * TBILLYIELD
+ *
+ * Returns the yield for a Treasury bill.
+ *
+ * @param mixed settlement The Treasury bill's settlement date.
+ * The Treasury bill's settlement date is the date after the issue date when the Treasury bill is traded to the buyer.
+ * @param mixed maturity The Treasury bill's maturity date.
+ * The maturity date is the date when the Treasury bill expires.
+ * @param int price The Treasury bill's price per $100 face value.
+ * @return float
+ */
+ public static function TBILLYIELD($settlement, $maturity, $price) {
+ $settlement = Calculation_Functions::flattenSingleValue($settlement);
+ $maturity = Calculation_Functions::flattenSingleValue($maturity);
+ $price = Calculation_Functions::flattenSingleValue($price);
+
+ // Validate
+ if (is_numeric($price)) {
+ if ($price <= 0) {
+ return Calculation_Functions::NaN();
+ }
+
+ if (Calculation_Functions::getCompatibilityMode() == Calculation_Functions::COMPATIBILITY_OPENOFFICE) {
+ ++$maturity;
+ $daysBetweenSettlementAndMaturity = Calculation_DateTime::YEARFRAC($settlement, $maturity) * 360;
+ if (!is_numeric($daysBetweenSettlementAndMaturity)) {
+ // return date error
+ return $daysBetweenSettlementAndMaturity;
+ }
+ } else {
+ $daysBetweenSettlementAndMaturity = (Calculation_DateTime::_getDateValue($maturity) - Calculation_DateTime::_getDateValue($settlement));
+ }
+
+ if ($daysBetweenSettlementAndMaturity > 360) {
+ return Calculation_Functions::NaN();
+ }
+
+ return ((100 - $price) / $price) * (360 / $daysBetweenSettlementAndMaturity);
+ }
+ return Calculation_Functions::VALUE();
+ } // function TBILLYIELD()
+
+
+ public static function XIRR($values, $dates, $guess = 0.1) {
+ if ((!is_array($values)) && (!is_array($dates))) return Calculation_Functions::VALUE();
+ $values = Calculation_Functions::flattenArray($values);
+ $dates = Calculation_Functions::flattenArray($dates);
+ $guess = Calculation_Functions::flattenSingleValue($guess);
+ if (count($values) != count($dates)) return Calculation_Functions::NaN();
+
+ // create an initial range, with a root somewhere between 0 and guess
+ $x1 = 0.0;
+ $x2 = $guess;
+ $f1 = self::XNPV($x1, $values, $dates);
+ $f2 = self::XNPV($x2, $values, $dates);
+ for ($i = 0; $i < FINANCIAL_MAX_ITERATIONS; ++$i) {
+ if (($f1 * $f2) < 0.0) break;
+ if (abs($f1) < abs($f2)) {
+ $f1 = self::XNPV($x1 += 1.6 * ($x1 - $x2), $values, $dates);
+ } else {
+ $f2 = self::XNPV($x2 += 1.6 * ($x2 - $x1), $values, $dates);
+ }
+ }
+ if (($f1 * $f2) > 0.0) return Calculation_Functions::VALUE();
+
+ $f = self::XNPV($x1, $values, $dates);
+ if ($f < 0.0) {
+ $rtb = $x1;
+ $dx = $x2 - $x1;
+ } else {
+ $rtb = $x2;
+ $dx = $x1 - $x2;
+ }
+
+ for ($i = 0; $i < FINANCIAL_MAX_ITERATIONS; ++$i) {
+ $dx *= 0.5;
+ $x_mid = $rtb + $dx;
+ $f_mid = self::XNPV($x_mid, $values, $dates);
+ if ($f_mid <= 0.0) $rtb = $x_mid;
+ if ((abs($f_mid) < FINANCIAL_PRECISION) || (abs($dx) < FINANCIAL_PRECISION)) return $x_mid;
+ }
+ return Calculation_Functions::VALUE();
+ }
+
+
+ /**
+ * XNPV
+ *
+ * Returns the net present value for a schedule of cash flows that is not necessarily periodic.
+ * To calculate the net present value for a series of cash flows that is periodic, use the NPV function.
+ *
+ * Excel Function:
+ * =XNPV(rate,values,dates)
+ *
+ * @param float $rate The discount rate to apply to the cash flows.
+ * @param array of float $values A series of cash flows that corresponds to a schedule of payments in dates. The first payment is optional and corresponds to a cost or payment that occurs at the beginning of the investment. If the first value is a cost or payment, it must be a negative value. All succeeding payments are discounted based on a 365-day year. The series of values must contain at least one positive value and one negative value.
+ * @param array of mixed $dates A schedule of payment dates that corresponds to the cash flow payments. The first payment date indicates the beginning of the schedule of payments. All other dates must be later than this date, but they may occur in any order.
+ * @return float
+ */
+ public static function XNPV($rate, $values, $dates) {
+ $rate = Calculation_Functions::flattenSingleValue($rate);
+ if (!is_numeric($rate)) return Calculation_Functions::VALUE();
+ if ((!is_array($values)) || (!is_array($dates))) return Calculation_Functions::VALUE();
+ $values = Calculation_Functions::flattenArray($values);
+ $dates = Calculation_Functions::flattenArray($dates);
+ $valCount = count($values);
+ if ($valCount != count($dates)) return Calculation_Functions::NaN();
+ if ((min($values) > 0) || (max($values) < 0)) return Calculation_Functions::VALUE();
+
+ $xnpv = 0.0;
+ for ($i = 0; $i < $valCount; ++$i) {
+ if (!is_numeric($values[$i])) return Calculation_Functions::VALUE();
+ $xnpv += $values[$i] / pow(1 + $rate, Calculation_DateTime::DATEDIF($dates[0],$dates[$i],'d') / 365);
+ }
+ return (is_finite($xnpv)) ? $xnpv : Calculation_Functions::VALUE();
+ } // function XNPV()
+
+
+ /**
+ * YIELDDISC
+ *
+ * Returns the annual yield of a security that pays interest at maturity.
+ *
+ * @param mixed settlement The security's settlement date.
+ * The security's settlement date is the date after the issue date when the security is traded to the buyer.
+ * @param mixed maturity The security's maturity date.
+ * The maturity date is the date when the security expires.
+ * @param int price The security's price per $100 face value.
+ * @param int redemption The security's redemption value per $100 face value.
+ * @param int basis The type of day count to use.
+ * 0 or omitted US (NASD) 30/360
+ * 1 Actual/actual
+ * 2 Actual/360
+ * 3 Actual/365
+ * 4 European 30/360
+ * @return float
+ */
+ public static function YIELDDISC($settlement, $maturity, $price, $redemption, $basis=0) {
+ $settlement = Calculation_Functions::flattenSingleValue($settlement);
+ $maturity = Calculation_Functions::flattenSingleValue($maturity);
+ $price = Calculation_Functions::flattenSingleValue($price);
+ $redemption = Calculation_Functions::flattenSingleValue($redemption);
+ $basis = (int) Calculation_Functions::flattenSingleValue($basis);
+
+ // Validate
+ if (is_numeric($price) && is_numeric($redemption)) {
+ if (($price <= 0) || ($redemption <= 0)) {
+ return Calculation_Functions::NaN();
+ }
+ $daysPerYear = self::_daysPerYear(Calculation_DateTime::YEAR($settlement),$basis);
+ if (!is_numeric($daysPerYear)) {
+ return $daysPerYear;
+ }
+ $daysBetweenSettlementAndMaturity = Calculation_DateTime::YEARFRAC($settlement, $maturity,$basis);
+ if (!is_numeric($daysBetweenSettlementAndMaturity)) {
+ // return date error
+ return $daysBetweenSettlementAndMaturity;
+ }
+ $daysBetweenSettlementAndMaturity *= $daysPerYear;
+
+ return (($redemption - $price) / $price) * ($daysPerYear / $daysBetweenSettlementAndMaturity);
+ }
+ return Calculation_Functions::VALUE();
+ } // function YIELDDISC()
+
+
+ /**
+ * YIELDMAT
+ *
+ * Returns the annual yield of a security that pays interest at maturity.
+ *
+ * @param mixed settlement The security's settlement date.
+ * The security's settlement date is the date after the issue date when the security is traded to the buyer.
+ * @param mixed maturity The security's maturity date.
+ * The maturity date is the date when the security expires.
+ * @param mixed issue The security's issue date.
+ * @param int rate The security's interest rate at date of issue.
+ * @param int price The security's price per $100 face value.
+ * @param int basis The type of day count to use.
+ * 0 or omitted US (NASD) 30/360
+ * 1 Actual/actual
+ * 2 Actual/360
+ * 3 Actual/365
+ * 4 European 30/360
+ * @return float
+ */
+ public static function YIELDMAT($settlement, $maturity, $issue, $rate, $price, $basis=0) {
+ $settlement = Calculation_Functions::flattenSingleValue($settlement);
+ $maturity = Calculation_Functions::flattenSingleValue($maturity);
+ $issue = Calculation_Functions::flattenSingleValue($issue);
+ $rate = Calculation_Functions::flattenSingleValue($rate);
+ $price = Calculation_Functions::flattenSingleValue($price);
+ $basis = (int) Calculation_Functions::flattenSingleValue($basis);
+
+ // Validate
+ if (is_numeric($rate) && is_numeric($price)) {
+ if (($rate <= 0) || ($price <= 0)) {
+ return Calculation_Functions::NaN();
+ }
+ $daysPerYear = self::_daysPerYear(Calculation_DateTime::YEAR($settlement),$basis);
+ if (!is_numeric($daysPerYear)) {
+ return $daysPerYear;
+ }
+ $daysBetweenIssueAndSettlement = Calculation_DateTime::YEARFRAC($issue, $settlement, $basis);
+ if (!is_numeric($daysBetweenIssueAndSettlement)) {
+ // return date error
+ return $daysBetweenIssueAndSettlement;
+ }
+ $daysBetweenIssueAndSettlement *= $daysPerYear;
+ $daysBetweenIssueAndMaturity = Calculation_DateTime::YEARFRAC($issue, $maturity, $basis);
+ if (!is_numeric($daysBetweenIssueAndMaturity)) {
+ // return date error
+ return $daysBetweenIssueAndMaturity;
+ }
+ $daysBetweenIssueAndMaturity *= $daysPerYear;
+ $daysBetweenSettlementAndMaturity = Calculation_DateTime::YEARFRAC($settlement, $maturity, $basis);
+ if (!is_numeric($daysBetweenSettlementAndMaturity)) {
+ // return date error
+ return $daysBetweenSettlementAndMaturity;
+ }
+ $daysBetweenSettlementAndMaturity *= $daysPerYear;
+
+ return ((1 + (($daysBetweenIssueAndMaturity / $daysPerYear) * $rate) - (($price / 100) + (($daysBetweenIssueAndSettlement / $daysPerYear) * $rate))) /
+ (($price / 100) + (($daysBetweenIssueAndSettlement / $daysPerYear) * $rate))) *
+ ($daysPerYear / $daysBetweenSettlementAndMaturity);
+ }
+ return Calculation_Functions::VALUE();
+ } // function YIELDMAT()
}
diff --git a/Classes/PHPExcel/Calculation/FormulaParser.php b/Classes/PHPExcel/Calculation/FormulaParser.php
index 3acd9fe..28ae179 100644
--- a/Classes/PHPExcel/Calculation/FormulaParser.php
+++ b/Classes/PHPExcel/Calculation/FormulaParser.php
@@ -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,55 +60,55 @@ namespace PHPExcel;
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
*/
class Calculation_FormulaParser {
- /* Character constants */
- const QUOTE_DOUBLE = '"';
- const QUOTE_SINGLE = '\'';
- const BRACKET_CLOSE = ']';
- const BRACKET_OPEN = '[';
- const BRACE_OPEN = '{';
- const BRACE_CLOSE = '}';
- const PAREN_OPEN = '(';
- const PAREN_CLOSE = ')';
- const SEMICOLON = ';';
- const WHITESPACE = ' ';
- const COMMA = ',';
- const ERROR_START = '#';
+ /* Character constants */
+ const QUOTE_DOUBLE = '"';
+ const QUOTE_SINGLE = '\'';
+ const BRACKET_CLOSE = ']';
+ const BRACKET_OPEN = '[';
+ const BRACE_OPEN = '{';
+ const BRACE_CLOSE = '}';
+ const PAREN_OPEN = '(';
+ const PAREN_CLOSE = ')';
+ const SEMICOLON = ';';
+ const WHITESPACE = ' ';
+ const COMMA = ',';
+ const ERROR_START = '#';
- const OPERATORS_SN = "+-";
- const OPERATORS_INFIX = "+-*/^&=><";
- const OPERATORS_POSTFIX = "%";
+ const OPERATORS_SN = "+-";
+ const OPERATORS_INFIX = "+-*/^&=><";
+ const OPERATORS_POSTFIX = "%";
- /**
- * Formula
- *
- * @var string
- */
- private $_formula;
+ /**
+ * Formula
+ *
+ * @var string
+ */
+ private $_formula;
- /**
- * Tokens
- *
- * @var PHPExcel\Calculation_FormulaToken[]
- */
- private $_tokens = array();
+ /**
+ * Tokens
+ *
+ * @var PHPExcel\Calculation_FormulaToken[]
+ */
+ private $_tokens = array();
/**
* Create a new PHPExcel\Calculation_FormulaParser
*
- * @param string $pFormula Formula to parse
- * @throws PHPExcel\Calculation_Exception
+ * @param string $pFormula Formula to parse
+ * @throws PHPExcel\Calculation_Exception
*/
public function __construct($pFormula = '')
{
- // Check parameters
- if (is_null($pFormula)) {
- throw new Calculation_Exception("Invalid parameter passed: formula");
- }
+ // Check parameters
+ if (is_null($pFormula)) {
+ throw new Calculation_Exception("Invalid parameter passed: formula");
+ }
- // Initialise values
- $this->_formula = trim($pFormula);
- // Parse!
- $this->_parseToTokens();
+ // Initialise values
+ $this->_formula = trim($pFormula);
+ // Parse!
+ $this->_parseToTokens();
}
/**
@@ -117,22 +117,22 @@ class Calculation_FormulaParser {
* @return string
*/
public function getFormula() {
- return $this->_formula;
+ return $this->_formula;
}
/**
* Get Token
*
- * @param int $pId Token id
- * @return string
+ * @param int $pId Token id
+ * @return string
* @throws PHPExcel\Calculation_Exception
*/
public function getToken($pId = 0) {
- if (isset($this->_tokens[$pId])) {
- return $this->_tokens[$pId];
- } else {
- throw new Calculation_Exception("Token with id $pId does not exist.");
- }
+ if (isset($this->_tokens[$pId])) {
+ return $this->_tokens[$pId];
+ } else {
+ throw new Calculation_Exception("Token with id $pId does not exist.");
+ }
}
/**
@@ -141,7 +141,7 @@ class Calculation_FormulaParser {
* @return string
*/
public function getTokenCount() {
- return count($this->_tokens);
+ return count($this->_tokens);
}
/**
@@ -150,468 +150,468 @@ class Calculation_FormulaParser {
* @return PHPExcel\Calculation_FormulaToken[]
*/
public function getTokens() {
- return $this->_tokens;
+ return $this->_tokens;
}
/**
* Parse to tokens
*/
private function _parseToTokens() {
- // No attempt is made to verify formulas; assumes formulas are derived from Excel, where
- // they can only exist if valid; stack overflows/underflows sunk as nulls without exceptions.
+ // No attempt is made to verify formulas; assumes formulas are derived from Excel, where
+ // they can only exist if valid; stack overflows/underflows sunk as nulls without exceptions.
- // Check if the formula has a valid starting =
- $formulaLength = strlen($this->_formula);
- if ($formulaLength < 2 || $this->_formula{0} != '=') return;
+ // Check if the formula has a valid starting =
+ $formulaLength = strlen($this->_formula);
+ if ($formulaLength < 2 || $this->_formula{0} != '=') return;
- // Helper variables
- $tokens1 = $tokens2 = $stack = array();
- $inString = $inPath = $inRange = $inError = false;
- $token = $previousToken = $nextToken = null;
+ // Helper variables
+ $tokens1 = $tokens2 = $stack = array();
+ $inString = $inPath = $inRange = $inError = false;
+ $token = $previousToken = $nextToken = null;
- $index = 1;
- $value = '';
+ $index = 1;
+ $value = '';
- $ERRORS = array("#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A");
- $COMPARATORS_MULTI = array(">=", "<=", "<>");
+ $ERRORS = array("#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A");
+ $COMPARATORS_MULTI = array(">=", "<=", "<>");
- while ($index < $formulaLength) {
- // state-dependent character evaluation (order is important)
+ while ($index < $formulaLength) {
+ // state-dependent character evaluation (order is important)
- // double-quoted strings
- // embeds are doubled
- // end marks token
- if ($inString) {
- if ($this->_formula{$index} == Calculation_FormulaParser::QUOTE_DOUBLE) {
- if ((($index + 2) <= $formulaLength) && ($this->_formula{$index + 1} == Calculation_FormulaParser::QUOTE_DOUBLE)) {
- $value .= Calculation_FormulaParser::QUOTE_DOUBLE;
- ++$index;
- } else {
- $inString = false;
- $tokens1[] = new Calculation_FormulaToken($value, Calculation_FormulaToken::TOKEN_TYPE_OPERAND, Calculation_FormulaToken::TOKEN_SUBTYPE_TEXT);
- $value = "";
- }
- } else {
- $value .= $this->_formula{$index};
- }
- ++$index;
- continue;
- }
+ // double-quoted strings
+ // embeds are doubled
+ // end marks token
+ if ($inString) {
+ if ($this->_formula{$index} == Calculation_FormulaParser::QUOTE_DOUBLE) {
+ if ((($index + 2) <= $formulaLength) && ($this->_formula{$index + 1} == Calculation_FormulaParser::QUOTE_DOUBLE)) {
+ $value .= Calculation_FormulaParser::QUOTE_DOUBLE;
+ ++$index;
+ } else {
+ $inString = false;
+ $tokens1[] = new Calculation_FormulaToken($value, Calculation_FormulaToken::TOKEN_TYPE_OPERAND, Calculation_FormulaToken::TOKEN_SUBTYPE_TEXT);
+ $value = "";
+ }
+ } else {
+ $value .= $this->_formula{$index};
+ }
+ ++$index;
+ continue;
+ }
- // single-quoted strings (links)
- // embeds are double
- // end does not mark a token
- if ($inPath) {
- if ($this->_formula{$index} == Calculation_FormulaParser::QUOTE_SINGLE) {
- if ((($index + 2) <= $formulaLength) && ($this->_formula{$index + 1} == Calculation_FormulaParser::QUOTE_SINGLE)) {
- $value .= Calculation_FormulaParser::QUOTE_SINGLE;
- ++$index;
- } else {
- $inPath = false;
- }
- } else {
- $value .= $this->_formula{$index};
- }
- ++$index;
- continue;
- }
+ // single-quoted strings (links)
+ // embeds are double
+ // end does not mark a token
+ if ($inPath) {
+ if ($this->_formula{$index} == Calculation_FormulaParser::QUOTE_SINGLE) {
+ if ((($index + 2) <= $formulaLength) && ($this->_formula{$index + 1} == Calculation_FormulaParser::QUOTE_SINGLE)) {
+ $value .= Calculation_FormulaParser::QUOTE_SINGLE;
+ ++$index;
+ } else {
+ $inPath = false;
+ }
+ } else {
+ $value .= $this->_formula{$index};
+ }
+ ++$index;
+ continue;
+ }
- // bracked strings (R1C1 range index or linked workbook name)
- // no embeds (changed to "()" by Excel)
- // end does not mark a token
- if ($inRange) {
- if ($this->_formula{$index} == Calculation_FormulaParser::BRACKET_CLOSE) {
- $inRange = false;
- }
- $value .= $this->_formula{$index};
- ++$index;
- continue;
- }
+ // bracked strings (R1C1 range index or linked workbook name)
+ // no embeds (changed to "()" by Excel)
+ // end does not mark a token
+ if ($inRange) {
+ if ($this->_formula{$index} == Calculation_FormulaParser::BRACKET_CLOSE) {
+ $inRange = false;
+ }
+ $value .= $this->_formula{$index};
+ ++$index;
+ continue;
+ }
- // error values
- // end marks a token, determined from absolute list of values
- if ($inError) {
- $value .= $this->_formula{$index};
- ++$index;
- if (in_array($value, $ERRORS)) {
- $inError = false;
- $tokens1[] = new Calculation_FormulaToken($value, Calculation_FormulaToken::TOKEN_TYPE_OPERAND, Calculation_FormulaToken::TOKEN_SUBTYPE_ERROR);
- $value = "";
- }
- continue;
- }
+ // error values
+ // end marks a token, determined from absolute list of values
+ if ($inError) {
+ $value .= $this->_formula{$index};
+ ++$index;
+ if (in_array($value, $ERRORS)) {
+ $inError = false;
+ $tokens1[] = new Calculation_FormulaToken($value, Calculation_FormulaToken::TOKEN_TYPE_OPERAND, Calculation_FormulaToken::TOKEN_SUBTYPE_ERROR);
+ $value = "";
+ }
+ continue;
+ }
- // scientific notation check
- if (strpos(Calculation_FormulaParser::OPERATORS_SN, $this->_formula{$index}) !== false) {
- if (strlen($value) > 1) {
- if (preg_match("/^[1-9]{1}(\.[0-9]+)?E{1}$/", $this->_formula{$index}) != 0) {
- $value .= $this->_formula{$index};
- ++$index;
- continue;
- }
- }
- }
+ // scientific notation check
+ if (strpos(Calculation_FormulaParser::OPERATORS_SN, $this->_formula{$index}) !== false) {
+ if (strlen($value) > 1) {
+ if (preg_match("/^[1-9]{1}(\.[0-9]+)?E{1}$/", $this->_formula{$index}) != 0) {
+ $value .= $this->_formula{$index};
+ ++$index;
+ continue;
+ }
+ }
+ }
- // independent character evaluation (order not important)
+ // independent character evaluation (order not important)
- // establish state-dependent character evaluations
- if ($this->_formula{$index} == Calculation_FormulaParser::QUOTE_DOUBLE) {
- if (strlen($value > 0)) { // unexpected
- $tokens1[] = new Calculation_FormulaToken($value, Calculation_FormulaToken::TOKEN_TYPE_UNKNOWN);
- $value = "";
- }
- $inString = true;
- ++$index;
- continue;
- }
+ // establish state-dependent character evaluations
+ if ($this->_formula{$index} == Calculation_FormulaParser::QUOTE_DOUBLE) {
+ if (strlen($value > 0)) { // unexpected
+ $tokens1[] = new Calculation_FormulaToken($value, Calculation_FormulaToken::TOKEN_TYPE_UNKNOWN);
+ $value = "";
+ }
+ $inString = true;
+ ++$index;
+ continue;
+ }
- if ($this->_formula{$index} == Calculation_FormulaParser::QUOTE_SINGLE) {
- if (strlen($value) > 0) { // unexpected
- $tokens1[] = new Calculation_FormulaToken($value, Calculation_FormulaToken::TOKEN_TYPE_UNKNOWN);
- $value = "";
- }
- $inPath = true;
- ++$index;
- continue;
- }
+ if ($this->_formula{$index} == Calculation_FormulaParser::QUOTE_SINGLE) {
+ if (strlen($value) > 0) { // unexpected
+ $tokens1[] = new Calculation_FormulaToken($value, Calculation_FormulaToken::TOKEN_TYPE_UNKNOWN);
+ $value = "";
+ }
+ $inPath = true;
+ ++$index;
+ continue;
+ }
- if ($this->_formula{$index} == Calculation_FormulaParser::BRACKET_OPEN) {
- $inRange = true;
- $value .= Calculation_FormulaParser::BRACKET_OPEN;
- ++$index;
- continue;
- }
+ if ($this->_formula{$index} == Calculation_FormulaParser::BRACKET_OPEN) {
+ $inRange = true;
+ $value .= Calculation_FormulaParser::BRACKET_OPEN;
+ ++$index;
+ continue;
+ }
- if ($this->_formula{$index} == Calculation_FormulaParser::ERROR_START) {
- if (strlen($value) > 0) { // unexpected
- $tokens1[] = new Calculation_FormulaToken($value, Calculation_FormulaToken::TOKEN_TYPE_UNKNOWN);
- $value = "";
- }
- $inError = true;
- $value .= Calculation_FormulaParser::ERROR_START;
- ++$index;
- continue;
- }
+ if ($this->_formula{$index} == Calculation_FormulaParser::ERROR_START) {
+ if (strlen($value) > 0) { // unexpected
+ $tokens1[] = new Calculation_FormulaToken($value, Calculation_FormulaToken::TOKEN_TYPE_UNKNOWN);
+ $value = "";
+ }
+ $inError = true;
+ $value .= Calculation_FormulaParser::ERROR_START;
+ ++$index;
+ continue;
+ }
- // mark start and end of arrays and array rows
- if ($this->_formula{$index} == Calculation_FormulaParser::BRACE_OPEN) {
- if (strlen($value) > 0) { // unexpected
- $tokens1[] = new Calculation_FormulaToken($value, Calculation_FormulaToken::TOKEN_TYPE_UNKNOWN);
- $value = "";
- }
+ // mark start and end of arrays and array rows
+ if ($this->_formula{$index} == Calculation_FormulaParser::BRACE_OPEN) {
+ if (strlen($value) > 0) { // unexpected
+ $tokens1[] = new Calculation_FormulaToken($value, Calculation_FormulaToken::TOKEN_TYPE_UNKNOWN);
+ $value = "";
+ }
- $tmp = new Calculation_FormulaToken("ARRAY", Calculation_FormulaToken::TOKEN_TYPE_FUNCTION, Calculation_FormulaToken::TOKEN_SUBTYPE_START);
- $tokens1[] = $tmp;
- $stack[] = clone $tmp;
+ $tmp = new Calculation_FormulaToken("ARRAY", Calculation_FormulaToken::TOKEN_TYPE_FUNCTION, Calculation_FormulaToken::TOKEN_SUBTYPE_START);
+ $tokens1[] = $tmp;
+ $stack[] = clone $tmp;
- $tmp = new Calculation_FormulaToken("ARRAYROW", Calculation_FormulaToken::TOKEN_TYPE_FUNCTION, Calculation_FormulaToken::TOKEN_SUBTYPE_START);
- $tokens1[] = $tmp;
- $stack[] = clone $tmp;
+ $tmp = new Calculation_FormulaToken("ARRAYROW", Calculation_FormulaToken::TOKEN_TYPE_FUNCTION, Calculation_FormulaToken::TOKEN_SUBTYPE_START);
+ $tokens1[] = $tmp;
+ $stack[] = clone $tmp;
- ++$index;
- continue;
- }
+ ++$index;
+ continue;
+ }
- if ($this->_formula{$index} == Calculation_FormulaParser::SEMICOLON) {
- if (strlen($value) > 0) {
- $tokens1[] = new Calculation_FormulaToken($value, Calculation_FormulaToken::TOKEN_TYPE_OPERAND);
- $value = "";
- }
+ if ($this->_formula{$index} == Calculation_FormulaParser::SEMICOLON) {
+ if (strlen($value) > 0) {
+ $tokens1[] = new Calculation_FormulaToken($value, Calculation_FormulaToken::TOKEN_TYPE_OPERAND);
+ $value = "";
+ }
- $tmp = array_pop($stack);
- $tmp->setValue("");
- $tmp->setTokenSubType(Calculation_FormulaToken::TOKEN_SUBTYPE_STOP);
- $tokens1[] = $tmp;
+ $tmp = array_pop($stack);
+ $tmp->setValue("");
+ $tmp->setTokenSubType(Calculation_FormulaToken::TOKEN_SUBTYPE_STOP);
+ $tokens1[] = $tmp;
- $tmp = new Calculation_FormulaToken(",", Calculation_FormulaToken::TOKEN_TYPE_ARGUMENT);
- $tokens1[] = $tmp;
+ $tmp = new Calculation_FormulaToken(",", Calculation_FormulaToken::TOKEN_TYPE_ARGUMENT);
+ $tokens1[] = $tmp;
- $tmp = new Calculation_FormulaToken("ARRAYROW", Calculation_FormulaToken::TOKEN_TYPE_FUNCTION, Calculation_FormulaToken::TOKEN_SUBTYPE_START);
- $tokens1[] = $tmp;
- $stack[] = clone $tmp;
+ $tmp = new Calculation_FormulaToken("ARRAYROW", Calculation_FormulaToken::TOKEN_TYPE_FUNCTION, Calculation_FormulaToken::TOKEN_SUBTYPE_START);
+ $tokens1[] = $tmp;
+ $stack[] = clone $tmp;
- ++$index;
- continue;
- }
+ ++$index;
+ continue;
+ }
- if ($this->_formula{$index} == Calculation_FormulaParser::BRACE_CLOSE) {
- if (strlen($value) > 0) {
- $tokens1[] = new Calculation_FormulaToken($value, Calculation_FormulaToken::TOKEN_TYPE_OPERAND);
- $value = "";
- }
+ if ($this->_formula{$index} == Calculation_FormulaParser::BRACE_CLOSE) {
+ if (strlen($value) > 0) {
+ $tokens1[] = new Calculation_FormulaToken($value, Calculation_FormulaToken::TOKEN_TYPE_OPERAND);
+ $value = "";
+ }
- $tmp = array_pop($stack);
- $tmp->setValue("");
- $tmp->setTokenSubType(Calculation_FormulaToken::TOKEN_SUBTYPE_STOP);
- $tokens1[] = $tmp;
+ $tmp = array_pop($stack);
+ $tmp->setValue("");
+ $tmp->setTokenSubType(Calculation_FormulaToken::TOKEN_SUBTYPE_STOP);
+ $tokens1[] = $tmp;
- $tmp = array_pop($stack);
- $tmp->setValue("");
- $tmp->setTokenSubType(Calculation_FormulaToken::TOKEN_SUBTYPE_STOP);
- $tokens1[] = $tmp;
+ $tmp = array_pop($stack);
+ $tmp->setValue("");
+ $tmp->setTokenSubType(Calculation_FormulaToken::TOKEN_SUBTYPE_STOP);
+ $tokens1[] = $tmp;
- ++$index;
- continue;
- }
+ ++$index;
+ continue;
+ }
- // trim white-space
- if ($this->_formula{$index} == Calculation_FormulaParser::WHITESPACE) {
- if (strlen($value) > 0) {
- $tokens1[] = new Calculation_FormulaToken($value, Calculation_FormulaToken::TOKEN_TYPE_OPERAND);
- $value = "";
- }
- $tokens1[] = new Calculation_FormulaToken("", Calculation_FormulaToken::TOKEN_TYPE_WHITESPACE);
- ++$index;
- while (($this->_formula{$index} == Calculation_FormulaParser::WHITESPACE) && ($index < $formulaLength)) {
- ++$index;
- }
- continue;
- }
+ // trim white-space
+ if ($this->_formula{$index} == Calculation_FormulaParser::WHITESPACE) {
+ if (strlen($value) > 0) {
+ $tokens1[] = new Calculation_FormulaToken($value, Calculation_FormulaToken::TOKEN_TYPE_OPERAND);
+ $value = "";
+ }
+ $tokens1[] = new Calculation_FormulaToken("", Calculation_FormulaToken::TOKEN_TYPE_WHITESPACE);
+ ++$index;
+ while (($this->_formula{$index} == Calculation_FormulaParser::WHITESPACE) && ($index < $formulaLength)) {
+ ++$index;
+ }
+ continue;
+ }
- // multi-character comparators
- if (($index + 2) <= $formulaLength) {
- if (in_array(substr($this->_formula, $index, 2), $COMPARATORS_MULTI)) {
- if (strlen($value) > 0) {
- $tokens1[] = new Calculation_FormulaToken($value, Calculation_FormulaToken::TOKEN_TYPE_OPERAND);
- $value = "";
- }
- $tokens1[] = new Calculation_FormulaToken(substr($this->_formula, $index, 2), Calculation_FormulaToken::TOKEN_TYPE_OPERATORINFIX, Calculation_FormulaToken::TOKEN_SUBTYPE_LOGICAL);
- $index += 2;
- continue;
- }
- }
+ // multi-character comparators
+ if (($index + 2) <= $formulaLength) {
+ if (in_array(substr($this->_formula, $index, 2), $COMPARATORS_MULTI)) {
+ if (strlen($value) > 0) {
+ $tokens1[] = new Calculation_FormulaToken($value, Calculation_FormulaToken::TOKEN_TYPE_OPERAND);
+ $value = "";
+ }
+ $tokens1[] = new Calculation_FormulaToken(substr($this->_formula, $index, 2), Calculation_FormulaToken::TOKEN_TYPE_OPERATORINFIX, Calculation_FormulaToken::TOKEN_SUBTYPE_LOGICAL);
+ $index += 2;
+ continue;
+ }
+ }
- // standard infix operators
- if (strpos(Calculation_FormulaParser::OPERATORS_INFIX, $this->_formula{$index}) !== false) {
- if (strlen($value) > 0) {
- $tokens1[] =new Calculation_FormulaToken($value, Calculation_FormulaToken::TOKEN_TYPE_OPERAND);
- $value = "";
- }
- $tokens1[] = new Calculation_FormulaToken($this->_formula{$index}, Calculation_FormulaToken::TOKEN_TYPE_OPERATORINFIX);
- ++$index;
- continue;
- }
+ // standard infix operators
+ if (strpos(Calculation_FormulaParser::OPERATORS_INFIX, $this->_formula{$index}) !== false) {
+ if (strlen($value) > 0) {
+ $tokens1[] =new Calculation_FormulaToken($value, Calculation_FormulaToken::TOKEN_TYPE_OPERAND);
+ $value = "";
+ }
+ $tokens1[] = new Calculation_FormulaToken($this->_formula{$index}, Calculation_FormulaToken::TOKEN_TYPE_OPERATORINFIX);
+ ++$index;
+ continue;
+ }
- // standard postfix operators (only one)
- if (strpos(Calculation_FormulaParser::OPERATORS_POSTFIX, $this->_formula{$index}) !== false) {
- if (strlen($value) > 0) {
- $tokens1[] = new Calculation_FormulaToken($value, Calculation_FormulaToken::TOKEN_TYPE_OPERAND);
- $value = "";
- }
- $tokens1[] = new Calculation_FormulaToken($this->_formula{$index}, Calculation_FormulaToken::TOKEN_TYPE_OPERATORPOSTFIX);
- ++$index;
- continue;
- }
+ // standard postfix operators (only one)
+ if (strpos(Calculation_FormulaParser::OPERATORS_POSTFIX, $this->_formula{$index}) !== false) {
+ if (strlen($value) > 0) {
+ $tokens1[] = new Calculation_FormulaToken($value, Calculation_FormulaToken::TOKEN_TYPE_OPERAND);
+ $value = "";
+ }
+ $tokens1[] = new Calculation_FormulaToken($this->_formula{$index}, Calculation_FormulaToken::TOKEN_TYPE_OPERATORPOSTFIX);
+ ++$index;
+ continue;
+ }
- // start subexpression or function
- if ($this->_formula{$index} == Calculation_FormulaParser::PAREN_OPEN) {
- if (strlen($value) > 0) {
- $tmp = new Calculation_FormulaToken($value, Calculation_FormulaToken::TOKEN_TYPE_FUNCTION, Calculation_FormulaToken::TOKEN_SUBTYPE_START);
- $tokens1[] = $tmp;
- $stack[] = clone $tmp;
- $value = "";
- } else {
- $tmp = new Calculation_FormulaToken("", Calculation_FormulaToken::TOKEN_TYPE_SUBEXPRESSION, Calculation_FormulaToken::TOKEN_SUBTYPE_START);
- $tokens1[] = $tmp;
- $stack[] = clone $tmp;
- }
- ++$index;
- continue;
- }
+ // start subexpression or function
+ if ($this->_formula{$index} == Calculation_FormulaParser::PAREN_OPEN) {
+ if (strlen($value) > 0) {
+ $tmp = new Calculation_FormulaToken($value, Calculation_FormulaToken::TOKEN_TYPE_FUNCTION, Calculation_FormulaToken::TOKEN_SUBTYPE_START);
+ $tokens1[] = $tmp;
+ $stack[] = clone $tmp;
+ $value = "";
+ } else {
+ $tmp = new Calculation_FormulaToken("", Calculation_FormulaToken::TOKEN_TYPE_SUBEXPRESSION, Calculation_FormulaToken::TOKEN_SUBTYPE_START);
+ $tokens1[] = $tmp;
+ $stack[] = clone $tmp;
+ }
+ ++$index;
+ continue;
+ }
- // function, subexpression, or array parameters, or operand unions
- if ($this->_formula{$index} == Calculation_FormulaParser::COMMA) {
- if (strlen($value) > 0) {
- $tokens1[] = new Calculation_FormulaToken($value, Calculation_FormulaToken::TOKEN_TYPE_OPERAND);
- $value = "";
- }
+ // function, subexpression, or array parameters, or operand unions
+ if ($this->_formula{$index} == Calculation_FormulaParser::COMMA) {
+ if (strlen($value) > 0) {
+ $tokens1[] = new Calculation_FormulaToken($value, Calculation_FormulaToken::TOKEN_TYPE_OPERAND);
+ $value = "";
+ }
- $tmp = array_pop($stack);
- $tmp->setValue("");
- $tmp->setTokenSubType(Calculation_FormulaToken::TOKEN_SUBTYPE_STOP);
- $stack[] = $tmp;
+ $tmp = array_pop($stack);
+ $tmp->setValue("");
+ $tmp->setTokenSubType(Calculation_FormulaToken::TOKEN_SUBTYPE_STOP);
+ $stack[] = $tmp;
- if ($tmp->getTokenType() == Calculation_FormulaToken::TOKEN_TYPE_FUNCTION) {
- $tokens1[] = new Calculation_FormulaToken(",", Calculation_FormulaToken::TOKEN_TYPE_OPERATORINFIX, Calculation_FormulaToken::TOKEN_SUBTYPE_UNION);
- } else {
- $tokens1[] = new Calculation_FormulaToken(",", Calculation_FormulaToken::TOKEN_TYPE_ARGUMENT);
- }
- ++$index;
- continue;
- }
+ if ($tmp->getTokenType() == Calculation_FormulaToken::TOKEN_TYPE_FUNCTION) {
+ $tokens1[] = new Calculation_FormulaToken(",", Calculation_FormulaToken::TOKEN_TYPE_OPERATORINFIX, Calculation_FormulaToken::TOKEN_SUBTYPE_UNION);
+ } else {
+ $tokens1[] = new Calculation_FormulaToken(",", Calculation_FormulaToken::TOKEN_TYPE_ARGUMENT);
+ }
+ ++$index;
+ continue;
+ }
- // stop subexpression
- if ($this->_formula{$index} == Calculation_FormulaParser::PAREN_CLOSE) {
- if (strlen($value) > 0) {
- $tokens1[] = new Calculation_FormulaToken($value, Calculation_FormulaToken::TOKEN_TYPE_OPERAND);
- $value = "";
- }
+ // stop subexpression
+ if ($this->_formula{$index} == Calculation_FormulaParser::PAREN_CLOSE) {
+ if (strlen($value) > 0) {
+ $tokens1[] = new Calculation_FormulaToken($value, Calculation_FormulaToken::TOKEN_TYPE_OPERAND);
+ $value = "";
+ }
- $tmp = array_pop($stack);
- $tmp->setValue("");
- $tmp->setTokenSubType(Calculation_FormulaToken::TOKEN_SUBTYPE_STOP);
- $tokens1[] = $tmp;
+ $tmp = array_pop($stack);
+ $tmp->setValue("");
+ $tmp->setTokenSubType(Calculation_FormulaToken::TOKEN_SUBTYPE_STOP);
+ $tokens1[] = $tmp;
- ++$index;
- continue;
- }
+ ++$index;
+ continue;
+ }
- // token accumulation
- $value .= $this->_formula{$index};
- ++$index;
- }
+ // token accumulation
+ $value .= $this->_formula{$index};
+ ++$index;
+ }
- // dump remaining accumulation
- if (strlen($value) > 0) {
- $tokens1[] = new Calculation_FormulaToken($value, Calculation_FormulaToken::TOKEN_TYPE_OPERAND);
- }
+ // dump remaining accumulation
+ if (strlen($value) > 0) {
+ $tokens1[] = new Calculation_FormulaToken($value, Calculation_FormulaToken::TOKEN_TYPE_OPERAND);
+ }
- // move tokenList to new set, excluding unnecessary white-space tokens and converting necessary ones to intersections
- $tokenCount = count($tokens1);
- for ($i = 0; $i < $tokenCount; ++$i) {
- $token = $tokens1[$i];
- if (isset($tokens1[$i - 1])) {
- $previousToken = $tokens1[$i - 1];
- } else {
- $previousToken = null;
- }
- if (isset($tokens1[$i + 1])) {
- $nextToken = $tokens1[$i + 1];
- } else {
- $nextToken = null;
- }
+ // move tokenList to new set, excluding unnecessary white-space tokens and converting necessary ones to intersections
+ $tokenCount = count($tokens1);
+ for ($i = 0; $i < $tokenCount; ++$i) {
+ $token = $tokens1[$i];
+ if (isset($tokens1[$i - 1])) {
+ $previousToken = $tokens1[$i - 1];
+ } else {
+ $previousToken = null;
+ }
+ if (isset($tokens1[$i + 1])) {
+ $nextToken = $tokens1[$i + 1];
+ } else {
+ $nextToken = null;
+ }
- if (is_null($token)) {
- continue;
- }
+ if (is_null($token)) {
+ continue;
+ }
- if ($token->getTokenType() != Calculation_FormulaToken::TOKEN_TYPE_WHITESPACE) {
- $tokens2[] = $token;
- continue;
- }
+ if ($token->getTokenType() != Calculation_FormulaToken::TOKEN_TYPE_WHITESPACE) {
+ $tokens2[] = $token;
+ continue;
+ }
- if (is_null($previousToken)) {
- continue;
- }
+ if (is_null($previousToken)) {
+ continue;
+ }
- if (! (
- (($previousToken->getTokenType() == Calculation_FormulaToken::TOKEN_TYPE_FUNCTION) && ($previousToken->getTokenSubType() == Calculation_FormulaToken::TOKEN_SUBTYPE_STOP)) ||
- (($previousToken->getTokenType() == Calculation_FormulaToken::TOKEN_TYPE_SUBEXPRESSION) && ($previousToken->getTokenSubType() == Calculation_FormulaToken::TOKEN_SUBTYPE_STOP)) ||
- ($previousToken->getTokenType() == Calculation_FormulaToken::TOKEN_TYPE_OPERAND)
- ) ) {
- continue;
- }
+ if (! (
+ (($previousToken->getTokenType() == Calculation_FormulaToken::TOKEN_TYPE_FUNCTION) && ($previousToken->getTokenSubType() == Calculation_FormulaToken::TOKEN_SUBTYPE_STOP)) ||
+ (($previousToken->getTokenType() == Calculation_FormulaToken::TOKEN_TYPE_SUBEXPRESSION) && ($previousToken->getTokenSubType() == Calculation_FormulaToken::TOKEN_SUBTYPE_STOP)) ||
+ ($previousToken->getTokenType() == Calculation_FormulaToken::TOKEN_TYPE_OPERAND)
+ ) ) {
+ continue;
+ }
- if (is_null($nextToken)) {
- continue;
- }
+ if (is_null($nextToken)) {
+ continue;
+ }
- if (! (
- (($nextToken->getTokenType() == Calculation_FormulaToken::TOKEN_TYPE_FUNCTION) && ($nextToken->getTokenSubType() == Calculation_FormulaToken::TOKEN_SUBTYPE_START)) ||
- (($nextToken->getTokenType() == Calculation_FormulaToken::TOKEN_TYPE_SUBEXPRESSION) && ($nextToken->getTokenSubType() == Calculation_FormulaToken::TOKEN_SUBTYPE_START)) ||
- ($nextToken->getTokenType() == Calculation_FormulaToken::TOKEN_TYPE_OPERAND)
- ) ) {
- continue;
- }
+ if (! (
+ (($nextToken->getTokenType() == Calculation_FormulaToken::TOKEN_TYPE_FUNCTION) && ($nextToken->getTokenSubType() == Calculation_FormulaToken::TOKEN_SUBTYPE_START)) ||
+ (($nextToken->getTokenType() == Calculation_FormulaToken::TOKEN_TYPE_SUBEXPRESSION) && ($nextToken->getTokenSubType() == Calculation_FormulaToken::TOKEN_SUBTYPE_START)) ||
+ ($nextToken->getTokenType() == Calculation_FormulaToken::TOKEN_TYPE_OPERAND)
+ ) ) {
+ continue;
+ }
- $tokens2[] = new Calculation_FormulaToken($value, Calculation_FormulaToken::TOKEN_TYPE_OPERATORINFIX, Calculation_FormulaToken::TOKEN_SUBTYPE_INTERSECTION);
- }
+ $tokens2[] = new Calculation_FormulaToken($value, Calculation_FormulaToken::TOKEN_TYPE_OPERATORINFIX, Calculation_FormulaToken::TOKEN_SUBTYPE_INTERSECTION);
+ }
- // move tokens to final list, switching infix "-" operators to prefix when appropriate, switching infix "+" operators
- // to noop when appropriate, identifying operand and infix-operator subtypes, and pulling "@" from function names
- $this->_tokens = array();
+ // move tokens to final list, switching infix "-" operators to prefix when appropriate, switching infix "+" operators
+ // to noop when appropriate, identifying operand and infix-operator subtypes, and pulling "@" from function names
+ $this->_tokens = array();
- $tokenCount = count($tokens2);
- for ($i = 0; $i < $tokenCount; ++$i) {
- $token = $tokens2[$i];
- if (isset($tokens2[$i - 1])) {
- $previousToken = $tokens2[$i - 1];
- } else {
- $previousToken = null;
- }
- if (isset($tokens2[$i + 1])) {
- $nextToken = $tokens2[$i + 1];
- } else {
- $nextToken = null;
- }
+ $tokenCount = count($tokens2);
+ for ($i = 0; $i < $tokenCount; ++$i) {
+ $token = $tokens2[$i];
+ if (isset($tokens2[$i - 1])) {
+ $previousToken = $tokens2[$i - 1];
+ } else {
+ $previousToken = null;
+ }
+ if (isset($tokens2[$i + 1])) {
+ $nextToken = $tokens2[$i + 1];
+ } else {
+ $nextToken = null;
+ }
- if (is_null($token)) {
- continue;
- }
+ if (is_null($token)) {
+ continue;
+ }
- if ($token->getTokenType() == Calculation_FormulaToken::TOKEN_TYPE_OPERATORINFIX && $token->getValue() == "-") {
- if ($i == 0) {
- $token->setTokenType(Calculation_FormulaToken::TOKEN_TYPE_OPERATORPREFIX);
- } else if (
- (($previousToken->getTokenType() == Calculation_FormulaToken::TOKEN_TYPE_FUNCTION) && ($previousToken->getTokenSubType() == Calculation_FormulaToken::TOKEN_SUBTYPE_STOP)) ||
- (($previousToken->getTokenType() == Calculation_FormulaToken::TOKEN_TYPE_SUBEXPRESSION) && ($previousToken->getTokenSubType() == Calculation_FormulaToken::TOKEN_SUBTYPE_STOP)) ||
- ($previousToken->getTokenType() == Calculation_FormulaToken::TOKEN_TYPE_OPERATORPOSTFIX) ||
- ($previousToken->getTokenType() == Calculation_FormulaToken::TOKEN_TYPE_OPERAND)
- ) {
- $token->setTokenSubType(Calculation_FormulaToken::TOKEN_SUBTYPE_MATH);
- } else {
- $token->setTokenType(Calculation_FormulaToken::TOKEN_TYPE_OPERATORPREFIX);
- }
+ if ($token->getTokenType() == Calculation_FormulaToken::TOKEN_TYPE_OPERATORINFIX && $token->getValue() == "-") {
+ if ($i == 0) {
+ $token->setTokenType(Calculation_FormulaToken::TOKEN_TYPE_OPERATORPREFIX);
+ } else if (
+ (($previousToken->getTokenType() == Calculation_FormulaToken::TOKEN_TYPE_FUNCTION) && ($previousToken->getTokenSubType() == Calculation_FormulaToken::TOKEN_SUBTYPE_STOP)) ||
+ (($previousToken->getTokenType() == Calculation_FormulaToken::TOKEN_TYPE_SUBEXPRESSION) && ($previousToken->getTokenSubType() == Calculation_FormulaToken::TOKEN_SUBTYPE_STOP)) ||
+ ($previousToken->getTokenType() == Calculation_FormulaToken::TOKEN_TYPE_OPERATORPOSTFIX) ||
+ ($previousToken->getTokenType() == Calculation_FormulaToken::TOKEN_TYPE_OPERAND)
+ ) {
+ $token->setTokenSubType(Calculation_FormulaToken::TOKEN_SUBTYPE_MATH);
+ } else {
+ $token->setTokenType(Calculation_FormulaToken::TOKEN_TYPE_OPERATORPREFIX);
+ }
- $this->_tokens[] = $token;
- continue;
- }
+ $this->_tokens[] = $token;
+ continue;
+ }
- if ($token->getTokenType() == Calculation_FormulaToken::TOKEN_TYPE_OPERATORINFIX && $token->getValue() == "+") {
- if ($i == 0) {
- continue;
- } else if (
- (($previousToken->getTokenType() == Calculation_FormulaToken::TOKEN_TYPE_FUNCTION) && ($previousToken->getTokenSubType() == Calculation_FormulaToken::TOKEN_SUBTYPE_STOP)) ||
- (($previousToken->getTokenType() == Calculation_FormulaToken::TOKEN_TYPE_SUBEXPRESSION) && ($previousToken->getTokenSubType() == Calculation_FormulaToken::TOKEN_SUBTYPE_STOP)) ||
- ($previousToken->getTokenType() == Calculation_FormulaToken::TOKEN_TYPE_OPERATORPOSTFIX) ||
- ($previousToken->getTokenType() == Calculation_FormulaToken::TOKEN_TYPE_OPERAND)
- ) {
- $token->setTokenSubType(Calculation_FormulaToken::TOKEN_SUBTYPE_MATH);
- } else {
- continue;
- }
+ if ($token->getTokenType() == Calculation_FormulaToken::TOKEN_TYPE_OPERATORINFIX && $token->getValue() == "+") {
+ if ($i == 0) {
+ continue;
+ } else if (
+ (($previousToken->getTokenType() == Calculation_FormulaToken::TOKEN_TYPE_FUNCTION) && ($previousToken->getTokenSubType() == Calculation_FormulaToken::TOKEN_SUBTYPE_STOP)) ||
+ (($previousToken->getTokenType() == Calculation_FormulaToken::TOKEN_TYPE_SUBEXPRESSION) && ($previousToken->getTokenSubType() == Calculation_FormulaToken::TOKEN_SUBTYPE_STOP)) ||
+ ($previousToken->getTokenType() == Calculation_FormulaToken::TOKEN_TYPE_OPERATORPOSTFIX) ||
+ ($previousToken->getTokenType() == Calculation_FormulaToken::TOKEN_TYPE_OPERAND)
+ ) {
+ $token->setTokenSubType(Calculation_FormulaToken::TOKEN_SUBTYPE_MATH);
+ } else {
+ continue;
+ }
- $this->_tokens[] = $token;
- continue;
- }
+ $this->_tokens[] = $token;
+ continue;
+ }
- if ($token->getTokenType() == Calculation_FormulaToken::TOKEN_TYPE_OPERATORINFIX && $token->getTokenSubType() == Calculation_FormulaToken::TOKEN_SUBTYPE_NOTHING) {
- if (strpos("<>=", substr($token->getValue(), 0, 1)) !== false) {
- $token->setTokenSubType(Calculation_FormulaToken::TOKEN_SUBTYPE_LOGICAL);
- } else if ($token->getValue() == "&") {
- $token->setTokenSubType(Calculation_FormulaToken::TOKEN_SUBTYPE_CONCATENATION);
- } else {
- $token->setTokenSubType(Calculation_FormulaToken::TOKEN_SUBTYPE_MATH);
- }
+ if ($token->getTokenType() == Calculation_FormulaToken::TOKEN_TYPE_OPERATORINFIX && $token->getTokenSubType() == Calculation_FormulaToken::TOKEN_SUBTYPE_NOTHING) {
+ if (strpos("<>=", substr($token->getValue(), 0, 1)) !== false) {
+ $token->setTokenSubType(Calculation_FormulaToken::TOKEN_SUBTYPE_LOGICAL);
+ } else if ($token->getValue() == "&") {
+ $token->setTokenSubType(Calculation_FormulaToken::TOKEN_SUBTYPE_CONCATENATION);
+ } else {
+ $token->setTokenSubType(Calculation_FormulaToken::TOKEN_SUBTYPE_MATH);
+ }
- $this->_tokens[] = $token;
- continue;
- }
+ $this->_tokens[] = $token;
+ continue;
+ }
- if ($token->getTokenType() == Calculation_FormulaToken::TOKEN_TYPE_OPERAND && $token->getTokenSubType() == Calculation_FormulaToken::TOKEN_SUBTYPE_NOTHING) {
- if (!is_numeric($token->getValue())) {
- if (strtoupper($token->getValue()) == "TRUE" || strtoupper($token->getValue() == "FALSE")) {
- $token->setTokenSubType(Calculation_FormulaToken::TOKEN_SUBTYPE_LOGICAL);
- } else {
- $token->setTokenSubType(Calculation_FormulaToken::TOKEN_SUBTYPE_RANGE);
- }
- } else {
- $token->setTokenSubType(Calculation_FormulaToken::TOKEN_SUBTYPE_NUMBER);
- }
+ if ($token->getTokenType() == Calculation_FormulaToken::TOKEN_TYPE_OPERAND && $token->getTokenSubType() == Calculation_FormulaToken::TOKEN_SUBTYPE_NOTHING) {
+ if (!is_numeric($token->getValue())) {
+ if (strtoupper($token->getValue()) == "TRUE" || strtoupper($token->getValue() == "FALSE")) {
+ $token->setTokenSubType(Calculation_FormulaToken::TOKEN_SUBTYPE_LOGICAL);
+ } else {
+ $token->setTokenSubType(Calculation_FormulaToken::TOKEN_SUBTYPE_RANGE);
+ }
+ } else {
+ $token->setTokenSubType(Calculation_FormulaToken::TOKEN_SUBTYPE_NUMBER);
+ }
- $this->_tokens[] = $token;
- continue;
- }
+ $this->_tokens[] = $token;
+ continue;
+ }
- if ($token->getTokenType() == Calculation_FormulaToken::TOKEN_TYPE_FUNCTION) {
- if (strlen($token->getValue() > 0)) {
- if (substr($token->getValue(), 0, 1) == "@") {
- $token->setValue(substr($token->getValue(), 1));
- }
- }
- }
+ if ($token->getTokenType() == Calculation_FormulaToken::TOKEN_TYPE_FUNCTION) {
+ if (strlen($token->getValue() > 0)) {
+ if (substr($token->getValue(), 0, 1) == "@") {
+ $token->setValue(substr($token->getValue(), 1));
+ }
+ }
+ }
- $this->_tokens[] = $token;
- }
+ $this->_tokens[] = $token;
+ }
}
}
diff --git a/Classes/PHPExcel/Calculation/FormulaToken.php b/Classes/PHPExcel/Calculation/FormulaToken.php
index eba3061..25ee089 100644
--- a/Classes/PHPExcel/Calculation/FormulaToken.php
+++ b/Classes/PHPExcel/Calculation/FormulaToken.php
@@ -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;
}
}
diff --git a/Classes/PHPExcel/Calculation/Function.php b/Classes/PHPExcel/Calculation/Function.php
index 22711b8..a0763cb 100644
--- a/Classes/PHPExcel/Calculation/Function.php
+++ b/Classes/PHPExcel/Calculation/Function.php
@@ -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;
}
}
diff --git a/Classes/PHPExcel/Calculation/Functions.php b/Classes/PHPExcel/Calculation/Functions.php
index 036b9e1..5aface6 100644
--- a/Classes/PHPExcel/Calculation/Functions.php
+++ b/Classes/PHPExcel/Calculation/Functions.php
@@ -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##
*/
namespace PHPExcel;
@@ -43,670 +43,670 @@ define('PRECISION', 8.88E-016);
/**
* PHPExcel\Calculation_Functions
*
- * @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_Functions {
- /** constants */
- const COMPATIBILITY_EXCEL = 'Excel';
- const COMPATIBILITY_GNUMERIC = 'Gnumeric';
- const COMPATIBILITY_OPENOFFICE = 'OpenOfficeCalc';
-
- const RETURNDATE_PHP_NUMERIC = 'P';
- const RETURNDATE_PHP_OBJECT = 'O';
- const RETURNDATE_EXCEL = 'E';
-
-
- /**
- * Compatibility mode to use for error checking and responses
- *
- * @access private
- * @var string
- */
- protected static $compatibilityMode = self::COMPATIBILITY_EXCEL;
-
- /**
- * Data Type to use when returning date values
- *
- * @access private
- * @var string
- */
- protected static $ReturnDateType = self::RETURNDATE_EXCEL;
-
- /**
- * List of error codes
- *
- * @access private
- * @var array
- */
- protected static $_errorCodes = array( 'null' => '#NULL!',
- 'divisionbyzero' => '#DIV/0!',
- 'value' => '#VALUE!',
- 'reference' => '#REF!',
- 'name' => '#NAME?',
- 'num' => '#NUM!',
- 'na' => '#N/A',
- 'gettingdata' => '#GETTING_DATA'
- );
-
-
- /**
- * Set the Compatibility Mode
- *
- * @access public
- * @category Function Configuration
- * @param string $compatibilityMode Compatibility Mode
- * Permitted values are:
- * PHPExcel\Calculation_Functions::COMPATIBILITY_EXCEL 'Excel'
- * PHPExcel\Calculation_Functions::COMPATIBILITY_GNUMERIC 'Gnumeric'
- * PHPExcel\Calculation_Functions::COMPATIBILITY_OPENOFFICE 'OpenOfficeCalc'
- * @return boolean (Success or Failure)
- */
- public static function setCompatibilityMode($compatibilityMode) {
- if (($compatibilityMode == self::COMPATIBILITY_EXCEL) ||
- ($compatibilityMode == self::COMPATIBILITY_GNUMERIC) ||
- ($compatibilityMode == self::COMPATIBILITY_OPENOFFICE)) {
- self::$compatibilityMode = $compatibilityMode;
- return True;
- }
- return False;
- } // function setCompatibilityMode()
-
-
- /**
- * Return the current Compatibility Mode
- *
- * @access public
- * @category Function Configuration
- * @return string Compatibility Mode
- * Possible Return values are:
- * PHPExcel\Calculation_Functions::COMPATIBILITY_EXCEL 'Excel'
- * PHPExcel\Calculation_Functions::COMPATIBILITY_GNUMERIC 'Gnumeric'
- * PHPExcel\Calculation_Functions::COMPATIBILITY_OPENOFFICE 'OpenOfficeCalc'
- */
- public static function getCompatibilityMode() {
- return self::$compatibilityMode;
- } // function getCompatibilityMode()
-
-
- /**
- * Set the Return Date Format used by functions that return a date/time (Excel, PHP Serialized Numeric or PHP Object)
- *
- * @access public
- * @category Function Configuration
- * @param string $returnDateType Return Date Format
- * Permitted values are:
- * PHPExcel\Calculation_Functions::RETURNDATE_PHP_NUMERIC 'P'
- * PHPExcel\Calculation_Functions::RETURNDATE_PHP_OBJECT 'O'
- * PHPExcel\Calculation_Functions::RETURNDATE_EXCEL 'E'
- * @return boolean Success or failure
- */
- public static function setReturnDateType($returnDateType) {
- if (($returnDateType == self::RETURNDATE_PHP_NUMERIC) ||
- ($returnDateType == self::RETURNDATE_PHP_OBJECT) ||
- ($returnDateType == self::RETURNDATE_EXCEL)) {
- self::$ReturnDateType = $returnDateType;
- return True;
- }
- return False;
- } // function setReturnDateType()
-
-
- /**
- * Return the current Return Date Format for functions that return a date/time (Excel, PHP Serialized Numeric or PHP Object)
- *
- * @access public
- * @category Function Configuration
- * @return string Return Date Format
- * Possible Return values are:
- * PHPExcel\Calculation_Functions::RETURNDATE_PHP_NUMERIC 'P'
- * PHPExcel\Calculation_Functions::RETURNDATE_PHP_OBJECT 'O'
- * PHPExcel\Calculation_Functions::RETURNDATE_EXCEL 'E'
- */
- public static function getReturnDateType() {
- return self::$ReturnDateType;
- } // function getReturnDateType()
-
-
- /**
- * DUMMY
- *
- * @access public
- * @category Error Returns
- * @return string #Not Yet Implemented
- */
- public static function DUMMY() {
- return '#Not Yet Implemented';
- } // function DUMMY()
-
-
- /**
- * DIV0
- *
- * @access public
- * @category Error Returns
- * @return string #Not Yet Implemented
- */
- public static function DIV0() {
- return self::$_errorCodes['divisionbyzero'];
- } // function DIV0()
-
-
- /**
- * NA
- *
- * Excel Function:
- * =NA()
- *
- * Returns the error value #N/A
- * #N/A is the error value that means "no value is available."
- *
- * @access public
- * @category Logical Functions
- * @return string #N/A!
- */
- public static function NA() {
- return self::$_errorCodes['na'];
- } // function NA()
-
-
- /**
- * NaN
- *
- * Returns the error value #NUM!
- *
- * @access public
- * @category Error Returns
- * @return string #NUM!
- */
- public static function NaN() {
- return self::$_errorCodes['num'];
- } // function NaN()
-
-
- /**
- * NAME
- *
- * Returns the error value #NAME?
- *
- * @access public
- * @category Error Returns
- * @return string #NAME?
- */
- public static function NAME() {
- return self::$_errorCodes['name'];
- } // function NAME()
-
-
- /**
- * REF
- *
- * Returns the error value #REF!
- *
- * @access public
- * @category Error Returns
- * @return string #REF!
- */
- public static function REF() {
- return self::$_errorCodes['reference'];
- } // function REF()
-
-
- /**
- * NULL
- *
- * Returns the error value #NULL!
- *
- * @access public
- * @category Error Returns
- * @return string #REF!
- */
- public static function NULL() {
- return self::$_errorCodes['null'];
- } // function NULL()
-
-
- /**
- * VALUE
- *
- * Returns the error value #VALUE!
- *
- * @access public
- * @category Error Returns
- * @return string #VALUE!
- */
- public static function VALUE() {
- return self::$_errorCodes['value'];
- } // function VALUE()
-
-
- public static function isMatrixValue($idx) {
- return ((substr_count($idx,'.') <= 1) || (preg_match('/\.[A-Z]/',$idx) > 0));
- }
-
-
- public static function isValue($idx) {
- return (substr_count($idx,'.') == 0);
- }
-
-
- public static function isCellValue($idx) {
- return (substr_count($idx,'.') > 1);
- }
-
-
- public static function _ifCondition($condition) {
- $condition = Calculation_Functions::flattenSingleValue($condition);
- if (!isset($condition{0}))
- $condition = '=""';
- if (!in_array($condition{0},array('>', '<', '='))) {
- if (!is_numeric($condition)) { $condition = Calculation::_wrapResult(strtoupper($condition)); }
- return '='.$condition;
- } else {
- preg_match('/([<>=]+)(.*)/',$condition,$matches);
- list(,$operator,$operand) = $matches;
- if (!is_numeric($operand)) { $operand = Calculation::_wrapResult(strtoupper($operand)); }
- return $operator.$operand;
- }
- } // function _ifCondition()
-
-
- /**
- * ERROR_TYPE
- *
- * @param mixed $value Value to check
- * @return boolean
- */
- public static function ERROR_TYPE($value = '') {
- $value = self::flattenSingleValue($value);
-
- $i = 1;
- foreach(self::$_errorCodes as $errorCode) {
- if ($value === $errorCode) {
- return $i;
- }
- ++$i;
- }
- return self::NA();
- } // function ERROR_TYPE()
-
-
- /**
- * IS_BLANK
- *
- * @param mixed $value Value to check
- * @return boolean
- */
- public static function IS_BLANK($value = NULL) {
- if (!is_null($value)) {
- $value = self::flattenSingleValue($value);
- }
-
- return is_null($value);
- } // function IS_BLANK()
-
-
- /**
- * IS_ERR
- *
- * @param mixed $value Value to check
- * @return boolean
- */
- public static function IS_ERR($value = '') {
- $value = self::flattenSingleValue($value);
-
- return self::IS_ERROR($value) && (!self::IS_NA($value));
- } // function IS_ERR()
-
-
- /**
- * IS_ERROR
- *
- * @param mixed $value Value to check
- * @return boolean
- */
- public static function IS_ERROR($value = '') {
- $value = self::flattenSingleValue($value);
-
- if (!is_string($value))
- return false;
- return in_array($value, array_values(self::$_errorCodes));
- } // function IS_ERROR()
-
-
- /**
- * IS_NA
- *
- * @param mixed $value Value to check
- * @return boolean
- */
- public static function IS_NA($value = '') {
- $value = self::flattenSingleValue($value);
-
- return ($value === self::NA());
- } // function IS_NA()
-
-
- /**
- * IS_EVEN
- *
- * @param mixed $value Value to check
- * @return boolean
- */
- public static function IS_EVEN($value = NULL) {
- $value = self::flattenSingleValue($value);
-
- if ($value === NULL)
- return self::NAME();
- if ((is_bool($value)) || ((is_string($value)) && (!is_numeric($value))))
- return self::VALUE();
- return ($value % 2 == 0);
- } // function IS_EVEN()
-
-
- /**
- * IS_ODD
- *
- * @param mixed $value Value to check
- * @return boolean
- */
- public static function IS_ODD($value = NULL) {
- $value = self::flattenSingleValue($value);
-
- if ($value === NULL)
- return self::NAME();
- if ((is_bool($value)) || ((is_string($value)) && (!is_numeric($value))))
- return self::VALUE();
- return (abs($value) % 2 == 1);
- } // function IS_ODD()
-
-
- /**
- * IS_NUMBER
- *
- * @param mixed $value Value to check
- * @return boolean
- */
- public static function IS_NUMBER($value = NULL) {
- $value = self::flattenSingleValue($value);
-
- if (is_string($value)) {
- return False;
- }
- return is_numeric($value);
- } // function IS_NUMBER()
-
-
- /**
- * IS_LOGICAL
- *
- * @param mixed $value Value to check
- * @return boolean
- */
- public static function IS_LOGICAL($value = NULL) {
- $value = self::flattenSingleValue($value);
-
- return is_bool($value);
- } // function IS_LOGICAL()
-
-
- /**
- * IS_TEXT
- *
- * @param mixed $value Value to check
- * @return boolean
- */
- public static function IS_TEXT($value = NULL) {
- $value = self::flattenSingleValue($value);
-
- return (is_string($value) && !self::IS_ERROR($value));
- } // function IS_TEXT()
-
-
- /**
- * IS_NONTEXT
- *
- * @param mixed $value Value to check
- * @return boolean
- */
- public static function IS_NONTEXT($value = NULL) {
- return !self::IS_TEXT($value);
- } // function IS_NONTEXT()
-
-
- /**
- * VERSION
- *
- * @return string Version information
- */
- public static function VERSION() {
- return 'PHPExcel ##VERSION##, ##DATE##';
- } // function VERSION()
-
-
- /**
- * N
- *
- * Returns a value converted to a number
- *
- * @param value The value you want converted
- * @return number N converts values listed in the following table
- * If value is or refers to N returns
- * A number That number
- * A date The serial number of that date
- * TRUE 1
- * FALSE 0
- * An error value The error value
- * Anything else 0
- */
- public static function N($value = NULL) {
- while (is_array($value)) {
- $value = array_shift($value);
- }
-
- switch (gettype($value)) {
- case 'double' :
- case 'float' :
- case 'integer' :
- return $value;
- break;
- case 'boolean' :
- return (integer) $value;
- break;
- case 'string' :
- // Errors
- if ((strlen($value) > 0) && ($value{0} == '#')) {
- return $value;
- }
- break;
- }
- return 0;
- } // function N()
-
-
- /**
- * TYPE
- *
- * Returns a number that identifies the type of a value
- *
- * @param value The value you want tested
- * @return number N converts values listed in the following table
- * If value is or refers to N returns
- * A number 1
- * Text 2
- * Logical Value 4
- * An error value 16
- * Array or Matrix 64
- */
- public static function TYPE($value = NULL) {
- $value = self::flattenArrayIndexed($value);
- if (is_array($value) && (count($value) > 1)) {
- $a = array_keys($value);
- $a = array_pop($a);
- // Range of cells is an error
- if (self::isCellValue($a)) {
- return 16;
- // Test for Matrix
- } elseif (self::isMatrixValue($a)) {
- return 64;
- }
- } elseif(empty($value)) {
- // Empty Cell
- return 1;
- }
- $value = self::flattenSingleValue($value);
-
- if (($value === NULL) || (is_float($value)) || (is_int($value))) {
- return 1;
- } elseif(is_bool($value)) {
- return 4;
- } elseif(is_array($value)) {
- return 64;
- break;
- } elseif(is_string($value)) {
- // Errors
- if ((strlen($value) > 0) && ($value{0} == '#')) {
- return 16;
- }
- return 2;
- }
- return 0;
- } // function TYPE()
-
-
- /**
- * Convert a multi-dimensional array to a simple 1-dimensional array
- *
- * @param array $array Array to be flattened
- * @return array Flattened array
- */
- public static function flattenArray($array) {
- if (!is_array($array)) {
- return (array) $array;
- }
-
- $arrayValues = array();
- foreach ($array as $value) {
- if (is_array($value)) {
- foreach ($value as $val) {
- if (is_array($val)) {
- foreach ($val as $v) {
- $arrayValues[] = $v;
- }
- } else {
- $arrayValues[] = $val;
- }
- }
- } else {
- $arrayValues[] = $value;
- }
- }
-
- return $arrayValues;
- } // function flattenArray()
-
-
- /**
- * Convert a multi-dimensional array to a simple 1-dimensional array, but retain an element of indexing
- *
- * @param array $array Array to be flattened
- * @return array Flattened array
- */
- public static function flattenArrayIndexed($array) {
- if (!is_array($array)) {
- return (array) $array;
- }
-
- $arrayValues = array();
- foreach ($array as $k1 => $value) {
- if (is_array($value)) {
- foreach ($value as $k2 => $val) {
- if (is_array($val)) {
- foreach ($val as $k3 => $v) {
- $arrayValues[$k1.'.'.$k2.'.'.$k3] = $v;
- }
- } else {
- $arrayValues[$k1.'.'.$k2] = $val;
- }
- }
- } else {
- $arrayValues[$k1] = $value;
- }
- }
-
- return $arrayValues;
- } // function flattenArrayIndexed()
-
-
- /**
- * Convert an array to a single scalar value by extracting the first element
- *
- * @param mixed $value Array or scalar value
- * @return mixed
- */
- public static function flattenSingleValue($value = '') {
- while (is_array($value)) {
- $value = array_pop($value);
- }
-
- return $value;
- } // function flattenSingleValue()
+ /** constants */
+ const COMPATIBILITY_EXCEL = 'Excel';
+ const COMPATIBILITY_GNUMERIC = 'Gnumeric';
+ const COMPATIBILITY_OPENOFFICE = 'OpenOfficeCalc';
+
+ const RETURNDATE_PHP_NUMERIC = 'P';
+ const RETURNDATE_PHP_OBJECT = 'O';
+ const RETURNDATE_EXCEL = 'E';
+
+
+ /**
+ * Compatibility mode to use for error checking and responses
+ *
+ * @access private
+ * @var string
+ */
+ protected static $compatibilityMode = self::COMPATIBILITY_EXCEL;
+
+ /**
+ * Data Type to use when returning date values
+ *
+ * @access private
+ * @var string
+ */
+ protected static $ReturnDateType = self::RETURNDATE_EXCEL;
+
+ /**
+ * List of error codes
+ *
+ * @access private
+ * @var array
+ */
+ protected static $_errorCodes = array( 'null' => '#NULL!',
+ 'divisionbyzero' => '#DIV/0!',
+ 'value' => '#VALUE!',
+ 'reference' => '#REF!',
+ 'name' => '#NAME?',
+ 'num' => '#NUM!',
+ 'na' => '#N/A',
+ 'gettingdata' => '#GETTING_DATA'
+ );
+
+
+ /**
+ * Set the Compatibility Mode
+ *
+ * @access public
+ * @category Function Configuration
+ * @param string $compatibilityMode Compatibility Mode
+ * Permitted values are:
+ * PHPExcel\Calculation_Functions::COMPATIBILITY_EXCEL 'Excel'
+ * PHPExcel\Calculation_Functions::COMPATIBILITY_GNUMERIC 'Gnumeric'
+ * PHPExcel\Calculation_Functions::COMPATIBILITY_OPENOFFICE 'OpenOfficeCalc'
+ * @return boolean (Success or Failure)
+ */
+ public static function setCompatibilityMode($compatibilityMode) {
+ if (($compatibilityMode == self::COMPATIBILITY_EXCEL) ||
+ ($compatibilityMode == self::COMPATIBILITY_GNUMERIC) ||
+ ($compatibilityMode == self::COMPATIBILITY_OPENOFFICE)) {
+ self::$compatibilityMode = $compatibilityMode;
+ return True;
+ }
+ return False;
+ } // function setCompatibilityMode()
+
+
+ /**
+ * Return the current Compatibility Mode
+ *
+ * @access public
+ * @category Function Configuration
+ * @return string Compatibility Mode
+ * Possible Return values are:
+ * PHPExcel\Calculation_Functions::COMPATIBILITY_EXCEL 'Excel'
+ * PHPExcel\Calculation_Functions::COMPATIBILITY_GNUMERIC 'Gnumeric'
+ * PHPExcel\Calculation_Functions::COMPATIBILITY_OPENOFFICE 'OpenOfficeCalc'
+ */
+ public static function getCompatibilityMode() {
+ return self::$compatibilityMode;
+ } // function getCompatibilityMode()
+
+
+ /**
+ * Set the Return Date Format used by functions that return a date/time (Excel, PHP Serialized Numeric or PHP Object)
+ *
+ * @access public
+ * @category Function Configuration
+ * @param string $returnDateType Return Date Format
+ * Permitted values are:
+ * PHPExcel\Calculation_Functions::RETURNDATE_PHP_NUMERIC 'P'
+ * PHPExcel\Calculation_Functions::RETURNDATE_PHP_OBJECT 'O'
+ * PHPExcel\Calculation_Functions::RETURNDATE_EXCEL 'E'
+ * @return boolean Success or failure
+ */
+ public static function setReturnDateType($returnDateType) {
+ if (($returnDateType == self::RETURNDATE_PHP_NUMERIC) ||
+ ($returnDateType == self::RETURNDATE_PHP_OBJECT) ||
+ ($returnDateType == self::RETURNDATE_EXCEL)) {
+ self::$ReturnDateType = $returnDateType;
+ return True;
+ }
+ return False;
+ } // function setReturnDateType()
+
+
+ /**
+ * Return the current Return Date Format for functions that return a date/time (Excel, PHP Serialized Numeric or PHP Object)
+ *
+ * @access public
+ * @category Function Configuration
+ * @return string Return Date Format
+ * Possible Return values are:
+ * PHPExcel\Calculation_Functions::RETURNDATE_PHP_NUMERIC 'P'
+ * PHPExcel\Calculation_Functions::RETURNDATE_PHP_OBJECT 'O'
+ * PHPExcel\Calculation_Functions::RETURNDATE_EXCEL 'E'
+ */
+ public static function getReturnDateType() {
+ return self::$ReturnDateType;
+ } // function getReturnDateType()
+
+
+ /**
+ * DUMMY
+ *
+ * @access public
+ * @category Error Returns
+ * @return string #Not Yet Implemented
+ */
+ public static function DUMMY() {
+ return '#Not Yet Implemented';
+ } // function DUMMY()
+
+
+ /**
+ * DIV0
+ *
+ * @access public
+ * @category Error Returns
+ * @return string #Not Yet Implemented
+ */
+ public static function DIV0() {
+ return self::$_errorCodes['divisionbyzero'];
+ } // function DIV0()
+
+
+ /**
+ * NA
+ *
+ * Excel Function:
+ * =NA()
+ *
+ * Returns the error value #N/A
+ * #N/A is the error value that means "no value is available."
+ *
+ * @access public
+ * @category Logical Functions
+ * @return string #N/A!
+ */
+ public static function NA() {
+ return self::$_errorCodes['na'];
+ } // function NA()
+
+
+ /**
+ * NaN
+ *
+ * Returns the error value #NUM!
+ *
+ * @access public
+ * @category Error Returns
+ * @return string #NUM!
+ */
+ public static function NaN() {
+ return self::$_errorCodes['num'];
+ } // function NaN()
+
+
+ /**
+ * NAME
+ *
+ * Returns the error value #NAME?
+ *
+ * @access public
+ * @category Error Returns
+ * @return string #NAME?
+ */
+ public static function NAME() {
+ return self::$_errorCodes['name'];
+ } // function NAME()
+
+
+ /**
+ * REF
+ *
+ * Returns the error value #REF!
+ *
+ * @access public
+ * @category Error Returns
+ * @return string #REF!
+ */
+ public static function REF() {
+ return self::$_errorCodes['reference'];
+ } // function REF()
+
+
+ /**
+ * NULL
+ *
+ * Returns the error value #NULL!
+ *
+ * @access public
+ * @category Error Returns
+ * @return string #REF!
+ */
+ public static function NULL() {
+ return self::$_errorCodes['null'];
+ } // function NULL()
+
+
+ /**
+ * VALUE
+ *
+ * Returns the error value #VALUE!
+ *
+ * @access public
+ * @category Error Returns
+ * @return string #VALUE!
+ */
+ public static function VALUE() {
+ return self::$_errorCodes['value'];
+ } // function VALUE()
+
+
+ public static function isMatrixValue($idx) {
+ return ((substr_count($idx,'.') <= 1) || (preg_match('/\.[A-Z]/',$idx) > 0));
+ }
+
+
+ public static function isValue($idx) {
+ return (substr_count($idx,'.') == 0);
+ }
+
+
+ public static function isCellValue($idx) {
+ return (substr_count($idx,'.') > 1);
+ }
+
+
+ public static function _ifCondition($condition) {
+ $condition = Calculation_Functions::flattenSingleValue($condition);
+ if (!isset($condition{0}))
+ $condition = '=""';
+ if (!in_array($condition{0},array('>', '<', '='))) {
+ if (!is_numeric($condition)) { $condition = Calculation::_wrapResult(strtoupper($condition)); }
+ return '='.$condition;
+ } else {
+ preg_match('/([<>=]+)(.*)/',$condition,$matches);
+ list(,$operator,$operand) = $matches;
+ if (!is_numeric($operand)) { $operand = Calculation::_wrapResult(strtoupper($operand)); }
+ return $operator.$operand;
+ }
+ } // function _ifCondition()
+
+
+ /**
+ * ERROR_TYPE
+ *
+ * @param mixed $value Value to check
+ * @return boolean
+ */
+ public static function ERROR_TYPE($value = '') {
+ $value = self::flattenSingleValue($value);
+
+ $i = 1;
+ foreach(self::$_errorCodes as $errorCode) {
+ if ($value === $errorCode) {
+ return $i;
+ }
+ ++$i;
+ }
+ return self::NA();
+ } // function ERROR_TYPE()
+
+
+ /**
+ * IS_BLANK
+ *
+ * @param mixed $value Value to check
+ * @return boolean
+ */
+ public static function IS_BLANK($value = null) {
+ if (!is_null($value)) {
+ $value = self::flattenSingleValue($value);
+ }
+
+ return is_null($value);
+ } // function IS_BLANK()
+
+
+ /**
+ * IS_ERR
+ *
+ * @param mixed $value Value to check
+ * @return boolean
+ */
+ public static function IS_ERR($value = '') {
+ $value = self::flattenSingleValue($value);
+
+ return self::IS_ERROR($value) && (!self::IS_NA($value));
+ } // function IS_ERR()
+
+
+ /**
+ * IS_ERROR
+ *
+ * @param mixed $value Value to check
+ * @return boolean
+ */
+ public static function IS_ERROR($value = '') {
+ $value = self::flattenSingleValue($value);
+
+ if (!is_string($value))
+ return false;
+ return in_array($value, array_values(self::$_errorCodes));
+ } // function IS_ERROR()
+
+
+ /**
+ * IS_NA
+ *
+ * @param mixed $value Value to check
+ * @return boolean
+ */
+ public static function IS_NA($value = '') {
+ $value = self::flattenSingleValue($value);
+
+ return ($value === self::NA());
+ } // function IS_NA()
+
+
+ /**
+ * IS_EVEN
+ *
+ * @param mixed $value Value to check
+ * @return boolean
+ */
+ public static function IS_EVEN($value = null) {
+ $value = self::flattenSingleValue($value);
+
+ if ($value === null)
+ return self::NAME();
+ if ((is_bool($value)) || ((is_string($value)) && (!is_numeric($value))))
+ return self::VALUE();
+ return ($value % 2 == 0);
+ } // function IS_EVEN()
+
+
+ /**
+ * IS_ODD
+ *
+ * @param mixed $value Value to check
+ * @return boolean
+ */
+ public static function IS_ODD($value = null) {
+ $value = self::flattenSingleValue($value);
+
+ if ($value === null)
+ return self::NAME();
+ if ((is_bool($value)) || ((is_string($value)) && (!is_numeric($value))))
+ return self::VALUE();
+ return (abs($value) % 2 == 1);
+ } // function IS_ODD()
+
+
+ /**
+ * IS_NUMBER
+ *
+ * @param mixed $value Value to check
+ * @return boolean
+ */
+ public static function IS_NUMBER($value = null) {
+ $value = self::flattenSingleValue($value);
+
+ if (is_string($value)) {
+ return False;
+ }
+ return is_numeric($value);
+ } // function IS_NUMBER()
+
+
+ /**
+ * IS_LOGICAL
+ *
+ * @param mixed $value Value to check
+ * @return boolean
+ */
+ public static function IS_LOGICAL($value = null) {
+ $value = self::flattenSingleValue($value);
+
+ return is_bool($value);
+ } // function IS_LOGICAL()
+
+
+ /**
+ * IS_TEXT
+ *
+ * @param mixed $value Value to check
+ * @return boolean
+ */
+ public static function IS_TEXT($value = null) {
+ $value = self::flattenSingleValue($value);
+
+ return (is_string($value) && !self::IS_ERROR($value));
+ } // function IS_TEXT()
+
+
+ /**
+ * IS_NONTEXT
+ *
+ * @param mixed $value Value to check
+ * @return boolean
+ */
+ public static function IS_NONTEXT($value = null) {
+ return !self::IS_TEXT($value);
+ } // function IS_NONTEXT()
+
+
+ /**
+ * VERSION
+ *
+ * @return string Version information
+ */
+ public static function VERSION() {
+ return 'PHPExcel ##VERSION##, ##DATE##';
+ } // function VERSION()
+
+
+ /**
+ * N
+ *
+ * Returns a value converted to a number
+ *
+ * @param value The value you want converted
+ * @return number N converts values listed in the following table
+ * If value is or refers to N returns
+ * A number That number
+ * A date The serial number of that date
+ * TRUE 1
+ * FALSE 0
+ * An error value The error value
+ * Anything else 0
+ */
+ public static function N($value = null) {
+ while (is_array($value)) {
+ $value = array_shift($value);
+ }
+
+ switch (gettype($value)) {
+ case 'double' :
+ case 'float' :
+ case 'integer' :
+ return $value;
+ break;
+ case 'boolean' :
+ return (integer) $value;
+ break;
+ case 'string' :
+ // Errors
+ if ((strlen($value) > 0) && ($value{0} == '#')) {
+ return $value;
+ }
+ break;
+ }
+ return 0;
+ } // function N()
+
+
+ /**
+ * TYPE
+ *
+ * Returns a number that identifies the type of a value
+ *
+ * @param value The value you want tested
+ * @return number N converts values listed in the following table
+ * If value is or refers to N returns
+ * A number 1
+ * Text 2
+ * Logical Value 4
+ * An error value 16
+ * Array or Matrix 64
+ */
+ public static function TYPE($value = null) {
+ $value = self::flattenArrayIndexed($value);
+ if (is_array($value) && (count($value) > 1)) {
+ $a = array_keys($value);
+ $a = array_pop($a);
+ // Range of cells is an error
+ if (self::isCellValue($a)) {
+ return 16;
+ // Test for Matrix
+ } elseif (self::isMatrixValue($a)) {
+ return 64;
+ }
+ } elseif(empty($value)) {
+ // Empty Cell
+ return 1;
+ }
+ $value = self::flattenSingleValue($value);
+
+ if (($value === null) || (is_float($value)) || (is_int($value))) {
+ return 1;
+ } elseif(is_bool($value)) {
+ return 4;
+ } elseif(is_array($value)) {
+ return 64;
+ break;
+ } elseif(is_string($value)) {
+ // Errors
+ if ((strlen($value) > 0) && ($value{0} == '#')) {
+ return 16;
+ }
+ return 2;
+ }
+ return 0;
+ } // function TYPE()
+
+
+ /**
+ * Convert a multi-dimensional array to a simple 1-dimensional array
+ *
+ * @param array $array Array to be flattened
+ * @return array Flattened array
+ */
+ public static function flattenArray($array) {
+ if (!is_array($array)) {
+ return (array) $array;
+ }
+
+ $arrayValues = array();
+ foreach ($array as $value) {
+ if (is_array($value)) {
+ foreach ($value as $val) {
+ if (is_array($val)) {
+ foreach ($val as $v) {
+ $arrayValues[] = $v;
+ }
+ } else {
+ $arrayValues[] = $val;
+ }
+ }
+ } else {
+ $arrayValues[] = $value;
+ }
+ }
+
+ return $arrayValues;
+ } // function flattenArray()
+
+
+ /**
+ * Convert a multi-dimensional array to a simple 1-dimensional array, but retain an element of indexing
+ *
+ * @param array $array Array to be flattened
+ * @return array Flattened array
+ */
+ public static function flattenArrayIndexed($array) {
+ if (!is_array($array)) {
+ return (array) $array;
+ }
+
+ $arrayValues = array();
+ foreach ($array as $k1 => $value) {
+ if (is_array($value)) {
+ foreach ($value as $k2 => $val) {
+ if (is_array($val)) {
+ foreach ($val as $k3 => $v) {
+ $arrayValues[$k1.'.'.$k2.'.'.$k3] = $v;
+ }
+ } else {
+ $arrayValues[$k1.'.'.$k2] = $val;
+ }
+ }
+ } else {
+ $arrayValues[$k1] = $value;
+ }
+ }
+
+ return $arrayValues;
+ } // function flattenArrayIndexed()
+
+
+ /**
+ * Convert an array to a single scalar value by extracting the first element
+ *
+ * @param mixed $value Array or scalar value
+ * @return mixed
+ */
+ public static function flattenSingleValue($value = '') {
+ while (is_array($value)) {
+ $value = array_pop($value);
+ }
+
+ return $value;
+ } // function flattenSingleValue()
}
//
-// There are a few mathematical functions that aren't available on all versions of PHP for all platforms
-// These functions aren't available in Windows implementations of PHP prior to version 5.3.0
-// So we test if they do exist for this version of PHP/operating platform; and if not we create them
+// There are a few mathematical functions that aren't available on all versions of PHP for all platforms
+// These functions aren't available in Windows implementations of PHP prior to version 5.3.0
+// So we test if they do exist for this version of PHP/operating platform; and if not we create them
//
if (!function_exists('acosh')) {
- function acosh($x) {
- return 2 * log(sqrt(($x + 1) / 2) + sqrt(($x - 1) / 2));
- } // function acosh()
+ function acosh($x) {
+ return 2 * log(sqrt(($x + 1) / 2) + sqrt(($x - 1) / 2));
+ } // function acosh()
}
if (!function_exists('asinh')) {
- function asinh($x) {
- return log($x + sqrt(1 + $x * $x));
- } // function asinh()
+ function asinh($x) {
+ return log($x + sqrt(1 + $x * $x));
+ } // function asinh()
}
if (!function_exists('atanh')) {
- function atanh($x) {
- return (log(1 + $x) - log(1 - $x)) / 2;
- } // function atanh()
+ function atanh($x) {
+ return (log(1 + $x) - log(1 - $x)) / 2;
+ } // function atanh()
}
//
-// Strangely, PHP doesn't have a mb_str_replace multibyte function
-// As we'll only ever use this function with UTF-8 characters, we can simply "hard-code" the character set
+// Strangely, PHP doesn't have a mb_str_replace multibyte function
+// As we'll only ever use this function with UTF-8 characters, we can simply "hard-code" the character set
//
if ((!function_exists('mb_str_replace')) &&
- (function_exists('mb_substr')) && (function_exists('mb_strlen')) && (function_exists('mb_strpos'))) {
- function mb_str_replace($search, $replace, $subject) {
- if(is_array($subject)) {
- $ret = array();
- foreach($subject as $key => $val) {
- $ret[$key] = mb_str_replace($search, $replace, $val);
- }
- return $ret;
- }
+ (function_exists('mb_substr')) && (function_exists('mb_strlen')) && (function_exists('mb_strpos'))) {
+ function mb_str_replace($search, $replace, $subject) {
+ if(is_array($subject)) {
+ $ret = array();
+ foreach($subject as $key => $val) {
+ $ret[$key] = mb_str_replace($search, $replace, $val);
+ }
+ return $ret;
+ }
- foreach((array) $search as $key => $s) {
- if($s == '') {
- continue;
- }
- $r = !is_array($replace) ? $replace : (array_key_exists($key, $replace) ? $replace[$key] : '');
- $pos = mb_strpos($subject, $s, 0, 'UTF-8');
- while($pos !== false) {
- $subject = mb_substr($subject, 0, $pos, 'UTF-8') . $r . mb_substr($subject, $pos + mb_strlen($s, 'UTF-8'), 65535, 'UTF-8');
- $pos = mb_strpos($subject, $s, $pos + mb_strlen($r, 'UTF-8'), 'UTF-8');
- }
- }
- return $subject;
- }
+ foreach((array) $search as $key => $s) {
+ if($s == '') {
+ continue;
+ }
+ $r = !is_array($replace) ? $replace : (array_key_exists($key, $replace) ? $replace[$key] : '');
+ $pos = mb_strpos($subject, $s, 0, 'UTF-8');
+ while($pos !== false) {
+ $subject = mb_substr($subject, 0, $pos, 'UTF-8') . $r . mb_substr($subject, $pos + mb_strlen($s, 'UTF-8'), 65535, 'UTF-8');
+ $pos = mb_strpos($subject, $s, $pos + mb_strlen($r, 'UTF-8'), 'UTF-8');
+ }
+ }
+ return $subject;
+ }
}
diff --git a/Classes/PHPExcel/Calculation/Logical.php b/Classes/PHPExcel/Calculation/Logical.php
index f28e9b0..29a3ecd 100644
--- a/Classes/PHPExcel/Calculation/Logical.php
+++ b/Classes/PHPExcel/Calculation/Logical.php
@@ -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()
}
diff --git a/Classes/PHPExcel/Calculation/LookupRef.php b/Classes/PHPExcel/Calculation/LookupRef.php
index 7a228cd..8d61f87 100644
--- a/Classes/PHPExcel/Calculation/LookupRef.php
+++ b/Classes/PHPExcel/Calculation/LookupRef.php
@@ -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,711 +31,711 @@ namespace PHPExcel;
/**
* PHPExcel\Calculation_LookupRef
*
- * @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_LookupRef {
- /**
- * CELL_ADDRESS
- *
- * Creates a cell address as text, given specified row and column numbers.
- *
- * Excel Function:
- * =ADDRESS(row, column, [relativity], [referenceStyle], [sheetText])
- *
- * @param row Row number to use in the cell reference
- * @param column Column number to use in the cell reference
- * @param relativity Flag indicating the type of reference to return
- * 1 or omitted Absolute
- * 2 Absolute row; relative column
- * 3 Relative row; absolute column
- * 4 Relative
- * @param referenceStyle A logical value that specifies the A1 or R1C1 reference style.
- * TRUE or omitted CELL_ADDRESS returns an A1-style reference
- * FALSE CELL_ADDRESS returns an R1C1-style reference
- * @param sheetText Optional Name of worksheet to use
- * @return string
- */
- public static function CELL_ADDRESS($row, $column, $relativity=1, $referenceStyle=True, $sheetText='') {
- $row = Calculation_Functions::flattenSingleValue($row);
- $column = Calculation_Functions::flattenSingleValue($column);
- $relativity = Calculation_Functions::flattenSingleValue($relativity);
- $sheetText = Calculation_Functions::flattenSingleValue($sheetText);
-
- if (($row < 1) || ($column < 1)) {
- return Calculation_Functions::VALUE();
- }
-
- if ($sheetText > '') {
- if (strpos($sheetText,' ') !== False) { $sheetText = "'".$sheetText."'"; }
- $sheetText .='!';
- }
- if ((!is_bool($referenceStyle)) || $referenceStyle) {
- $rowRelative = $columnRelative = '$';
- $column = Cell::stringFromColumnIndex($column-1);
- if (($relativity == 2) || ($relativity == 4)) { $columnRelative = ''; }
- if (($relativity == 3) || ($relativity == 4)) { $rowRelative = ''; }
- return $sheetText.$columnRelative.$column.$rowRelative.$row;
- } else {
- if (($relativity == 2) || ($relativity == 4)) { $column = '['.$column.']'; }
- if (($relativity == 3) || ($relativity == 4)) { $row = '['.$row.']'; }
- return $sheetText.'R'.$row.'C'.$column;
- }
- } // function CELL_ADDRESS()
-
-
- /**
- * COLUMN
- *
- * Returns the column number of the given cell reference
- * If the cell reference is a range of cells, COLUMN returns the column numbers of each column in the reference as a horizontal array.
- * If cell reference is omitted, and the function is being called through the calculation engine, then it is assumed to be the
- * reference of the cell in which the COLUMN function appears; otherwise this function returns 0.
- *
- * Excel Function:
- * =COLUMN([cellAddress])
- *
- * @param cellAddress A reference to a range of cells for which you want the column numbers
- * @return integer or array of integer
- */
- public static function COLUMN($cellAddress=Null) {
- if (is_null($cellAddress) || trim($cellAddress) === '') { return 0; }
-
- if (is_array($cellAddress)) {
- foreach($cellAddress as $columnKey => $value) {
- $columnKey = preg_replace('/[^a-z]/i','',$columnKey);
- return (integer) Cell::columnIndexFromString($columnKey);
- }
- } else {
- if (strpos($cellAddress,'!') !== false) {
- list($sheet,$cellAddress) = explode('!',$cellAddress);
- }
- if (strpos($cellAddress,':') !== false) {
- list($startAddress,$endAddress) = explode(':',$cellAddress);
- $startAddress = preg_replace('/[^a-z]/i','',$startAddress);
- $endAddress = preg_replace('/[^a-z]/i','',$endAddress);
- $returnValue = array();
- do {
- $returnValue[] = (integer) Cell::columnIndexFromString($startAddress);
- } while ($startAddress++ != $endAddress);
- return $returnValue;
- } else {
- $cellAddress = preg_replace('/[^a-z]/i','',$cellAddress);
- return (integer) Cell::columnIndexFromString($cellAddress);
- }
- }
- } // function COLUMN()
-
-
- /**
- * COLUMNS
- *
- * Returns the number of columns in an array or reference.
- *
- * Excel Function:
- * =COLUMNS(cellAddress)
- *
- * @param cellAddress An array or array formula, or a reference to a range of cells for which you want the number of columns
- * @return integer The number of columns in cellAddress
- */
- public static function COLUMNS($cellAddress=Null) {
- if (is_null($cellAddress) || $cellAddress === '') {
- return 1;
- } elseif (!is_array($cellAddress)) {
- return Calculation_Functions::VALUE();
- }
-
- $x = array_keys($cellAddress);
- $x = array_shift($x);
- $isMatrix = (is_numeric($x));
- list($columns,$rows) = Calculation::_getMatrixDimensions($cellAddress);
-
- if ($isMatrix) {
- return $rows;
- } else {
- return $columns;
- }
- } // function COLUMNS()
-
-
- /**
- * ROW
- *
- * Returns the row number of the given cell reference
- * If the cell reference is a range of cells, ROW returns the row numbers of each row in the reference as a vertical array.
- * If cell reference is omitted, and the function is being called through the calculation engine, then it is assumed to be the
- * reference of the cell in which the ROW function appears; otherwise this function returns 0.
- *
- * Excel Function:
- * =ROW([cellAddress])
- *
- * @param cellAddress A reference to a range of cells for which you want the row numbers
- * @return integer or array of integer
- */
- public static function ROW($cellAddress=Null) {
- if (is_null($cellAddress) || trim($cellAddress) === '') { return 0; }
-
- if (is_array($cellAddress)) {
- foreach($cellAddress as $columnKey => $rowValue) {
- foreach($rowValue as $rowKey => $cellValue) {
- return (integer) preg_replace('/[^0-9]/i','',$rowKey);
- }
- }
- } else {
- if (strpos($cellAddress,'!') !== false) {
- list($sheet,$cellAddress) = explode('!',$cellAddress);
- }
- if (strpos($cellAddress,':') !== false) {
- list($startAddress,$endAddress) = explode(':',$cellAddress);
- $startAddress = preg_replace('/[^0-9]/','',$startAddress);
- $endAddress = preg_replace('/[^0-9]/','',$endAddress);
- $returnValue = array();
- do {
- $returnValue[][] = (integer) $startAddress;
- } while ($startAddress++ != $endAddress);
- return $returnValue;
- } else {
- list($cellAddress) = explode(':',$cellAddress);
- return (integer) preg_replace('/[^0-9]/','',$cellAddress);
- }
- }
- } // function ROW()
-
-
- /**
- * ROWS
- *
- * Returns the number of rows in an array or reference.
- *
- * Excel Function:
- * =ROWS(cellAddress)
- *
- * @param cellAddress An array or array formula, or a reference to a range of cells for which you want the number of rows
- * @return integer The number of rows in cellAddress
- */
- public static function ROWS($cellAddress=Null) {
- if (is_null($cellAddress) || $cellAddress === '') {
- return 1;
- } elseif (!is_array($cellAddress)) {
- return Calculation_Functions::VALUE();
- }
-
- $i = array_keys($cellAddress);
- $isMatrix = (is_numeric(array_shift($i)));
- list($columns,$rows) = Calculation::_getMatrixDimensions($cellAddress);
-
- if ($isMatrix) {
- return $columns;
- } else {
- return $rows;
- }
- } // function ROWS()
-
-
- /**
- * HYPERLINK
- *
- * Excel Function:
- * =HYPERLINK(linkURL,displayName)
- *
- * @access public
- * @category Logical Functions
- * @param string $linkURL Value to check, is also the value returned when no error
- * @param string $displayName Value to return when testValue is an error condition
- * @param PHPExcel\Cell $pCell The cell to set the hyperlink in
- * @return mixed The value of $displayName (or $linkURL if $displayName was blank)
- */
- public static function HYPERLINK($linkURL = '', $displayName = null, Cell $pCell = null) {
- $args = func_get_args();
- $pCell = array_pop($args);
-
- $linkURL = (is_null($linkURL)) ? '' : Calculation_Functions::flattenSingleValue($linkURL);
- $displayName = (is_null($displayName)) ? '' : Calculation_Functions::flattenSingleValue($displayName);
-
- if ((!is_object($pCell)) || (trim($linkURL) == '')) {
- return Calculation_Functions::REF();
- }
-
- if ((is_object($displayName)) || trim($displayName) == '') {
- $displayName = $linkURL;
- }
-
- $pCell->getHyperlink()->setUrl($linkURL);
-
- return $displayName;
- } // function HYPERLINK()
-
-
- /**
- * INDIRECT
- *
- * Returns the reference specified by a text string.
- * References are immediately evaluated to display their contents.
- *
- * Excel Function:
- * =INDIRECT(cellAddress)
- *
- * NOTE - INDIRECT() does not yet support the optional a1 parameter introduced in Excel 2010
- *
- * @param cellAddress $cellAddress The cell address of the current cell (containing this formula)
- * @param PHPExcel\Cell $pCell The current cell (containing this formula)
- * @return mixed The cells referenced by cellAddress
- *
- * @todo Support for the optional a1 parameter introduced in Excel 2010
- *
- */
- public static function INDIRECT($cellAddress = NULL, Cell $pCell = NULL) {
- $cellAddress = Calculation_Functions::flattenSingleValue($cellAddress);
- if (is_null($cellAddress) || $cellAddress === '') {
- return Calculation_Functions::REF();
- }
-
- $cellAddress1 = $cellAddress;
- $cellAddress2 = NULL;
- if (strpos($cellAddress,':') !== false) {
- list($cellAddress1,$cellAddress2) = explode(':',$cellAddress);
- }
-
- if ((!preg_match('/^'.Calculation::CALCULATION_REGEXP_CELLREF.'$/i', $cellAddress1, $matches)) ||
- ((!is_null($cellAddress2)) && (!preg_match('/^'.Calculation::CALCULATION_REGEXP_CELLREF.'$/i', $cellAddress2, $matches)))) {
- if (!preg_match('/^'.Calculation::CALCULATION_REGEXP_NAMEDRANGE.'$/i', $cellAddress1, $matches)) {
- return Calculation_Functions::REF();
- }
-
- if (strpos($cellAddress,'!') !== FALSE) {
- list($sheetName, $cellAddress) = explode('!',$cellAddress);
- $sheetName = trim($sheetName, "'");
- $pSheet = $pCell->getParent()->getParent()->getSheetByName($sheetName);
- } else {
- $pSheet = $pCell->getParent();
- }
-
- return Calculation::getInstance()->extractNamedRange($cellAddress, $pSheet, FALSE);
- }
-
- if (strpos($cellAddress,'!') !== FALSE) {
- list($sheetName,$cellAddress) = explode('!',$cellAddress);
- $sheetName = trim($sheetName, "'");
- $pSheet = $pCell->getParent()->getParent()->getSheetByName($sheetName);
- } else {
- $pSheet = $pCell->getParent();
- }
-
- return Calculation::getInstance()->extractCellRange($cellAddress, $pSheet, FALSE);
- } // function INDIRECT()
-
-
- /**
- * OFFSET
- *
- * Returns a reference to a range that is a specified number of rows and columns from a cell or range of cells.
- * The reference that is returned can be a single cell or a range of cells. You can specify the number of rows and
- * the number of columns to be returned.
- *
- * Excel Function:
- * =OFFSET(cellAddress, rows, cols, [height], [width])
- *
- * @param cellAddress The reference from which you want to base the offset. Reference must refer to a cell or
- * range of adjacent cells; otherwise, OFFSET returns the #VALUE! error value.
- * @param rows The number of rows, up or down, that you want the upper-left cell to refer to.
- * Using 5 as the rows argument specifies that the upper-left cell in the reference is
- * five rows below reference. Rows can be positive (which means below the starting reference)
- * or negative (which means above the starting reference).
- * @param cols The number of columns, to the left or right, that you want the upper-left cell of the result
- * to refer to. Using 5 as the cols argument specifies that the upper-left cell in the
- * reference is five columns to the right of reference. Cols can be positive (which means
- * to the right of the starting reference) or negative (which means to the left of the
- * starting reference).
- * @param height The height, in number of rows, that you want the returned reference to be. Height must be a positive number.
- * @param width The width, in number of columns, that you want the returned reference to be. Width must be a positive number.
- * @return string A reference to a cell or range of cells
- */
- public static function OFFSET($cellAddress=Null,$rows=0,$columns=0,$height=null,$width=null) {
- $rows = Calculation_Functions::flattenSingleValue($rows);
- $columns = Calculation_Functions::flattenSingleValue($columns);
- $height = Calculation_Functions::flattenSingleValue($height);
- $width = Calculation_Functions::flattenSingleValue($width);
- if ($cellAddress == Null) {
- return 0;
- }
-
- $args = func_get_args();
- $pCell = array_pop($args);
- if (!is_object($pCell)) {
- return Calculation_Functions::REF();
- }
-
- $sheetName = NULL;
- if (strpos($cellAddress,"!")) {
- list($sheetName,$cellAddress) = explode("!",$cellAddress);
- $sheetName = trim($sheetName, "'");
- }
- if (strpos($cellAddress,":")) {
- list($startCell,$endCell) = explode(":",$cellAddress);
- } else {
- $startCell = $endCell = $cellAddress;
- }
- list($startCellColumn,$startCellRow) = Cell::coordinateFromString($startCell);
- list($endCellColumn,$endCellRow) = Cell::coordinateFromString($endCell);
-
- $startCellRow += $rows;
- $startCellColumn = Cell::columnIndexFromString($startCellColumn) - 1;
- $startCellColumn += $columns;
-
- if (($startCellRow <= 0) || ($startCellColumn < 0)) {
- return Calculation_Functions::REF();
- }
- $endCellColumn = Cell::columnIndexFromString($endCellColumn) - 1;
- if (($width != null) && (!is_object($width))) {
- $endCellColumn = $startCellColumn + $width - 1;
- } else {
- $endCellColumn += $columns;
- }
- $startCellColumn = Cell::stringFromColumnIndex($startCellColumn);
-
- if (($height != null) && (!is_object($height))) {
- $endCellRow = $startCellRow + $height - 1;
- } else {
- $endCellRow += $rows;
- }
-
- if (($endCellRow <= 0) || ($endCellColumn < 0)) {
- return Calculation_Functions::REF();
- }
- $endCellColumn = Cell::stringFromColumnIndex($endCellColumn);
-
- $cellAddress = $startCellColumn.$startCellRow;
- if (($startCellColumn != $endCellColumn) || ($startCellRow != $endCellRow)) {
- $cellAddress .= ':'.$endCellColumn.$endCellRow;
- }
-
- if ($sheetName !== NULL) {
- $pSheet = $pCell->getParent()->getParent()->getSheetByName($sheetName);
- } else {
- $pSheet = $pCell->getParent();
- }
-
- return Calculation::getInstance()->extractCellRange($cellAddress, $pSheet, False);
- } // function OFFSET()
-
-
- /**
- * CHOOSE
- *
- * Uses lookup_value to return a value from the list of value arguments.
- * Use CHOOSE to select one of up to 254 values based on the lookup_value.
- *
- * Excel Function:
- * =CHOOSE(index_num, value1, [value2], ...)
- *
- * @param index_num Specifies which value argument is selected.
- * Index_num must be a number between 1 and 254, or a formula or reference to a cell containing a number
- * between 1 and 254.
- * @param value1... Value1 is required, subsequent values are optional.
- * Between 1 to 254 value arguments from which CHOOSE selects a value or an action to perform based on
- * index_num. The arguments can be numbers, cell references, defined names, formulas, functions, or
- * text.
- * @return mixed The selected value
- */
- public static function CHOOSE() {
- $chooseArgs = func_get_args();
- $chosenEntry = Calculation_Functions::flattenArray(array_shift($chooseArgs));
- $entryCount = count($chooseArgs) - 1;
-
- if(is_array($chosenEntry)) {
- $chosenEntry = array_shift($chosenEntry);
- }
- if ((is_numeric($chosenEntry)) && (!is_bool($chosenEntry))) {
- --$chosenEntry;
- } else {
- return Calculation_Functions::VALUE();
- }
- $chosenEntry = floor($chosenEntry);
- if (($chosenEntry <= 0) || ($chosenEntry > $entryCount)) {
- return Calculation_Functions::VALUE();
- }
-
- if (is_array($chooseArgs[$chosenEntry])) {
- return Calculation_Functions::flattenArray($chooseArgs[$chosenEntry]);
- } else {
- return $chooseArgs[$chosenEntry];
- }
- } // function CHOOSE()
-
-
- /**
- * MATCH
- *
- * The MATCH function searches for a specified item in a range of cells
- *
- * Excel Function:
- * =MATCH(lookup_value, lookup_array, [match_type])
- *
- * @param lookup_value The value that you want to match in lookup_array
- * @param lookup_array The range of cells being searched
- * @param match_type The number -1, 0, or 1. -1 means above, 0 means exact match, 1 means below. If match_type is 1 or -1, the list has to be ordered.
- * @return integer The relative position of the found item
- */
- public static function MATCH($lookup_value, $lookup_array, $match_type=1) {
- $lookup_array = Calculation_Functions::flattenArray($lookup_array);
- $lookup_value = Calculation_Functions::flattenSingleValue($lookup_value);
- $match_type = (is_null($match_type)) ? 1 : (int) Calculation_Functions::flattenSingleValue($match_type);
- // MATCH is not case sensitive
- $lookup_value = strtolower($lookup_value);
-
- // lookup_value type has to be number, text, or logical values
- if ((!is_numeric($lookup_value)) && (!is_string($lookup_value)) && (!is_bool($lookup_value))) {
- return Calculation_Functions::NA();
- }
-
- // match_type is 0, 1 or -1
- if (($match_type !== 0) && ($match_type !== -1) && ($match_type !== 1)) {
- return Calculation_Functions::NA();
- }
-
- // lookup_array should not be empty
- $lookupArraySize = count($lookup_array);
- if ($lookupArraySize <= 0) {
- return Calculation_Functions::NA();
- }
-
- // lookup_array should contain only number, text, or logical values, or empty (null) cells
- foreach($lookup_array as $i => $lookupArrayValue) {
- // check the type of the value
- if ((!is_numeric($lookupArrayValue)) && (!is_string($lookupArrayValue)) &&
- (!is_bool($lookupArrayValue)) && (!is_null($lookupArrayValue))) {
- return Calculation_Functions::NA();
- }
- // convert strings to lowercase for case-insensitive testing
- if (is_string($lookupArrayValue)) {
- $lookup_array[$i] = strtolower($lookupArrayValue);
- }
- if ((is_null($lookupArrayValue)) && (($match_type == 1) || ($match_type == -1))) {
- $lookup_array = array_slice($lookup_array,0,$i-1);
- }
- }
-
- // if match_type is 1 or -1, the list has to be ordered
- if ($match_type == 1) {
- asort($lookup_array);
- $keySet = array_keys($lookup_array);
- } elseif($match_type == -1) {
- arsort($lookup_array);
- $keySet = array_keys($lookup_array);
- }
-
- // **
- // find the match
- // **
- // loop on the cells
-// var_dump($lookup_array);
-// echo '
';
- foreach($lookup_array as $i => $lookupArrayValue) {
- if (($match_type == 0) && ($lookupArrayValue == $lookup_value)) {
- // exact match
- return ++$i;
- } elseif (($match_type == -1) && ($lookupArrayValue <= $lookup_value)) {
-// echo '$i = '.$i.' => ';
-// var_dump($lookupArrayValue);
-// echo '
';
-// echo 'Keyset = ';
-// var_dump($keySet);
-// echo '
';
- $i = array_search($i,$keySet);
-// echo '$i='.$i.'
';
- // if match_type is -1 <=> find the smallest value that is greater than or equal to lookup_value
- if ($i < 1){
- // 1st cell was allready smaller than the lookup_value
- break;
- } else {
- // the previous cell was the match
- return $keySet[$i-1]+1;
- }
- } elseif (($match_type == 1) && ($lookupArrayValue >= $lookup_value)) {
-// echo '$i = '.$i.' => ';
-// var_dump($lookupArrayValue);
-// echo '
';
-// echo 'Keyset = ';
-// var_dump($keySet);
-// echo '
';
- $i = array_search($i,$keySet);
-// echo '$i='.$i.'
';
- // if match_type is 1 <=> find the largest value that is less than or equal to lookup_value
- if ($i < 1){
- // 1st cell was allready bigger than the lookup_value
- break;
- } else {
- // the previous cell was the match
- return $keySet[$i-1]+1;
- }
- }
- }
-
- // unsuccessful in finding a match, return #N/A error value
- return Calculation_Functions::NA();
- } // function MATCH()
-
-
- /**
- * INDEX
- *
- * Uses an index to choose a value from a reference or array
- *
- * Excel Function:
- * =INDEX(range_array, row_num, [column_num])
- *
- * @param range_array A range of cells or an array constant
- * @param row_num The row in array from which to return a value. If row_num is omitted, column_num is required.
- * @param column_num The column in array from which to return a value. If column_num is omitted, row_num is required.
- * @return mixed the value of a specified cell or array of cells
- */
- public static function INDEX($arrayValues,$rowNum = 0,$columnNum = 0) {
-
- if (($rowNum < 0) || ($columnNum < 0)) {
- return Calculation_Functions::VALUE();
- }
-
- if (!is_array($arrayValues)) {
- return Calculation_Functions::REF();
- }
-
- $rowKeys = array_keys($arrayValues);
- $columnKeys = @array_keys($arrayValues[$rowKeys[0]]);
-
- if ($columnNum > count($columnKeys)) {
- return Calculation_Functions::VALUE();
- } elseif ($columnNum == 0) {
- if ($rowNum == 0) {
- return $arrayValues;
- }
- $rowNum = $rowKeys[--$rowNum];
- $returnArray = array();
- foreach($arrayValues as $arrayColumn) {
- if (is_array($arrayColumn)) {
- if (isset($arrayColumn[$rowNum])) {
- $returnArray[] = $arrayColumn[$rowNum];
- } else {
- return $arrayValues[$rowNum];
- }
- } else {
- return $arrayValues[$rowNum];
- }
- }
- return $returnArray;
- }
- $columnNum = $columnKeys[--$columnNum];
- if ($rowNum > count($rowKeys)) {
- return Calculation_Functions::VALUE();
- } elseif ($rowNum == 0) {
- return $arrayValues[$columnNum];
- }
- $rowNum = $rowKeys[--$rowNum];
-
- return $arrayValues[$rowNum][$columnNum];
- } // function INDEX()
-
-
- /**
- * TRANSPOSE
- *
- * @param array $matrixData A matrix of values
- * @return array
- *
- * Unlike the Excel TRANSPOSE function, which will only work on a single row or column, this function will transpose a full matrix.
- */
- public static function TRANSPOSE($matrixData) {
- $returnMatrix = array();
- if (!is_array($matrixData)) { $matrixData = array(array($matrixData)); }
-
- $column = 0;
- foreach($matrixData as $matrixRow) {
- $row = 0;
- foreach($matrixRow as $matrixCell) {
- $returnMatrix[$row][$column] = $matrixCell;
- ++$row;
- }
- ++$column;
- }
- return $returnMatrix;
- } // function TRANSPOSE()
-
-
- private static function _vlookupSort($a,$b) {
- $f = array_keys($a);
- $firstColumn = array_shift($f);
- if (strtolower($a[$firstColumn]) == strtolower($b[$firstColumn])) {
- return 0;
- }
- return (strtolower($a[$firstColumn]) < strtolower($b[$firstColumn])) ? -1 : 1;
- } // function _vlookupSort()
-
-
- /**
- * VLOOKUP
- * The VLOOKUP function searches for value in the left-most column of lookup_array and returns the value in the same row based on the index_number.
- * @param lookup_value The value that you want to match in lookup_array
- * @param lookup_array The range of cells being searched
- * @param index_number The column number in table_array from which the matching value must be returned. The first column is 1.
- * @param not_exact_match Determines if you are looking for an exact match based on lookup_value.
- * @return mixed The value of the found cell
- */
- public static function VLOOKUP($lookup_value, $lookup_array, $index_number, $not_exact_match=true) {
- $lookup_value = Calculation_Functions::flattenSingleValue($lookup_value);
- $index_number = Calculation_Functions::flattenSingleValue($index_number);
- $not_exact_match = Calculation_Functions::flattenSingleValue($not_exact_match);
-
- // index_number must be greater than or equal to 1
- if ($index_number < 1) {
- return Calculation_Functions::VALUE();
- }
-
- // index_number must be less than or equal to the number of columns in lookup_array
- if ((!is_array($lookup_array)) || (empty($lookup_array))) {
- return Calculation_Functions::REF();
- } else {
- $f = array_keys($lookup_array);
- $firstRow = array_pop($f);
- if ((!is_array($lookup_array[$firstRow])) || ($index_number > count($lookup_array[$firstRow]))) {
- return Calculation_Functions::REF();
- } else {
- $columnKeys = array_keys($lookup_array[$firstRow]);
- $returnColumn = $columnKeys[--$index_number];
- $firstColumn = array_shift($columnKeys);
- }
- }
-
- if (!$not_exact_match) {
- uasort($lookup_array,array('self','_vlookupSort'));
- }
-
- $rowNumber = $rowValue = False;
- foreach($lookup_array as $rowKey => $rowData) {
- if ((is_numeric($lookup_value) && is_numeric($rowData[$firstColumn]) && ($rowData[$firstColumn] > $lookup_value)) ||
- (!is_numeric($lookup_value) && !is_numeric($rowData[$firstColumn]) && (strtolower($rowData[$firstColumn]) > strtolower($lookup_value)))) {
- break;
- }
- $rowNumber = $rowKey;
- $rowValue = $rowData[$firstColumn];
- }
-
- if ($rowNumber !== false) {
- if ((!$not_exact_match) && ($rowValue != $lookup_value)) {
- // if an exact match is required, we have what we need to return an appropriate response
- return Calculation_Functions::NA();
- } else {
- // otherwise return the appropriate value
- $result = $lookup_array[$rowNumber][$returnColumn];
- if ((is_numeric($lookup_value) && is_numeric($result)) ||
- (!is_numeric($lookup_value) && !is_numeric($result))) {
- return $result;
- }
- }
- }
-
- return Calculation_Functions::NA();
- } // function VLOOKUP()
+ /**
+ * CELL_ADDRESS
+ *
+ * Creates a cell address as text, given specified row and column numbers.
+ *
+ * Excel Function:
+ * =ADDRESS(row, column, [relativity], [referenceStyle], [sheetText])
+ *
+ * @param row Row number to use in the cell reference
+ * @param column Column number to use in the cell reference
+ * @param relativity Flag indicating the type of reference to return
+ * 1 or omitted Absolute
+ * 2 Absolute row; relative column
+ * 3 Relative row; absolute column
+ * 4 Relative
+ * @param referenceStyle A logical value that specifies the A1 or R1C1 reference style.
+ * TRUE or omitted CELL_ADDRESS returns an A1-style reference
+ * FALSE CELL_ADDRESS returns an R1C1-style reference
+ * @param sheetText Optional Name of worksheet to use
+ * @return string
+ */
+ public static function CELL_ADDRESS($row, $column, $relativity=1, $referenceStyle=True, $sheetText='') {
+ $row = Calculation_Functions::flattenSingleValue($row);
+ $column = Calculation_Functions::flattenSingleValue($column);
+ $relativity = Calculation_Functions::flattenSingleValue($relativity);
+ $sheetText = Calculation_Functions::flattenSingleValue($sheetText);
+
+ if (($row < 1) || ($column < 1)) {
+ return Calculation_Functions::VALUE();
+ }
+
+ if ($sheetText > '') {
+ if (strpos($sheetText,' ') !== False) { $sheetText = "'".$sheetText."'"; }
+ $sheetText .='!';
+ }
+ if ((!is_bool($referenceStyle)) || $referenceStyle) {
+ $rowRelative = $columnRelative = '$';
+ $column = Cell::stringFromColumnIndex($column-1);
+ if (($relativity == 2) || ($relativity == 4)) { $columnRelative = ''; }
+ if (($relativity == 3) || ($relativity == 4)) { $rowRelative = ''; }
+ return $sheetText.$columnRelative.$column.$rowRelative.$row;
+ } else {
+ if (($relativity == 2) || ($relativity == 4)) { $column = '['.$column.']'; }
+ if (($relativity == 3) || ($relativity == 4)) { $row = '['.$row.']'; }
+ return $sheetText.'R'.$row.'C'.$column;
+ }
+ } // function CELL_ADDRESS()
+
+
+ /**
+ * COLUMN
+ *
+ * Returns the column number of the given cell reference
+ * If the cell reference is a range of cells, COLUMN returns the column numbers of each column in the reference as a horizontal array.
+ * If cell reference is omitted, and the function is being called through the calculation engine, then it is assumed to be the
+ * reference of the cell in which the COLUMN function appears; otherwise this function returns 0.
+ *
+ * Excel Function:
+ * =COLUMN([cellAddress])
+ *
+ * @param cellAddress A reference to a range of cells for which you want the column numbers
+ * @return integer or array of integer
+ */
+ public static function COLUMN($cellAddress=Null) {
+ if (is_null($cellAddress) || trim($cellAddress) === '') { return 0; }
+
+ if (is_array($cellAddress)) {
+ foreach($cellAddress as $columnKey => $value) {
+ $columnKey = preg_replace('/[^a-z]/i','',$columnKey);
+ return (integer) Cell::columnIndexFromString($columnKey);
+ }
+ } else {
+ if (strpos($cellAddress,'!') !== false) {
+ list($sheet,$cellAddress) = explode('!',$cellAddress);
+ }
+ if (strpos($cellAddress,':') !== false) {
+ list($startAddress,$endAddress) = explode(':',$cellAddress);
+ $startAddress = preg_replace('/[^a-z]/i','',$startAddress);
+ $endAddress = preg_replace('/[^a-z]/i','',$endAddress);
+ $returnValue = array();
+ do {
+ $returnValue[] = (integer) Cell::columnIndexFromString($startAddress);
+ } while ($startAddress++ != $endAddress);
+ return $returnValue;
+ } else {
+ $cellAddress = preg_replace('/[^a-z]/i','',$cellAddress);
+ return (integer) Cell::columnIndexFromString($cellAddress);
+ }
+ }
+ } // function COLUMN()
+
+
+ /**
+ * COLUMNS
+ *
+ * Returns the number of columns in an array or reference.
+ *
+ * Excel Function:
+ * =COLUMNS(cellAddress)
+ *
+ * @param cellAddress An array or array formula, or a reference to a range of cells for which you want the number of columns
+ * @return integer The number of columns in cellAddress
+ */
+ public static function COLUMNS($cellAddress=Null) {
+ if (is_null($cellAddress) || $cellAddress === '') {
+ return 1;
+ } elseif (!is_array($cellAddress)) {
+ return Calculation_Functions::VALUE();
+ }
+
+ $x = array_keys($cellAddress);
+ $x = array_shift($x);
+ $isMatrix = (is_numeric($x));
+ list($columns,$rows) = Calculation::_getMatrixDimensions($cellAddress);
+
+ if ($isMatrix) {
+ return $rows;
+ } else {
+ return $columns;
+ }
+ } // function COLUMNS()
+
+
+ /**
+ * ROW
+ *
+ * Returns the row number of the given cell reference
+ * If the cell reference is a range of cells, ROW returns the row numbers of each row in the reference as a vertical array.
+ * If cell reference is omitted, and the function is being called through the calculation engine, then it is assumed to be the
+ * reference of the cell in which the ROW function appears; otherwise this function returns 0.
+ *
+ * Excel Function:
+ * =ROW([cellAddress])
+ *
+ * @param cellAddress A reference to a range of cells for which you want the row numbers
+ * @return integer or array of integer
+ */
+ public static function ROW($cellAddress=Null) {
+ if (is_null($cellAddress) || trim($cellAddress) === '') { return 0; }
+
+ if (is_array($cellAddress)) {
+ foreach($cellAddress as $columnKey => $rowValue) {
+ foreach($rowValue as $rowKey => $cellValue) {
+ return (integer) preg_replace('/[^0-9]/i','',$rowKey);
+ }
+ }
+ } else {
+ if (strpos($cellAddress,'!') !== false) {
+ list($sheet,$cellAddress) = explode('!',$cellAddress);
+ }
+ if (strpos($cellAddress,':') !== false) {
+ list($startAddress,$endAddress) = explode(':',$cellAddress);
+ $startAddress = preg_replace('/[^0-9]/','',$startAddress);
+ $endAddress = preg_replace('/[^0-9]/','',$endAddress);
+ $returnValue = array();
+ do {
+ $returnValue[][] = (integer) $startAddress;
+ } while ($startAddress++ != $endAddress);
+ return $returnValue;
+ } else {
+ list($cellAddress) = explode(':',$cellAddress);
+ return (integer) preg_replace('/[^0-9]/','',$cellAddress);
+ }
+ }
+ } // function ROW()
+
+
+ /**
+ * ROWS
+ *
+ * Returns the number of rows in an array or reference.
+ *
+ * Excel Function:
+ * =ROWS(cellAddress)
+ *
+ * @param cellAddress An array or array formula, or a reference to a range of cells for which you want the number of rows
+ * @return integer The number of rows in cellAddress
+ */
+ public static function ROWS($cellAddress=Null) {
+ if (is_null($cellAddress) || $cellAddress === '') {
+ return 1;
+ } elseif (!is_array($cellAddress)) {
+ return Calculation_Functions::VALUE();
+ }
+
+ $i = array_keys($cellAddress);
+ $isMatrix = (is_numeric(array_shift($i)));
+ list($columns,$rows) = Calculation::_getMatrixDimensions($cellAddress);
+
+ if ($isMatrix) {
+ return $columns;
+ } else {
+ return $rows;
+ }
+ } // function ROWS()
+
+
+ /**
+ * HYPERLINK
+ *
+ * Excel Function:
+ * =HYPERLINK(linkURL,displayName)
+ *
+ * @access public
+ * @category Logical Functions
+ * @param string $linkURL Value to check, is also the value returned when no error
+ * @param string $displayName Value to return when testValue is an error condition
+ * @param PHPExcel\Cell $pCell The cell to set the hyperlink in
+ * @return mixed The value of $displayName (or $linkURL if $displayName was blank)
+ */
+ public static function HYPERLINK($linkURL = '', $displayName = null, Cell $pCell = null) {
+ $args = func_get_args();
+ $pCell = array_pop($args);
+
+ $linkURL = (is_null($linkURL)) ? '' : Calculation_Functions::flattenSingleValue($linkURL);
+ $displayName = (is_null($displayName)) ? '' : Calculation_Functions::flattenSingleValue($displayName);
+
+ if ((!is_object($pCell)) || (trim($linkURL) == '')) {
+ return Calculation_Functions::REF();
+ }
+
+ if ((is_object($displayName)) || trim($displayName) == '') {
+ $displayName = $linkURL;
+ }
+
+ $pCell->getHyperlink()->setUrl($linkURL);
+
+ return $displayName;
+ } // function HYPERLINK()
+
+
+ /**
+ * INDIRECT
+ *
+ * Returns the reference specified by a text string.
+ * References are immediately evaluated to display their contents.
+ *
+ * Excel Function:
+ * =INDIRECT(cellAddress)
+ *
+ * NOTE - INDIRECT() does not yet support the optional a1 parameter introduced in Excel 2010
+ *
+ * @param cellAddress $cellAddress The cell address of the current cell (containing this formula)
+ * @param PHPExcel\Cell $pCell The current cell (containing this formula)
+ * @return mixed The cells referenced by cellAddress
+ *
+ * @todo Support for the optional a1 parameter introduced in Excel 2010
+ *
+ */
+ public static function INDIRECT($cellAddress = null, Cell $pCell = null) {
+ $cellAddress = Calculation_Functions::flattenSingleValue($cellAddress);
+ if (is_null($cellAddress) || $cellAddress === '') {
+ return Calculation_Functions::REF();
+ }
+
+ $cellAddress1 = $cellAddress;
+ $cellAddress2 = null;
+ if (strpos($cellAddress,':') !== false) {
+ list($cellAddress1,$cellAddress2) = explode(':',$cellAddress);
+ }
+
+ if ((!preg_match('/^'.Calculation::CALCULATION_REGEXP_CELLREF.'$/i', $cellAddress1, $matches)) ||
+ ((!is_null($cellAddress2)) && (!preg_match('/^'.Calculation::CALCULATION_REGEXP_CELLREF.'$/i', $cellAddress2, $matches)))) {
+ if (!preg_match('/^'.Calculation::CALCULATION_REGEXP_NAMEDRANGE.'$/i', $cellAddress1, $matches)) {
+ return Calculation_Functions::REF();
+ }
+
+ if (strpos($cellAddress,'!') !== false) {
+ list($sheetName, $cellAddress) = explode('!',$cellAddress);
+ $sheetName = trim($sheetName, "'");
+ $pSheet = $pCell->getParent()->getParent()->getSheetByName($sheetName);
+ } else {
+ $pSheet = $pCell->getParent();
+ }
+
+ return Calculation::getInstance()->extractNamedRange($cellAddress, $pSheet, false);
+ }
+
+ if (strpos($cellAddress,'!') !== false) {
+ list($sheetName,$cellAddress) = explode('!',$cellAddress);
+ $sheetName = trim($sheetName, "'");
+ $pSheet = $pCell->getParent()->getParent()->getSheetByName($sheetName);
+ } else {
+ $pSheet = $pCell->getParent();
+ }
+
+ return Calculation::getInstance()->extractCellRange($cellAddress, $pSheet, false);
+ } // function INDIRECT()
+
+
+ /**
+ * OFFSET
+ *
+ * Returns a reference to a range that is a specified number of rows and columns from a cell or range of cells.
+ * The reference that is returned can be a single cell or a range of cells. You can specify the number of rows and
+ * the number of columns to be returned.
+ *
+ * Excel Function:
+ * =OFFSET(cellAddress, rows, cols, [height], [width])
+ *
+ * @param cellAddress The reference from which you want to base the offset. Reference must refer to a cell or
+ * range of adjacent cells; otherwise, OFFSET returns the #VALUE! error value.
+ * @param rows The number of rows, up or down, that you want the upper-left cell to refer to.
+ * Using 5 as the rows argument specifies that the upper-left cell in the reference is
+ * five rows below reference. Rows can be positive (which means below the starting reference)
+ * or negative (which means above the starting reference).
+ * @param cols The number of columns, to the left or right, that you want the upper-left cell of the result
+ * to refer to. Using 5 as the cols argument specifies that the upper-left cell in the
+ * reference is five columns to the right of reference. Cols can be positive (which means
+ * to the right of the starting reference) or negative (which means to the left of the
+ * starting reference).
+ * @param height The height, in number of rows, that you want the returned reference to be. Height must be a positive number.
+ * @param width The width, in number of columns, that you want the returned reference to be. Width must be a positive number.
+ * @return string A reference to a cell or range of cells
+ */
+ public static function OFFSET($cellAddress=Null,$rows=0,$columns=0,$height=null,$width=null) {
+ $rows = Calculation_Functions::flattenSingleValue($rows);
+ $columns = Calculation_Functions::flattenSingleValue($columns);
+ $height = Calculation_Functions::flattenSingleValue($height);
+ $width = Calculation_Functions::flattenSingleValue($width);
+ if ($cellAddress == Null) {
+ return 0;
+ }
+
+ $args = func_get_args();
+ $pCell = array_pop($args);
+ if (!is_object($pCell)) {
+ return Calculation_Functions::REF();
+ }
+
+ $sheetName = null;
+ if (strpos($cellAddress,"!")) {
+ list($sheetName,$cellAddress) = explode("!",$cellAddress);
+ $sheetName = trim($sheetName, "'");
+ }
+ if (strpos($cellAddress,":")) {
+ list($startCell,$endCell) = explode(":",$cellAddress);
+ } else {
+ $startCell = $endCell = $cellAddress;
+ }
+ list($startCellColumn,$startCellRow) = Cell::coordinateFromString($startCell);
+ list($endCellColumn,$endCellRow) = Cell::coordinateFromString($endCell);
+
+ $startCellRow += $rows;
+ $startCellColumn = Cell::columnIndexFromString($startCellColumn) - 1;
+ $startCellColumn += $columns;
+
+ if (($startCellRow <= 0) || ($startCellColumn < 0)) {
+ return Calculation_Functions::REF();
+ }
+ $endCellColumn = Cell::columnIndexFromString($endCellColumn) - 1;
+ if (($width != null) && (!is_object($width))) {
+ $endCellColumn = $startCellColumn + $width - 1;
+ } else {
+ $endCellColumn += $columns;
+ }
+ $startCellColumn = Cell::stringFromColumnIndex($startCellColumn);
+
+ if (($height != null) && (!is_object($height))) {
+ $endCellRow = $startCellRow + $height - 1;
+ } else {
+ $endCellRow += $rows;
+ }
+
+ if (($endCellRow <= 0) || ($endCellColumn < 0)) {
+ return Calculation_Functions::REF();
+ }
+ $endCellColumn = Cell::stringFromColumnIndex($endCellColumn);
+
+ $cellAddress = $startCellColumn.$startCellRow;
+ if (($startCellColumn != $endCellColumn) || ($startCellRow != $endCellRow)) {
+ $cellAddress .= ':'.$endCellColumn.$endCellRow;
+ }
+
+ if ($sheetName !== null) {
+ $pSheet = $pCell->getParent()->getParent()->getSheetByName($sheetName);
+ } else {
+ $pSheet = $pCell->getParent();
+ }
+
+ return Calculation::getInstance()->extractCellRange($cellAddress, $pSheet, False);
+ } // function OFFSET()
+
+
+ /**
+ * CHOOSE
+ *
+ * Uses lookup_value to return a value from the list of value arguments.
+ * Use CHOOSE to select one of up to 254 values based on the lookup_value.
+ *
+ * Excel Function:
+ * =CHOOSE(index_num, value1, [value2], ...)
+ *
+ * @param index_num Specifies which value argument is selected.
+ * Index_num must be a number between 1 and 254, or a formula or reference to a cell containing a number
+ * between 1 and 254.
+ * @param value1... Value1 is required, subsequent values are optional.
+ * Between 1 to 254 value arguments from which CHOOSE selects a value or an action to perform based on
+ * index_num. The arguments can be numbers, cell references, defined names, formulas, functions, or
+ * text.
+ * @return mixed The selected value
+ */
+ public static function CHOOSE() {
+ $chooseArgs = func_get_args();
+ $chosenEntry = Calculation_Functions::flattenArray(array_shift($chooseArgs));
+ $entryCount = count($chooseArgs) - 1;
+
+ if(is_array($chosenEntry)) {
+ $chosenEntry = array_shift($chosenEntry);
+ }
+ if ((is_numeric($chosenEntry)) && (!is_bool($chosenEntry))) {
+ --$chosenEntry;
+ } else {
+ return Calculation_Functions::VALUE();
+ }
+ $chosenEntry = floor($chosenEntry);
+ if (($chosenEntry <= 0) || ($chosenEntry > $entryCount)) {
+ return Calculation_Functions::VALUE();
+ }
+
+ if (is_array($chooseArgs[$chosenEntry])) {
+ return Calculation_Functions::flattenArray($chooseArgs[$chosenEntry]);
+ } else {
+ return $chooseArgs[$chosenEntry];
+ }
+ } // function CHOOSE()
+
+
+ /**
+ * MATCH
+ *
+ * The MATCH function searches for a specified item in a range of cells
+ *
+ * Excel Function:
+ * =MATCH(lookup_value, lookup_array, [match_type])
+ *
+ * @param lookup_value The value that you want to match in lookup_array
+ * @param lookup_array The range of cells being searched
+ * @param match_type The number -1, 0, or 1. -1 means above, 0 means exact match, 1 means below. If match_type is 1 or -1, the list has to be ordered.
+ * @return integer The relative position of the found item
+ */
+ public static function MATCH($lookup_value, $lookup_array, $match_type=1) {
+ $lookup_array = Calculation_Functions::flattenArray($lookup_array);
+ $lookup_value = Calculation_Functions::flattenSingleValue($lookup_value);
+ $match_type = (is_null($match_type)) ? 1 : (int) Calculation_Functions::flattenSingleValue($match_type);
+ // MATCH is not case sensitive
+ $lookup_value = strtolower($lookup_value);
+
+ // lookup_value type has to be number, text, or logical values
+ if ((!is_numeric($lookup_value)) && (!is_string($lookup_value)) && (!is_bool($lookup_value))) {
+ return Calculation_Functions::NA();
+ }
+
+ // match_type is 0, 1 or -1
+ if (($match_type !== 0) && ($match_type !== -1) && ($match_type !== 1)) {
+ return Calculation_Functions::NA();
+ }
+
+ // lookup_array should not be empty
+ $lookupArraySize = count($lookup_array);
+ if ($lookupArraySize <= 0) {
+ return Calculation_Functions::NA();
+ }
+
+ // lookup_array should contain only number, text, or logical values, or empty (null) cells
+ foreach($lookup_array as $i => $lookupArrayValue) {
+ // check the type of the value
+ if ((!is_numeric($lookupArrayValue)) && (!is_string($lookupArrayValue)) &&
+ (!is_bool($lookupArrayValue)) && (!is_null($lookupArrayValue))) {
+ return Calculation_Functions::NA();
+ }
+ // convert strings to lowercase for case-insensitive testing
+ if (is_string($lookupArrayValue)) {
+ $lookup_array[$i] = strtolower($lookupArrayValue);
+ }
+ if ((is_null($lookupArrayValue)) && (($match_type == 1) || ($match_type == -1))) {
+ $lookup_array = array_slice($lookup_array,0,$i-1);
+ }
+ }
+
+ // if match_type is 1 or -1, the list has to be ordered
+ if ($match_type == 1) {
+ asort($lookup_array);
+ $keySet = array_keys($lookup_array);
+ } elseif($match_type == -1) {
+ arsort($lookup_array);
+ $keySet = array_keys($lookup_array);
+ }
+
+ // **
+ // find the match
+ // **
+ // loop on the cells
+// var_dump($lookup_array);
+// echo '
';
+ foreach($lookup_array as $i => $lookupArrayValue) {
+ if (($match_type == 0) && ($lookupArrayValue == $lookup_value)) {
+ // exact match
+ return ++$i;
+ } elseif (($match_type == -1) && ($lookupArrayValue <= $lookup_value)) {
+// echo '$i = '.$i.' => ';
+// var_dump($lookupArrayValue);
+// echo '
';
+// echo 'Keyset = ';
+// var_dump($keySet);
+// echo '
';
+ $i = array_search($i,$keySet);
+// echo '$i='.$i.'
';
+ // if match_type is -1 <=> find the smallest value that is greater than or equal to lookup_value
+ if ($i < 1){
+ // 1st cell was allready smaller than the lookup_value
+ break;
+ } else {
+ // the previous cell was the match
+ return $keySet[$i-1]+1;
+ }
+ } elseif (($match_type == 1) && ($lookupArrayValue >= $lookup_value)) {
+// echo '$i = '.$i.' => ';
+// var_dump($lookupArrayValue);
+// echo '
';
+// echo 'Keyset = ';
+// var_dump($keySet);
+// echo '
';
+ $i = array_search($i,$keySet);
+// echo '$i='.$i.'
';
+ // if match_type is 1 <=> find the largest value that is less than or equal to lookup_value
+ if ($i < 1){
+ // 1st cell was allready bigger than the lookup_value
+ break;
+ } else {
+ // the previous cell was the match
+ return $keySet[$i-1]+1;
+ }
+ }
+ }
+
+ // unsuccessful in finding a match, return #N/A error value
+ return Calculation_Functions::NA();
+ } // function MATCH()
+
+
+ /**
+ * INDEX
+ *
+ * Uses an index to choose a value from a reference or array
+ *
+ * Excel Function:
+ * =INDEX(range_array, row_num, [column_num])
+ *
+ * @param range_array A range of cells or an array constant
+ * @param row_num The row in array from which to return a value. If row_num is omitted, column_num is required.
+ * @param column_num The column in array from which to return a value. If column_num is omitted, row_num is required.
+ * @return mixed the value of a specified cell or array of cells
+ */
+ public static function INDEX($arrayValues,$rowNum = 0,$columnNum = 0) {
+
+ if (($rowNum < 0) || ($columnNum < 0)) {
+ return Calculation_Functions::VALUE();
+ }
+
+ if (!is_array($arrayValues)) {
+ return Calculation_Functions::REF();
+ }
+
+ $rowKeys = array_keys($arrayValues);
+ $columnKeys = @array_keys($arrayValues[$rowKeys[0]]);
+
+ if ($columnNum > count($columnKeys)) {
+ return Calculation_Functions::VALUE();
+ } elseif ($columnNum == 0) {
+ if ($rowNum == 0) {
+ return $arrayValues;
+ }
+ $rowNum = $rowKeys[--$rowNum];
+ $returnArray = array();
+ foreach($arrayValues as $arrayColumn) {
+ if (is_array($arrayColumn)) {
+ if (isset($arrayColumn[$rowNum])) {
+ $returnArray[] = $arrayColumn[$rowNum];
+ } else {
+ return $arrayValues[$rowNum];
+ }
+ } else {
+ return $arrayValues[$rowNum];
+ }
+ }
+ return $returnArray;
+ }
+ $columnNum = $columnKeys[--$columnNum];
+ if ($rowNum > count($rowKeys)) {
+ return Calculation_Functions::VALUE();
+ } elseif ($rowNum == 0) {
+ return $arrayValues[$columnNum];
+ }
+ $rowNum = $rowKeys[--$rowNum];
+
+ return $arrayValues[$rowNum][$columnNum];
+ } // function INDEX()
+
+
+ /**
+ * TRANSPOSE
+ *
+ * @param array $matrixData A matrix of values
+ * @return array
+ *
+ * Unlike the Excel TRANSPOSE function, which will only work on a single row or column, this function will transpose a full matrix.
+ */
+ public static function TRANSPOSE($matrixData) {
+ $returnMatrix = array();
+ if (!is_array($matrixData)) { $matrixData = array(array($matrixData)); }
+
+ $column = 0;
+ foreach($matrixData as $matrixRow) {
+ $row = 0;
+ foreach($matrixRow as $matrixCell) {
+ $returnMatrix[$row][$column] = $matrixCell;
+ ++$row;
+ }
+ ++$column;
+ }
+ return $returnMatrix;
+ } // function TRANSPOSE()
+
+
+ private static function _vlookupSort($a,$b) {
+ $f = array_keys($a);
+ $firstColumn = array_shift($f);
+ if (strtolower($a[$firstColumn]) == strtolower($b[$firstColumn])) {
+ return 0;
+ }
+ return (strtolower($a[$firstColumn]) < strtolower($b[$firstColumn])) ? -1 : 1;
+ } // function _vlookupSort()
+
+
+ /**
+ * VLOOKUP
+ * The VLOOKUP function searches for value in the left-most column of lookup_array and returns the value in the same row based on the index_number.
+ * @param lookup_value The value that you want to match in lookup_array
+ * @param lookup_array The range of cells being searched
+ * @param index_number The column number in table_array from which the matching value must be returned. The first column is 1.
+ * @param not_exact_match Determines if you are looking for an exact match based on lookup_value.
+ * @return mixed The value of the found cell
+ */
+ public static function VLOOKUP($lookup_value, $lookup_array, $index_number, $not_exact_match=true) {
+ $lookup_value = Calculation_Functions::flattenSingleValue($lookup_value);
+ $index_number = Calculation_Functions::flattenSingleValue($index_number);
+ $not_exact_match = Calculation_Functions::flattenSingleValue($not_exact_match);
+
+ // index_number must be greater than or equal to 1
+ if ($index_number < 1) {
+ return Calculation_Functions::VALUE();
+ }
+
+ // index_number must be less than or equal to the number of columns in lookup_array
+ if ((!is_array($lookup_array)) || (empty($lookup_array))) {
+ return Calculation_Functions::REF();
+ } else {
+ $f = array_keys($lookup_array);
+ $firstRow = array_pop($f);
+ if ((!is_array($lookup_array[$firstRow])) || ($index_number > count($lookup_array[$firstRow]))) {
+ return Calculation_Functions::REF();
+ } else {
+ $columnKeys = array_keys($lookup_array[$firstRow]);
+ $returnColumn = $columnKeys[--$index_number];
+ $firstColumn = array_shift($columnKeys);
+ }
+ }
+
+ if (!$not_exact_match) {
+ uasort($lookup_array,array('self','_vlookupSort'));
+ }
+
+ $rowNumber = $rowValue = False;
+ foreach($lookup_array as $rowKey => $rowData) {
+ if ((is_numeric($lookup_value) && is_numeric($rowData[$firstColumn]) && ($rowData[$firstColumn] > $lookup_value)) ||
+ (!is_numeric($lookup_value) && !is_numeric($rowData[$firstColumn]) && (strtolower($rowData[$firstColumn]) > strtolower($lookup_value)))) {
+ break;
+ }
+ $rowNumber = $rowKey;
+ $rowValue = $rowData[$firstColumn];
+ }
+
+ if ($rowNumber !== false) {
+ if ((!$not_exact_match) && ($rowValue != $lookup_value)) {
+ // if an exact match is required, we have what we need to return an appropriate response
+ return Calculation_Functions::NA();
+ } else {
+ // otherwise return the appropriate value
+ $result = $lookup_array[$rowNumber][$returnColumn];
+ if ((is_numeric($lookup_value) && is_numeric($result)) ||
+ (!is_numeric($lookup_value) && !is_numeric($result))) {
+ return $result;
+ }
+ }
+ }
+
+ return Calculation_Functions::NA();
+ } // function VLOOKUP()
/**
@@ -779,8 +779,8 @@ class Calculation_LookupRef {
$rowNumber = $rowValue = False;
foreach($lookup_array[$firstColumn] as $rowKey => $rowData) {
- if ((is_numeric($lookup_value) && is_numeric($rowData) && ($rowData > $lookup_value)) ||
- (!is_numeric($lookup_value) && !is_numeric($rowData) && (strtolower($rowData) > strtolower($lookup_value)))) {
+ if ((is_numeric($lookup_value) && is_numeric($rowData) && ($rowData > $lookup_value)) ||
+ (!is_numeric($lookup_value) && !is_numeric($rowData) && (strtolower($rowData) > strtolower($lookup_value)))) {
break;
}
$rowNumber = $rowKey;
@@ -794,7 +794,7 @@ class Calculation_LookupRef {
} else {
// otherwise return the appropriate value
$result = $lookup_array[$returnColumn][$rowNumber];
- return $result;
+ return $result;
}
}
@@ -802,71 +802,70 @@ class Calculation_LookupRef {
} // function HLOOKUP()
- /**
- * LOOKUP
- * The LOOKUP function searches for value either from a one-row or one-column range or from an array.
- * @param lookup_value The value that you want to match in lookup_array
- * @param lookup_vector The range of cells being searched
- * @param result_vector The column from which the matching value must be returned
- * @return mixed The value of the found cell
- */
- public static function LOOKUP($lookup_value, $lookup_vector, $result_vector=null) {
- $lookup_value = Calculation_Functions::flattenSingleValue($lookup_value);
+ /**
+ * LOOKUP
+ * The LOOKUP function searches for value either from a one-row or one-column range or from an array.
+ * @param lookup_value The value that you want to match in lookup_array
+ * @param lookup_vector The range of cells being searched
+ * @param result_vector The column from which the matching value must be returned
+ * @return mixed The value of the found cell
+ */
+ public static function LOOKUP($lookup_value, $lookup_vector, $result_vector=null) {
+ $lookup_value = Calculation_Functions::flattenSingleValue($lookup_value);
- if (!is_array($lookup_vector)) {
- return Calculation_Functions::NA();
- }
- $lookupRows = count($lookup_vector);
- $l = array_keys($lookup_vector);
- $l = array_shift($l);
- $lookupColumns = count($lookup_vector[$l]);
- if ((($lookupRows == 1) && ($lookupColumns > 1)) || (($lookupRows == 2) && ($lookupColumns != 2))) {
- $lookup_vector = self::TRANSPOSE($lookup_vector);
- $lookupRows = count($lookup_vector);
- $l = array_keys($lookup_vector);
- $lookupColumns = count($lookup_vector[array_shift($l)]);
- }
+ if (!is_array($lookup_vector)) {
+ return Calculation_Functions::NA();
+ }
+ $lookupRows = count($lookup_vector);
+ $l = array_keys($lookup_vector);
+ $l = array_shift($l);
+ $lookupColumns = count($lookup_vector[$l]);
+ if ((($lookupRows == 1) && ($lookupColumns > 1)) || (($lookupRows == 2) && ($lookupColumns != 2))) {
+ $lookup_vector = self::TRANSPOSE($lookup_vector);
+ $lookupRows = count($lookup_vector);
+ $l = array_keys($lookup_vector);
+ $lookupColumns = count($lookup_vector[array_shift($l)]);
+ }
- if (is_null($result_vector)) {
- $result_vector = $lookup_vector;
- }
- $resultRows = count($result_vector);
- $l = array_keys($result_vector);
- $l = array_shift($l);
- $resultColumns = count($result_vector[$l]);
- if ((($resultRows == 1) && ($resultColumns > 1)) || (($resultRows == 2) && ($resultColumns != 2))) {
- $result_vector = self::TRANSPOSE($result_vector);
- $resultRows = count($result_vector);
- $r = array_keys($result_vector);
- $resultColumns = count($result_vector[array_shift($r)]);
- }
+ if (is_null($result_vector)) {
+ $result_vector = $lookup_vector;
+ }
+ $resultRows = count($result_vector);
+ $l = array_keys($result_vector);
+ $l = array_shift($l);
+ $resultColumns = count($result_vector[$l]);
+ if ((($resultRows == 1) && ($resultColumns > 1)) || (($resultRows == 2) && ($resultColumns != 2))) {
+ $result_vector = self::TRANSPOSE($result_vector);
+ $resultRows = count($result_vector);
+ $r = array_keys($result_vector);
+ $resultColumns = count($result_vector[array_shift($r)]);
+ }
- if ($lookupRows == 2) {
- $result_vector = array_pop($lookup_vector);
- $lookup_vector = array_shift($lookup_vector);
- }
- if ($lookupColumns != 2) {
- foreach($lookup_vector as &$value) {
- if (is_array($value)) {
- $k = array_keys($value);
- $key1 = $key2 = array_shift($k);
- $key2++;
- $dataValue1 = $value[$key1];
- } else {
- $key1 = 0;
- $key2 = 1;
- $dataValue1 = $value;
- }
- $dataValue2 = array_shift($result_vector);
- if (is_array($dataValue2)) {
- $dataValue2 = array_shift($dataValue2);
- }
- $value = array($key1 => $dataValue1, $key2 => $dataValue2);
- }
- unset($value);
- }
-
- return self::VLOOKUP($lookup_value,$lookup_vector,2);
- } // function LOOKUP()
+ if ($lookupRows == 2) {
+ $result_vector = array_pop($lookup_vector);
+ $lookup_vector = array_shift($lookup_vector);
+ }
+ if ($lookupColumns != 2) {
+ foreach($lookup_vector as &$value) {
+ if (is_array($value)) {
+ $k = array_keys($value);
+ $key1 = $key2 = array_shift($k);
+ $key2++;
+ $dataValue1 = $value[$key1];
+ } else {
+ $key1 = 0;
+ $key2 = 1;
+ $dataValue1 = $value;
+ }
+ $dataValue2 = array_shift($result_vector);
+ if (is_array($dataValue2)) {
+ $dataValue2 = array_shift($dataValue2);
+ }
+ $value = array($key1 => $dataValue1, $key2 => $dataValue2);
+ }
+ unset($value);
+ }
+ return self::VLOOKUP($lookup_value,$lookup_vector,2);
+ } // function LOOKUP()
}
diff --git a/Classes/PHPExcel/Calculation/MathTrig.php b/Classes/PHPExcel/Calculation/MathTrig.php
index 06c07ad..8e2843f 100644
--- a/Classes/PHPExcel/Calculation/MathTrig.php
+++ b/Classes/PHPExcel/Calculation/MathTrig.php
@@ -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,1331 +31,1330 @@ namespace PHPExcel;
/**
* PHPExcel\Calculation_MathTrig
*
- * @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_MathTrig {
- //
- // Private method to return an array of the factors of the input value
- //
- private static function _factors($value) {
- $startVal = floor(sqrt($value));
-
- $factorArray = array();
- for ($i = $startVal; $i > 1; --$i) {
- if (($value % $i) == 0) {
- $factorArray = array_merge($factorArray,self::_factors($value / $i));
- $factorArray = array_merge($factorArray,self::_factors($i));
- if ($i <= sqrt($value)) {
- break;
- }
- }
- }
- if (!empty($factorArray)) {
- rsort($factorArray);
- return $factorArray;
- } else {
- return array((integer) $value);
- }
- } // function _factors()
-
-
- private static function _romanCut($num, $n) {
- return ($num - ($num % $n ) ) / $n;
- } // function _romanCut()
-
-
- /**
- * ATAN2
- *
- * This function calculates the arc tangent of the two variables x and y. It is similar to
- * calculating the arc tangent of y ÷ x, except that the signs of both arguments are used
- * to determine the quadrant of the result.
- * The arctangent is the angle from the x-axis to a line containing the origin (0, 0) and a
- * point with coordinates (xCoordinate, yCoordinate). The angle is given in radians between
- * -pi and pi, excluding -pi.
- *
- * Note that the Excel ATAN2() function accepts its arguments in the reverse order to the standard
- * PHP atan2() function, so we need to reverse them here before calling the PHP atan() function.
- *
- * Excel Function:
- * ATAN2(xCoordinate,yCoordinate)
- *
- * @access public
- * @category Mathematical and Trigonometric Functions
- * @param float $xCoordinate The x-coordinate of the point.
- * @param float $yCoordinate The y-coordinate of the point.
- * @return float The inverse tangent of the specified x- and y-coordinates.
- */
- public static function ATAN2($xCoordinate = NULL, $yCoordinate = NULL) {
- $xCoordinate = Calculation_Functions::flattenSingleValue($xCoordinate);
- $yCoordinate = Calculation_Functions::flattenSingleValue($yCoordinate);
-
- $xCoordinate = ($xCoordinate !== NULL) ? $xCoordinate : 0.0;
- $yCoordinate = ($yCoordinate !== NULL) ? $yCoordinate : 0.0;
-
- if (((is_numeric($xCoordinate)) || (is_bool($xCoordinate))) &&
- ((is_numeric($yCoordinate))) || (is_bool($yCoordinate))) {
- $xCoordinate = (float) $xCoordinate;
- $yCoordinate = (float) $yCoordinate;
-
- if (($xCoordinate == 0) && ($yCoordinate == 0)) {
- return Calculation_Functions::DIV0();
- }
-
- return atan2($yCoordinate, $xCoordinate);
- }
- return Calculation_Functions::VALUE();
- } // function ATAN2()
-
-
- /**
- * CEILING
- *
- * Returns number rounded up, away from zero, to the nearest multiple of significance.
- * For example, if you want to avoid using pennies in your prices and your product is
- * priced at $4.42, use the formula =CEILING(4.42,0.05) to round prices up to the
- * nearest nickel.
- *
- * Excel Function:
- * CEILING(number[,significance])
- *
- * @access public
- * @category Mathematical and Trigonometric Functions
- * @param float $number The number you want to round.
- * @param float $significance The multiple to which you want to round.
- * @return float Rounded Number
- */
- public static function CEILING($number, $significance = NULL) {
- $number = Calculation_Functions::flattenSingleValue($number);
- $significance = Calculation_Functions::flattenSingleValue($significance);
-
- if ((is_null($significance)) &&
- (Calculation_Functions::getCompatibilityMode() == Calculation_Functions::COMPATIBILITY_GNUMERIC)) {
- $significance = $number/abs($number);
- }
-
- if ((is_numeric($number)) && (is_numeric($significance))) {
- if ($significance == 0.0) {
- return 0.0;
- } elseif (self::SIGN($number) == self::SIGN($significance)) {
- return ceil($number / $significance) * $significance;
- } else {
- return Calculation_Functions::NaN();
- }
- }
- return Calculation_Functions::VALUE();
- } // function CEILING()
-
-
- /**
- * COMBIN
- *
- * Returns the number of combinations for a given number of items. Use COMBIN to
- * determine the total possible number of groups for a given number of items.
- *
- * Excel Function:
- * COMBIN(numObjs,numInSet)
- *
- * @access public
- * @category Mathematical and Trigonometric Functions
- * @param int $numObjs Number of different objects
- * @param int $numInSet Number of objects in each combination
- * @return int Number of combinations
- */
- public static function COMBIN($numObjs, $numInSet) {
- $numObjs = Calculation_Functions::flattenSingleValue($numObjs);
- $numInSet = Calculation_Functions::flattenSingleValue($numInSet);
-
- if ((is_numeric($numObjs)) && (is_numeric($numInSet))) {
- if ($numObjs < $numInSet) {
- return Calculation_Functions::NaN();
- } elseif ($numInSet < 0) {
- return Calculation_Functions::NaN();
- }
- return round(self::FACT($numObjs) / self::FACT($numObjs - $numInSet)) / self::FACT($numInSet);
- }
- return Calculation_Functions::VALUE();
- } // function COMBIN()
-
-
- /**
- * EVEN
- *
- * Returns number rounded up to the nearest even integer.
- * You can use this function for processing items that come in twos. For example,
- * a packing crate accepts rows of one or two items. The crate is full when
- * the number of items, rounded up to the nearest two, matches the crate's
- * capacity.
- *
- * Excel Function:
- * EVEN(number)
- *
- * @access public
- * @category Mathematical and Trigonometric Functions
- * @param float $number Number to round
- * @return int Rounded Number
- */
- public static function EVEN($number) {
- $number = Calculation_Functions::flattenSingleValue($number);
-
- if (is_null($number)) {
- return 0;
- } elseif (is_bool($number)) {
- $number = (int) $number;
- }
-
- if (is_numeric($number)) {
- $significance = 2 * self::SIGN($number);
- return (int) self::CEILING($number,$significance);
- }
- return Calculation_Functions::VALUE();
- } // function EVEN()
-
-
- /**
- * FACT
- *
- * Returns the factorial of a number.
- * The factorial of a number is equal to 1*2*3*...* number.
- *
- * Excel Function:
- * FACT(factVal)
- *
- * @access public
- * @category Mathematical and Trigonometric Functions
- * @param float $factVal Factorial Value
- * @return int Factorial
- */
- public static function FACT($factVal) {
- $factVal = Calculation_Functions::flattenSingleValue($factVal);
-
- if (is_numeric($factVal)) {
- if ($factVal < 0) {
- return Calculation_Functions::NaN();
- }
- $factLoop = floor($factVal);
- if (Calculation_Functions::getCompatibilityMode() == Calculation_Functions::COMPATIBILITY_GNUMERIC) {
- if ($factVal > $factLoop) {
- return Calculation_Functions::NaN();
- }
- }
-
- $factorial = 1;
- while ($factLoop > 1) {
- $factorial *= $factLoop--;
- }
- return $factorial ;
- }
- return Calculation_Functions::VALUE();
- } // function FACT()
-
-
- /**
- * FACTDOUBLE
- *
- * Returns the double factorial of a number.
- *
- * Excel Function:
- * FACTDOUBLE(factVal)
- *
- * @access public
- * @category Mathematical and Trigonometric Functions
- * @param float $factVal Factorial Value
- * @return int Double Factorial
- */
- public static function FACTDOUBLE($factVal) {
- $factLoop = Calculation_Functions::flattenSingleValue($factVal);
-
- if (is_numeric($factLoop)) {
- $factLoop = floor($factLoop);
- if ($factVal < 0) {
- return Calculation_Functions::NaN();
- }
- $factorial = 1;
- while ($factLoop > 1) {
- $factorial *= $factLoop--;
- --$factLoop;
- }
- return $factorial ;
- }
- return Calculation_Functions::VALUE();
- } // function FACTDOUBLE()
-
-
- /**
- * FLOOR
- *
- * Rounds number down, toward zero, to the nearest multiple of significance.
- *
- * Excel Function:
- * FLOOR(number[,significance])
- *
- * @access public
- * @category Mathematical and Trigonometric Functions
- * @param float $number Number to round
- * @param float $significance Significance
- * @return float Rounded Number
- */
- public static function FLOOR($number, $significance = NULL) {
- $number = Calculation_Functions::flattenSingleValue($number);
- $significance = Calculation_Functions::flattenSingleValue($significance);
-
- if ((is_null($significance)) && (Calculation_Functions::getCompatibilityMode() == Calculation_Functions::COMPATIBILITY_GNUMERIC)) {
- $significance = $number/abs($number);
- }
-
- if ((is_numeric($number)) && (is_numeric($significance))) {
- if ((float) $significance == 0.0) {
- return Calculation_Functions::DIV0();
- }
- if (self::SIGN($number) == self::SIGN($significance)) {
- return floor($number / $significance) * $significance;
- } else {
- return Calculation_Functions::NaN();
- }
- }
- return Calculation_Functions::VALUE();
- } // function FLOOR()
-
-
- /**
- * GCD
- *
- * Returns the greatest common divisor of a series of numbers.
- * The greatest common divisor is the largest integer that divides both
- * number1 and number2 without a remainder.
- *
- * Excel Function:
- * GCD(number1[,number2[, ...]])
- *
- * @access public
- * @category Mathematical and Trigonometric Functions
- * @param mixed $arg,... Data values
- * @return integer Greatest Common Divisor
- */
- public static function GCD() {
- $returnValue = 1;
- $allValuesFactors = array();
- // Loop through arguments
- foreach(Calculation_Functions::flattenArray(func_get_args()) as $value) {
- if (!is_numeric($value)) {
- return Calculation_Functions::VALUE();
- } elseif ($value == 0) {
- continue;
- } elseif($value < 0) {
- return Calculation_Functions::NaN();
- }
- $myFactors = self::_factors($value);
- $myCountedFactors = array_count_values($myFactors);
- $allValuesFactors[] = $myCountedFactors;
- }
- $allValuesCount = count($allValuesFactors);
- if ($allValuesCount == 0) {
- return 0;
- }
-
- $mergedArray = $allValuesFactors[0];
- for ($i=1;$i < $allValuesCount; ++$i) {
- $mergedArray = array_intersect_key($mergedArray,$allValuesFactors[$i]);
- }
- $mergedArrayValues = count($mergedArray);
- if ($mergedArrayValues == 0) {
- return $returnValue;
- } elseif ($mergedArrayValues > 1) {
- foreach($mergedArray as $mergedKey => $mergedValue) {
- foreach($allValuesFactors as $highestPowerTest) {
- foreach($highestPowerTest as $testKey => $testValue) {
- if (($testKey == $mergedKey) && ($testValue < $mergedValue)) {
- $mergedArray[$mergedKey] = $testValue;
- $mergedValue = $testValue;
- }
- }
- }
- }
-
- $returnValue = 1;
- foreach($mergedArray as $key => $value) {
- $returnValue *= pow($key,$value);
- }
- return $returnValue;
- } else {
- $keys = array_keys($mergedArray);
- $key = $keys[0];
- $value = $mergedArray[$key];
- foreach($allValuesFactors as $testValue) {
- foreach($testValue as $mergedKey => $mergedValue) {
- if (($mergedKey == $key) && ($mergedValue < $value)) {
- $value = $mergedValue;
- }
- }
- }
- return pow($key,$value);
- }
- } // function GCD()
-
-
- /**
- * INT
- *
- * Casts a floating point value to an integer
- *
- * Excel Function:
- * INT(number)
- *
- * @access public
- * @category Mathematical and Trigonometric Functions
- * @param float $number Number to cast to an integer
- * @return integer Integer value
- */
- public static function INT($number) {
- $number = Calculation_Functions::flattenSingleValue($number);
-
- if (is_null($number)) {
- return 0;
- } elseif (is_bool($number)) {
- return (int) $number;
- }
- if (is_numeric($number)) {
- return (int) floor($number);
- }
- return Calculation_Functions::VALUE();
- } // function INT()
-
-
- /**
- * LCM
- *
- * Returns the lowest common multiplier of a series of numbers
- * The least common multiple is the smallest positive integer that is a multiple
- * of all integer arguments number1, number2, and so on. Use LCM to add fractions
- * with different denominators.
- *
- * Excel Function:
- * LCM(number1[,number2[, ...]])
- *
- * @access public
- * @category Mathematical and Trigonometric Functions
- * @param mixed $arg,... Data values
- * @return int Lowest Common Multiplier
- */
- public static function LCM() {
- $returnValue = 1;
- $allPoweredFactors = array();
- // Loop through arguments
- foreach(Calculation_Functions::flattenArray(func_get_args()) as $value) {
- if (!is_numeric($value)) {
- return Calculation_Functions::VALUE();
- }
- if ($value == 0) {
- return 0;
- } elseif ($value < 0) {
- return Calculation_Functions::NaN();
- }
- $myFactors = self::_factors(floor($value));
- $myCountedFactors = array_count_values($myFactors);
- $myPoweredFactors = array();
- foreach($myCountedFactors as $myCountedFactor => $myCountedPower) {
- $myPoweredFactors[$myCountedFactor] = pow($myCountedFactor,$myCountedPower);
- }
- foreach($myPoweredFactors as $myPoweredValue => $myPoweredFactor) {
- if (array_key_exists($myPoweredValue,$allPoweredFactors)) {
- if ($allPoweredFactors[$myPoweredValue] < $myPoweredFactor) {
- $allPoweredFactors[$myPoweredValue] = $myPoweredFactor;
- }
- } else {
- $allPoweredFactors[$myPoweredValue] = $myPoweredFactor;
- }
- }
- }
- foreach($allPoweredFactors as $allPoweredFactor) {
- $returnValue *= (integer) $allPoweredFactor;
- }
- return $returnValue;
- } // function LCM()
-
-
- /**
- * LOG_BASE
- *
- * Returns the logarithm of a number to a specified base. The default base is 10.
- *
- * Excel Function:
- * LOG(number[,base])
- *
- * @access public
- * @category Mathematical and Trigonometric Functions
- * @param float $number The positive real number for which you want the logarithm
- * @param float $base The base of the logarithm. If base is omitted, it is assumed to be 10.
- * @return float
- */
- public static function LOG_BASE($number = NULL, $base = 10) {
- $number = Calculation_Functions::flattenSingleValue($number);
- $base = (is_null($base)) ? 10 : (float) Calculation_Functions::flattenSingleValue($base);
-
- if ((!is_numeric($base)) || (!is_numeric($number)))
- return Calculation_Functions::VALUE();
- if (($base <= 0) || ($number <= 0))
- return Calculation_Functions::NaN();
- return log($number, $base);
- } // function LOG_BASE()
-
-
- /**
- * MDETERM
- *
- * Returns the matrix determinant of an array.
- *
- * Excel Function:
- * MDETERM(array)
- *
- * @access public
- * @category Mathematical and Trigonometric Functions
- * @param array $matrixValues A matrix of values
- * @return float
- */
- public static function MDETERM($matrixValues) {
- $matrixData = array();
- if (!is_array($matrixValues)) { $matrixValues = array(array($matrixValues)); }
-
- $row = $maxColumn = 0;
- foreach($matrixValues as $matrixRow) {
- if (!is_array($matrixRow)) { $matrixRow = array($matrixRow); }
- $column = 0;
- foreach($matrixRow as $matrixCell) {
- if ((is_string($matrixCell)) || ($matrixCell === null)) {
- return Calculation_Functions::VALUE();
- }
- $matrixData[$column][$row] = $matrixCell;
- ++$column;
- }
- if ($column > $maxColumn) { $maxColumn = $column; }
- ++$row;
- }
- if ($row != $maxColumn) { return Calculation_Functions::VALUE(); }
-
- try {
- $matrix = new Shared_JAMA_Matrix($matrixData);
- return $matrix->det();
- } catch (Exception $ex) {
- return Calculation_Functions::VALUE();
- }
- } // function MDETERM()
-
-
- /**
- * MINVERSE
- *
- * Returns the inverse matrix for the matrix stored in an array.
- *
- * Excel Function:
- * MINVERSE(array)
- *
- * @access public
- * @category Mathematical and Trigonometric Functions
- * @param array $matrixValues A matrix of values
- * @return array
- */
- public static function MINVERSE($matrixValues) {
- $matrixData = array();
- if (!is_array($matrixValues)) { $matrixValues = array(array($matrixValues)); }
-
- $row = $maxColumn = 0;
- foreach($matrixValues as $matrixRow) {
- if (!is_array($matrixRow)) { $matrixRow = array($matrixRow); }
- $column = 0;
- foreach($matrixRow as $matrixCell) {
- if ((is_string($matrixCell)) || ($matrixCell === null)) {
- return Calculation_Functions::VALUE();
- }
- $matrixData[$column][$row] = $matrixCell;
- ++$column;
- }
- if ($column > $maxColumn) { $maxColumn = $column; }
- ++$row;
- }
- if ($row != $maxColumn) { return Calculation_Functions::VALUE(); }
-
- try {
- $matrix = new Shared_JAMA_Matrix($matrixData);
- return $matrix->inverse()->getArray();
- } catch (Exception $ex) {
- return Calculation_Functions::VALUE();
- }
- } // function MINVERSE()
-
-
- /**
- * MMULT
- *
- * @param array $matrixData1 A matrix of values
- * @param array $matrixData2 A matrix of values
- * @return array
- */
- public static function MMULT($matrixData1,$matrixData2) {
- $matrixAData = $matrixBData = array();
- if (!is_array($matrixData1)) { $matrixData1 = array(array($matrixData1)); }
- if (!is_array($matrixData2)) { $matrixData2 = array(array($matrixData2)); }
-
- $rowA = 0;
- foreach($matrixData1 as $matrixRow) {
- if (!is_array($matrixRow)) { $matrixRow = array($matrixRow); }
- $columnA = 0;
- foreach($matrixRow as $matrixCell) {
- if ((is_string($matrixCell)) || ($matrixCell === null)) {
- return Calculation_Functions::VALUE();
- }
- $matrixAData[$rowA][$columnA] = $matrixCell;
- ++$columnA;
- }
- ++$rowA;
- }
- try {
- $matrixA = new Shared_JAMA_Matrix($matrixAData);
- $rowB = 0;
- foreach($matrixData2 as $matrixRow) {
- if (!is_array($matrixRow)) { $matrixRow = array($matrixRow); }
- $columnB = 0;
- foreach($matrixRow as $matrixCell) {
- if ((is_string($matrixCell)) || ($matrixCell === null)) {
- return Calculation_Functions::VALUE();
- }
- $matrixBData[$rowB][$columnB] = $matrixCell;
- ++$columnB;
- }
- ++$rowB;
- }
- $matrixB = new Shared_JAMA_Matrix($matrixBData);
-
- if (($rowA != $columnB) || ($rowB != $columnA)) {
- return Calculation_Functions::VALUE();
- }
-
- return $matrixA->times($matrixB)->getArray();
- } catch (Exception $ex) {
- return Calculation_Functions::VALUE();
- }
- } // function MMULT()
-
-
- /**
- * MOD
- *
- * @param int $a Dividend
- * @param int $b Divisor
- * @return int Remainder
- */
- public static function MOD($a = 1, $b = 1) {
- $a = Calculation_Functions::flattenSingleValue($a);
- $b = Calculation_Functions::flattenSingleValue($b);
-
- if ($b == 0.0) {
- return Calculation_Functions::DIV0();
- } elseif (($a < 0.0) && ($b > 0.0)) {
- return $b - fmod(abs($a),$b);
- } elseif (($a > 0.0) && ($b < 0.0)) {
- return $b + fmod($a,abs($b));
- }
-
- return fmod($a,$b);
- } // function MOD()
-
-
- /**
- * MROUND
- *
- * Rounds a number to the nearest multiple of a specified value
- *
- * @param float $number Number to round
- * @param int $multiple Multiple to which you want to round $number
- * @return float Rounded Number
- */
- public static function MROUND($number,$multiple) {
- $number = Calculation_Functions::flattenSingleValue($number);
- $multiple = Calculation_Functions::flattenSingleValue($multiple);
-
- if ((is_numeric($number)) && (is_numeric($multiple))) {
- if ($multiple == 0) {
- return 0;
- }
- if ((self::SIGN($number)) == (self::SIGN($multiple))) {
- $multiplier = 1 / $multiple;
- return round($number * $multiplier) / $multiplier;
- }
- return Calculation_Functions::NaN();
- }
- return Calculation_Functions::VALUE();
- } // function MROUND()
-
-
- /**
- * MULTINOMIAL
- *
- * Returns the ratio of the factorial of a sum of values to the product of factorials.
- *
- * @param array of mixed Data Series
- * @return float
- */
- public static function MULTINOMIAL() {
- $summer = 0;
- $divisor = 1;
- // Loop through arguments
- foreach (Calculation_Functions::flattenArray(func_get_args()) as $arg) {
- // Is it a numeric value?
- if (is_numeric($arg)) {
- if ($arg < 1) {
- return Calculation_Functions::NaN();
- }
- $summer += floor($arg);
- $divisor *= self::FACT($arg);
- } else {
- return Calculation_Functions::VALUE();
- }
- }
-
- // Return
- if ($summer > 0) {
- $summer = self::FACT($summer);
- return $summer / $divisor;
- }
- return 0;
- } // function MULTINOMIAL()
-
-
- /**
- * ODD
- *
- * Returns number rounded up to the nearest odd integer.
- *
- * @param float $number Number to round
- * @return int Rounded Number
- */
- public static function ODD($number) {
- $number = Calculation_Functions::flattenSingleValue($number);
-
- if (is_null($number)) {
- return 1;
- } elseif (is_bool($number)) {
- $number = (int) $number;
- }
-
- if (is_numeric($number)) {
- $significance = self::SIGN($number);
- if ($significance == 0) {
- return 1;
- }
-
- $result = self::CEILING($number,$significance);
- if ($result == self::EVEN($result)) {
- $result += $significance;
- }
-
- return (int) $result;
- }
- return Calculation_Functions::VALUE();
- } // function ODD()
-
-
- /**
- * POWER
- *
- * Computes x raised to the power y.
- *
- * @param float $x
- * @param float $y
- * @return float
- */
- public static function POWER($x = 0, $y = 2) {
- $x = Calculation_Functions::flattenSingleValue($x);
- $y = Calculation_Functions::flattenSingleValue($y);
-
- // Validate parameters
- if ($x == 0.0 && $y == 0.0) {
- return Calculation_Functions::NaN();
- } elseif ($x == 0.0 && $y < 0.0) {
- return Calculation_Functions::DIV0();
- }
-
- // Return
- $result = pow($x, $y);
- return (!is_nan($result) && !is_infinite($result)) ? $result : Calculation_Functions::NaN();
- } // function POWER()
-
-
- /**
- * PRODUCT
- *
- * PRODUCT returns the product of all the values and cells referenced in the argument list.
- *
- * Excel Function:
- * PRODUCT(value1[,value2[, ...]])
- *
- * @access public
- * @category Mathematical and Trigonometric Functions
- * @param mixed $arg,... Data values
- * @return float
- */
- public static function PRODUCT() {
- // Return value
- $returnValue = null;
-
- // Loop through arguments
- foreach (Calculation_Functions::flattenArray(func_get_args()) as $arg) {
- // Is it a numeric value?
- if ((is_numeric($arg)) && (!is_string($arg))) {
- if (is_null($returnValue)) {
- $returnValue = $arg;
- } else {
- $returnValue *= $arg;
- }
- }
- }
-
- // Return
- if (is_null($returnValue)) {
- return 0;
- }
- return $returnValue;
- } // function PRODUCT()
-
-
- /**
- * QUOTIENT
- *
- * QUOTIENT function returns the integer portion of a division. Numerator is the divided number
- * and denominator is the divisor.
- *
- * Excel Function:
- * QUOTIENT(value1[,value2[, ...]])
- *
- * @access public
- * @category Mathematical and Trigonometric Functions
- * @param mixed $arg,... Data values
- * @return float
- */
- public static function QUOTIENT() {
- // Return value
- $returnValue = null;
-
- // Loop through arguments
- foreach (Calculation_Functions::flattenArray(func_get_args()) as $arg) {
- // Is it a numeric value?
- if ((is_numeric($arg)) && (!is_string($arg))) {
- if (is_null($returnValue)) {
- $returnValue = ($arg == 0) ? 0 : $arg;
- } else {
- if (($returnValue == 0) || ($arg == 0)) {
- $returnValue = 0;
- } else {
- $returnValue /= $arg;
- }
- }
- }
- }
-
- // Return
- return intval($returnValue);
- } // function QUOTIENT()
-
-
- /**
- * RAND
- *
- * @param int $min Minimal value
- * @param int $max Maximal value
- * @return int Random number
- */
- public static function RAND($min = 0, $max = 0) {
- $min = Calculation_Functions::flattenSingleValue($min);
- $max = Calculation_Functions::flattenSingleValue($max);
-
- if ($min == 0 && $max == 0) {
- return (rand(0,10000000)) / 10000000;
- } else {
- return rand($min, $max);
- }
- } // function RAND()
-
-
- public static function ROMAN($aValue, $style=0) {
- $aValue = Calculation_Functions::flattenSingleValue($aValue);
- $style = (is_null($style)) ? 0 : (integer) Calculation_Functions::flattenSingleValue($style);
- if ((!is_numeric($aValue)) || ($aValue < 0) || ($aValue >= 4000)) {
- return Calculation_Functions::VALUE();
- }
- $aValue = (integer) $aValue;
- if ($aValue == 0) {
- return '';
- }
-
- $mill = Array('', 'M', 'MM', 'MMM', 'MMMM', 'MMMMM');
- $cent = Array('', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM');
- $tens = Array('', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC');
- $ones = Array('', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX');
-
- $roman = '';
- while ($aValue > 5999) {
- $roman .= 'M';
- $aValue -= 1000;
- }
- $m = self::_romanCut($aValue, 1000); $aValue %= 1000;
- $c = self::_romanCut($aValue, 100); $aValue %= 100;
- $t = self::_romanCut($aValue, 10); $aValue %= 10;
-
- return $roman.$mill[$m].$cent[$c].$tens[$t].$ones[$aValue];
- } // function ROMAN()
-
-
- /**
- * ROUNDUP
- *
- * Rounds a number up to a specified number of decimal places
- *
- * @param float $number Number to round
- * @param int $digits Number of digits to which you want to round $number
- * @return float Rounded Number
- */
- public static function ROUNDUP($number,$digits) {
- $number = Calculation_Functions::flattenSingleValue($number);
- $digits = Calculation_Functions::flattenSingleValue($digits);
-
- if ((is_numeric($number)) && (is_numeric($digits))) {
- $significance = pow(10,(int) $digits);
- if ($number < 0.0) {
- return floor($number * $significance) / $significance;
- } else {
- return ceil($number * $significance) / $significance;
- }
- }
- return Calculation_Functions::VALUE();
- } // function ROUNDUP()
-
-
- /**
- * ROUNDDOWN
- *
- * Rounds a number down to a specified number of decimal places
- *
- * @param float $number Number to round
- * @param int $digits Number of digits to which you want to round $number
- * @return float Rounded Number
- */
- public static function ROUNDDOWN($number,$digits) {
- $number = Calculation_Functions::flattenSingleValue($number);
- $digits = Calculation_Functions::flattenSingleValue($digits);
-
- if ((is_numeric($number)) && (is_numeric($digits))) {
- $significance = pow(10,(int) $digits);
- if ($number < 0.0) {
- return ceil($number * $significance) / $significance;
- } else {
- return floor($number * $significance) / $significance;
- }
- }
- return Calculation_Functions::VALUE();
- } // function ROUNDDOWN()
-
-
- /**
- * SERIESSUM
- *
- * Returns the sum of a power series
- *
- * @param float $x Input value to the power series
- * @param float $n Initial power to which you want to raise $x
- * @param float $m Step by which to increase $n for each term in the series
- * @param array of mixed Data Series
- * @return float
- */
- public static function SERIESSUM() {
- // Return value
- $returnValue = 0;
-
- // Loop through arguments
- $aArgs = Calculation_Functions::flattenArray(func_get_args());
-
- $x = array_shift($aArgs);
- $n = array_shift($aArgs);
- $m = array_shift($aArgs);
-
- if ((is_numeric($x)) && (is_numeric($n)) && (is_numeric($m))) {
- // Calculate
- $i = 0;
- foreach($aArgs as $arg) {
- // Is it a numeric value?
- if ((is_numeric($arg)) && (!is_string($arg))) {
- $returnValue += $arg * pow($x,$n + ($m * $i++));
- } else {
- return Calculation_Functions::VALUE();
- }
- }
- // Return
- return $returnValue;
- }
- return Calculation_Functions::VALUE();
- } // function SERIESSUM()
-
-
- /**
- * SIGN
- *
- * Determines the sign of a number. Returns 1 if the number is positive, zero (0)
- * if the number is 0, and -1 if the number is negative.
- *
- * @param float $number Number to round
- * @return int sign value
- */
- public static function SIGN($number) {
- $number = Calculation_Functions::flattenSingleValue($number);
-
- if (is_bool($number))
- return (int) $number;
- if (is_numeric($number)) {
- if ($number == 0.0) {
- return 0;
- }
- return $number / abs($number);
- }
- return Calculation_Functions::VALUE();
- } // function SIGN()
-
-
- /**
- * SQRTPI
- *
- * Returns the square root of (number * pi).
- *
- * @param float $number Number
- * @return float Square Root of Number * Pi
- */
- public static function SQRTPI($number) {
- $number = Calculation_Functions::flattenSingleValue($number);
-
- if (is_numeric($number)) {
- if ($number < 0) {
- return Calculation_Functions::NaN();
- }
- return sqrt($number * M_PI) ;
- }
- return Calculation_Functions::VALUE();
- } // function SQRTPI()
-
-
- /**
- * SUBTOTAL
- *
- * Returns a subtotal in a list or database.
- *
- * @param int the number 1 to 11 that specifies which function to
- * use in calculating subtotals within a list.
- * @param array of mixed Data Series
- * @return float
- */
- public static function SUBTOTAL() {
- $aArgs = Calculation_Functions::flattenArray(func_get_args());
-
- // Calculate
- $subtotal = array_shift($aArgs);
-
- if ((is_numeric($subtotal)) && (!is_string($subtotal))) {
- switch($subtotal) {
- case 1 :
- return Calculation_Statistical::AVERAGE($aArgs);
- break;
- case 2 :
- return Calculation_Statistical::COUNT($aArgs);
- break;
- case 3 :
- return Calculation_Statistical::COUNTA($aArgs);
- break;
- case 4 :
- return Calculation_Statistical::MAX($aArgs);
- break;
- case 5 :
- return Calculation_Statistical::MIN($aArgs);
- break;
- case 6 :
- return self::PRODUCT($aArgs);
- break;
- case 7 :
- return Calculation_Statistical::STDEV($aArgs);
- break;
- case 8 :
- return Calculation_Statistical::STDEVP($aArgs);
- break;
- case 9 :
- return self::SUM($aArgs);
- break;
- case 10 :
- return Calculation_Statistical::VARFunc($aArgs);
- break;
- case 11 :
- return Calculation_Statistical::VARP($aArgs);
- break;
- }
- }
- return Calculation_Functions::VALUE();
- } // function SUBTOTAL()
-
-
- /**
- * SUM
- *
- * SUM computes the sum of all the values and cells referenced in the argument list.
- *
- * Excel Function:
- * SUM(value1[,value2[, ...]])
- *
- * @access public
- * @category Mathematical and Trigonometric Functions
- * @param mixed $arg,... Data values
- * @return float
- */
- public static function SUM() {
- // Return value
- $returnValue = 0;
-
- // Loop through the arguments
- foreach (Calculation_Functions::flattenArray(func_get_args()) as $arg) {
- // Is it a numeric value?
- if ((is_numeric($arg)) && (!is_string($arg))) {
- $returnValue += $arg;
- }
- }
-
- // Return
- return $returnValue;
- } // function SUM()
-
-
- /**
- * SUMIF
- *
- * Counts the number of cells that contain numbers within the list of arguments
- *
- * Excel Function:
- * SUMIF(value1[,value2[, ...]],condition)
- *
- * @access public
- * @category Mathematical and Trigonometric Functions
- * @param mixed $arg,... Data values
- * @param string $condition The criteria that defines which cells will be summed.
- * @return float
- */
- public static function SUMIF($aArgs,$condition,$sumArgs = array()) {
- // Return value
- $returnValue = 0;
-
- $aArgs = Calculation_Functions::flattenArray($aArgs);
- $sumArgs = Calculation_Functions::flattenArray($sumArgs);
- if (empty($sumArgs)) {
- $sumArgs = $aArgs;
- }
- $condition = Calculation_Functions::_ifCondition($condition);
- // Loop through arguments
- foreach ($aArgs as $key => $arg) {
- if (!is_numeric($arg)) { $arg = Calculation::_wrapResult(strtoupper($arg)); }
- $testCondition = '='.$arg.$condition;
- if (Calculation::getInstance()->_calculateFormulaValue($testCondition)) {
- // Is it a value within our criteria
- $returnValue += $sumArgs[$key];
- }
- }
-
- // Return
- return $returnValue;
- } // function SUMIF()
-
-
- /**
- * SUMPRODUCT
- *
- * Excel Function:
- * SUMPRODUCT(value1[,value2[, ...]])
- *
- * @access public
- * @category Mathematical and Trigonometric Functions
- * @param mixed $arg,... Data values
- * @return float
- */
- public static function SUMPRODUCT() {
- $arrayList = func_get_args();
-
- $wrkArray = Calculation_Functions::flattenArray(array_shift($arrayList));
- $wrkCellCount = count($wrkArray);
-
- for ($i=0; $i< $wrkCellCount; ++$i) {
- if ((!is_numeric($wrkArray[$i])) || (is_string($wrkArray[$i]))) {
- $wrkArray[$i] = 0;
- }
- }
-
- foreach($arrayList as $matrixData) {
- $array2 = Calculation_Functions::flattenArray($matrixData);
- $count = count($array2);
- if ($wrkCellCount != $count) {
- return Calculation_Functions::VALUE();
- }
-
- foreach ($array2 as $i => $val) {
- if ((!is_numeric($val)) || (is_string($val))) {
- $val = 0;
- }
- $wrkArray[$i] *= $val;
- }
- }
-
- return array_sum($wrkArray);
- } // function SUMPRODUCT()
-
-
- /**
- * SUMSQ
- *
- * SUMSQ returns the sum of the squares of the arguments
- *
- * Excel Function:
- * SUMSQ(value1[,value2[, ...]])
- *
- * @access public
- * @category Mathematical and Trigonometric Functions
- * @param mixed $arg,... Data values
- * @return float
- */
- public static function SUMSQ() {
- // Return value
- $returnValue = 0;
-
- // Loop through arguments
- foreach (Calculation_Functions::flattenArray(func_get_args()) as $arg) {
- // Is it a numeric value?
- if ((is_numeric($arg)) && (!is_string($arg))) {
- $returnValue += ($arg * $arg);
- }
- }
-
- // Return
- return $returnValue;
- } // function SUMSQ()
-
-
- /**
- * SUMX2MY2
- *
- * @param mixed[] $matrixData1 Matrix #1
- * @param mixed[] $matrixData2 Matrix #2
- * @return float
- */
- public static function SUMX2MY2($matrixData1,$matrixData2) {
- $array1 = Calculation_Functions::flattenArray($matrixData1);
- $array2 = Calculation_Functions::flattenArray($matrixData2);
- $count1 = count($array1);
- $count2 = count($array2);
- if ($count1 < $count2) {
- $count = $count1;
- } else {
- $count = $count2;
- }
-
- $result = 0;
- for ($i = 0; $i < $count; ++$i) {
- if (((is_numeric($array1[$i])) && (!is_string($array1[$i]))) &&
- ((is_numeric($array2[$i])) && (!is_string($array2[$i])))) {
- $result += ($array1[$i] * $array1[$i]) - ($array2[$i] * $array2[$i]);
- }
- }
-
- return $result;
- } // function SUMX2MY2()
-
-
- /**
- * SUMX2PY2
- *
- * @param mixed[] $matrixData1 Matrix #1
- * @param mixed[] $matrixData2 Matrix #2
- * @return float
- */
- public static function SUMX2PY2($matrixData1,$matrixData2) {
- $array1 = Calculation_Functions::flattenArray($matrixData1);
- $array2 = Calculation_Functions::flattenArray($matrixData2);
- $count1 = count($array1);
- $count2 = count($array2);
- if ($count1 < $count2) {
- $count = $count1;
- } else {
- $count = $count2;
- }
-
- $result = 0;
- for ($i = 0; $i < $count; ++$i) {
- if (((is_numeric($array1[$i])) && (!is_string($array1[$i]))) &&
- ((is_numeric($array2[$i])) && (!is_string($array2[$i])))) {
- $result += ($array1[$i] * $array1[$i]) + ($array2[$i] * $array2[$i]);
- }
- }
-
- return $result;
- } // function SUMX2PY2()
-
-
- /**
- * SUMXMY2
- *
- * @param mixed[] $matrixData1 Matrix #1
- * @param mixed[] $matrixData2 Matrix #2
- * @return float
- */
- public static function SUMXMY2($matrixData1,$matrixData2) {
- $array1 = Calculation_Functions::flattenArray($matrixData1);
- $array2 = Calculation_Functions::flattenArray($matrixData2);
- $count1 = count($array1);
- $count2 = count($array2);
- if ($count1 < $count2) {
- $count = $count1;
- } else {
- $count = $count2;
- }
-
- $result = 0;
- for ($i = 0; $i < $count; ++$i) {
- if (((is_numeric($array1[$i])) && (!is_string($array1[$i]))) &&
- ((is_numeric($array2[$i])) && (!is_string($array2[$i])))) {
- $result += ($array1[$i] - $array2[$i]) * ($array1[$i] - $array2[$i]);
- }
- }
-
- return $result;
- } // function SUMXMY2()
-
-
- /**
- * TRUNC
- *
- * Truncates value to the number of fractional digits by number_digits.
- *
- * @param float $value
- * @param int $digits
- * @return float Truncated value
- */
- public static function TRUNC($value = 0, $digits = 0) {
- $value = Calculation_Functions::flattenSingleValue($value);
- $digits = Calculation_Functions::flattenSingleValue($digits);
-
- // Validate parameters
- if ((!is_numeric($value)) || (!is_numeric($digits)))
- return Calculation_Functions::VALUE();
- $digits = floor($digits);
-
- // Truncate
- $adjust = pow(10, $digits);
-
- if (($digits > 0) && (rtrim(intval((abs($value) - abs(intval($value))) * $adjust),'0') < $adjust/10))
- return $value;
-
- return (intval($value * $adjust)) / $adjust;
- } // function TRUNC()
-
+ //
+ // Private method to return an array of the factors of the input value
+ //
+ private static function _factors($value) {
+ $startVal = floor(sqrt($value));
+
+ $factorArray = array();
+ for ($i = $startVal; $i > 1; --$i) {
+ if (($value % $i) == 0) {
+ $factorArray = array_merge($factorArray,self::_factors($value / $i));
+ $factorArray = array_merge($factorArray,self::_factors($i));
+ if ($i <= sqrt($value)) {
+ break;
+ }
+ }
+ }
+ if (!empty($factorArray)) {
+ rsort($factorArray);
+ return $factorArray;
+ } else {
+ return array((integer) $value);
+ }
+ } // function _factors()
+
+
+ private static function _romanCut($num, $n) {
+ return ($num - ($num % $n ) ) / $n;
+ } // function _romanCut()
+
+
+ /**
+ * ATAN2
+ *
+ * This function calculates the arc tangent of the two variables x and y. It is similar to
+ * calculating the arc tangent of y ÷ x, except that the signs of both arguments are used
+ * to determine the quadrant of the result.
+ * The arctangent is the angle from the x-axis to a line containing the origin (0, 0) and a
+ * point with coordinates (xCoordinate, yCoordinate). The angle is given in radians between
+ * -pi and pi, excluding -pi.
+ *
+ * Note that the Excel ATAN2() function accepts its arguments in the reverse order to the standard
+ * PHP atan2() function, so we need to reverse them here before calling the PHP atan() function.
+ *
+ * Excel Function:
+ * ATAN2(xCoordinate,yCoordinate)
+ *
+ * @access public
+ * @category Mathematical and Trigonometric Functions
+ * @param float $xCoordinate The x-coordinate of the point.
+ * @param float $yCoordinate The y-coordinate of the point.
+ * @return float The inverse tangent of the specified x- and y-coordinates.
+ */
+ public static function ATAN2($xCoordinate = null, $yCoordinate = null) {
+ $xCoordinate = Calculation_Functions::flattenSingleValue($xCoordinate);
+ $yCoordinate = Calculation_Functions::flattenSingleValue($yCoordinate);
+
+ $xCoordinate = ($xCoordinate !== null) ? $xCoordinate : 0.0;
+ $yCoordinate = ($yCoordinate !== null) ? $yCoordinate : 0.0;
+
+ if (((is_numeric($xCoordinate)) || (is_bool($xCoordinate))) &&
+ ((is_numeric($yCoordinate))) || (is_bool($yCoordinate))) {
+ $xCoordinate = (float) $xCoordinate;
+ $yCoordinate = (float) $yCoordinate;
+
+ if (($xCoordinate == 0) && ($yCoordinate == 0)) {
+ return Calculation_Functions::DIV0();
+ }
+
+ return atan2($yCoordinate, $xCoordinate);
+ }
+ return Calculation_Functions::VALUE();
+ } // function ATAN2()
+
+
+ /**
+ * CEILING
+ *
+ * Returns number rounded up, away from zero, to the nearest multiple of significance.
+ * For example, if you want to avoid using pennies in your prices and your product is
+ * priced at $4.42, use the formula =CEILING(4.42,0.05) to round prices up to the
+ * nearest nickel.
+ *
+ * Excel Function:
+ * CEILING(number[,significance])
+ *
+ * @access public
+ * @category Mathematical and Trigonometric Functions
+ * @param float $number The number you want to round.
+ * @param float $significance The multiple to which you want to round.
+ * @return float Rounded Number
+ */
+ public static function CEILING($number, $significance = null) {
+ $number = Calculation_Functions::flattenSingleValue($number);
+ $significance = Calculation_Functions::flattenSingleValue($significance);
+
+ if ((is_null($significance)) &&
+ (Calculation_Functions::getCompatibilityMode() == Calculation_Functions::COMPATIBILITY_GNUMERIC)) {
+ $significance = $number/abs($number);
+ }
+
+ if ((is_numeric($number)) && (is_numeric($significance))) {
+ if ($significance == 0.0) {
+ return 0.0;
+ } elseif (self::SIGN($number) == self::SIGN($significance)) {
+ return ceil($number / $significance) * $significance;
+ } else {
+ return Calculation_Functions::NaN();
+ }
+ }
+ return Calculation_Functions::VALUE();
+ } // function CEILING()
+
+
+ /**
+ * COMBIN
+ *
+ * Returns the number of combinations for a given number of items. Use COMBIN to
+ * determine the total possible number of groups for a given number of items.
+ *
+ * Excel Function:
+ * COMBIN(numObjs,numInSet)
+ *
+ * @access public
+ * @category Mathematical and Trigonometric Functions
+ * @param int $numObjs Number of different objects
+ * @param int $numInSet Number of objects in each combination
+ * @return int Number of combinations
+ */
+ public static function COMBIN($numObjs, $numInSet) {
+ $numObjs = Calculation_Functions::flattenSingleValue($numObjs);
+ $numInSet = Calculation_Functions::flattenSingleValue($numInSet);
+
+ if ((is_numeric($numObjs)) && (is_numeric($numInSet))) {
+ if ($numObjs < $numInSet) {
+ return Calculation_Functions::NaN();
+ } elseif ($numInSet < 0) {
+ return Calculation_Functions::NaN();
+ }
+ return round(self::FACT($numObjs) / self::FACT($numObjs - $numInSet)) / self::FACT($numInSet);
+ }
+ return Calculation_Functions::VALUE();
+ } // function COMBIN()
+
+
+ /**
+ * EVEN
+ *
+ * Returns number rounded up to the nearest even integer.
+ * You can use this function for processing items that come in twos. For example,
+ * a packing crate accepts rows of one or two items. The crate is full when
+ * the number of items, rounded up to the nearest two, matches the crate's
+ * capacity.
+ *
+ * Excel Function:
+ * EVEN(number)
+ *
+ * @access public
+ * @category Mathematical and Trigonometric Functions
+ * @param float $number Number to round
+ * @return int Rounded Number
+ */
+ public static function EVEN($number) {
+ $number = Calculation_Functions::flattenSingleValue($number);
+
+ if (is_null($number)) {
+ return 0;
+ } elseif (is_bool($number)) {
+ $number = (int) $number;
+ }
+
+ if (is_numeric($number)) {
+ $significance = 2 * self::SIGN($number);
+ return (int) self::CEILING($number,$significance);
+ }
+ return Calculation_Functions::VALUE();
+ } // function EVEN()
+
+
+ /**
+ * FACT
+ *
+ * Returns the factorial of a number.
+ * The factorial of a number is equal to 1*2*3*...* number.
+ *
+ * Excel Function:
+ * FACT(factVal)
+ *
+ * @access public
+ * @category Mathematical and Trigonometric Functions
+ * @param float $factVal Factorial Value
+ * @return int Factorial
+ */
+ public static function FACT($factVal) {
+ $factVal = Calculation_Functions::flattenSingleValue($factVal);
+
+ if (is_numeric($factVal)) {
+ if ($factVal < 0) {
+ return Calculation_Functions::NaN();
+ }
+ $factLoop = floor($factVal);
+ if (Calculation_Functions::getCompatibilityMode() == Calculation_Functions::COMPATIBILITY_GNUMERIC) {
+ if ($factVal > $factLoop) {
+ return Calculation_Functions::NaN();
+ }
+ }
+
+ $factorial = 1;
+ while ($factLoop > 1) {
+ $factorial *= $factLoop--;
+ }
+ return $factorial ;
+ }
+ return Calculation_Functions::VALUE();
+ } // function FACT()
+
+
+ /**
+ * FACTDOUBLE
+ *
+ * Returns the double factorial of a number.
+ *
+ * Excel Function:
+ * FACTDOUBLE(factVal)
+ *
+ * @access public
+ * @category Mathematical and Trigonometric Functions
+ * @param float $factVal Factorial Value
+ * @return int Double Factorial
+ */
+ public static function FACTDOUBLE($factVal) {
+ $factLoop = Calculation_Functions::flattenSingleValue($factVal);
+
+ if (is_numeric($factLoop)) {
+ $factLoop = floor($factLoop);
+ if ($factVal < 0) {
+ return Calculation_Functions::NaN();
+ }
+ $factorial = 1;
+ while ($factLoop > 1) {
+ $factorial *= $factLoop--;
+ --$factLoop;
+ }
+ return $factorial ;
+ }
+ return Calculation_Functions::VALUE();
+ } // function FACTDOUBLE()
+
+
+ /**
+ * FLOOR
+ *
+ * Rounds number down, toward zero, to the nearest multiple of significance.
+ *
+ * Excel Function:
+ * FLOOR(number[,significance])
+ *
+ * @access public
+ * @category Mathematical and Trigonometric Functions
+ * @param float $number Number to round
+ * @param float $significance Significance
+ * @return float Rounded Number
+ */
+ public static function FLOOR($number, $significance = null) {
+ $number = Calculation_Functions::flattenSingleValue($number);
+ $significance = Calculation_Functions::flattenSingleValue($significance);
+
+ if ((is_null($significance)) && (Calculation_Functions::getCompatibilityMode() == Calculation_Functions::COMPATIBILITY_GNUMERIC)) {
+ $significance = $number/abs($number);
+ }
+
+ if ((is_numeric($number)) && (is_numeric($significance))) {
+ if ((float) $significance == 0.0) {
+ return Calculation_Functions::DIV0();
+ }
+ if (self::SIGN($number) == self::SIGN($significance)) {
+ return floor($number / $significance) * $significance;
+ } else {
+ return Calculation_Functions::NaN();
+ }
+ }
+ return Calculation_Functions::VALUE();
+ } // function FLOOR()
+
+
+ /**
+ * GCD
+ *
+ * Returns the greatest common divisor of a series of numbers.
+ * The greatest common divisor is the largest integer that divides both
+ * number1 and number2 without a remainder.
+ *
+ * Excel Function:
+ * GCD(number1[,number2[, ...]])
+ *
+ * @access public
+ * @category Mathematical and Trigonometric Functions
+ * @param mixed $arg,... Data values
+ * @return integer Greatest Common Divisor
+ */
+ public static function GCD() {
+ $returnValue = 1;
+ $allValuesFactors = array();
+ // Loop through arguments
+ foreach(Calculation_Functions::flattenArray(func_get_args()) as $value) {
+ if (!is_numeric($value)) {
+ return Calculation_Functions::VALUE();
+ } elseif ($value == 0) {
+ continue;
+ } elseif($value < 0) {
+ return Calculation_Functions::NaN();
+ }
+ $myFactors = self::_factors($value);
+ $myCountedFactors = array_count_values($myFactors);
+ $allValuesFactors[] = $myCountedFactors;
+ }
+ $allValuesCount = count($allValuesFactors);
+ if ($allValuesCount == 0) {
+ return 0;
+ }
+
+ $mergedArray = $allValuesFactors[0];
+ for ($i=1;$i < $allValuesCount; ++$i) {
+ $mergedArray = array_intersect_key($mergedArray,$allValuesFactors[$i]);
+ }
+ $mergedArrayValues = count($mergedArray);
+ if ($mergedArrayValues == 0) {
+ return $returnValue;
+ } elseif ($mergedArrayValues > 1) {
+ foreach($mergedArray as $mergedKey => $mergedValue) {
+ foreach($allValuesFactors as $highestPowerTest) {
+ foreach($highestPowerTest as $testKey => $testValue) {
+ if (($testKey == $mergedKey) && ($testValue < $mergedValue)) {
+ $mergedArray[$mergedKey] = $testValue;
+ $mergedValue = $testValue;
+ }
+ }
+ }
+ }
+
+ $returnValue = 1;
+ foreach($mergedArray as $key => $value) {
+ $returnValue *= pow($key,$value);
+ }
+ return $returnValue;
+ } else {
+ $keys = array_keys($mergedArray);
+ $key = $keys[0];
+ $value = $mergedArray[$key];
+ foreach($allValuesFactors as $testValue) {
+ foreach($testValue as $mergedKey => $mergedValue) {
+ if (($mergedKey == $key) && ($mergedValue < $value)) {
+ $value = $mergedValue;
+ }
+ }
+ }
+ return pow($key,$value);
+ }
+ } // function GCD()
+
+
+ /**
+ * INT
+ *
+ * Casts a floating point value to an integer
+ *
+ * Excel Function:
+ * INT(number)
+ *
+ * @access public
+ * @category Mathematical and Trigonometric Functions
+ * @param float $number Number to cast to an integer
+ * @return integer Integer value
+ */
+ public static function INT($number) {
+ $number = Calculation_Functions::flattenSingleValue($number);
+
+ if (is_null($number)) {
+ return 0;
+ } elseif (is_bool($number)) {
+ return (int) $number;
+ }
+ if (is_numeric($number)) {
+ return (int) floor($number);
+ }
+ return Calculation_Functions::VALUE();
+ } // function INT()
+
+
+ /**
+ * LCM
+ *
+ * Returns the lowest common multiplier of a series of numbers
+ * The least common multiple is the smallest positive integer that is a multiple
+ * of all integer arguments number1, number2, and so on. Use LCM to add fractions
+ * with different denominators.
+ *
+ * Excel Function:
+ * LCM(number1[,number2[, ...]])
+ *
+ * @access public
+ * @category Mathematical and Trigonometric Functions
+ * @param mixed $arg,... Data values
+ * @return int Lowest Common Multiplier
+ */
+ public static function LCM() {
+ $returnValue = 1;
+ $allPoweredFactors = array();
+ // Loop through arguments
+ foreach(Calculation_Functions::flattenArray(func_get_args()) as $value) {
+ if (!is_numeric($value)) {
+ return Calculation_Functions::VALUE();
+ }
+ if ($value == 0) {
+ return 0;
+ } elseif ($value < 0) {
+ return Calculation_Functions::NaN();
+ }
+ $myFactors = self::_factors(floor($value));
+ $myCountedFactors = array_count_values($myFactors);
+ $myPoweredFactors = array();
+ foreach($myCountedFactors as $myCountedFactor => $myCountedPower) {
+ $myPoweredFactors[$myCountedFactor] = pow($myCountedFactor,$myCountedPower);
+ }
+ foreach($myPoweredFactors as $myPoweredValue => $myPoweredFactor) {
+ if (array_key_exists($myPoweredValue,$allPoweredFactors)) {
+ if ($allPoweredFactors[$myPoweredValue] < $myPoweredFactor) {
+ $allPoweredFactors[$myPoweredValue] = $myPoweredFactor;
+ }
+ } else {
+ $allPoweredFactors[$myPoweredValue] = $myPoweredFactor;
+ }
+ }
+ }
+ foreach($allPoweredFactors as $allPoweredFactor) {
+ $returnValue *= (integer) $allPoweredFactor;
+ }
+ return $returnValue;
+ } // function LCM()
+
+
+ /**
+ * LOG_BASE
+ *
+ * Returns the logarithm of a number to a specified base. The default base is 10.
+ *
+ * Excel Function:
+ * LOG(number[,base])
+ *
+ * @access public
+ * @category Mathematical and Trigonometric Functions
+ * @param float $number The positive real number for which you want the logarithm
+ * @param float $base The base of the logarithm. If base is omitted, it is assumed to be 10.
+ * @return float
+ */
+ public static function LOG_BASE($number = null, $base = 10) {
+ $number = Calculation_Functions::flattenSingleValue($number);
+ $base = (is_null($base)) ? 10 : (float) Calculation_Functions::flattenSingleValue($base);
+
+ if ((!is_numeric($base)) || (!is_numeric($number)))
+ return Calculation_Functions::VALUE();
+ if (($base <= 0) || ($number <= 0))
+ return Calculation_Functions::NaN();
+ return log($number, $base);
+ } // function LOG_BASE()
+
+
+ /**
+ * MDETERM
+ *
+ * Returns the matrix determinant of an array.
+ *
+ * Excel Function:
+ * MDETERM(array)
+ *
+ * @access public
+ * @category Mathematical and Trigonometric Functions
+ * @param array $matrixValues A matrix of values
+ * @return float
+ */
+ public static function MDETERM($matrixValues) {
+ $matrixData = array();
+ if (!is_array($matrixValues)) { $matrixValues = array(array($matrixValues)); }
+
+ $row = $maxColumn = 0;
+ foreach($matrixValues as $matrixRow) {
+ if (!is_array($matrixRow)) { $matrixRow = array($matrixRow); }
+ $column = 0;
+ foreach($matrixRow as $matrixCell) {
+ if ((is_string($matrixCell)) || ($matrixCell === null)) {
+ return Calculation_Functions::VALUE();
+ }
+ $matrixData[$column][$row] = $matrixCell;
+ ++$column;
+ }
+ if ($column > $maxColumn) { $maxColumn = $column; }
+ ++$row;
+ }
+ if ($row != $maxColumn) { return Calculation_Functions::VALUE(); }
+
+ try {
+ $matrix = new Shared_JAMA_Matrix($matrixData);
+ return $matrix->det();
+ } catch (Exception $ex) {
+ return Calculation_Functions::VALUE();
+ }
+ } // function MDETERM()
+
+
+ /**
+ * MINVERSE
+ *
+ * Returns the inverse matrix for the matrix stored in an array.
+ *
+ * Excel Function:
+ * MINVERSE(array)
+ *
+ * @access public
+ * @category Mathematical and Trigonometric Functions
+ * @param array $matrixValues A matrix of values
+ * @return array
+ */
+ public static function MINVERSE($matrixValues) {
+ $matrixData = array();
+ if (!is_array($matrixValues)) { $matrixValues = array(array($matrixValues)); }
+
+ $row = $maxColumn = 0;
+ foreach($matrixValues as $matrixRow) {
+ if (!is_array($matrixRow)) { $matrixRow = array($matrixRow); }
+ $column = 0;
+ foreach($matrixRow as $matrixCell) {
+ if ((is_string($matrixCell)) || ($matrixCell === null)) {
+ return Calculation_Functions::VALUE();
+ }
+ $matrixData[$column][$row] = $matrixCell;
+ ++$column;
+ }
+ if ($column > $maxColumn) { $maxColumn = $column; }
+ ++$row;
+ }
+ if ($row != $maxColumn) { return Calculation_Functions::VALUE(); }
+
+ try {
+ $matrix = new Shared_JAMA_Matrix($matrixData);
+ return $matrix->inverse()->getArray();
+ } catch (Exception $ex) {
+ return Calculation_Functions::VALUE();
+ }
+ } // function MINVERSE()
+
+
+ /**
+ * MMULT
+ *
+ * @param array $matrixData1 A matrix of values
+ * @param array $matrixData2 A matrix of values
+ * @return array
+ */
+ public static function MMULT($matrixData1,$matrixData2) {
+ $matrixAData = $matrixBData = array();
+ if (!is_array($matrixData1)) { $matrixData1 = array(array($matrixData1)); }
+ if (!is_array($matrixData2)) { $matrixData2 = array(array($matrixData2)); }
+
+ $rowA = 0;
+ foreach($matrixData1 as $matrixRow) {
+ if (!is_array($matrixRow)) { $matrixRow = array($matrixRow); }
+ $columnA = 0;
+ foreach($matrixRow as $matrixCell) {
+ if ((is_string($matrixCell)) || ($matrixCell === null)) {
+ return Calculation_Functions::VALUE();
+ }
+ $matrixAData[$rowA][$columnA] = $matrixCell;
+ ++$columnA;
+ }
+ ++$rowA;
+ }
+ try {
+ $matrixA = new Shared_JAMA_Matrix($matrixAData);
+ $rowB = 0;
+ foreach($matrixData2 as $matrixRow) {
+ if (!is_array($matrixRow)) { $matrixRow = array($matrixRow); }
+ $columnB = 0;
+ foreach($matrixRow as $matrixCell) {
+ if ((is_string($matrixCell)) || ($matrixCell === null)) {
+ return Calculation_Functions::VALUE();
+ }
+ $matrixBData[$rowB][$columnB] = $matrixCell;
+ ++$columnB;
+ }
+ ++$rowB;
+ }
+ $matrixB = new Shared_JAMA_Matrix($matrixBData);
+
+ if (($rowA != $columnB) || ($rowB != $columnA)) {
+ return Calculation_Functions::VALUE();
+ }
+
+ return $matrixA->times($matrixB)->getArray();
+ } catch (Exception $ex) {
+ return Calculation_Functions::VALUE();
+ }
+ } // function MMULT()
+
+
+ /**
+ * MOD
+ *
+ * @param int $a Dividend
+ * @param int $b Divisor
+ * @return int Remainder
+ */
+ public static function MOD($a = 1, $b = 1) {
+ $a = Calculation_Functions::flattenSingleValue($a);
+ $b = Calculation_Functions::flattenSingleValue($b);
+
+ if ($b == 0.0) {
+ return Calculation_Functions::DIV0();
+ } elseif (($a < 0.0) && ($b > 0.0)) {
+ return $b - fmod(abs($a),$b);
+ } elseif (($a > 0.0) && ($b < 0.0)) {
+ return $b + fmod($a,abs($b));
+ }
+
+ return fmod($a,$b);
+ } // function MOD()
+
+
+ /**
+ * MROUND
+ *
+ * Rounds a number to the nearest multiple of a specified value
+ *
+ * @param float $number Number to round
+ * @param int $multiple Multiple to which you want to round $number
+ * @return float Rounded Number
+ */
+ public static function MROUND($number,$multiple) {
+ $number = Calculation_Functions::flattenSingleValue($number);
+ $multiple = Calculation_Functions::flattenSingleValue($multiple);
+
+ if ((is_numeric($number)) && (is_numeric($multiple))) {
+ if ($multiple == 0) {
+ return 0;
+ }
+ if ((self::SIGN($number)) == (self::SIGN($multiple))) {
+ $multiplier = 1 / $multiple;
+ return round($number * $multiplier) / $multiplier;
+ }
+ return Calculation_Functions::NaN();
+ }
+ return Calculation_Functions::VALUE();
+ } // function MROUND()
+
+
+ /**
+ * MULTINOMIAL
+ *
+ * Returns the ratio of the factorial of a sum of values to the product of factorials.
+ *
+ * @param array of mixed Data Series
+ * @return float
+ */
+ public static function MULTINOMIAL() {
+ $summer = 0;
+ $divisor = 1;
+ // Loop through arguments
+ foreach (Calculation_Functions::flattenArray(func_get_args()) as $arg) {
+ // Is it a numeric value?
+ if (is_numeric($arg)) {
+ if ($arg < 1) {
+ return Calculation_Functions::NaN();
+ }
+ $summer += floor($arg);
+ $divisor *= self::FACT($arg);
+ } else {
+ return Calculation_Functions::VALUE();
+ }
+ }
+
+ // Return
+ if ($summer > 0) {
+ $summer = self::FACT($summer);
+ return $summer / $divisor;
+ }
+ return 0;
+ } // function MULTINOMIAL()
+
+
+ /**
+ * ODD
+ *
+ * Returns number rounded up to the nearest odd integer.
+ *
+ * @param float $number Number to round
+ * @return int Rounded Number
+ */
+ public static function ODD($number) {
+ $number = Calculation_Functions::flattenSingleValue($number);
+
+ if (is_null($number)) {
+ return 1;
+ } elseif (is_bool($number)) {
+ $number = (int) $number;
+ }
+
+ if (is_numeric($number)) {
+ $significance = self::SIGN($number);
+ if ($significance == 0) {
+ return 1;
+ }
+
+ $result = self::CEILING($number,$significance);
+ if ($result == self::EVEN($result)) {
+ $result += $significance;
+ }
+
+ return (int) $result;
+ }
+ return Calculation_Functions::VALUE();
+ } // function ODD()
+
+
+ /**
+ * POWER
+ *
+ * Computes x raised to the power y.
+ *
+ * @param float $x
+ * @param float $y
+ * @return float
+ */
+ public static function POWER($x = 0, $y = 2) {
+ $x = Calculation_Functions::flattenSingleValue($x);
+ $y = Calculation_Functions::flattenSingleValue($y);
+
+ // Validate parameters
+ if ($x == 0.0 && $y == 0.0) {
+ return Calculation_Functions::NaN();
+ } elseif ($x == 0.0 && $y < 0.0) {
+ return Calculation_Functions::DIV0();
+ }
+
+ // Return
+ $result = pow($x, $y);
+ return (!is_nan($result) && !is_infinite($result)) ? $result : Calculation_Functions::NaN();
+ } // function POWER()
+
+
+ /**
+ * PRODUCT
+ *
+ * PRODUCT returns the product of all the values and cells referenced in the argument list.
+ *
+ * Excel Function:
+ * PRODUCT(value1[,value2[, ...]])
+ *
+ * @access public
+ * @category Mathematical and Trigonometric Functions
+ * @param mixed $arg,... Data values
+ * @return float
+ */
+ public static function PRODUCT() {
+ // Return value
+ $returnValue = null;
+
+ // Loop through arguments
+ foreach (Calculation_Functions::flattenArray(func_get_args()) as $arg) {
+ // Is it a numeric value?
+ if ((is_numeric($arg)) && (!is_string($arg))) {
+ if (is_null($returnValue)) {
+ $returnValue = $arg;
+ } else {
+ $returnValue *= $arg;
+ }
+ }
+ }
+
+ // Return
+ if (is_null($returnValue)) {
+ return 0;
+ }
+ return $returnValue;
+ } // function PRODUCT()
+
+
+ /**
+ * QUOTIENT
+ *
+ * QUOTIENT function returns the integer portion of a division. Numerator is the divided number
+ * and denominator is the divisor.
+ *
+ * Excel Function:
+ * QUOTIENT(value1[,value2[, ...]])
+ *
+ * @access public
+ * @category Mathematical and Trigonometric Functions
+ * @param mixed $arg,... Data values
+ * @return float
+ */
+ public static function QUOTIENT() {
+ // Return value
+ $returnValue = null;
+
+ // Loop through arguments
+ foreach (Calculation_Functions::flattenArray(func_get_args()) as $arg) {
+ // Is it a numeric value?
+ if ((is_numeric($arg)) && (!is_string($arg))) {
+ if (is_null($returnValue)) {
+ $returnValue = ($arg == 0) ? 0 : $arg;
+ } else {
+ if (($returnValue == 0) || ($arg == 0)) {
+ $returnValue = 0;
+ } else {
+ $returnValue /= $arg;
+ }
+ }
+ }
+ }
+
+ // Return
+ return intval($returnValue);
+ } // function QUOTIENT()
+
+
+ /**
+ * RAND
+ *
+ * @param int $min Minimal value
+ * @param int $max Maximal value
+ * @return int Random number
+ */
+ public static function RAND($min = 0, $max = 0) {
+ $min = Calculation_Functions::flattenSingleValue($min);
+ $max = Calculation_Functions::flattenSingleValue($max);
+
+ if ($min == 0 && $max == 0) {
+ return (rand(0,10000000)) / 10000000;
+ } else {
+ return rand($min, $max);
+ }
+ } // function RAND()
+
+
+ public static function ROMAN($aValue, $style=0) {
+ $aValue = Calculation_Functions::flattenSingleValue($aValue);
+ $style = (is_null($style)) ? 0 : (integer) Calculation_Functions::flattenSingleValue($style);
+ if ((!is_numeric($aValue)) || ($aValue < 0) || ($aValue >= 4000)) {
+ return Calculation_Functions::VALUE();
+ }
+ $aValue = (integer) $aValue;
+ if ($aValue == 0) {
+ return '';
+ }
+
+ $mill = Array('', 'M', 'MM', 'MMM', 'MMMM', 'MMMMM');
+ $cent = Array('', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM');
+ $tens = Array('', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC');
+ $ones = Array('', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX');
+
+ $roman = '';
+ while ($aValue > 5999) {
+ $roman .= 'M';
+ $aValue -= 1000;
+ }
+ $m = self::_romanCut($aValue, 1000); $aValue %= 1000;
+ $c = self::_romanCut($aValue, 100); $aValue %= 100;
+ $t = self::_romanCut($aValue, 10); $aValue %= 10;
+
+ return $roman.$mill[$m].$cent[$c].$tens[$t].$ones[$aValue];
+ } // function ROMAN()
+
+
+ /**
+ * ROUNDUP
+ *
+ * Rounds a number up to a specified number of decimal places
+ *
+ * @param float $number Number to round
+ * @param int $digits Number of digits to which you want to round $number
+ * @return float Rounded Number
+ */
+ public static function ROUNDUP($number,$digits) {
+ $number = Calculation_Functions::flattenSingleValue($number);
+ $digits = Calculation_Functions::flattenSingleValue($digits);
+
+ if ((is_numeric($number)) && (is_numeric($digits))) {
+ $significance = pow(10,(int) $digits);
+ if ($number < 0.0) {
+ return floor($number * $significance) / $significance;
+ } else {
+ return ceil($number * $significance) / $significance;
+ }
+ }
+ return Calculation_Functions::VALUE();
+ } // function ROUNDUP()
+
+
+ /**
+ * ROUNDDOWN
+ *
+ * Rounds a number down to a specified number of decimal places
+ *
+ * @param float $number Number to round
+ * @param int $digits Number of digits to which you want to round $number
+ * @return float Rounded Number
+ */
+ public static function ROUNDDOWN($number,$digits) {
+ $number = Calculation_Functions::flattenSingleValue($number);
+ $digits = Calculation_Functions::flattenSingleValue($digits);
+
+ if ((is_numeric($number)) && (is_numeric($digits))) {
+ $significance = pow(10,(int) $digits);
+ if ($number < 0.0) {
+ return ceil($number * $significance) / $significance;
+ } else {
+ return floor($number * $significance) / $significance;
+ }
+ }
+ return Calculation_Functions::VALUE();
+ } // function ROUNDDOWN()
+
+
+ /**
+ * SERIESSUM
+ *
+ * Returns the sum of a power series
+ *
+ * @param float $x Input value to the power series
+ * @param float $n Initial power to which you want to raise $x
+ * @param float $m Step by which to increase $n for each term in the series
+ * @param array of mixed Data Series
+ * @return float
+ */
+ public static function SERIESSUM() {
+ // Return value
+ $returnValue = 0;
+
+ // Loop through arguments
+ $aArgs = Calculation_Functions::flattenArray(func_get_args());
+
+ $x = array_shift($aArgs);
+ $n = array_shift($aArgs);
+ $m = array_shift($aArgs);
+
+ if ((is_numeric($x)) && (is_numeric($n)) && (is_numeric($m))) {
+ // Calculate
+ $i = 0;
+ foreach($aArgs as $arg) {
+ // Is it a numeric value?
+ if ((is_numeric($arg)) && (!is_string($arg))) {
+ $returnValue += $arg * pow($x,$n + ($m * $i++));
+ } else {
+ return Calculation_Functions::VALUE();
+ }
+ }
+ // Return
+ return $returnValue;
+ }
+ return Calculation_Functions::VALUE();
+ } // function SERIESSUM()
+
+
+ /**
+ * SIGN
+ *
+ * Determines the sign of a number. Returns 1 if the number is positive, zero (0)
+ * if the number is 0, and -1 if the number is negative.
+ *
+ * @param float $number Number to round
+ * @return int sign value
+ */
+ public static function SIGN($number) {
+ $number = Calculation_Functions::flattenSingleValue($number);
+
+ if (is_bool($number))
+ return (int) $number;
+ if (is_numeric($number)) {
+ if ($number == 0.0) {
+ return 0;
+ }
+ return $number / abs($number);
+ }
+ return Calculation_Functions::VALUE();
+ } // function SIGN()
+
+
+ /**
+ * SQRTPI
+ *
+ * Returns the square root of (number * pi).
+ *
+ * @param float $number Number
+ * @return float Square Root of Number * Pi
+ */
+ public static function SQRTPI($number) {
+ $number = Calculation_Functions::flattenSingleValue($number);
+
+ if (is_numeric($number)) {
+ if ($number < 0) {
+ return Calculation_Functions::NaN();
+ }
+ return sqrt($number * M_PI) ;
+ }
+ return Calculation_Functions::VALUE();
+ } // function SQRTPI()
+
+
+ /**
+ * SUBTOTAL
+ *
+ * Returns a subtotal in a list or database.
+ *
+ * @param int the number 1 to 11 that specifies which function to
+ * use in calculating subtotals within a list.
+ * @param array of mixed Data Series
+ * @return float
+ */
+ public static function SUBTOTAL() {
+ $aArgs = Calculation_Functions::flattenArray(func_get_args());
+
+ // Calculate
+ $subtotal = array_shift($aArgs);
+
+ if ((is_numeric($subtotal)) && (!is_string($subtotal))) {
+ switch($subtotal) {
+ case 1 :
+ return Calculation_Statistical::AVERAGE($aArgs);
+ break;
+ case 2 :
+ return Calculation_Statistical::COUNT($aArgs);
+ break;
+ case 3 :
+ return Calculation_Statistical::COUNTA($aArgs);
+ break;
+ case 4 :
+ return Calculation_Statistical::MAX($aArgs);
+ break;
+ case 5 :
+ return Calculation_Statistical::MIN($aArgs);
+ break;
+ case 6 :
+ return self::PRODUCT($aArgs);
+ break;
+ case 7 :
+ return Calculation_Statistical::STDEV($aArgs);
+ break;
+ case 8 :
+ return Calculation_Statistical::STDEVP($aArgs);
+ break;
+ case 9 :
+ return self::SUM($aArgs);
+ break;
+ case 10 :
+ return Calculation_Statistical::VARFunc($aArgs);
+ break;
+ case 11 :
+ return Calculation_Statistical::VARP($aArgs);
+ break;
+ }
+ }
+ return Calculation_Functions::VALUE();
+ } // function SUBTOTAL()
+
+
+ /**
+ * SUM
+ *
+ * SUM computes the sum of all the values and cells referenced in the argument list.
+ *
+ * Excel Function:
+ * SUM(value1[,value2[, ...]])
+ *
+ * @access public
+ * @category Mathematical and Trigonometric Functions
+ * @param mixed $arg,... Data values
+ * @return float
+ */
+ public static function SUM() {
+ // Return value
+ $returnValue = 0;
+
+ // Loop through the arguments
+ foreach (Calculation_Functions::flattenArray(func_get_args()) as $arg) {
+ // Is it a numeric value?
+ if ((is_numeric($arg)) && (!is_string($arg))) {
+ $returnValue += $arg;
+ }
+ }
+
+ // Return
+ return $returnValue;
+ } // function SUM()
+
+
+ /**
+ * SUMIF
+ *
+ * Counts the number of cells that contain numbers within the list of arguments
+ *
+ * Excel Function:
+ * SUMIF(value1[,value2[, ...]],condition)
+ *
+ * @access public
+ * @category Mathematical and Trigonometric Functions
+ * @param mixed $arg,... Data values
+ * @param string $condition The criteria that defines which cells will be summed.
+ * @return float
+ */
+ public static function SUMIF($aArgs,$condition,$sumArgs = array()) {
+ // Return value
+ $returnValue = 0;
+
+ $aArgs = Calculation_Functions::flattenArray($aArgs);
+ $sumArgs = Calculation_Functions::flattenArray($sumArgs);
+ if (empty($sumArgs)) {
+ $sumArgs = $aArgs;
+ }
+ $condition = Calculation_Functions::_ifCondition($condition);
+ // Loop through arguments
+ foreach ($aArgs as $key => $arg) {
+ if (!is_numeric($arg)) { $arg = Calculation::_wrapResult(strtoupper($arg)); }
+ $testCondition = '='.$arg.$condition;
+ if (Calculation::getInstance()->_calculateFormulaValue($testCondition)) {
+ // Is it a value within our criteria
+ $returnValue += $sumArgs[$key];
+ }
+ }
+
+ // Return
+ return $returnValue;
+ } // function SUMIF()
+
+
+ /**
+ * SUMPRODUCT
+ *
+ * Excel Function:
+ * SUMPRODUCT(value1[,value2[, ...]])
+ *
+ * @access public
+ * @category Mathematical and Trigonometric Functions
+ * @param mixed $arg,... Data values
+ * @return float
+ */
+ public static function SUMPRODUCT() {
+ $arrayList = func_get_args();
+
+ $wrkArray = Calculation_Functions::flattenArray(array_shift($arrayList));
+ $wrkCellCount = count($wrkArray);
+
+ for ($i=0; $i< $wrkCellCount; ++$i) {
+ if ((!is_numeric($wrkArray[$i])) || (is_string($wrkArray[$i]))) {
+ $wrkArray[$i] = 0;
+ }
+ }
+
+ foreach($arrayList as $matrixData) {
+ $array2 = Calculation_Functions::flattenArray($matrixData);
+ $count = count($array2);
+ if ($wrkCellCount != $count) {
+ return Calculation_Functions::VALUE();
+ }
+
+ foreach ($array2 as $i => $val) {
+ if ((!is_numeric($val)) || (is_string($val))) {
+ $val = 0;
+ }
+ $wrkArray[$i] *= $val;
+ }
+ }
+
+ return array_sum($wrkArray);
+ } // function SUMPRODUCT()
+
+
+ /**
+ * SUMSQ
+ *
+ * SUMSQ returns the sum of the squares of the arguments
+ *
+ * Excel Function:
+ * SUMSQ(value1[,value2[, ...]])
+ *
+ * @access public
+ * @category Mathematical and Trigonometric Functions
+ * @param mixed $arg,... Data values
+ * @return float
+ */
+ public static function SUMSQ() {
+ // Return value
+ $returnValue = 0;
+
+ // Loop through arguments
+ foreach (Calculation_Functions::flattenArray(func_get_args()) as $arg) {
+ // Is it a numeric value?
+ if ((is_numeric($arg)) && (!is_string($arg))) {
+ $returnValue += ($arg * $arg);
+ }
+ }
+
+ // Return
+ return $returnValue;
+ } // function SUMSQ()
+
+
+ /**
+ * SUMX2MY2
+ *
+ * @param mixed[] $matrixData1 Matrix #1
+ * @param mixed[] $matrixData2 Matrix #2
+ * @return float
+ */
+ public static function SUMX2MY2($matrixData1,$matrixData2) {
+ $array1 = Calculation_Functions::flattenArray($matrixData1);
+ $array2 = Calculation_Functions::flattenArray($matrixData2);
+ $count1 = count($array1);
+ $count2 = count($array2);
+ if ($count1 < $count2) {
+ $count = $count1;
+ } else {
+ $count = $count2;
+ }
+
+ $result = 0;
+ for ($i = 0; $i < $count; ++$i) {
+ if (((is_numeric($array1[$i])) && (!is_string($array1[$i]))) &&
+ ((is_numeric($array2[$i])) && (!is_string($array2[$i])))) {
+ $result += ($array1[$i] * $array1[$i]) - ($array2[$i] * $array2[$i]);
+ }
+ }
+
+ return $result;
+ } // function SUMX2MY2()
+
+
+ /**
+ * SUMX2PY2
+ *
+ * @param mixed[] $matrixData1 Matrix #1
+ * @param mixed[] $matrixData2 Matrix #2
+ * @return float
+ */
+ public static function SUMX2PY2($matrixData1,$matrixData2) {
+ $array1 = Calculation_Functions::flattenArray($matrixData1);
+ $array2 = Calculation_Functions::flattenArray($matrixData2);
+ $count1 = count($array1);
+ $count2 = count($array2);
+ if ($count1 < $count2) {
+ $count = $count1;
+ } else {
+ $count = $count2;
+ }
+
+ $result = 0;
+ for ($i = 0; $i < $count; ++$i) {
+ if (((is_numeric($array1[$i])) && (!is_string($array1[$i]))) &&
+ ((is_numeric($array2[$i])) && (!is_string($array2[$i])))) {
+ $result += ($array1[$i] * $array1[$i]) + ($array2[$i] * $array2[$i]);
+ }
+ }
+
+ return $result;
+ } // function SUMX2PY2()
+
+
+ /**
+ * SUMXMY2
+ *
+ * @param mixed[] $matrixData1 Matrix #1
+ * @param mixed[] $matrixData2 Matrix #2
+ * @return float
+ */
+ public static function SUMXMY2($matrixData1,$matrixData2) {
+ $array1 = Calculation_Functions::flattenArray($matrixData1);
+ $array2 = Calculation_Functions::flattenArray($matrixData2);
+ $count1 = count($array1);
+ $count2 = count($array2);
+ if ($count1 < $count2) {
+ $count = $count1;
+ } else {
+ $count = $count2;
+ }
+
+ $result = 0;
+ for ($i = 0; $i < $count; ++$i) {
+ if (((is_numeric($array1[$i])) && (!is_string($array1[$i]))) &&
+ ((is_numeric($array2[$i])) && (!is_string($array2[$i])))) {
+ $result += ($array1[$i] - $array2[$i]) * ($array1[$i] - $array2[$i]);
+ }
+ }
+
+ return $result;
+ } // function SUMXMY2()
+
+
+ /**
+ * TRUNC
+ *
+ * Truncates value to the number of fractional digits by number_digits.
+ *
+ * @param float $value
+ * @param int $digits
+ * @return float Truncated value
+ */
+ public static function TRUNC($value = 0, $digits = 0) {
+ $value = Calculation_Functions::flattenSingleValue($value);
+ $digits = Calculation_Functions::flattenSingleValue($digits);
+
+ // Validate parameters
+ if ((!is_numeric($value)) || (!is_numeric($digits)))
+ return Calculation_Functions::VALUE();
+ $digits = floor($digits);
+
+ // Truncate
+ $adjust = pow(10, $digits);
+
+ if (($digits > 0) && (rtrim(intval((abs($value) - abs(intval($value))) * $adjust),'0') < $adjust/10))
+ return $value;
+
+ return (intval($value * $adjust)) / $adjust;
+ } // function TRUNC()
}
diff --git a/Classes/PHPExcel/Calculation/Statistical.php b/Classes/PHPExcel/Calculation/Statistical.php
index cf8f272..5fdd72c 100644
--- a/Classes/PHPExcel/Calculation/Statistical.php
+++ b/Classes/PHPExcel/Calculation/Statistical.php
@@ -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##
*/
@@ -46,3597 +46,3596 @@ define('SQRT2PI', 2.5066282746310005024157652848110452530069867406099);
/**
* PHPExcel\Calculation_Statistical
*
- * @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_Statistical {
- private static function _checkTrendArrays(&$array1,&$array2) {
- if (!is_array($array1)) { $array1 = array($array1); }
- if (!is_array($array2)) { $array2 = array($array2); }
-
- $array1 = Calculation_Functions::flattenArray($array1);
- $array2 = Calculation_Functions::flattenArray($array2);
- foreach($array1 as $key => $value) {
- if ((is_bool($value)) || (is_string($value)) || (is_null($value))) {
- unset($array1[$key]);
- unset($array2[$key]);
- }
- }
- foreach($array2 as $key => $value) {
- if ((is_bool($value)) || (is_string($value)) || (is_null($value))) {
- unset($array1[$key]);
- unset($array2[$key]);
- }
- }
- $array1 = array_merge($array1);
- $array2 = array_merge($array2);
-
- return True;
- } // function _checkTrendArrays()
-
-
- /**
- * Beta function.
- *
- * @author Jaco van Kooten
- *
- * @param p require p>0
- * @param q require q>0
- * @return 0 if p<=0, q<=0 or p+q>2.55E305 to avoid errors and over/underflow
- */
- private static function _beta($p, $q) {
- if ($p <= 0.0 || $q <= 0.0 || ($p + $q) > LOG_GAMMA_X_MAX_VALUE) {
- return 0.0;
- } else {
- return exp(self::_logBeta($p, $q));
- }
- } // function _beta()
-
-
- /**
- * Incomplete beta function
- *
- * @author Jaco van Kooten
- * @author Paul Meagher
- *
- * The computation is based on formulas from Numerical Recipes, Chapter 6.4 (W.H. Press et al, 1992).
- * @param x require 0<=x<=1
- * @param p require p>0
- * @param q require q>0
- * @return 0 if x<0, p<=0, q<=0 or p+q>2.55E305 and 1 if x>1 to avoid errors and over/underflow
- */
- private static function _incompleteBeta($x, $p, $q) {
- if ($x <= 0.0) {
- return 0.0;
- } elseif ($x >= 1.0) {
- return 1.0;
- } elseif (($p <= 0.0) || ($q <= 0.0) || (($p + $q) > LOG_GAMMA_X_MAX_VALUE)) {
- return 0.0;
- }
- $beta_gam = exp((0 - self::_logBeta($p, $q)) + $p * log($x) + $q * log(1.0 - $x));
- if ($x < ($p + 1.0) / ($p + $q + 2.0)) {
- return $beta_gam * self::_betaFraction($x, $p, $q) / $p;
- } else {
- return 1.0 - ($beta_gam * self::_betaFraction(1 - $x, $q, $p) / $q);
- }
- } // function _incompleteBeta()
-
-
- // Function cache for _logBeta function
- private static $_logBetaCache_p = 0.0;
- private static $_logBetaCache_q = 0.0;
- private static $_logBetaCache_result = 0.0;
-
- /**
- * The natural logarithm of the beta function.
- *
- * @param p require p>0
- * @param q require q>0
- * @return 0 if p<=0, q<=0 or p+q>2.55E305 to avoid errors and over/underflow
- * @author Jaco van Kooten
- */
- private static function _logBeta($p, $q) {
- if ($p != self::$_logBetaCache_p || $q != self::$_logBetaCache_q) {
- self::$_logBetaCache_p = $p;
- self::$_logBetaCache_q = $q;
- if (($p <= 0.0) || ($q <= 0.0) || (($p + $q) > LOG_GAMMA_X_MAX_VALUE)) {
- self::$_logBetaCache_result = 0.0;
- } else {
- self::$_logBetaCache_result = self::_logGamma($p) + self::_logGamma($q) - self::_logGamma($p + $q);
- }
- }
- return self::$_logBetaCache_result;
- } // function _logBeta()
-
-
- /**
- * Evaluates of continued fraction part of incomplete beta function.
- * Based on an idea from Numerical Recipes (W.H. Press et al, 1992).
- * @author Jaco van Kooten
- */
- private static function _betaFraction($x, $p, $q) {
- $c = 1.0;
- $sum_pq = $p + $q;
- $p_plus = $p + 1.0;
- $p_minus = $p - 1.0;
- $h = 1.0 - $sum_pq * $x / $p_plus;
- if (abs($h) < XMININ) {
- $h = XMININ;
- }
- $h = 1.0 / $h;
- $frac = $h;
- $m = 1;
- $delta = 0.0;
- while ($m <= MAX_ITERATIONS && abs($delta-1.0) > PRECISION ) {
- $m2 = 2 * $m;
- // even index for d
- $d = $m * ($q - $m) * $x / ( ($p_minus + $m2) * ($p + $m2));
- $h = 1.0 + $d * $h;
- if (abs($h) < XMININ) {
- $h = XMININ;
- }
- $h = 1.0 / $h;
- $c = 1.0 + $d / $c;
- if (abs($c) < XMININ) {
- $c = XMININ;
- }
- $frac *= $h * $c;
- // odd index for d
- $d = -($p + $m) * ($sum_pq + $m) * $x / (($p + $m2) * ($p_plus + $m2));
- $h = 1.0 + $d * $h;
- if (abs($h) < XMININ) {
- $h = XMININ;
- }
- $h = 1.0 / $h;
- $c = 1.0 + $d / $c;
- if (abs($c) < XMININ) {
- $c = XMININ;
- }
- $delta = $h * $c;
- $frac *= $delta;
- ++$m;
- }
- return $frac;
- } // function _betaFraction()
-
-
- /**
- * logGamma function
- *
- * @version 1.1
- * @author Jaco van Kooten
- *
- * Original author was Jaco van Kooten. Ported to PHP by Paul Meagher.
- *
- * The natural logarithm of the gamma function.
- * Based on public domain NETLIB (Fortran) code by W. J. Cody and L. Stoltz
- * Applied Mathematics Division
- * Argonne National Laboratory
- * Argonne, IL 60439
- *
- *
- *
- * From the original documentation: - *
- *- * This routine calculates the LOG(GAMMA) function for a positive real argument X. - * Computation is based on an algorithm outlined in references 1 and 2. - * The program uses rational functions that theoretically approximate LOG(GAMMA) - * to at least 18 significant decimal digits. The approximation for X > 12 is from - * reference 3, while approximations for X < 12.0 are similar to those in reference - * 1, but are unpublished. The accuracy achieved depends on the arithmetic system, - * the compiler, the intrinsic functions, and proper selection of the - * machine-dependent constants. - *
- *
- * Error returns:
- * The program returns the value XINF for X .LE. 0.0 or when overflow would occur.
- * The computation is believed to be free of underflow and overflow.
- *
+ * References: + *
+ * From the original documentation: + *
+ *+ * This routine calculates the LOG(GAMMA) function for a positive real argument X. + * Computation is based on an algorithm outlined in references 1 and 2. + * The program uses rational functions that theoretically approximate LOG(GAMMA) + * to at least 18 significant decimal digits. The approximation for X > 12 is from + * reference 3, while approximations for X < 12.0 are similar to those in reference + * 1, but are unpublished. The accuracy achieved depends on the arithmetic system, + * the compiler, the intrinsic functions, and proper selection of the + * machine-dependent constants. + *
+ *
+ * Error returns:
+ * The program returns the value XINF for X .LE. 0.0 or when overflow would occur.
+ * The computation is believed to be free of underflow and overflow.
+ *
'; -// print_r($sharedFormulas); -// echo ''; - if (!isset($sharedFormulas[(string)$c->f['si']])) { -// echo 'SETTING NEW SHARED FORMULA
'; -// print_r($sharedFormulas); -// echo ''; - } else { -// echo 'GETTING SHARED FORMULA
'; +// print_r($sharedFormulas); +// echo ''; + if (!isset($sharedFormulas[(string)$c->f['si']])) { +// echo 'SETTING NEW SHARED FORMULA
'; +// print_r($sharedFormulas); +// echo ''; + } else { +// echo 'GETTING SHARED FORMULA
'; -// echo htmlentities($gFileData,ENT_QUOTES,'UTF-8'); -// echo '
'; +// echo htmlentities($gFileData,ENT_QUOTES,'UTF-8'); +// echo '
'; -// print_r($namespacesMeta); -// echo '
'; +// print_r($namespacesMeta); +// echo '
'; -// print_r($namespacesContent); -// echo '
'; +// print_r($namespacesContent); +// echo '
= -1; --$k) { - if ($k == -1) { - break; - } - if (abs($e[$k]) <= $eps * (abs($this->s[$k]) + abs($this->s[$k+1]))) { - $e[$k] = 0.0; - break; - } - } - if ($k == $p - 2) { - $kase = 4; - } else { - for ($ks = $p - 1; $ks >= $k; --$ks) { - if ($ks == $k) { - break; - } - $t = ($ks != $p ? abs($e[$ks]) : 0.) + ($ks != $k + 1 ? abs($e[$ks-1]) : 0.); - if (abs($this->s[$ks]) <= $eps * $t) { - $this->s[$ks] = 0.0; - break; - } - } - if ($ks == $k) { - $kase = 3; - } else if ($ks == $p-1) { - $kase = 1; - } else { - $kase = 2; - $k = $ks; - } - } - ++$k; + while ($p > 0) { + // Here is where a test for too many iterations would go. + // This section of the program inspects for negligible + // elements in the s and e arrays. On completion the + // variables kase and k are set as follows: + // kase = 1 if s(p) and e[k-1] are negligible and k
= -1; --$k) {
+ if ($k == -1) {
+ break;
+ }
+ if (abs($e[$k]) <= $eps * (abs($this->s[$k]) + abs($this->s[$k+1]))) {
+ $e[$k] = 0.0;
+ break;
+ }
+ }
+ if ($k == $p - 2) {
+ $kase = 4;
+ } else {
+ for ($ks = $p - 1; $ks >= $k; --$ks) {
+ if ($ks == $k) {
+ break;
+ }
+ $t = ($ks != $p ? abs($e[$ks]) : 0.) + ($ks != $k + 1 ? abs($e[$ks-1]) : 0.);
+ if (abs($this->s[$ks]) <= $eps * $t) {
+ $this->s[$ks] = 0.0;
+ break;
+ }
+ }
+ if ($ks == $k) {
+ $kase = 3;
+ } else if ($ks == $p-1) {
+ $kase = 1;
+ } else {
+ $kase = 2;
+ $k = $ks;
+ }
+ }
+ ++$k;
- // Perform the task indicated by kase.
- switch ($kase) {
- // Deflate negligible s(p).
- case 1:
- $f = $e[$p-2];
- $e[$p-2] = 0.0;
- for ($j = $p - 2; $j >= $k; --$j) {
- $t = hypo($this->s[$j],$f);
- $cs = $this->s[$j] / $t;
- $sn = $f / $t;
- $this->s[$j] = $t;
- if ($j != $k) {
- $f = -$sn * $e[$j-1];
- $e[$j-1] = $cs * $e[$j-1];
- }
- if ($wantv) {
- for ($i = 0; $i < $this->n; ++$i) {
- $t = $cs * $this->V[$i][$j] + $sn * $this->V[$i][$p-1];
- $this->V[$i][$p-1] = -$sn * $this->V[$i][$j] + $cs * $this->V[$i][$p-1];
- $this->V[$i][$j] = $t;
- }
- }
- }
- break;
- // Split at negligible s(k).
- case 2:
- $f = $e[$k-1];
- $e[$k-1] = 0.0;
- for ($j = $k; $j < $p; ++$j) {
- $t = hypo($this->s[$j], $f);
- $cs = $this->s[$j] / $t;
- $sn = $f / $t;
- $this->s[$j] = $t;
- $f = -$sn * $e[$j];
- $e[$j] = $cs * $e[$j];
- if ($wantu) {
- for ($i = 0; $i < $this->m; ++$i) {
- $t = $cs * $this->U[$i][$j] + $sn * $this->U[$i][$k-1];
- $this->U[$i][$k-1] = -$sn * $this->U[$i][$j] + $cs * $this->U[$i][$k-1];
- $this->U[$i][$j] = $t;
- }
- }
- }
- break;
- // Perform one qr step.
- case 3:
- // Calculate the shift.
- $scale = max(max(max(max(
- abs($this->s[$p-1]),abs($this->s[$p-2])),abs($e[$p-2])),
- abs($this->s[$k])), abs($e[$k]));
- $sp = $this->s[$p-1] / $scale;
- $spm1 = $this->s[$p-2] / $scale;
- $epm1 = $e[$p-2] / $scale;
- $sk = $this->s[$k] / $scale;
- $ek = $e[$k] / $scale;
- $b = (($spm1 + $sp) * ($spm1 - $sp) + $epm1 * $epm1) / 2.0;
- $c = ($sp * $epm1) * ($sp * $epm1);
- $shift = 0.0;
- if (($b != 0.0) || ($c != 0.0)) {
- $shift = sqrt($b * $b + $c);
- if ($b < 0.0) {
- $shift = -$shift;
- }
- $shift = $c / ($b + $shift);
- }
- $f = ($sk + $sp) * ($sk - $sp) + $shift;
- $g = $sk * $ek;
- // Chase zeros.
- for ($j = $k; $j < $p-1; ++$j) {
- $t = hypo($f,$g);
- $cs = $f/$t;
- $sn = $g/$t;
- if ($j != $k) {
- $e[$j-1] = $t;
- }
- $f = $cs * $this->s[$j] + $sn * $e[$j];
- $e[$j] = $cs * $e[$j] - $sn * $this->s[$j];
- $g = $sn * $this->s[$j+1];
- $this->s[$j+1] = $cs * $this->s[$j+1];
- if ($wantv) {
- for ($i = 0; $i < $this->n; ++$i) {
- $t = $cs * $this->V[$i][$j] + $sn * $this->V[$i][$j+1];
- $this->V[$i][$j+1] = -$sn * $this->V[$i][$j] + $cs * $this->V[$i][$j+1];
- $this->V[$i][$j] = $t;
- }
- }
- $t = hypo($f,$g);
- $cs = $f/$t;
- $sn = $g/$t;
- $this->s[$j] = $t;
- $f = $cs * $e[$j] + $sn * $this->s[$j+1];
- $this->s[$j+1] = -$sn * $e[$j] + $cs * $this->s[$j+1];
- $g = $sn * $e[$j+1];
- $e[$j+1] = $cs * $e[$j+1];
- if ($wantu && ($j < $this->m - 1)) {
- for ($i = 0; $i < $this->m; ++$i) {
- $t = $cs * $this->U[$i][$j] + $sn * $this->U[$i][$j+1];
- $this->U[$i][$j+1] = -$sn * $this->U[$i][$j] + $cs * $this->U[$i][$j+1];
- $this->U[$i][$j] = $t;
- }
- }
- }
- $e[$p-2] = $f;
- $iter = $iter + 1;
- break;
- // Convergence.
- case 4:
- // Make the singular values positive.
- if ($this->s[$k] <= 0.0) {
- $this->s[$k] = ($this->s[$k] < 0.0 ? -$this->s[$k] : 0.0);
- if ($wantv) {
- for ($i = 0; $i <= $pp; ++$i) {
- $this->V[$i][$k] = -$this->V[$i][$k];
- }
- }
- }
- // Order the singular values.
- while ($k < $pp) {
- if ($this->s[$k] >= $this->s[$k+1]) {
- break;
- }
- $t = $this->s[$k];
- $this->s[$k] = $this->s[$k+1];
- $this->s[$k+1] = $t;
- if ($wantv AND ($k < $this->n - 1)) {
- for ($i = 0; $i < $this->n; ++$i) {
- $t = $this->V[$i][$k+1];
- $this->V[$i][$k+1] = $this->V[$i][$k];
- $this->V[$i][$k] = $t;
- }
- }
- if ($wantu AND ($k < $this->m-1)) {
- for ($i = 0; $i < $this->m; ++$i) {
- $t = $this->U[$i][$k+1];
- $this->U[$i][$k+1] = $this->U[$i][$k];
- $this->U[$i][$k] = $t;
- }
- }
- ++$k;
- }
- $iter = 0;
- --$p;
- break;
- } // end switch
- } // end while
+ // Perform the task indicated by kase.
+ switch ($kase) {
+ // Deflate negligible s(p).
+ case 1:
+ $f = $e[$p-2];
+ $e[$p-2] = 0.0;
+ for ($j = $p - 2; $j >= $k; --$j) {
+ $t = hypo($this->s[$j],$f);
+ $cs = $this->s[$j] / $t;
+ $sn = $f / $t;
+ $this->s[$j] = $t;
+ if ($j != $k) {
+ $f = -$sn * $e[$j-1];
+ $e[$j-1] = $cs * $e[$j-1];
+ }
+ if ($wantv) {
+ for ($i = 0; $i < $this->n; ++$i) {
+ $t = $cs * $this->V[$i][$j] + $sn * $this->V[$i][$p-1];
+ $this->V[$i][$p-1] = -$sn * $this->V[$i][$j] + $cs * $this->V[$i][$p-1];
+ $this->V[$i][$j] = $t;
+ }
+ }
+ }
+ break;
+ // Split at negligible s(k).
+ case 2:
+ $f = $e[$k-1];
+ $e[$k-1] = 0.0;
+ for ($j = $k; $j < $p; ++$j) {
+ $t = hypo($this->s[$j], $f);
+ $cs = $this->s[$j] / $t;
+ $sn = $f / $t;
+ $this->s[$j] = $t;
+ $f = -$sn * $e[$j];
+ $e[$j] = $cs * $e[$j];
+ if ($wantu) {
+ for ($i = 0; $i < $this->m; ++$i) {
+ $t = $cs * $this->U[$i][$j] + $sn * $this->U[$i][$k-1];
+ $this->U[$i][$k-1] = -$sn * $this->U[$i][$j] + $cs * $this->U[$i][$k-1];
+ $this->U[$i][$j] = $t;
+ }
+ }
+ }
+ break;
+ // Perform one qr step.
+ case 3:
+ // Calculate the shift.
+ $scale = max(max(max(max(
+ abs($this->s[$p-1]),abs($this->s[$p-2])),abs($e[$p-2])),
+ abs($this->s[$k])), abs($e[$k]));
+ $sp = $this->s[$p-1] / $scale;
+ $spm1 = $this->s[$p-2] / $scale;
+ $epm1 = $e[$p-2] / $scale;
+ $sk = $this->s[$k] / $scale;
+ $ek = $e[$k] / $scale;
+ $b = (($spm1 + $sp) * ($spm1 - $sp) + $epm1 * $epm1) / 2.0;
+ $c = ($sp * $epm1) * ($sp * $epm1);
+ $shift = 0.0;
+ if (($b != 0.0) || ($c != 0.0)) {
+ $shift = sqrt($b * $b + $c);
+ if ($b < 0.0) {
+ $shift = -$shift;
+ }
+ $shift = $c / ($b + $shift);
+ }
+ $f = ($sk + $sp) * ($sk - $sp) + $shift;
+ $g = $sk * $ek;
+ // Chase zeros.
+ for ($j = $k; $j < $p-1; ++$j) {
+ $t = hypo($f,$g);
+ $cs = $f/$t;
+ $sn = $g/$t;
+ if ($j != $k) {
+ $e[$j-1] = $t;
+ }
+ $f = $cs * $this->s[$j] + $sn * $e[$j];
+ $e[$j] = $cs * $e[$j] - $sn * $this->s[$j];
+ $g = $sn * $this->s[$j+1];
+ $this->s[$j+1] = $cs * $this->s[$j+1];
+ if ($wantv) {
+ for ($i = 0; $i < $this->n; ++$i) {
+ $t = $cs * $this->V[$i][$j] + $sn * $this->V[$i][$j+1];
+ $this->V[$i][$j+1] = -$sn * $this->V[$i][$j] + $cs * $this->V[$i][$j+1];
+ $this->V[$i][$j] = $t;
+ }
+ }
+ $t = hypo($f,$g);
+ $cs = $f/$t;
+ $sn = $g/$t;
+ $this->s[$j] = $t;
+ $f = $cs * $e[$j] + $sn * $this->s[$j+1];
+ $this->s[$j+1] = -$sn * $e[$j] + $cs * $this->s[$j+1];
+ $g = $sn * $e[$j+1];
+ $e[$j+1] = $cs * $e[$j+1];
+ if ($wantu && ($j < $this->m - 1)) {
+ for ($i = 0; $i < $this->m; ++$i) {
+ $t = $cs * $this->U[$i][$j] + $sn * $this->U[$i][$j+1];
+ $this->U[$i][$j+1] = -$sn * $this->U[$i][$j] + $cs * $this->U[$i][$j+1];
+ $this->U[$i][$j] = $t;
+ }
+ }
+ }
+ $e[$p-2] = $f;
+ $iter = $iter + 1;
+ break;
+ // Convergence.
+ case 4:
+ // Make the singular values positive.
+ if ($this->s[$k] <= 0.0) {
+ $this->s[$k] = ($this->s[$k] < 0.0 ? -$this->s[$k] : 0.0);
+ if ($wantv) {
+ for ($i = 0; $i <= $pp; ++$i) {
+ $this->V[$i][$k] = -$this->V[$i][$k];
+ }
+ }
+ }
+ // Order the singular values.
+ while ($k < $pp) {
+ if ($this->s[$k] >= $this->s[$k+1]) {
+ break;
+ }
+ $t = $this->s[$k];
+ $this->s[$k] = $this->s[$k+1];
+ $this->s[$k+1] = $t;
+ if ($wantv AND ($k < $this->n - 1)) {
+ for ($i = 0; $i < $this->n; ++$i) {
+ $t = $this->V[$i][$k+1];
+ $this->V[$i][$k+1] = $this->V[$i][$k];
+ $this->V[$i][$k] = $t;
+ }
+ }
+ if ($wantu AND ($k < $this->m-1)) {
+ for ($i = 0; $i < $this->m; ++$i) {
+ $t = $this->U[$i][$k+1];
+ $this->U[$i][$k+1] = $this->U[$i][$k];
+ $this->U[$i][$k] = $t;
+ }
+ }
+ ++$k;
+ }
+ $iter = 0;
+ --$p;
+ break;
+ } // end switch
+ } // end while
- } // end constructor
+ } // end constructor
- /**
- * Return the left singular vectors
- *
- * @access public
- * @return U
- */
- public function getU() {
- return new Matrix($this->U, $this->m, min($this->m + 1, $this->n));
- }
+ /**
+ * Return the left singular vectors
+ *
+ * @access public
+ * @return U
+ */
+ public function getU() {
+ return new Matrix($this->U, $this->m, min($this->m + 1, $this->n));
+ }
- /**
- * Return the right singular vectors
- *
- * @access public
- * @return V
- */
- public function getV() {
- return new Matrix($this->V);
- }
+ /**
+ * Return the right singular vectors
+ *
+ * @access public
+ * @return V
+ */
+ public function getV() {
+ return new Matrix($this->V);
+ }
- /**
- * Return the one-dimensional array of singular values
- *
- * @access public
- * @return diagonal of S.
- */
- public function getSingularValues() {
- return $this->s;
- }
+ /**
+ * Return the one-dimensional array of singular values
+ *
+ * @access public
+ * @return diagonal of S.
+ */
+ public function getSingularValues() {
+ return $this->s;
+ }
- /**
- * Return the diagonal matrix of singular values
- *
- * @access public
- * @return S
- */
- public function getS() {
- for ($i = 0; $i < $this->n; ++$i) {
- for ($j = 0; $j < $this->n; ++$j) {
- $S[$i][$j] = 0.0;
- }
- $S[$i][$i] = $this->s[$i];
- }
- return new Matrix($S);
- }
+ /**
+ * Return the diagonal matrix of singular values
+ *
+ * @access public
+ * @return S
+ */
+ public function getS() {
+ for ($i = 0; $i < $this->n; ++$i) {
+ for ($j = 0; $j < $this->n; ++$j) {
+ $S[$i][$j] = 0.0;
+ }
+ $S[$i][$i] = $this->s[$i];
+ }
+ return new Matrix($S);
+ }
- /**
- * Two norm
- *
- * @access public
- * @return max(S)
- */
- public function norm2() {
- return $this->s[0];
- }
+ /**
+ * Two norm
+ *
+ * @access public
+ * @return max(S)
+ */
+ public function norm2() {
+ return $this->s[0];
+ }
- /**
- * Two norm condition number
- *
- * @access public
- * @return max(S)/min(S)
- */
- public function cond() {
- return $this->s[0] / $this->s[min($this->m, $this->n) - 1];
- }
+ /**
+ * Two norm condition number
+ *
+ * @access public
+ * @return max(S)/min(S)
+ */
+ public function cond() {
+ return $this->s[0] / $this->s[min($this->m, $this->n) - 1];
+ }
- /**
- * Effective numerical matrix rank
- *
- * @access public
- * @return Number of nonnegligible singular values.
- */
- public function rank() {
- $eps = pow(2.0, -52.0);
- $tol = max($this->m, $this->n) * $this->s[0] * $eps;
- $r = 0;
- for ($i = 0; $i < count($this->s); ++$i) {
- if ($this->s[$i] > $tol) {
- ++$r;
- }
- }
- return $r;
- }
+ /**
+ * Effective numerical matrix rank
+ *
+ * @access public
+ * @return Number of nonnegligible singular values.
+ */
+ public function rank() {
+ $eps = pow(2.0, -52.0);
+ $tol = max($this->m, $this->n) * $this->s[0] * $eps;
+ $r = 0;
+ for ($i = 0; $i < count($this->s); ++$i) {
+ if ($this->s[$i] > $tol) {
+ ++$r;
+ }
+ }
+ return $r;
+ }
-} // class SingularValueDecomposition
+} // class SingularValueDecomposition
diff --git a/Classes/PHPExcel/Shared/JAMA/utils/Error.php b/Classes/PHPExcel/Shared/JAMA/utils/Error.php
index e73252b..ff51ccc 100644
--- a/Classes/PHPExcel/Shared/JAMA/utils/Error.php
+++ b/Classes/PHPExcel/Shared/JAMA/utils/Error.php
@@ -1,10 +1,10 @@
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);
}
*/
diff --git a/Classes/PHPExcel/Shared/OLE.php b/Classes/PHPExcel/Shared/OLE.php
index 9f2729c..29e8d6e 100644
--- a/Classes/PHPExcel/Shared/OLE.php
+++ b/Classes/PHPExcel/Shared/OLE.php
@@ -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);
+ }
}
diff --git a/Classes/PHPExcel/Shared/OLE/ChainedBlockStream.php b/Classes/PHPExcel/Shared/OLE/ChainedBlockStream.php
index 95758dc..3ea5405 100644
--- a/Classes/PHPExcel/Shared/OLE/ChainedBlockStream.php
+++ b/Classes/PHPExcel/Shared/OLE/ChainedBlockStream.php
@@ -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 )
}
diff --git a/Classes/PHPExcel/Shared/OLE/PPS.php b/Classes/PHPExcel/Shared/OLE/PPS.php
index 619427a..e7f6d66 100644
--- a/Classes/PHPExcel/Shared/OLE/PPS.php
+++ b/Classes/PHPExcel/Shared/OLE/PPS.php
@@ -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;
+ }
}
diff --git a/Classes/PHPExcel/Shared/OLE/PPS/File.php b/Classes/PHPExcel/Shared/OLE/PPS/File.php
index ce3275d..3aa7715 100644
--- a/Classes/PHPExcel/Shared/OLE/PPS/File.php
+++ b/Classes/PHPExcel/Shared/OLE/PPS/File.php
@@ -30,57 +30,57 @@ namespace PHPExcel;
* @package PHPExcel\Shared_OLE
*/
class Shared_OLE_PPS_File extends Shared_OLE_PPS
- {
- /**
- * The constructor
- *
- * @access public
- * @param string $name The name of the file (in Unicode)
- * @see OLE::Asc2Ucs()
- */
- public function __construct($name)
- {
- parent::__construct(
- null,
- $name,
- Shared_OLE::OLE_PPS_TYPE_FILE,
- null,
- null,
- null,
- null,
- null,
- '',
- array());
- }
+ {
+ /**
+ * The constructor
+ *
+ * @access public
+ * @param string $name The name of the file (in Unicode)
+ * @see OLE::Asc2Ucs()
+ */
+ public function __construct($name)
+ {
+ parent::__construct(
+ null,
+ $name,
+ Shared_OLE::OLE_PPS_TYPE_FILE,
+ null,
+ null,
+ null,
+ null,
+ null,
+ '',
+ array());
+ }
- /**
- * Initialization method. Has to be called right after OLE_PPS_File().
- *
- * @access public
- * @return mixed true on success
- */
- public function init()
- {
- return true;
- }
+ /**
+ * Initialization method. Has to be called right after OLE_PPS_File().
+ *
+ * @access public
+ * @return mixed true on success
+ */
+ public function init()
+ {
+ return true;
+ }
- /**
- * Append data to PPS
- *
- * @access public
- * @param string $data The data to append
- */
- public function append($data)
- {
- $this->_data .= $data;
- }
+ /**
+ * Append data to PPS
+ *
+ * @access public
+ * @param string $data The data to append
+ */
+ public function append($data)
+ {
+ $this->_data .= $data;
+ }
- /**
- * Returns a stream for reading this file using fread() etc.
- * @return resource a read-only stream
- */
- public function getStream()
- {
- $this->ole->getStream($this);
- }
+ /**
+ * Returns a stream for reading this file using fread() etc.
+ * @return resource a read-only stream
+ */
+ public function getStream()
+ {
+ $this->ole->getStream($this);
+ }
}
diff --git a/Classes/PHPExcel/Shared/OLE/PPS/Root.php b/Classes/PHPExcel/Shared/OLE/PPS/Root.php
index f21ec85..f4d7fa4 100644
--- a/Classes/PHPExcel/Shared/OLE/PPS/Root.php
+++ b/Classes/PHPExcel/Shared/OLE/PPS/Root.php
@@ -30,440 +30,440 @@ namespace PHPExcel;
* @package PHPExcel\Shared_OLE
*/
class Shared_OLE_PPS_Root extends Shared_OLE_PPS
- {
+ {
- /**
- * Directory for temporary files
- * @var string
- */
- protected $_tmp_dir = NULL;
+ /**
+ * Directory for temporary files
+ * @var string
+ */
+ protected $_tmp_dir = null;
- /**
- * @param integer $time_1st A timestamp
- * @param integer $time_2nd A timestamp
- */
- public function __construct($time_1st, $time_2nd, $raChild)
- {
- $this->_tempDir = Shared_File::sys_get_temp_dir();
+ /**
+ * @param integer $time_1st A timestamp
+ * @param integer $time_2nd A timestamp
+ */
+ public function __construct($time_1st, $time_2nd, $raChild)
+ {
+ $this->_tempDir = Shared_File::sys_get_temp_dir();
- parent::__construct(
- null,
- Shared_OLE::Asc2Ucs('Root Entry'),
- Shared_OLE::OLE_PPS_TYPE_ROOT,
- null,
- null,
- null,
- $time_1st,
- $time_2nd,
- null,
- $raChild);
- }
+ parent::__construct(
+ null,
+ Shared_OLE::Asc2Ucs('Root Entry'),
+ Shared_OLE::OLE_PPS_TYPE_ROOT,
+ null,
+ null,
+ null,
+ $time_1st,
+ $time_2nd,
+ null,
+ $raChild);
+ }
- /**
- * Method for saving the whole OLE container (including files).
- * In fact, if called with an empty argument (or '-'), it saves to a
- * temporary file and then outputs it's contents to stdout.
- * If a resource pointer to a stream created by fopen() is passed
- * it will be used, but you have to close such stream by yourself.
- *
- * @param string|resource $filename The name of the file or stream where to save the OLE container.
- * @access public
- * @return mixed true on success
- */
- public function save($filename)
- {
- // Initial Setting for saving
- $this->_BIG_BLOCK_SIZE = pow(2,
- ((isset($this->_BIG_BLOCK_SIZE))? self::_adjust2($this->_BIG_BLOCK_SIZE) : 9));
- $this->_SMALL_BLOCK_SIZE= pow(2,
- ((isset($this->_SMALL_BLOCK_SIZE))? self::_adjust2($this->_SMALL_BLOCK_SIZE): 6));
+ /**
+ * Method for saving the whole OLE container (including files).
+ * In fact, if called with an empty argument (or '-'), it saves to a
+ * temporary file and then outputs it's contents to stdout.
+ * If a resource pointer to a stream created by fopen() is passed
+ * it will be used, but you have to close such stream by yourself.
+ *
+ * @param string|resource $filename The name of the file or stream where to save the OLE container.
+ * @access public
+ * @return mixed true on success
+ */
+ public function save($filename)
+ {
+ // Initial Setting for saving
+ $this->_BIG_BLOCK_SIZE = pow(2,
+ ((isset($this->_BIG_BLOCK_SIZE))? self::_adjust2($this->_BIG_BLOCK_SIZE) : 9));
+ $this->_SMALL_BLOCK_SIZE= pow(2,
+ ((isset($this->_SMALL_BLOCK_SIZE))? self::_adjust2($this->_SMALL_BLOCK_SIZE): 6));
- if (is_resource($filename)) {
- $this->_FILEH_ = $filename;
- } else if ($filename == '-' || $filename == '') {
- if ($this->_tmp_dir === NULL)
- $this->_tmp_dir = Shared_File::sys_get_temp_dir();
- $this->_tmp_filename = tempnam($this->_tmp_dir, "OLE_PPS_Root");
- $this->_FILEH_ = fopen($this->_tmp_filename,"w+b");
- if ($this->_FILEH_ == false) {
- throw new Writer_Exception("Can't create temporary file.");
- }
- } else {
- $this->_FILEH_ = fopen($filename, "wb");
- }
- if ($this->_FILEH_ == false) {
- throw new Writer_Exception("Can't open $filename. It may be in use or protected.");
- }
- // Make an array of PPS's (for Save)
- $aList = array();
- Shared_OLE_PPS::_savePpsSetPnt($aList, array($this));
- // calculate values for header
- list($iSBDcnt, $iBBcnt, $iPPScnt) = $this->_calcSize($aList); //, $rhInfo);
- // Save Header
- $this->_saveHeader($iSBDcnt, $iBBcnt, $iPPScnt);
+ if (is_resource($filename)) {
+ $this->_FILEH_ = $filename;
+ } else if ($filename == '-' || $filename == '') {
+ if ($this->_tmp_dir === null)
+ $this->_tmp_dir = Shared_File::sys_get_temp_dir();
+ $this->_tmp_filename = tempnam($this->_tmp_dir, "OLE_PPS_Root");
+ $this->_FILEH_ = fopen($this->_tmp_filename,"w+b");
+ if ($this->_FILEH_ == false) {
+ throw new Writer_Exception("Can't create temporary file.");
+ }
+ } else {
+ $this->_FILEH_ = fopen($filename, "wb");
+ }
+ if ($this->_FILEH_ == false) {
+ throw new Writer_Exception("Can't open $filename. It may be in use or protected.");
+ }
+ // Make an array of PPS's (for Save)
+ $aList = array();
+ Shared_OLE_PPS::_savePpsSetPnt($aList, array($this));
+ // calculate values for header
+ list($iSBDcnt, $iBBcnt, $iPPScnt) = $this->_calcSize($aList); //, $rhInfo);
+ // Save Header
+ $this->_saveHeader($iSBDcnt, $iBBcnt, $iPPScnt);
- // Make Small Data string (write SBD)
- $this->_data = $this->_makeSmallData($aList);
+ // Make Small Data string (write SBD)
+ $this->_data = $this->_makeSmallData($aList);
- // Write BB
- $this->_saveBigData($iSBDcnt, $aList);
- // Write PPS
- $this->_savePps($aList);
- // Write Big Block Depot and BDList and Adding Header informations
- $this->_saveBbd($iSBDcnt, $iBBcnt, $iPPScnt);
+ // Write BB
+ $this->_saveBigData($iSBDcnt, $aList);
+ // Write PPS
+ $this->_savePps($aList);
+ // Write Big Block Depot and BDList and Adding Header informations
+ $this->_saveBbd($iSBDcnt, $iBBcnt, $iPPScnt);
- if (!is_resource($filename)) {
- fclose($this->_FILEH_);
- }
+ if (!is_resource($filename)) {
+ fclose($this->_FILEH_);
+ }
- return true;
- }
+ return true;
+ }
- /**
- * Calculate some numbers
- *
- * @access public
- * @param array $raList Reference to an array of PPS's
- * @return array The array of numbers
- */
- public function _calcSize(&$raList)
- {
- // Calculate Basic Setting
- list($iSBDcnt, $iBBcnt, $iPPScnt) = array(0,0,0);
- $iSmallLen = 0;
- $iSBcnt = 0;
- $iCount = count($raList);
- for ($i = 0; $i < $iCount; ++$i) {
- if ($raList[$i]->Type == Shared_OLE::OLE_PPS_TYPE_FILE) {
- $raList[$i]->Size = $raList[$i]->_DataLen();
- if ($raList[$i]->Size < Shared_OLE::OLE_DATA_SIZE_SMALL) {
- $iSBcnt += floor($raList[$i]->Size / $this->_SMALL_BLOCK_SIZE)
- + (($raList[$i]->Size % $this->_SMALL_BLOCK_SIZE)? 1: 0);
- } else {
- $iBBcnt += (floor($raList[$i]->Size / $this->_BIG_BLOCK_SIZE) +
- (($raList[$i]->Size % $this->_BIG_BLOCK_SIZE)? 1: 0));
- }
- }
- }
- $iSmallLen = $iSBcnt * $this->_SMALL_BLOCK_SIZE;
- $iSlCnt = floor($this->_BIG_BLOCK_SIZE / Shared_OLE::OLE_LONG_INT_SIZE);
- $iSBDcnt = floor($iSBcnt / $iSlCnt) + (($iSBcnt % $iSlCnt)? 1:0);
- $iBBcnt += (floor($iSmallLen / $this->_BIG_BLOCK_SIZE) +
- (( $iSmallLen % $this->_BIG_BLOCK_SIZE)? 1: 0));
- $iCnt = count($raList);
- $iBdCnt = $this->_BIG_BLOCK_SIZE / Shared_OLE::OLE_PPS_SIZE;
- $iPPScnt = (floor($iCnt/$iBdCnt) + (($iCnt % $iBdCnt)? 1: 0));
+ /**
+ * Calculate some numbers
+ *
+ * @access public
+ * @param array $raList Reference to an array of PPS's
+ * @return array The array of numbers
+ */
+ public function _calcSize(&$raList)
+ {
+ // Calculate Basic Setting
+ list($iSBDcnt, $iBBcnt, $iPPScnt) = array(0,0,0);
+ $iSmallLen = 0;
+ $iSBcnt = 0;
+ $iCount = count($raList);
+ for ($i = 0; $i < $iCount; ++$i) {
+ if ($raList[$i]->Type == Shared_OLE::OLE_PPS_TYPE_FILE) {
+ $raList[$i]->Size = $raList[$i]->_DataLen();
+ if ($raList[$i]->Size < Shared_OLE::OLE_DATA_SIZE_SMALL) {
+ $iSBcnt += floor($raList[$i]->Size / $this->_SMALL_BLOCK_SIZE)
+ + (($raList[$i]->Size % $this->_SMALL_BLOCK_SIZE)? 1: 0);
+ } else {
+ $iBBcnt += (floor($raList[$i]->Size / $this->_BIG_BLOCK_SIZE) +
+ (($raList[$i]->Size % $this->_BIG_BLOCK_SIZE)? 1: 0));
+ }
+ }
+ }
+ $iSmallLen = $iSBcnt * $this->_SMALL_BLOCK_SIZE;
+ $iSlCnt = floor($this->_BIG_BLOCK_SIZE / Shared_OLE::OLE_LONG_INT_SIZE);
+ $iSBDcnt = floor($iSBcnt / $iSlCnt) + (($iSBcnt % $iSlCnt)? 1:0);
+ $iBBcnt += (floor($iSmallLen / $this->_BIG_BLOCK_SIZE) +
+ (( $iSmallLen % $this->_BIG_BLOCK_SIZE)? 1: 0));
+ $iCnt = count($raList);
+ $iBdCnt = $this->_BIG_BLOCK_SIZE / Shared_OLE::OLE_PPS_SIZE;
+ $iPPScnt = (floor($iCnt/$iBdCnt) + (($iCnt % $iBdCnt)? 1: 0));
- return array($iSBDcnt, $iBBcnt, $iPPScnt);
- }
+ return array($iSBDcnt, $iBBcnt, $iPPScnt);
+ }
- /**
- * Helper function for caculating a magic value for block sizes
- *
- * @access public
- * @param integer $i2 The argument
- * @see save()
- * @return integer
- */
- private static function _adjust2($i2)
- {
- $iWk = log($i2)/log(2);
- return ($iWk > floor($iWk))? floor($iWk)+1:$iWk;
- }
+ /**
+ * Helper function for caculating a magic value for block sizes
+ *
+ * @access public
+ * @param integer $i2 The argument
+ * @see save()
+ * @return integer
+ */
+ private static function _adjust2($i2)
+ {
+ $iWk = log($i2)/log(2);
+ return ($iWk > floor($iWk))? floor($iWk)+1:$iWk;
+ }
- /**
- * Save OLE header
- *
- * @access public
- * @param integer $iSBDcnt
- * @param integer $iBBcnt
- * @param integer $iPPScnt
- */
- public function _saveHeader($iSBDcnt, $iBBcnt, $iPPScnt)
- {
- $FILE = $this->_FILEH_;
+ /**
+ * Save OLE header
+ *
+ * @access public
+ * @param integer $iSBDcnt
+ * @param integer $iBBcnt
+ * @param integer $iPPScnt
+ */
+ public function _saveHeader($iSBDcnt, $iBBcnt, $iPPScnt)
+ {
+ $FILE = $this->_FILEH_;
- // Calculate Basic Setting
- $iBlCnt = $this->_BIG_BLOCK_SIZE / Shared_OLE::OLE_LONG_INT_SIZE;
- $i1stBdL = ($this->_BIG_BLOCK_SIZE - 0x4C) / Shared_OLE::OLE_LONG_INT_SIZE;
+ // Calculate Basic Setting
+ $iBlCnt = $this->_BIG_BLOCK_SIZE / Shared_OLE::OLE_LONG_INT_SIZE;
+ $i1stBdL = ($this->_BIG_BLOCK_SIZE - 0x4C) / Shared_OLE::OLE_LONG_INT_SIZE;
- $iBdExL = 0;
- $iAll = $iBBcnt + $iPPScnt + $iSBDcnt;
- $iAllW = $iAll;
- $iBdCntW = floor($iAllW / $iBlCnt) + (($iAllW % $iBlCnt)? 1: 0);
- $iBdCnt = floor(($iAll + $iBdCntW) / $iBlCnt) + ((($iAllW+$iBdCntW) % $iBlCnt)? 1: 0);
+ $iBdExL = 0;
+ $iAll = $iBBcnt + $iPPScnt + $iSBDcnt;
+ $iAllW = $iAll;
+ $iBdCntW = floor($iAllW / $iBlCnt) + (($iAllW % $iBlCnt)? 1: 0);
+ $iBdCnt = floor(($iAll + $iBdCntW) / $iBlCnt) + ((($iAllW+$iBdCntW) % $iBlCnt)? 1: 0);
- // Calculate BD count
- if ($iBdCnt > $i1stBdL) {
- while (1) {
- ++$iBdExL;
- ++$iAllW;
- $iBdCntW = floor($iAllW / $iBlCnt) + (($iAllW % $iBlCnt)? 1: 0);
- $iBdCnt = floor(($iAllW + $iBdCntW) / $iBlCnt) + ((($iAllW+$iBdCntW) % $iBlCnt)? 1: 0);
- if ($iBdCnt <= ($iBdExL*$iBlCnt+ $i1stBdL)) {
- break;
- }
- }
- }
+ // Calculate BD count
+ if ($iBdCnt > $i1stBdL) {
+ while (1) {
+ ++$iBdExL;
+ ++$iAllW;
+ $iBdCntW = floor($iAllW / $iBlCnt) + (($iAllW % $iBlCnt)? 1: 0);
+ $iBdCnt = floor(($iAllW + $iBdCntW) / $iBlCnt) + ((($iAllW+$iBdCntW) % $iBlCnt)? 1: 0);
+ if ($iBdCnt <= ($iBdExL*$iBlCnt+ $i1stBdL)) {
+ break;
+ }
+ }
+ }
- // Save Header
- fwrite($FILE,
- "\xD0\xCF\x11\xE0\xA1\xB1\x1A\xE1"
- . "\x00\x00\x00\x00"
- . "\x00\x00\x00\x00"
- . "\x00\x00\x00\x00"
- . "\x00\x00\x00\x00"
- . pack("v", 0x3b)
- . pack("v", 0x03)
- . pack("v", -2)
- . pack("v", 9)
- . pack("v", 6)
- . pack("v", 0)
- . "\x00\x00\x00\x00"
- . "\x00\x00\x00\x00"
- . pack("V", $iBdCnt)
- . pack("V", $iBBcnt+$iSBDcnt) //ROOT START
- . pack("V", 0)
- . pack("V", 0x1000)
- . pack("V", $iSBDcnt ? 0 : -2) //Small Block Depot
- . pack("V", $iSBDcnt)
- );
- // Extra BDList Start, Count
- if ($iBdCnt < $i1stBdL) {
- fwrite($FILE,
- pack("V", -2) // Extra BDList Start
- . pack("V", 0) // Extra BDList Count
- );
- } else {
- fwrite($FILE, pack("V", $iAll+$iBdCnt) . pack("V", $iBdExL));
- }
+ // Save Header
+ fwrite($FILE,
+ "\xD0\xCF\x11\xE0\xA1\xB1\x1A\xE1"
+ . "\x00\x00\x00\x00"
+ . "\x00\x00\x00\x00"
+ . "\x00\x00\x00\x00"
+ . "\x00\x00\x00\x00"
+ . pack("v", 0x3b)
+ . pack("v", 0x03)
+ . pack("v", -2)
+ . pack("v", 9)
+ . pack("v", 6)
+ . pack("v", 0)
+ . "\x00\x00\x00\x00"
+ . "\x00\x00\x00\x00"
+ . pack("V", $iBdCnt)
+ . pack("V", $iBBcnt+$iSBDcnt) //ROOT START
+ . pack("V", 0)
+ . pack("V", 0x1000)
+ . pack("V", $iSBDcnt ? 0 : -2) //Small Block Depot
+ . pack("V", $iSBDcnt)
+ );
+ // Extra BDList Start, Count
+ if ($iBdCnt < $i1stBdL) {
+ fwrite($FILE,
+ pack("V", -2) // Extra BDList Start
+ . pack("V", 0) // Extra BDList Count
+ );
+ } else {
+ fwrite($FILE, pack("V", $iAll+$iBdCnt) . pack("V", $iBdExL));
+ }
- // BDList
- for ($i = 0; $i < $i1stBdL && $i < $iBdCnt; ++$i) {
- fwrite($FILE, pack("V", $iAll+$i));
- }
- if ($i < $i1stBdL) {
- $jB = $i1stBdL - $i;
- for ($j = 0; $j < $jB; ++$j) {
- fwrite($FILE, (pack("V", -1)));
- }
- }
- }
+ // BDList
+ for ($i = 0; $i < $i1stBdL && $i < $iBdCnt; ++$i) {
+ fwrite($FILE, pack("V", $iAll+$i));
+ }
+ if ($i < $i1stBdL) {
+ $jB = $i1stBdL - $i;
+ for ($j = 0; $j < $jB; ++$j) {
+ fwrite($FILE, (pack("V", -1)));
+ }
+ }
+ }
- /**
- * Saving big data (PPS's with data bigger than PHPExcel\Shared_OLE::OLE_DATA_SIZE_SMALL)
- *
- * @access public
- * @param integer $iStBlk
- * @param array &$raList Reference to array of PPS's
- */
- public function _saveBigData($iStBlk, &$raList)
- {
- $FILE = $this->_FILEH_;
+ /**
+ * Saving big data (PPS's with data bigger than PHPExcel\Shared_OLE::OLE_DATA_SIZE_SMALL)
+ *
+ * @access public
+ * @param integer $iStBlk
+ * @param array &$raList Reference to array of PPS's
+ */
+ public function _saveBigData($iStBlk, &$raList)
+ {
+ $FILE = $this->_FILEH_;
- // cycle through PPS's
- $iCount = count($raList);
- for ($i = 0; $i < $iCount; ++$i) {
- if ($raList[$i]->Type != Shared_OLE::OLE_PPS_TYPE_DIR) {
- $raList[$i]->Size = $raList[$i]->_DataLen();
- if (($raList[$i]->Size >= Shared_OLE::OLE_DATA_SIZE_SMALL) ||
- (($raList[$i]->Type == Shared_OLE::OLE_PPS_TYPE_ROOT) && isset($raList[$i]->_data)))
- {
- // Write Data
- //if (isset($raList[$i]->_PPS_FILE)) {
- // $iLen = 0;
- // fseek($raList[$i]->_PPS_FILE, 0); // To The Top
- // while($sBuff = fread($raList[$i]->_PPS_FILE, 4096)) {
- // $iLen += strlen($sBuff);
- // fwrite($FILE, $sBuff);
- // }
- //} else {
- fwrite($FILE, $raList[$i]->_data);
- //}
+ // cycle through PPS's
+ $iCount = count($raList);
+ for ($i = 0; $i < $iCount; ++$i) {
+ if ($raList[$i]->Type != Shared_OLE::OLE_PPS_TYPE_DIR) {
+ $raList[$i]->Size = $raList[$i]->_DataLen();
+ if (($raList[$i]->Size >= Shared_OLE::OLE_DATA_SIZE_SMALL) ||
+ (($raList[$i]->Type == Shared_OLE::OLE_PPS_TYPE_ROOT) && isset($raList[$i]->_data)))
+ {
+ // Write Data
+ //if (isset($raList[$i]->_PPS_FILE)) {
+ // $iLen = 0;
+ // fseek($raList[$i]->_PPS_FILE, 0); // To The Top
+ // while($sBuff = fread($raList[$i]->_PPS_FILE, 4096)) {
+ // $iLen += strlen($sBuff);
+ // fwrite($FILE, $sBuff);
+ // }
+ //} else {
+ fwrite($FILE, $raList[$i]->_data);
+ //}
- if ($raList[$i]->Size % $this->_BIG_BLOCK_SIZE) {
- fwrite($FILE, str_repeat("\x00", $this->_BIG_BLOCK_SIZE - ($raList[$i]->Size % $this->_BIG_BLOCK_SIZE)));
- }
- // Set For PPS
- $raList[$i]->_StartBlock = $iStBlk;
- $iStBlk +=
- (floor($raList[$i]->Size / $this->_BIG_BLOCK_SIZE) +
- (($raList[$i]->Size % $this->_BIG_BLOCK_SIZE)? 1: 0));
- }
- // Close file for each PPS, and unlink it
- //if (isset($raList[$i]->_PPS_FILE)) {
- // fclose($raList[$i]->_PPS_FILE);
- // $raList[$i]->_PPS_FILE = null;
- // unlink($raList[$i]->_tmp_filename);
- //}
- }
- }
- }
+ if ($raList[$i]->Size % $this->_BIG_BLOCK_SIZE) {
+ fwrite($FILE, str_repeat("\x00", $this->_BIG_BLOCK_SIZE - ($raList[$i]->Size % $this->_BIG_BLOCK_SIZE)));
+ }
+ // Set For PPS
+ $raList[$i]->_StartBlock = $iStBlk;
+ $iStBlk +=
+ (floor($raList[$i]->Size / $this->_BIG_BLOCK_SIZE) +
+ (($raList[$i]->Size % $this->_BIG_BLOCK_SIZE)? 1: 0));
+ }
+ // Close file for each PPS, and unlink it
+ //if (isset($raList[$i]->_PPS_FILE)) {
+ // fclose($raList[$i]->_PPS_FILE);
+ // $raList[$i]->_PPS_FILE = null;
+ // unlink($raList[$i]->_tmp_filename);
+ //}
+ }
+ }
+ }
- /**
- * get small data (PPS's with data smaller than PHPExcel\Shared_OLE::OLE_DATA_SIZE_SMALL)
- *
- * @access public
- * @param array &$raList Reference to array of PPS's
- */
- public function _makeSmallData(&$raList)
- {
- $sRes = '';
- $FILE = $this->_FILEH_;
- $iSmBlk = 0;
+ /**
+ * get small data (PPS's with data smaller than PHPExcel\Shared_OLE::OLE_DATA_SIZE_SMALL)
+ *
+ * @access public
+ * @param array &$raList Reference to array of PPS's
+ */
+ public function _makeSmallData(&$raList)
+ {
+ $sRes = '';
+ $FILE = $this->_FILEH_;
+ $iSmBlk = 0;
- $iCount = count($raList);
- for ($i = 0; $i < $iCount; ++$i) {
- // Make SBD, small data string
- if ($raList[$i]->Type == Shared_OLE::OLE_PPS_TYPE_FILE) {
- if ($raList[$i]->Size <= 0) {
- continue;
- }
- if ($raList[$i]->Size < Shared_OLE::OLE_DATA_SIZE_SMALL) {
- $iSmbCnt = floor($raList[$i]->Size / $this->_SMALL_BLOCK_SIZE)
- + (($raList[$i]->Size % $this->_SMALL_BLOCK_SIZE)? 1: 0);
- // Add to SBD
- $jB = $iSmbCnt - 1;
- for ($j = 0; $j < $jB; ++$j) {
- fwrite($FILE, pack("V", $j+$iSmBlk+1));
- }
- fwrite($FILE, pack("V", -2));
+ $iCount = count($raList);
+ for ($i = 0; $i < $iCount; ++$i) {
+ // Make SBD, small data string
+ if ($raList[$i]->Type == Shared_OLE::OLE_PPS_TYPE_FILE) {
+ if ($raList[$i]->Size <= 0) {
+ continue;
+ }
+ if ($raList[$i]->Size < Shared_OLE::OLE_DATA_SIZE_SMALL) {
+ $iSmbCnt = floor($raList[$i]->Size / $this->_SMALL_BLOCK_SIZE)
+ + (($raList[$i]->Size % $this->_SMALL_BLOCK_SIZE)? 1: 0);
+ // Add to SBD
+ $jB = $iSmbCnt - 1;
+ for ($j = 0; $j < $jB; ++$j) {
+ fwrite($FILE, pack("V", $j+$iSmBlk+1));
+ }
+ fwrite($FILE, pack("V", -2));
- //// Add to Data String(this will be written for RootEntry)
- //if ($raList[$i]->_PPS_FILE) {
- // fseek($raList[$i]->_PPS_FILE, 0); // To The Top
- // while ($sBuff = fread($raList[$i]->_PPS_FILE, 4096)) {
- // $sRes .= $sBuff;
- // }
- //} else {
- $sRes .= $raList[$i]->_data;
- //}
- if ($raList[$i]->Size % $this->_SMALL_BLOCK_SIZE) {
- $sRes .= str_repeat("\x00",$this->_SMALL_BLOCK_SIZE - ($raList[$i]->Size % $this->_SMALL_BLOCK_SIZE));
- }
- // Set for PPS
- $raList[$i]->_StartBlock = $iSmBlk;
- $iSmBlk += $iSmbCnt;
- }
- }
- }
- $iSbCnt = floor($this->_BIG_BLOCK_SIZE / Shared_OLE::OLE_LONG_INT_SIZE);
- if ($iSmBlk % $iSbCnt) {
- $iB = $iSbCnt - ($iSmBlk % $iSbCnt);
- for ($i = 0; $i < $iB; ++$i) {
- fwrite($FILE, pack("V", -1));
- }
- }
- return $sRes;
- }
+ //// Add to Data String(this will be written for RootEntry)
+ //if ($raList[$i]->_PPS_FILE) {
+ // fseek($raList[$i]->_PPS_FILE, 0); // To The Top
+ // while ($sBuff = fread($raList[$i]->_PPS_FILE, 4096)) {
+ // $sRes .= $sBuff;
+ // }
+ //} else {
+ $sRes .= $raList[$i]->_data;
+ //}
+ if ($raList[$i]->Size % $this->_SMALL_BLOCK_SIZE) {
+ $sRes .= str_repeat("\x00",$this->_SMALL_BLOCK_SIZE - ($raList[$i]->Size % $this->_SMALL_BLOCK_SIZE));
+ }
+ // Set for PPS
+ $raList[$i]->_StartBlock = $iSmBlk;
+ $iSmBlk += $iSmbCnt;
+ }
+ }
+ }
+ $iSbCnt = floor($this->_BIG_BLOCK_SIZE / Shared_OLE::OLE_LONG_INT_SIZE);
+ if ($iSmBlk % $iSbCnt) {
+ $iB = $iSbCnt - ($iSmBlk % $iSbCnt);
+ for ($i = 0; $i < $iB; ++$i) {
+ fwrite($FILE, pack("V", -1));
+ }
+ }
+ return $sRes;
+ }
- /**
- * Saves all the PPS's WKs
- *
- * @access public
- * @param array $raList Reference to an array with all PPS's
- */
- public function _savePps(&$raList)
- {
- // Save each PPS WK
- $iC = count($raList);
- for ($i = 0; $i < $iC; ++$i) {
- fwrite($this->_FILEH_, $raList[$i]->_getPpsWk());
- }
- // Adjust for Block
- $iCnt = count($raList);
- $iBCnt = $this->_BIG_BLOCK_SIZE / Shared_OLE::OLE_PPS_SIZE;
- if ($iCnt % $iBCnt) {
- fwrite($this->_FILEH_, str_repeat("\x00",($iBCnt - ($iCnt % $iBCnt)) * Shared_OLE::OLE_PPS_SIZE));
- }
- }
+ /**
+ * Saves all the PPS's WKs
+ *
+ * @access public
+ * @param array $raList Reference to an array with all PPS's
+ */
+ public function _savePps(&$raList)
+ {
+ // Save each PPS WK
+ $iC = count($raList);
+ for ($i = 0; $i < $iC; ++$i) {
+ fwrite($this->_FILEH_, $raList[$i]->_getPpsWk());
+ }
+ // Adjust for Block
+ $iCnt = count($raList);
+ $iBCnt = $this->_BIG_BLOCK_SIZE / Shared_OLE::OLE_PPS_SIZE;
+ if ($iCnt % $iBCnt) {
+ fwrite($this->_FILEH_, str_repeat("\x00",($iBCnt - ($iCnt % $iBCnt)) * Shared_OLE::OLE_PPS_SIZE));
+ }
+ }
- /**
- * Saving Big Block Depot
- *
- * @access public
- * @param integer $iSbdSize
- * @param integer $iBsize
- * @param integer $iPpsCnt
- */
- public function _saveBbd($iSbdSize, $iBsize, $iPpsCnt)
- {
- $FILE = $this->_FILEH_;
- // Calculate Basic Setting
- $iBbCnt = $this->_BIG_BLOCK_SIZE / Shared_OLE::OLE_LONG_INT_SIZE;
- $i1stBdL = ($this->_BIG_BLOCK_SIZE - 0x4C) / Shared_OLE::OLE_LONG_INT_SIZE;
+ /**
+ * Saving Big Block Depot
+ *
+ * @access public
+ * @param integer $iSbdSize
+ * @param integer $iBsize
+ * @param integer $iPpsCnt
+ */
+ public function _saveBbd($iSbdSize, $iBsize, $iPpsCnt)
+ {
+ $FILE = $this->_FILEH_;
+ // Calculate Basic Setting
+ $iBbCnt = $this->_BIG_BLOCK_SIZE / Shared_OLE::OLE_LONG_INT_SIZE;
+ $i1stBdL = ($this->_BIG_BLOCK_SIZE - 0x4C) / Shared_OLE::OLE_LONG_INT_SIZE;
- $iBdExL = 0;
- $iAll = $iBsize + $iPpsCnt + $iSbdSize;
- $iAllW = $iAll;
- $iBdCntW = floor($iAllW / $iBbCnt) + (($iAllW % $iBbCnt)? 1: 0);
- $iBdCnt = floor(($iAll + $iBdCntW) / $iBbCnt) + ((($iAllW+$iBdCntW) % $iBbCnt)? 1: 0);
- // Calculate BD count
- if ($iBdCnt >$i1stBdL) {
- while (1) {
- ++$iBdExL;
- ++$iAllW;
- $iBdCntW = floor($iAllW / $iBbCnt) + (($iAllW % $iBbCnt)? 1: 0);
- $iBdCnt = floor(($iAllW + $iBdCntW) / $iBbCnt) + ((($iAllW+$iBdCntW) % $iBbCnt)? 1: 0);
- if ($iBdCnt <= ($iBdExL*$iBbCnt+ $i1stBdL)) {
- break;
- }
- }
- }
+ $iBdExL = 0;
+ $iAll = $iBsize + $iPpsCnt + $iSbdSize;
+ $iAllW = $iAll;
+ $iBdCntW = floor($iAllW / $iBbCnt) + (($iAllW % $iBbCnt)? 1: 0);
+ $iBdCnt = floor(($iAll + $iBdCntW) / $iBbCnt) + ((($iAllW+$iBdCntW) % $iBbCnt)? 1: 0);
+ // Calculate BD count
+ if ($iBdCnt >$i1stBdL) {
+ while (1) {
+ ++$iBdExL;
+ ++$iAllW;
+ $iBdCntW = floor($iAllW / $iBbCnt) + (($iAllW % $iBbCnt)? 1: 0);
+ $iBdCnt = floor(($iAllW + $iBdCntW) / $iBbCnt) + ((($iAllW+$iBdCntW) % $iBbCnt)? 1: 0);
+ if ($iBdCnt <= ($iBdExL*$iBbCnt+ $i1stBdL)) {
+ break;
+ }
+ }
+ }
- // Making BD
- // Set for SBD
- if ($iSbdSize > 0) {
- for ($i = 0; $i < ($iSbdSize - 1); ++$i) {
- fwrite($FILE, pack("V", $i+1));
- }
- fwrite($FILE, pack("V", -2));
- }
- // Set for B
- for ($i = 0; $i < ($iBsize - 1); ++$i) {
- fwrite($FILE, pack("V", $i+$iSbdSize+1));
- }
- fwrite($FILE, pack("V", -2));
+ // Making BD
+ // Set for SBD
+ if ($iSbdSize > 0) {
+ for ($i = 0; $i < ($iSbdSize - 1); ++$i) {
+ fwrite($FILE, pack("V", $i+1));
+ }
+ fwrite($FILE, pack("V", -2));
+ }
+ // Set for B
+ for ($i = 0; $i < ($iBsize - 1); ++$i) {
+ fwrite($FILE, pack("V", $i+$iSbdSize+1));
+ }
+ fwrite($FILE, pack("V", -2));
- // Set for PPS
- for ($i = 0; $i < ($iPpsCnt - 1); ++$i) {
- fwrite($FILE, pack("V", $i+$iSbdSize+$iBsize+1));
- }
- fwrite($FILE, pack("V", -2));
- // Set for BBD itself ( 0xFFFFFFFD : BBD)
- for ($i = 0; $i < $iBdCnt; ++$i) {
- fwrite($FILE, pack("V", 0xFFFFFFFD));
- }
- // Set for ExtraBDList
- for ($i = 0; $i < $iBdExL; ++$i) {
- fwrite($FILE, pack("V", 0xFFFFFFFC));
- }
- // Adjust for Block
- if (($iAllW + $iBdCnt) % $iBbCnt) {
- $iBlock = ($iBbCnt - (($iAllW + $iBdCnt) % $iBbCnt));
- for ($i = 0; $i < $iBlock; ++$i) {
- fwrite($FILE, pack("V", -1));
- }
- }
- // Extra BDList
- if ($iBdCnt > $i1stBdL) {
- $iN=0;
- $iNb=0;
- for ($i = $i1stBdL;$i < $iBdCnt; $i++, ++$iN) {
- if ($iN >= ($iBbCnt - 1)) {
- $iN = 0;
- ++$iNb;
- fwrite($FILE, pack("V", $iAll+$iBdCnt+$iNb));
- }
- fwrite($FILE, pack("V", $iBsize+$iSbdSize+$iPpsCnt+$i));
- }
- if (($iBdCnt-$i1stBdL) % ($iBbCnt-1)) {
- $iB = ($iBbCnt - 1) - (($iBdCnt - $i1stBdL) % ($iBbCnt - 1));
- for ($i = 0; $i < $iB; ++$i) {
- fwrite($FILE, pack("V", -1));
- }
- }
- fwrite($FILE, pack("V", -2));
- }
- }
+ // Set for PPS
+ for ($i = 0; $i < ($iPpsCnt - 1); ++$i) {
+ fwrite($FILE, pack("V", $i+$iSbdSize+$iBsize+1));
+ }
+ fwrite($FILE, pack("V", -2));
+ // Set for BBD itself ( 0xFFFFFFFD : BBD)
+ for ($i = 0; $i < $iBdCnt; ++$i) {
+ fwrite($FILE, pack("V", 0xFFFFFFFD));
+ }
+ // Set for ExtraBDList
+ for ($i = 0; $i < $iBdExL; ++$i) {
+ fwrite($FILE, pack("V", 0xFFFFFFFC));
+ }
+ // Adjust for Block
+ if (($iAllW + $iBdCnt) % $iBbCnt) {
+ $iBlock = ($iBbCnt - (($iAllW + $iBdCnt) % $iBbCnt));
+ for ($i = 0; $i < $iBlock; ++$i) {
+ fwrite($FILE, pack("V", -1));
+ }
+ }
+ // Extra BDList
+ if ($iBdCnt > $i1stBdL) {
+ $iN=0;
+ $iNb=0;
+ for ($i = $i1stBdL;$i < $iBdCnt; $i++, ++$iN) {
+ if ($iN >= ($iBbCnt - 1)) {
+ $iN = 0;
+ ++$iNb;
+ fwrite($FILE, pack("V", $iAll+$iBdCnt+$iNb));
+ }
+ fwrite($FILE, pack("V", $iBsize+$iSbdSize+$iPpsCnt+$i));
+ }
+ if (($iBdCnt-$i1stBdL) % ($iBbCnt-1)) {
+ $iB = ($iBbCnt - 1) - (($iBdCnt - $i1stBdL) % ($iBbCnt - 1));
+ for ($i = 0; $i < $iB; ++$i) {
+ fwrite($FILE, pack("V", -1));
+ }
+ }
+ fwrite($FILE, pack("V", -2));
+ }
+ }
}
diff --git a/Classes/PHPExcel/Shared/OLERead.php b/Classes/PHPExcel/Shared/OLERead.php
index e591efb..50157b3 100644
--- a/Classes/PHPExcel/Shared/OLERead.php
+++ b/Classes/PHPExcel/Shared/OLERead.php
@@ -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##
*/
@@ -32,289 +32,288 @@ defined('IDENTIFIER_OLE') ||
define('IDENTIFIER_OLE', pack('CCCCCCCC', 0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1));
class Shared_OLERead {
- private $data = '';
+ private $data = '';
- // OLE identifier
- const IDENTIFIER_OLE = IDENTIFIER_OLE;
+ // OLE identifier
+ const IDENTIFIER_OLE = IDENTIFIER_OLE;
- // Size of a sector = 512 bytes
- const BIG_BLOCK_SIZE = 0x200;
+ // Size of a sector = 512 bytes
+ const BIG_BLOCK_SIZE = 0x200;
- // Size of a short sector = 64 bytes
- const SMALL_BLOCK_SIZE = 0x40;
+ // Size of a short sector = 64 bytes
+ const SMALL_BLOCK_SIZE = 0x40;
- // Size of a directory entry always = 128 bytes
- const PROPERTY_STORAGE_BLOCK_SIZE = 0x80;
+ // Size of a directory entry always = 128 bytes
+ const PROPERTY_STORAGE_BLOCK_SIZE = 0x80;
- // Minimum size of a standard stream = 4096 bytes, streams smaller than this are stored as short streams
- const SMALL_BLOCK_THRESHOLD = 0x1000;
+ // Minimum size of a standard stream = 4096 bytes, streams smaller than this are stored as short streams
+ const SMALL_BLOCK_THRESHOLD = 0x1000;
- // header offsets
- const NUM_BIG_BLOCK_DEPOT_BLOCKS_POS = 0x2c;
- const ROOT_START_BLOCK_POS = 0x30;
- const SMALL_BLOCK_DEPOT_BLOCK_POS = 0x3c;
- const EXTENSION_BLOCK_POS = 0x44;
- const NUM_EXTENSION_BLOCK_POS = 0x48;
- const BIG_BLOCK_DEPOT_BLOCKS_POS = 0x4c;
+ // header offsets
+ const NUM_BIG_BLOCK_DEPOT_BLOCKS_POS = 0x2c;
+ const ROOT_START_BLOCK_POS = 0x30;
+ const SMALL_BLOCK_DEPOT_BLOCK_POS = 0x3c;
+ const EXTENSION_BLOCK_POS = 0x44;
+ const NUM_EXTENSION_BLOCK_POS = 0x48;
+ const BIG_BLOCK_DEPOT_BLOCKS_POS = 0x4c;
- // property storage offsets (directory offsets)
- const SIZE_OF_NAME_POS = 0x40;
- const TYPE_POS = 0x42;
- const START_BLOCK_POS = 0x74;
- const SIZE_POS = 0x78;
+ // property storage offsets (directory offsets)
+ const SIZE_OF_NAME_POS = 0x40;
+ const TYPE_POS = 0x42;
+ const START_BLOCK_POS = 0x74;
+ const SIZE_POS = 0x78;
- public $wrkbook = null;
- public $summaryInformation = null;
- public $documentSummaryInformation = null;
+ public $wrkbook = null;
+ public $summaryInformation = null;
+ public $documentSummaryInformation = null;
- /**
- * Read the file
- *
- * @param $sFileName string Filename
- * @throws PHPExcel\Reader_Exception
- */
- public function read($sFileName)
- {
- // Check if file exists and is readable
- if(!is_readable($sFileName)) {
- throw new Reader_Exception("Could not open " . $sFileName . " for reading! File does not exist, or it is not readable.");
- }
+ /**
+ * Read the file
+ *
+ * @param $sFileName string Filename
+ * @throws PHPExcel\Reader_Exception
+ */
+ public function read($sFileName)
+ {
+ // Check if file exists and is readable
+ if(!is_readable($sFileName)) {
+ throw new Reader_Exception("Could not open " . $sFileName . " for reading! File does not exist, or it is not readable.");
+ }
- // Get the file identifier
- // Don't bother reading the whole file until we know it's a valid OLE file
- $this->data = file_get_contents($sFileName, FALSE, NULL, 0, 8);
+ // Get the file identifier
+ // Don't bother reading the whole file until we know it's a valid OLE file
+ $this->data = file_get_contents($sFileName, false, null, 0, 8);
- // Check OLE identifier
- if ($this->data != self::IDENTIFIER_OLE) {
- throw new Reader_Exception('The filename ' . $sFileName . ' is not recognised as an OLE file');
- }
+ // Check OLE identifier
+ if ($this->data != self::IDENTIFIER_OLE) {
+ throw new Reader_Exception('The filename ' . $sFileName . ' is not recognised as an OLE file');
+ }
- // Get the file data
- $this->data = file_get_contents($sFileName);
+ // Get the file data
+ $this->data = file_get_contents($sFileName);
- // Total number of sectors used for the SAT
- $this->numBigBlockDepotBlocks = self::_GetInt4d($this->data, self::NUM_BIG_BLOCK_DEPOT_BLOCKS_POS);
+ // Total number of sectors used for the SAT
+ $this->numBigBlockDepotBlocks = self::_GetInt4d($this->data, self::NUM_BIG_BLOCK_DEPOT_BLOCKS_POS);
- // SecID of the first sector of the directory stream
- $this->rootStartBlock = self::_GetInt4d($this->data, self::ROOT_START_BLOCK_POS);
+ // SecID of the first sector of the directory stream
+ $this->rootStartBlock = self::_GetInt4d($this->data, self::ROOT_START_BLOCK_POS);
- // SecID of the first sector of the SSAT (or -2 if not extant)
- $this->sbdStartBlock = self::_GetInt4d($this->data, self::SMALL_BLOCK_DEPOT_BLOCK_POS);
+ // SecID of the first sector of the SSAT (or -2 if not extant)
+ $this->sbdStartBlock = self::_GetInt4d($this->data, self::SMALL_BLOCK_DEPOT_BLOCK_POS);
- // SecID of the first sector of the MSAT (or -2 if no additional sectors are used)
- $this->extensionBlock = self::_GetInt4d($this->data, self::EXTENSION_BLOCK_POS);
+ // SecID of the first sector of the MSAT (or -2 if no additional sectors are used)
+ $this->extensionBlock = self::_GetInt4d($this->data, self::EXTENSION_BLOCK_POS);
- // Total number of sectors used by MSAT
- $this->numExtensionBlocks = self::_GetInt4d($this->data, self::NUM_EXTENSION_BLOCK_POS);
+ // Total number of sectors used by MSAT
+ $this->numExtensionBlocks = self::_GetInt4d($this->data, self::NUM_EXTENSION_BLOCK_POS);
- $bigBlockDepotBlocks = array();
- $pos = self::BIG_BLOCK_DEPOT_BLOCKS_POS;
+ $bigBlockDepotBlocks = array();
+ $pos = self::BIG_BLOCK_DEPOT_BLOCKS_POS;
- $bbdBlocks = $this->numBigBlockDepotBlocks;
+ $bbdBlocks = $this->numBigBlockDepotBlocks;
- if ($this->numExtensionBlocks != 0) {
- $bbdBlocks = (self::BIG_BLOCK_SIZE - self::BIG_BLOCK_DEPOT_BLOCKS_POS)/4;
- }
+ if ($this->numExtensionBlocks != 0) {
+ $bbdBlocks = (self::BIG_BLOCK_SIZE - self::BIG_BLOCK_DEPOT_BLOCKS_POS)/4;
+ }
- for ($i = 0; $i < $bbdBlocks; ++$i) {
- $bigBlockDepotBlocks[$i] = self::_GetInt4d($this->data, $pos);
- $pos += 4;
- }
+ for ($i = 0; $i < $bbdBlocks; ++$i) {
+ $bigBlockDepotBlocks[$i] = self::_GetInt4d($this->data, $pos);
+ $pos += 4;
+ }
- for ($j = 0; $j < $this->numExtensionBlocks; ++$j) {
- $pos = ($this->extensionBlock + 1) * self::BIG_BLOCK_SIZE;
- $blocksToRead = min($this->numBigBlockDepotBlocks - $bbdBlocks, self::BIG_BLOCK_SIZE / 4 - 1);
+ for ($j = 0; $j < $this->numExtensionBlocks; ++$j) {
+ $pos = ($this->extensionBlock + 1) * self::BIG_BLOCK_SIZE;
+ $blocksToRead = min($this->numBigBlockDepotBlocks - $bbdBlocks, self::BIG_BLOCK_SIZE / 4 - 1);
- for ($i = $bbdBlocks; $i < $bbdBlocks + $blocksToRead; ++$i) {
- $bigBlockDepotBlocks[$i] = self::_GetInt4d($this->data, $pos);
- $pos += 4;
- }
+ for ($i = $bbdBlocks; $i < $bbdBlocks + $blocksToRead; ++$i) {
+ $bigBlockDepotBlocks[$i] = self::_GetInt4d($this->data, $pos);
+ $pos += 4;
+ }
- $bbdBlocks += $blocksToRead;
- if ($bbdBlocks < $this->numBigBlockDepotBlocks) {
- $this->extensionBlock = self::_GetInt4d($this->data, $pos);
- }
- }
+ $bbdBlocks += $blocksToRead;
+ if ($bbdBlocks < $this->numBigBlockDepotBlocks) {
+ $this->extensionBlock = self::_GetInt4d($this->data, $pos);
+ }
+ }
- $pos = 0;
- $this->bigBlockChain = '';
- $bbs = self::BIG_BLOCK_SIZE / 4;
- for ($i = 0; $i < $this->numBigBlockDepotBlocks; ++$i) {
- $pos = ($bigBlockDepotBlocks[$i] + 1) * self::BIG_BLOCK_SIZE;
+ $pos = 0;
+ $this->bigBlockChain = '';
+ $bbs = self::BIG_BLOCK_SIZE / 4;
+ for ($i = 0; $i < $this->numBigBlockDepotBlocks; ++$i) {
+ $pos = ($bigBlockDepotBlocks[$i] + 1) * self::BIG_BLOCK_SIZE;
- $this->bigBlockChain .= substr($this->data, $pos, 4*$bbs);
- $pos += 4*$bbs;
- }
+ $this->bigBlockChain .= substr($this->data, $pos, 4*$bbs);
+ $pos += 4*$bbs;
+ }
- $pos = 0;
- $sbdBlock = $this->sbdStartBlock;
- $this->smallBlockChain = '';
- while ($sbdBlock != -2) {
- $pos = ($sbdBlock + 1) * self::BIG_BLOCK_SIZE;
+ $pos = 0;
+ $sbdBlock = $this->sbdStartBlock;
+ $this->smallBlockChain = '';
+ while ($sbdBlock != -2) {
+ $pos = ($sbdBlock + 1) * self::BIG_BLOCK_SIZE;
- $this->smallBlockChain .= substr($this->data, $pos, 4*$bbs);
- $pos += 4*$bbs;
+ $this->smallBlockChain .= substr($this->data, $pos, 4*$bbs);
+ $pos += 4*$bbs;
- $sbdBlock = self::_GetInt4d($this->bigBlockChain, $sbdBlock*4);
- }
+ $sbdBlock = self::_GetInt4d($this->bigBlockChain, $sbdBlock*4);
+ }
- // read the directory stream
- $block = $this->rootStartBlock;
- $this->entry = $this->_readData($block);
+ // read the directory stream
+ $block = $this->rootStartBlock;
+ $this->entry = $this->_readData($block);
- $this->_readPropertySets();
- }
+ $this->_readPropertySets();
+ }
- /**
- * Extract binary stream data
- *
- * @return string
- */
- public function getStream($stream)
- {
- if ($stream === NULL) {
- return null;
- }
+ /**
+ * Extract binary stream data
+ *
+ * @return string
+ */
+ public function getStream($stream)
+ {
+ if ($stream === null) {
+ return null;
+ }
- $streamData = '';
+ $streamData = '';
- if ($this->props[$stream]['size'] < self::SMALL_BLOCK_THRESHOLD) {
- $rootdata = $this->_readData($this->props[$this->rootentry]['startBlock']);
+ if ($this->props[$stream]['size'] < self::SMALL_BLOCK_THRESHOLD) {
+ $rootdata = $this->_readData($this->props[$this->rootentry]['startBlock']);
- $block = $this->props[$stream]['startBlock'];
+ $block = $this->props[$stream]['startBlock'];
- while ($block != -2) {
- $pos = $block * self::SMALL_BLOCK_SIZE;
- $streamData .= substr($rootdata, $pos, self::SMALL_BLOCK_SIZE);
+ while ($block != -2) {
+ $pos = $block * self::SMALL_BLOCK_SIZE;
+ $streamData .= substr($rootdata, $pos, self::SMALL_BLOCK_SIZE);
- $block = self::_GetInt4d($this->smallBlockChain, $block*4);
- }
+ $block = self::_GetInt4d($this->smallBlockChain, $block*4);
+ }
- return $streamData;
- } else {
- $numBlocks = $this->props[$stream]['size'] / self::BIG_BLOCK_SIZE;
- if ($this->props[$stream]['size'] % self::BIG_BLOCK_SIZE != 0) {
- ++$numBlocks;
- }
+ return $streamData;
+ } else {
+ $numBlocks = $this->props[$stream]['size'] / self::BIG_BLOCK_SIZE;
+ if ($this->props[$stream]['size'] % self::BIG_BLOCK_SIZE != 0) {
+ ++$numBlocks;
+ }
- if ($numBlocks == 0) return '';
+ if ($numBlocks == 0) return '';
- $block = $this->props[$stream]['startBlock'];
+ $block = $this->props[$stream]['startBlock'];
- while ($block != -2) {
- $pos = ($block + 1) * self::BIG_BLOCK_SIZE;
- $streamData .= substr($this->data, $pos, self::BIG_BLOCK_SIZE);
- $block = self::_GetInt4d($this->bigBlockChain, $block*4);
- }
+ while ($block != -2) {
+ $pos = ($block + 1) * self::BIG_BLOCK_SIZE;
+ $streamData .= substr($this->data, $pos, self::BIG_BLOCK_SIZE);
+ $block = self::_GetInt4d($this->bigBlockChain, $block*4);
+ }
- return $streamData;
- }
- }
+ return $streamData;
+ }
+ }
- /**
- * Read a standard stream (by joining sectors using information from SAT)
- *
- * @param int $bl Sector ID where the stream starts
- * @return string Data for standard stream
- */
- private function _readData($bl)
- {
- $block = $bl;
- $data = '';
+ /**
+ * Read a standard stream (by joining sectors using information from SAT)
+ *
+ * @param int $bl Sector ID where the stream starts
+ * @return string Data for standard stream
+ */
+ private function _readData($bl)
+ {
+ $block = $bl;
+ $data = '';
- while ($block != -2) {
- $pos = ($block + 1) * self::BIG_BLOCK_SIZE;
- $data .= substr($this->data, $pos, self::BIG_BLOCK_SIZE);
- $block = self::_GetInt4d($this->bigBlockChain, $block*4);
- }
- return $data;
- }
+ while ($block != -2) {
+ $pos = ($block + 1) * self::BIG_BLOCK_SIZE;
+ $data .= substr($this->data, $pos, self::BIG_BLOCK_SIZE);
+ $block = self::_GetInt4d($this->bigBlockChain, $block*4);
+ }
+ return $data;
+ }
- /**
- * Read entries in the directory stream.
- */
- private function _readPropertySets() {
- $offset = 0;
+ /**
+ * Read entries in the directory stream.
+ */
+ private function _readPropertySets() {
+ $offset = 0;
- // loop through entires, each entry is 128 bytes
- $entryLen = strlen($this->entry);
- while ($offset < $entryLen) {
- // entry data (128 bytes)
- $d = substr($this->entry, $offset, self::PROPERTY_STORAGE_BLOCK_SIZE);
+ // loop through entires, each entry is 128 bytes
+ $entryLen = strlen($this->entry);
+ while ($offset < $entryLen) {
+ // entry data (128 bytes)
+ $d = substr($this->entry, $offset, self::PROPERTY_STORAGE_BLOCK_SIZE);
- // size in bytes of name
- $nameSize = ord($d[self::SIZE_OF_NAME_POS]) | (ord($d[self::SIZE_OF_NAME_POS+1]) << 8);
+ // size in bytes of name
+ $nameSize = ord($d[self::SIZE_OF_NAME_POS]) | (ord($d[self::SIZE_OF_NAME_POS+1]) << 8);
- // type of entry
- $type = ord($d[self::TYPE_POS]);
+ // type of entry
+ $type = ord($d[self::TYPE_POS]);
- // sectorID of first sector or short sector, if this entry refers to a stream (the case with workbook)
- // sectorID of first sector of the short-stream container stream, if this entry is root entry
- $startBlock = self::_GetInt4d($d, self::START_BLOCK_POS);
+ // sectorID of first sector or short sector, if this entry refers to a stream (the case with workbook)
+ // sectorID of first sector of the short-stream container stream, if this entry is root entry
+ $startBlock = self::_GetInt4d($d, self::START_BLOCK_POS);
- $size = self::_GetInt4d($d, self::SIZE_POS);
+ $size = self::_GetInt4d($d, self::SIZE_POS);
- $name = str_replace("\x00", "", substr($d,0,$nameSize));
+ $name = str_replace("\x00", "", substr($d,0,$nameSize));
- $this->props[] = array (
- 'name' => $name,
- 'type' => $type,
- 'startBlock' => $startBlock,
- 'size' => $size);
+ $this->props[] = array (
+ 'name' => $name,
+ 'type' => $type,
+ 'startBlock' => $startBlock,
+ 'size' => $size);
- // tmp helper to simplify checks
- $upName = strtoupper($name);
+ // tmp helper to simplify checks
+ $upName = strtoupper($name);
- // Workbook directory entry (BIFF5 uses Book, BIFF8 uses Workbook)
- if (($upName === 'WORKBOOK') || ($upName === 'BOOK')) {
- $this->wrkbook = count($this->props) - 1;
- }
- else if ( $upName === 'ROOT ENTRY' || $upName === 'R') {
- // Root entry
- $this->rootentry = count($this->props) - 1;
- }
+ // Workbook directory entry (BIFF5 uses Book, BIFF8 uses Workbook)
+ if (($upName === 'WORKBOOK') || ($upName === 'BOOK')) {
+ $this->wrkbook = count($this->props) - 1;
+ }
+ else if ( $upName === 'ROOT ENTRY' || $upName === 'R') {
+ // Root entry
+ $this->rootentry = count($this->props) - 1;
+ }
- // Summary information
- if ($name == chr(5) . 'SummaryInformation') {
-// echo 'Summary Information
';
- $this->summaryInformation = count($this->props) - 1;
- }
+ // Summary information
+ if ($name == chr(5) . 'SummaryInformation') {
+// echo 'Summary Information
';
+ $this->summaryInformation = count($this->props) - 1;
+ }
- // Additional Document Summary information
- if ($name == chr(5) . 'DocumentSummaryInformation') {
-// echo 'Document Summary Information
';
- $this->documentSummaryInformation = count($this->props) - 1;
- }
+ // Additional Document Summary information
+ if ($name == chr(5) . 'DocumentSummaryInformation') {
+// echo 'Document Summary Information
';
+ $this->documentSummaryInformation = count($this->props) - 1;
+ }
- $offset += self::PROPERTY_STORAGE_BLOCK_SIZE;
- }
+ $offset += self::PROPERTY_STORAGE_BLOCK_SIZE;
+ }
- }
-
- /**
- * Read 4 bytes of data at specified position
- *
- * @param string $data
- * @param int $pos
- * @return int
- */
- private static function _GetInt4d($data, $pos)
- {
- // FIX: represent numbers correctly on 64-bit system
- // http://sourceforge.net/tracker/index.php?func=detail&aid=1487372&group_id=99160&atid=623334
- // Hacked by Andreas Rehm 2006 to ensure correct result of the <<24 block on 32 and 64bit systems
- $_or_24 = ord($data[$pos + 3]);
- if ($_or_24 >= 128) {
- // negative number
- $_ord_24 = -abs((256 - $_or_24) << 24);
- } else {
- $_ord_24 = ($_or_24 & 127) << 24;
- }
- return ord($data[$pos]) | (ord($data[$pos + 1]) << 8) | (ord($data[$pos + 2]) << 16) | $_ord_24;
- }
+ }
+ /**
+ * Read 4 bytes of data at specified position
+ *
+ * @param string $data
+ * @param int $pos
+ * @return int
+ */
+ private static function _GetInt4d($data, $pos)
+ {
+ // FIX: represent numbers correctly on 64-bit system
+ // http://sourceforge.net/tracker/index.php?func=detail&aid=1487372&group_id=99160&atid=623334
+ // Hacked by Andreas Rehm 2006 to ensure correct result of the <<24 block on 32 and 64bit systems
+ $_or_24 = ord($data[$pos + 3]);
+ if ($_or_24 >= 128) {
+ // negative number
+ $_ord_24 = -abs((256 - $_or_24) << 24);
+ } else {
+ $_ord_24 = ($_or_24 & 127) << 24;
+ }
+ return ord($data[$pos]) | (ord($data[$pos + 1]) << 8) | (ord($data[$pos + 2]) << 16) | $_ord_24;
+ }
}
diff --git a/Classes/PHPExcel/Shared/PCLZip/pclzip.lib.php b/Classes/PHPExcel/Shared/PCLZip/pclzip.lib.php
index 4bf05a5..4ff8566 100644
--- a/Classes/PHPExcel/Shared/PCLZip/pclzip.lib.php
+++ b/Classes/PHPExcel/Shared/PCLZip/pclzip.lib.php
@@ -327,7 +327,7 @@
}
else if ($v_size > 2) {
PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER,
- "Invalid number / type of arguments");
+ "Invalid number / type of arguments");
return 0;
}
}
@@ -388,7 +388,7 @@
,PCLZIP_ATT_FILE_MTIME => 'optional'
,PCLZIP_ATT_FILE_CONTENT => 'optional'
,PCLZIP_ATT_FILE_COMMENT => 'optional'
- );
+ );
foreach ($v_att_list as $v_entry) {
$v_result = $this->privFileDescrParseAtt($v_entry,
$v_filedescr_list[],
@@ -492,7 +492,7 @@
PCLZIP_OPT_TEMP_FILE_ON => 'optional',
PCLZIP_OPT_TEMP_FILE_OFF => 'optional'
//, PCLZIP_OPT_CRYPT => 'optional'
- ));
+ ));
if ($v_result != 1) {
return 0;
}
@@ -571,7 +571,7 @@
,PCLZIP_ATT_FILE_MTIME => 'optional'
,PCLZIP_ATT_FILE_CONTENT => 'optional'
,PCLZIP_ATT_FILE_COMMENT => 'optional'
- );
+ );
foreach ($v_att_list as $v_entry) {
$v_result = $this->privFileDescrParseAtt($v_entry,
$v_filedescr_list[],
@@ -751,7 +751,7 @@
PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional',
PCLZIP_OPT_TEMP_FILE_ON => 'optional',
PCLZIP_OPT_TEMP_FILE_OFF => 'optional'
- ));
+ ));
if ($v_result != 1) {
return 0;
}
@@ -805,7 +805,7 @@
// ----- Call the extracting fct
$p_list = array();
$v_result = $this->privExtractByRule($p_list, $v_path, $v_remove_path,
- $v_remove_all_path, $v_options);
+ $v_remove_all_path, $v_options);
if ($v_result < 1) {
unset($p_list);
return(0);
@@ -907,7 +907,7 @@
PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional',
PCLZIP_OPT_TEMP_FILE_ON => 'optional',
PCLZIP_OPT_TEMP_FILE_OFF => 'optional'
- ));
+ ));
if ($v_result != 1) {
return 0;
}
@@ -1374,7 +1374,7 @@
{
$v_result = true;
- // ----- Reset the file system cache
+ // ----- Reset the file system cache
clearstatcache();
// ----- Reset the error handler
@@ -1596,9 +1596,9 @@
if (($i+1) >= $p_size) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE,
- "Missing parameter value for option '"
- .PclZipUtilOptionText($p_options_list[$i])
- ."'");
+ "Missing parameter value for option '"
+ .PclZipUtilOptionText($p_options_list[$i])
+ ."'");
// ----- Return
return PclZip::errorCode();
@@ -1611,9 +1611,9 @@
else {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE,
- "Wrong parameter value for option '"
- .PclZipUtilOptionText($p_options_list[$i])
- ."'");
+ "Wrong parameter value for option '"
+ .PclZipUtilOptionText($p_options_list[$i])
+ ."'");
// ----- Return
return PclZip::errorCode();
@@ -1779,8 +1779,8 @@
default :
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER,
- "Unknown parameter '"
- .$p_options_list[$i]."'");
+ "Unknown parameter '"
+ .$p_options_list[$i]."'");
// ----- Return
return PclZip::errorCode();
@@ -1954,7 +1954,7 @@
default :
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER,
- "Unknown parameter '".$v_key."'");
+ "Unknown parameter '".$v_key."'");
// ----- Return
return PclZip::errorCode();
@@ -3033,12 +3033,12 @@
// ----- Packed data
$v_binary_data = pack("VvvvvvVVVvv", 0x04034b50,
- $p_header['version_extracted'], $p_header['flag'],
+ $p_header['version_extracted'], $p_header['flag'],
$p_header['compression'], $v_mtime, $v_mdate,
$p_header['crc'], $p_header['compressed_size'],
- $p_header['size'],
+ $p_header['size'],
strlen($p_header['stored_filename']),
- $p_header['extra_len']);
+ $p_header['extra_len']);
// ----- Write the first 148 bytes of the header in the archive
fputs($this->zip_fd, $v_binary_data, 30);
@@ -3080,14 +3080,14 @@
// ----- Packed data
$v_binary_data = pack("VvvvvvvVVVvvvvvVV", 0x02014b50,
- $p_header['version'], $p_header['version_extracted'],
+ $p_header['version'], $p_header['version_extracted'],
$p_header['flag'], $p_header['compression'],
- $v_mtime, $v_mdate, $p_header['crc'],
+ $v_mtime, $v_mdate, $p_header['crc'],
$p_header['compressed_size'], $p_header['size'],
strlen($p_header['stored_filename']),
- $p_header['extra_len'], $p_header['comment_len'],
+ $p_header['extra_len'], $p_header['comment_len'],
$p_header['disk'], $p_header['internal'],
- $p_header['external'], $p_header['offset']);
+ $p_header['external'], $p_header['offset']);
// ----- Write the 42 bytes of the header in the zip file
fputs($this->zip_fd, $v_binary_data, 46);
@@ -3123,8 +3123,8 @@
// ----- Packed data
$v_binary_data = pack("VvvvvVVv", 0x06054b50, 0, 0, $p_nb_entries,
- $p_nb_entries, $p_size,
- $p_offset, strlen($p_comment));
+ $p_nb_entries, $p_size,
+ $p_offset, strlen($p_comment));
// ----- Write the 22 bytes of the header in the zip file
fputs($this->zip_fd, $v_binary_data, 22);
@@ -3281,9 +3281,9 @@
// ----- Check the path
if ( ($p_path == "")
- || ( (substr($p_path, 0, 1) != "/")
- && (substr($p_path, 0, 3) != "../")
- && (substr($p_path,1,2)!=":/")))
+ || ( (substr($p_path, 0, 1) != "/")
+ && (substr($p_path, 0, 3) != "../")
+ && (substr($p_path,1,2)!=":/")))
$p_path = "./".$p_path;
// ----- Reduce the path last (and duplicated) '/'
@@ -3433,50 +3433,50 @@
$v_extract = true;
}
- // ----- Check compression method
- if ( ($v_extract)
- && ( ($v_header['compression'] != 8)
- && ($v_header['compression'] != 0))) {
+ // ----- Check compression method
+ if ( ($v_extract)
+ && ( ($v_header['compression'] != 8)
+ && ($v_header['compression'] != 0))) {
$v_header['status'] = 'unsupported_compression';
// ----- Look for PCLZIP_OPT_STOP_ON_ERROR
if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR]))
- && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) {
+ && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) {
$this->privSwapBackMagicQuotes();
PclZip::privErrorLog(PCLZIP_ERR_UNSUPPORTED_COMPRESSION,
- "Filename '".$v_header['stored_filename']."' is "
- ."compressed by an unsupported compression "
- ."method (".$v_header['compression'].") ");
+ "Filename '".$v_header['stored_filename']."' is "
+ ."compressed by an unsupported compression "
+ ."method (".$v_header['compression'].") ");
return PclZip::errorCode();
- }
- }
-
- // ----- Check encrypted files
- if (($v_extract) && (($v_header['flag'] & 1) == 1)) {
+ }
+ }
+
+ // ----- Check encrypted files
+ if (($v_extract) && (($v_header['flag'] & 1) == 1)) {
$v_header['status'] = 'unsupported_encryption';
// ----- Look for PCLZIP_OPT_STOP_ON_ERROR
if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR]))
- && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) {
+ && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) {
$this->privSwapBackMagicQuotes();
PclZip::privErrorLog(PCLZIP_ERR_UNSUPPORTED_ENCRYPTION,
- "Unsupported encryption for "
- ." filename '".$v_header['stored_filename']
- ."'");
+ "Unsupported encryption for "
+ ." filename '".$v_header['stored_filename']
+ ."'");
return PclZip::errorCode();
- }
+ }
}
// ----- Look for real extraction
if (($v_extract) && ($v_header['status'] != 'ok')) {
$v_result = $this->privConvertHeader2FileInfo($v_header,
- $p_file_list[$v_nb_extracted++]);
+ $p_file_list[$v_nb_extracted++]);
if ($v_result != 1) {
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
@@ -3537,12 +3537,12 @@
// ----- Look for user callback abort
if ($v_result1 == 2) {
- break;
+ break;
}
}
// ----- Look for extraction in standard output
elseif ( (isset($p_options[PCLZIP_OPT_EXTRACT_IN_OUTPUT]))
- && ($p_options[PCLZIP_OPT_EXTRACT_IN_OUTPUT])) {
+ && ($p_options[PCLZIP_OPT_EXTRACT_IN_OUTPUT])) {
// ----- Extracting the file in standard output
$v_result1 = $this->privExtractFileInOutput($v_header, $p_options);
if ($v_result1 < 1) {
@@ -3560,16 +3560,16 @@
// ----- Look for user callback abort
if ($v_result1 == 2) {
- break;
+ break;
}
}
// ----- Look for normal extraction
else {
// ----- Extracting the file
$v_result1 = $this->privExtractFile($v_header,
- $p_path, $p_remove_path,
- $p_remove_all_path,
- $p_options);
+ $p_path, $p_remove_path,
+ $p_remove_all_path,
+ $p_options);
if ($v_result1 < 1) {
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
@@ -3588,7 +3588,7 @@
// ----- Look for user callback abort
if ($v_result1 == 2) {
- break;
+ break;
}
}
}
@@ -3679,8 +3679,8 @@
if ($v_inclusion == 0) {
PclZip::privErrorLog(PCLZIP_ERR_DIRECTORY_RESTRICTION,
- "Filename '".$p_entry['filename']."' is "
- ."outside PCLZIP_OPT_EXTRACT_DIR_RESTRICTION");
+ "Filename '".$p_entry['filename']."' is "
+ ."outside PCLZIP_OPT_EXTRACT_DIR_RESTRICTION");
return PclZip::errorCode();
}
@@ -3708,7 +3708,7 @@
if ($v_result == 2) {
// ----- This status is internal and will be changed in 'skipped'
$p_entry['status'] = "aborted";
- $v_result = PCLZIP_ERR_USER_ABORTED;
+ $v_result = PCLZIP_ERR_USER_ABORTED;
}
// ----- Update the informations
@@ -3735,14 +3735,14 @@
// For historical reason first PclZip implementation does not stop
// when this kind of error occurs.
if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR]))
- && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) {
+ && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) {
PclZip::privErrorLog(PCLZIP_ERR_ALREADY_A_DIRECTORY,
- "Filename '".$p_entry['filename']."' is "
- ."already used by an existing directory");
+ "Filename '".$p_entry['filename']."' is "
+ ."already used by an existing directory");
return PclZip::errorCode();
- }
+ }
}
// ----- Look if file is write protected
else if (!is_writeable($p_entry['filename']))
@@ -3755,14 +3755,14 @@
// For historical reason first PclZip implementation does not stop
// when this kind of error occurs.
if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR]))
- && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) {
+ && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) {
PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL,
- "Filename '".$p_entry['filename']."' exists "
- ."and is write protected");
+ "Filename '".$p_entry['filename']."' exists "
+ ."and is write protected");
return PclZip::errorCode();
- }
+ }
}
// ----- Look if the extracted file is older
@@ -3770,24 +3770,24 @@
{
// ----- Change the file status
if ( (isset($p_options[PCLZIP_OPT_REPLACE_NEWER]))
- && ($p_options[PCLZIP_OPT_REPLACE_NEWER]===true)) {
- }
- else {
+ && ($p_options[PCLZIP_OPT_REPLACE_NEWER]===true)) {
+ }
+ else {
$p_entry['status'] = "newer_exist";
// ----- Look for PCLZIP_OPT_STOP_ON_ERROR
// For historical reason first PclZip implementation does not stop
// when this kind of error occurs.
if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR]))
- && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) {
+ && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) {
PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL,
- "Newer version of '".$p_entry['filename']."' exists "
- ."and option PCLZIP_OPT_REPLACE_NEWER is not selected");
+ "Newer version of '".$p_entry['filename']."' exists "
+ ."and option PCLZIP_OPT_REPLACE_NEWER is not selected");
return PclZip::errorCode();
- }
- }
+ }
+ }
}
else {
}
@@ -3823,7 +3823,7 @@
// ----- Look for not compressed file
if ($p_entry['compression'] == 0) {
- // ----- Opening destination file
+ // ----- Opening destination file
if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0)
{
@@ -3928,11 +3928,11 @@
}
}
- // ----- Change abort status
- if ($p_entry['status'] == "aborted") {
+ // ----- Change abort status
+ if ($p_entry['status'] == "aborted") {
$p_entry['status'] = "skipped";
- }
-
+ }
+
// ----- Look for post-extract callback
elseif (isset($p_options[PCLZIP_CB_POST_EXTRACT])) {
@@ -3948,7 +3948,7 @@
// ----- Look for abort result
if ($v_result == 2) {
- $v_result = PCLZIP_ERR_USER_ABORTED;
+ $v_result = PCLZIP_ERR_USER_ABORTED;
}
}
@@ -4076,7 +4076,7 @@
if ($v_result == 2) {
// ----- This status is internal and will be changed in 'skipped'
$p_entry['status'] = "aborted";
- $v_result = PCLZIP_ERR_USER_ABORTED;
+ $v_result = PCLZIP_ERR_USER_ABORTED;
}
// ----- Update the informations
@@ -4117,10 +4117,10 @@
}
}
- // ----- Change abort status
- if ($p_entry['status'] == "aborted") {
+ // ----- Change abort status
+ if ($p_entry['status'] == "aborted") {
$p_entry['status'] = "skipped";
- }
+ }
// ----- Look for post-extract callback
elseif (isset($p_options[PCLZIP_CB_POST_EXTRACT])) {
@@ -4137,7 +4137,7 @@
// ----- Look for abort result
if ($v_result == 2) {
- $v_result = PCLZIP_ERR_USER_ABORTED;
+ $v_result = PCLZIP_ERR_USER_ABORTED;
}
}
@@ -4191,7 +4191,7 @@
if ($v_result == 2) {
// ----- This status is internal and will be changed in 'skipped'
$p_entry['status'] = "aborted";
- $v_result = PCLZIP_ERR_USER_ABORTED;
+ $v_result = PCLZIP_ERR_USER_ABORTED;
}
// ----- Update the informations
@@ -4231,11 +4231,11 @@
}
- // ----- Change abort status
- if ($p_entry['status'] == "aborted") {
+ // ----- Change abort status
+ if ($p_entry['status'] == "aborted") {
$p_entry['status'] = "skipped";
- }
-
+ }
+
// ----- Look for post-extract callback
elseif (isset($p_options[PCLZIP_CB_POST_EXTRACT])) {
@@ -4259,7 +4259,7 @@
// ----- Look for abort result
if ($v_result == 2) {
- $v_result = PCLZIP_ERR_USER_ABORTED;
+ $v_result = PCLZIP_ERR_USER_ABORTED;
}
}
@@ -4489,27 +4489,27 @@
{
$v_result=1;
- // ----- Check the static values
- // TBC
- if ($p_local_header['filename'] != $p_central_header['filename']) {
- }
- if ($p_local_header['version_extracted'] != $p_central_header['version_extracted']) {
- }
- if ($p_local_header['flag'] != $p_central_header['flag']) {
- }
- if ($p_local_header['compression'] != $p_central_header['compression']) {
- }
- if ($p_local_header['mtime'] != $p_central_header['mtime']) {
- }
- if ($p_local_header['filename_len'] != $p_central_header['filename_len']) {
- }
+ // ----- Check the static values
+ // TBC
+ if ($p_local_header['filename'] != $p_central_header['filename']) {
+ }
+ if ($p_local_header['version_extracted'] != $p_central_header['version_extracted']) {
+ }
+ if ($p_local_header['flag'] != $p_central_header['flag']) {
+ }
+ if ($p_local_header['compression'] != $p_central_header['compression']) {
+ }
+ if ($p_local_header['mtime'] != $p_central_header['mtime']) {
+ }
+ if ($p_local_header['filename_len'] != $p_central_header['filename_len']) {
+ }
- // ----- Look for flag bit 3
- if (($p_local_header['flag'] & 8) == 8) {
+ // ----- Look for flag bit 3
+ if (($p_local_header['flag'] & 8) == 8) {
$p_local_header['size'] = $p_central_header['size'];
$p_local_header['compressed_size'] = $p_central_header['compressed_size'];
$p_local_header['crc'] = $p_central_header['crc'];
- }
+ }
// ----- Return
return $v_result;
@@ -4635,19 +4635,19 @@
// ----- Check the global size
if (($v_pos + $v_data['comment_size'] + 18) != $v_size) {
- // ----- Removed in release 2.2 see readme file
- // The check of the file size is a little too strict.
- // Some bugs where found when a zip is encrypted/decrypted with 'crypt'.
- // While decrypted, zip has training 0 bytes
- if (0) {
+ // ----- Removed in release 2.2 see readme file
+ // The check of the file size is a little too strict.
+ // Some bugs where found when a zip is encrypted/decrypted with 'crypt'.
+ // While decrypted, zip has training 0 bytes
+ if (0) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT,
- 'The central dir is not at the end of the archive.'
- .' Some trailing bytes exists after the archive.');
+ 'The central dir is not at the end of the archive.'
+ .' Some trailing bytes exists after the archive.');
// ----- Return
return PclZip::errorCode();
- }
+ }
}
// ----- Get comment
@@ -4809,7 +4809,7 @@
}
}
else {
- $v_found = true;
+ $v_found = true;
}
// ----- Look for deletion
@@ -4872,7 +4872,7 @@
// ----- Check that local file header is same as central file header
if ($this->privCheckFileHeaders($v_local_header,
- $v_header_list[$i]) != 1) {
+ $v_header_list[$i]) != 1) {
// TBC
}
unset($v_local_header);
@@ -5330,22 +5330,22 @@
// ----- Look if function exists
if ( (!function_exists("get_magic_quotes_runtime"))
- || (!function_exists("set_magic_quotes_runtime"))) {
+ || (!function_exists("set_magic_quotes_runtime"))) {
return $v_result;
- }
+ }
// ----- Look if already done
if ($this->magic_quotes_status != -1) {
return $v_result;
- }
+ }
- // ----- Get and memorize the magic_quote value
- $this->magic_quotes_status = @get_magic_quotes_runtime();
+ // ----- Get and memorize the magic_quote value
+ $this->magic_quotes_status = @get_magic_quotes_runtime();
- // ----- Disable magic_quotes
- if ($this->magic_quotes_status == 1) {
- @set_magic_quotes_runtime(0);
- }
+ // ----- Disable magic_quotes
+ if ($this->magic_quotes_status == 1) {
+ @set_magic_quotes_runtime(0);
+ }
// ----- Return
return $v_result;
@@ -5364,19 +5364,19 @@
// ----- Look if function exists
if ( (!function_exists("get_magic_quotes_runtime"))
- || (!function_exists("set_magic_quotes_runtime"))) {
+ || (!function_exists("set_magic_quotes_runtime"))) {
return $v_result;
- }
+ }
// ----- Look if something to do
if ($this->magic_quotes_status != -1) {
return $v_result;
- }
+ }
- // ----- Swap back magic_quotes
- if ($this->magic_quotes_status == 1) {
- @set_magic_quotes_runtime($this->magic_quotes_status);
- }
+ // ----- Swap back magic_quotes
+ if ($this->magic_quotes_status == 1) {
+ @set_magic_quotes_runtime($this->magic_quotes_status);
+ }
// ----- Return
return $v_result;
@@ -5411,37 +5411,37 @@
// Should be the first $i=0, but no check is done
}
else if ($v_list[$i] == "..") {
- $v_skip++;
+ $v_skip++;
}
else if ($v_list[$i] == "") {
- // ----- First '/' i.e. root slash
- if ($i == 0) {
+ // ----- First '/' i.e. root slash
+ if ($i == 0) {
$v_result = "/".$v_result;
- if ($v_skip > 0) {
- // ----- It is an invalid path, so the path is not modified
- // TBC
- $v_result = $p_dir;
+ if ($v_skip > 0) {
+ // ----- It is an invalid path, so the path is not modified
+ // TBC
+ $v_result = $p_dir;
$v_skip = 0;
- }
- }
- // ----- Last '/' i.e. indicates a directory
- else if ($i == (sizeof($v_list)-1)) {
+ }
+ }
+ // ----- Last '/' i.e. indicates a directory
+ else if ($i == (sizeof($v_list)-1)) {
$v_result = $v_list[$i];
- }
- // ----- Double '/' inside the path
- else {
+ }
+ // ----- Double '/' inside the path
+ else {
// ----- Ignore only the double '//' in path,
// but not the first and last '/'
- }
+ }
}
else {
- // ----- Look for item to skip
- if ($v_skip > 0) {
- $v_skip--;
- }
- else {
+ // ----- Look for item to skip
+ if ($v_skip > 0) {
+ $v_skip--;
+ }
+ else {
$v_result = $v_list[$i].($i!=(sizeof($v_list)-1)?"/".$v_result:"");
- }
+ }
}
}
@@ -5648,13 +5648,13 @@
$v_list = get_defined_constants();
for (reset($v_list); $v_key = key($v_list); next($v_list)) {
- $v_prefix = substr($v_key, 0, 10);
- if (( ($v_prefix == 'PCLZIP_OPT')
+ $v_prefix = substr($v_key, 0, 10);
+ if (( ($v_prefix == 'PCLZIP_OPT')
|| ($v_prefix == 'PCLZIP_CB_')
|| ($v_prefix == 'PCLZIP_ATT'))
- && ($v_list[$v_key] == $p_option)) {
+ && ($v_list[$v_key] == $p_option)) {
return $v_key;
- }
+ }
}
$v_result = 'Unknown';
diff --git a/Classes/PHPExcel/Shared/PasswordHasher.php b/Classes/PHPExcel/Shared/PasswordHasher.php
index 42c045d..0ee7ae6 100644
--- a/Classes/PHPExcel/Shared/PasswordHasher.php
+++ b/Classes/PHPExcel/Shared/PasswordHasher.php
@@ -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,32 +37,32 @@ namespace PHPExcel;
*/
class Shared_PasswordHasher
{
- /**
- * Create a password hash from a given string.
- *
- * This method is based on the algorithm provided by
- * Daniel Rentz of OpenOffice and the PEAR package
- * Spreadsheet_Excel_Writer by Xavier Noguer
- * $objPHPExcel->getActiveSheet()->getStyle('B2')->getAlignment()->applyFromArray(
- * array(
- * 'horizontal' => PHPExcel\Style_Alignment::HORIZONTAL_CENTER,
- * 'vertical' => PHPExcel\Style_Alignment::VERTICAL_CENTER,
- * 'rotation' => 0,
- * 'wrap' => TRUE
- * )
- * );
- *
- *
- * @param array $pStyles Array containing style information
- * @throws PHPExcel\Exception
- * @return PHPExcel\Style_Alignment
- */
- public function applyFromArray($pStyles = NULL) {
- if (is_array($pStyles)) {
- if ($this->_isSupervisor) {
- $this->getActiveSheet()->getStyle($this->getSelectedCells())
- ->applyFromArray($this->getStyleArray($pStyles));
- } else {
- if (isset($pStyles['horizontal'])) {
- $this->setHorizontal($pStyles['horizontal']);
- }
- if (isset($pStyles['vertical'])) {
- $this->setVertical($pStyles['vertical']);
- }
- if (isset($pStyles['rotation'])) {
- $this->setTextRotation($pStyles['rotation']);
- }
- if (isset($pStyles['wrap'])) {
- $this->setWrapText($pStyles['wrap']);
- }
- if (isset($pStyles['shrinkToFit'])) {
- $this->setShrinkToFit($pStyles['shrinkToFit']);
- }
- if (isset($pStyles['indent'])) {
- $this->setIndent($pStyles['indent']);
- }
- }
- } else {
- throw new Exception("Invalid style array passed.");
- }
- return $this;
- }
+ /**
+ * Apply styles from array
+ *
+ *
+ * $objPHPExcel->getActiveSheet()->getStyle('B2')->getAlignment()->applyFromArray(
+ * array(
+ * 'horizontal' => PHPExcel\Style_Alignment::HORIZONTAL_CENTER,
+ * 'vertical' => PHPExcel\Style_Alignment::VERTICAL_CENTER,
+ * 'rotation' => 0,
+ * 'wrap' => TRUE
+ * )
+ * );
+ *
+ *
+ * @param array $pStyles Array containing style information
+ * @throws PHPExcel\Exception
+ * @return PHPExcel\Style_Alignment
+ */
+ public function applyFromArray($pStyles = null) {
+ if (is_array($pStyles)) {
+ if ($this->_isSupervisor) {
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())
+ ->applyFromArray($this->getStyleArray($pStyles));
+ } else {
+ if (isset($pStyles['horizontal'])) {
+ $this->setHorizontal($pStyles['horizontal']);
+ }
+ if (isset($pStyles['vertical'])) {
+ $this->setVertical($pStyles['vertical']);
+ }
+ if (isset($pStyles['rotation'])) {
+ $this->setTextRotation($pStyles['rotation']);
+ }
+ if (isset($pStyles['wrap'])) {
+ $this->setWrapText($pStyles['wrap']);
+ }
+ if (isset($pStyles['shrinkToFit'])) {
+ $this->setShrinkToFit($pStyles['shrinkToFit']);
+ }
+ if (isset($pStyles['indent'])) {
+ $this->setIndent($pStyles['indent']);
+ }
+ }
+ } else {
+ throw new Exception("Invalid style array passed.");
+ }
+ return $this;
+ }
- /**
- * Get Horizontal
- *
- * @return string
- */
- public function getHorizontal() {
- if ($this->_isSupervisor) {
- return $this->getSharedComponent()->getHorizontal();
- }
- return $this->_horizontal;
- }
+ /**
+ * Get Horizontal
+ *
+ * @return string
+ */
+ public function getHorizontal() {
+ if ($this->_isSupervisor) {
+ return $this->getSharedComponent()->getHorizontal();
+ }
+ return $this->_horizontal;
+ }
- /**
- * Set Horizontal
- *
- * @param string $pValue
- * @return PHPExcel\Style_Alignment
- */
- public function setHorizontal($pValue = Style_Alignment::HORIZONTAL_GENERAL) {
- if ($pValue == '') {
- $pValue = Style_Alignment::HORIZONTAL_GENERAL;
- }
+ /**
+ * Set Horizontal
+ *
+ * @param string $pValue
+ * @return PHPExcel\Style_Alignment
+ */
+ public function setHorizontal($pValue = Style_Alignment::HORIZONTAL_GENERAL) {
+ if ($pValue == '') {
+ $pValue = Style_Alignment::HORIZONTAL_GENERAL;
+ }
- if ($this->_isSupervisor) {
- $styleArray = $this->getStyleArray(array('horizontal' => $pValue));
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
- }
- else {
- $this->_horizontal = $pValue;
- }
- return $this;
- }
+ if ($this->_isSupervisor) {
+ $styleArray = $this->getStyleArray(array('horizontal' => $pValue));
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
+ }
+ else {
+ $this->_horizontal = $pValue;
+ }
+ return $this;
+ }
- /**
- * Get Vertical
- *
- * @return string
- */
- public function getVertical() {
- if ($this->_isSupervisor) {
- return $this->getSharedComponent()->getVertical();
- }
- return $this->_vertical;
- }
+ /**
+ * Get Vertical
+ *
+ * @return string
+ */
+ public function getVertical() {
+ if ($this->_isSupervisor) {
+ return $this->getSharedComponent()->getVertical();
+ }
+ return $this->_vertical;
+ }
- /**
- * Set Vertical
- *
- * @param string $pValue
- * @return PHPExcel\Style_Alignment
- */
- public function setVertical($pValue = Style_Alignment::VERTICAL_BOTTOM) {
- if ($pValue == '') {
- $pValue = Style_Alignment::VERTICAL_BOTTOM;
- }
+ /**
+ * Set Vertical
+ *
+ * @param string $pValue
+ * @return PHPExcel\Style_Alignment
+ */
+ public function setVertical($pValue = Style_Alignment::VERTICAL_BOTTOM) {
+ if ($pValue == '') {
+ $pValue = Style_Alignment::VERTICAL_BOTTOM;
+ }
- if ($this->_isSupervisor) {
- $styleArray = $this->getStyleArray(array('vertical' => $pValue));
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
- } else {
- $this->_vertical = $pValue;
- }
- return $this;
- }
+ if ($this->_isSupervisor) {
+ $styleArray = $this->getStyleArray(array('vertical' => $pValue));
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
+ } else {
+ $this->_vertical = $pValue;
+ }
+ return $this;
+ }
- /**
- * Get TextRotation
- *
- * @return int
- */
- public function getTextRotation() {
- if ($this->_isSupervisor) {
- return $this->getSharedComponent()->getTextRotation();
- }
- return $this->_textRotation;
- }
+ /**
+ * Get TextRotation
+ *
+ * @return int
+ */
+ public function getTextRotation() {
+ if ($this->_isSupervisor) {
+ return $this->getSharedComponent()->getTextRotation();
+ }
+ return $this->_textRotation;
+ }
- /**
- * Set TextRotation
- *
- * @param int $pValue
- * @throws PHPExcel\Exception
- * @return PHPExcel\Style_Alignment
- */
- public function setTextRotation($pValue = 0) {
- // Excel2007 value 255 => PHPExcel value -165
- if ($pValue == 255) {
- $pValue = -165;
- }
+ /**
+ * Set TextRotation
+ *
+ * @param int $pValue
+ * @throws PHPExcel\Exception
+ * @return PHPExcel\Style_Alignment
+ */
+ public function setTextRotation($pValue = 0) {
+ // Excel2007 value 255 => PHPExcel value -165
+ if ($pValue == 255) {
+ $pValue = -165;
+ }
- // Set rotation
- if ( ($pValue >= -90 && $pValue <= 90) || $pValue == -165 ) {
- if ($this->_isSupervisor) {
- $styleArray = $this->getStyleArray(array('rotation' => $pValue));
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
- } else {
- $this->_textRotation = $pValue;
- }
- } else {
- throw new Exception("Text rotation should be a value between -90 and 90.");
- }
+ // Set rotation
+ if ( ($pValue >= -90 && $pValue <= 90) || $pValue == -165 ) {
+ if ($this->_isSupervisor) {
+ $styleArray = $this->getStyleArray(array('rotation' => $pValue));
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
+ } else {
+ $this->_textRotation = $pValue;
+ }
+ } else {
+ throw new Exception("Text rotation should be a value between -90 and 90.");
+ }
- return $this;
- }
+ return $this;
+ }
- /**
- * Get Wrap Text
- *
- * @return boolean
- */
- public function getWrapText() {
- if ($this->_isSupervisor) {
- return $this->getSharedComponent()->getWrapText();
- }
- return $this->_wrapText;
- }
+ /**
+ * Get Wrap Text
+ *
+ * @return boolean
+ */
+ public function getWrapText() {
+ if ($this->_isSupervisor) {
+ return $this->getSharedComponent()->getWrapText();
+ }
+ return $this->_wrapText;
+ }
- /**
- * Set Wrap Text
- *
- * @param boolean $pValue
- * @return PHPExcel\Style_Alignment
- */
- public function setWrapText($pValue = FALSE) {
- if ($pValue == '') {
- $pValue = FALSE;
- }
- if ($this->_isSupervisor) {
- $styleArray = $this->getStyleArray(array('wrap' => $pValue));
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
- } else {
- $this->_wrapText = $pValue;
- }
- return $this;
- }
+ /**
+ * Set Wrap Text
+ *
+ * @param boolean $pValue
+ * @return PHPExcel\Style_Alignment
+ */
+ public function setWrapText($pValue = false) {
+ if ($pValue == '') {
+ $pValue = false;
+ }
+ if ($this->_isSupervisor) {
+ $styleArray = $this->getStyleArray(array('wrap' => $pValue));
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
+ } else {
+ $this->_wrapText = $pValue;
+ }
+ return $this;
+ }
- /**
- * Get Shrink to fit
- *
- * @return boolean
- */
- public function getShrinkToFit() {
- if ($this->_isSupervisor) {
- return $this->getSharedComponent()->getShrinkToFit();
- }
- return $this->_shrinkToFit;
- }
+ /**
+ * Get Shrink to fit
+ *
+ * @return boolean
+ */
+ public function getShrinkToFit() {
+ if ($this->_isSupervisor) {
+ return $this->getSharedComponent()->getShrinkToFit();
+ }
+ return $this->_shrinkToFit;
+ }
- /**
- * Set Shrink to fit
- *
- * @param boolean $pValue
- * @return PHPExcel\Style_Alignment
- */
- public function setShrinkToFit($pValue = FALSE) {
- if ($pValue == '') {
- $pValue = FALSE;
- }
- if ($this->_isSupervisor) {
- $styleArray = $this->getStyleArray(array('shrinkToFit' => $pValue));
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
- } else {
- $this->_shrinkToFit = $pValue;
- }
- return $this;
- }
+ /**
+ * Set Shrink to fit
+ *
+ * @param boolean $pValue
+ * @return PHPExcel\Style_Alignment
+ */
+ public function setShrinkToFit($pValue = false) {
+ if ($pValue == '') {
+ $pValue = false;
+ }
+ if ($this->_isSupervisor) {
+ $styleArray = $this->getStyleArray(array('shrinkToFit' => $pValue));
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
+ } else {
+ $this->_shrinkToFit = $pValue;
+ }
+ return $this;
+ }
- /**
- * Get indent
- *
- * @return int
- */
- public function getIndent() {
- if ($this->_isSupervisor) {
- return $this->getSharedComponent()->getIndent();
- }
- return $this->_indent;
- }
+ /**
+ * Get indent
+ *
+ * @return int
+ */
+ public function getIndent() {
+ if ($this->_isSupervisor) {
+ return $this->getSharedComponent()->getIndent();
+ }
+ return $this->_indent;
+ }
- /**
- * Set indent
- *
- * @param int $pValue
- * @return PHPExcel\Style_Alignment
- */
- public function setIndent($pValue = 0) {
- if ($pValue > 0) {
- if ($this->getHorizontal() != self::HORIZONTAL_GENERAL &&
- $this->getHorizontal() != self::HORIZONTAL_LEFT &&
- $this->getHorizontal() != self::HORIZONTAL_RIGHT) {
- $pValue = 0; // indent not supported
- }
- }
- if ($this->_isSupervisor) {
- $styleArray = $this->getStyleArray(array('indent' => $pValue));
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
- } else {
- $this->_indent = $pValue;
- }
- return $this;
- }
-
- /**
- * Get hash code
- *
- * @return string Hash code
- */
- public function getHashCode() {
- if ($this->_isSupervisor) {
- return $this->getSharedComponent()->getHashCode();
- }
- return md5(
- $this->_horizontal
- . $this->_vertical
- . $this->_textRotation
- . ($this->_wrapText ? 't' : 'f')
- . ($this->_shrinkToFit ? 't' : 'f')
- . $this->_indent
- . __CLASS__
- );
- }
+ /**
+ * Set indent
+ *
+ * @param int $pValue
+ * @return PHPExcel\Style_Alignment
+ */
+ public function setIndent($pValue = 0) {
+ if ($pValue > 0) {
+ if ($this->getHorizontal() != self::HORIZONTAL_GENERAL &&
+ $this->getHorizontal() != self::HORIZONTAL_LEFT &&
+ $this->getHorizontal() != self::HORIZONTAL_RIGHT) {
+ $pValue = 0; // indent not supported
+ }
+ }
+ if ($this->_isSupervisor) {
+ $styleArray = $this->getStyleArray(array('indent' => $pValue));
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
+ } else {
+ $this->_indent = $pValue;
+ }
+ return $this;
+ }
+ /**
+ * Get hash code
+ *
+ * @return string Hash code
+ */
+ public function getHashCode() {
+ if ($this->_isSupervisor) {
+ return $this->getSharedComponent()->getHashCode();
+ }
+ return md5(
+ $this->_horizontal
+ . $this->_vertical
+ . $this->_textRotation
+ . ($this->_wrapText ? 't' : 'f')
+ . ($this->_shrinkToFit ? 't' : 'f')
+ . $this->_indent
+ . __CLASS__
+ );
+ }
}
diff --git a/Classes/PHPExcel/Style/Border.php b/Classes/PHPExcel/Style/Border.php
index 906e5b0..0de33dd 100644
--- a/Classes/PHPExcel/Style/Border.php
+++ b/Classes/PHPExcel/Style/Border.php
@@ -19,10 +19,10 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category PHPExcel
- * @package PHPExcel\Style
+ * @package PHPExcel\Style
* @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,264 @@ namespace PHPExcel;
* PHPExcel\Style_Border
*
* @category PHPExcel
- * @package PHPExcel\Style
+ * @package PHPExcel\Style
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
*/
class Style_Border extends Style_Supervisor implements IComparable
{
- /* Border style */
- const BORDER_NONE = 'none';
- const BORDER_DASHDOT = 'dashDot';
- const BORDER_DASHDOTDOT = 'dashDotDot';
- const BORDER_DASHED = 'dashed';
- const BORDER_DOTTED = 'dotted';
- const BORDER_DOUBLE = 'double';
- const BORDER_HAIR = 'hair';
- const BORDER_MEDIUM = 'medium';
- const BORDER_MEDIUMDASHDOT = 'mediumDashDot';
- const BORDER_MEDIUMDASHDOTDOT = 'mediumDashDotDot';
- const BORDER_MEDIUMDASHED = 'mediumDashed';
- const BORDER_SLANTDASHDOT = 'slantDashDot';
- const BORDER_THICK = 'thick';
- const BORDER_THIN = 'thin';
+ /* Border style */
+ const BORDER_NONE = 'none';
+ const BORDER_DASHDOT = 'dashDot';
+ const BORDER_DASHDOTDOT = 'dashDotDot';
+ const BORDER_DASHED = 'dashed';
+ const BORDER_DOTTED = 'dotted';
+ const BORDER_DOUBLE = 'double';
+ const BORDER_HAIR = 'hair';
+ const BORDER_MEDIUM = 'medium';
+ const BORDER_MEDIUMDASHDOT = 'mediumDashDot';
+ const BORDER_MEDIUMDASHDOTDOT = 'mediumDashDotDot';
+ const BORDER_MEDIUMDASHED = 'mediumDashed';
+ const BORDER_SLANTDASHDOT = 'slantDashDot';
+ const BORDER_THICK = 'thick';
+ const BORDER_THIN = 'thin';
- /**
- * Border style
- *
- * @var string
- */
- protected $_borderStyle = Style_Border::BORDER_NONE;
+ /**
+ * Border style
+ *
+ * @var string
+ */
+ protected $_borderStyle = Style_Border::BORDER_NONE;
- /**
- * Border color
- *
- * @var PHPExcel\Style_Color
- */
- protected $_color;
+ /**
+ * Border color
+ *
+ * @var PHPExcel\Style_Color
+ */
+ protected $_color;
- /**
- * Parent property name
- *
- * @var string
- */
- protected $_parentPropertyName;
+ /**
+ * Parent property name
+ *
+ * @var string
+ */
+ protected $_parentPropertyName;
- /**
- * Create a new PHPExcel\Style_Border
- *
- * @param boolean $isSupervisor Flag indicating if this is a supervisor or not
- * Leave this value at default unless you understand exactly what
- * its ramifications are
- * @param boolean $isConditional Flag indicating if this is a conditional style or not
- * Leave this value at default unless you understand exactly what
- * its ramifications are
- */
- public function __construct($isSupervisor = FALSE, $isConditional = FALSE)
- {
- // Supervisor?
- parent::__construct($isSupervisor);
+ /**
+ * Create a new PHPExcel\Style_Border
+ *
+ * @param boolean $isSupervisor Flag indicating if this is a supervisor or not
+ * Leave this value at default unless you understand exactly what
+ * its ramifications are
+ * @param boolean $isConditional Flag indicating if this is a conditional style or not
+ * Leave this value at default unless you understand exactly what
+ * its ramifications are
+ */
+ public function __construct($isSupervisor = false, $isConditional = false)
+ {
+ // Supervisor?
+ parent::__construct($isSupervisor);
- // Initialise values
- $this->_color = new Style_Color(Style_Color::COLOR_BLACK, $isSupervisor);
+ // Initialise values
+ $this->_color = new Style_Color(Style_Color::COLOR_BLACK, $isSupervisor);
- // bind parent if we are a supervisor
- if ($isSupervisor) {
- $this->_color->bindParent($this, '_color');
- }
- }
+ // bind parent if we are a supervisor
+ if ($isSupervisor) {
+ $this->_color->bindParent($this, '_color');
+ }
+ }
- /**
- * Bind parent. Only used for supervisor
- *
- * @param PHPExcel\Style_Borders $parent
- * @param string $parentPropertyName
- * @return PHPExcel\Style_Border
- */
- public function bindParent($parent, $parentPropertyName=NULL)
- {
- $this->_parent = $parent;
- $this->_parentPropertyName = $parentPropertyName;
- return $this;
- }
+ /**
+ * Bind parent. Only used for supervisor
+ *
+ * @param PHPExcel\Style_Borders $parent
+ * @param string $parentPropertyName
+ * @return PHPExcel\Style_Border
+ */
+ public function bindParent($parent, $parentPropertyName=null)
+ {
+ $this->_parent = $parent;
+ $this->_parentPropertyName = $parentPropertyName;
+ return $this;
+ }
- /**
- * Get the shared style component for the currently active cell in currently active sheet.
- * Only used for style supervisor
- *
- * @return PHPExcel\Style_Border
- * @throws PHPExcel\Exception
- */
- public function getSharedComponent()
- {
- switch ($this->_parentPropertyName) {
- case '_allBorders':
- case '_horizontal':
- case '_inside':
- case '_outline':
- case '_vertical':
- throw new Exception('Cannot get shared component for a pseudo-border.');
- break;
- case '_bottom':
- return $this->_parent->getSharedComponent()->getBottom(); break;
- case '_diagonal':
- return $this->_parent->getSharedComponent()->getDiagonal(); break;
- case '_left':
- return $this->_parent->getSharedComponent()->getLeft(); break;
- case '_right':
- return $this->_parent->getSharedComponent()->getRight(); break;
- case '_top':
- return $this->_parent->getSharedComponent()->getTop(); break;
+ /**
+ * Get the shared style component for the currently active cell in currently active sheet.
+ * Only used for style supervisor
+ *
+ * @return PHPExcel\Style_Border
+ * @throws PHPExcel\Exception
+ */
+ public function getSharedComponent()
+ {
+ switch ($this->_parentPropertyName) {
+ case '_allBorders':
+ case '_horizontal':
+ case '_inside':
+ case '_outline':
+ case '_vertical':
+ throw new Exception('Cannot get shared component for a pseudo-border.');
+ break;
+ case '_bottom':
+ return $this->_parent->getSharedComponent()->getBottom(); break;
+ case '_diagonal':
+ return $this->_parent->getSharedComponent()->getDiagonal(); break;
+ case '_left':
+ return $this->_parent->getSharedComponent()->getLeft(); break;
+ case '_right':
+ return $this->_parent->getSharedComponent()->getRight(); break;
+ case '_top':
+ return $this->_parent->getSharedComponent()->getTop(); break;
- }
- }
+ }
+ }
- /**
- * Build style array from subcomponents
- *
- * @param array $array
- * @return array
- */
- public function getStyleArray($array)
- {
- switch ($this->_parentPropertyName) {
- case '_allBorders':
- $key = 'allborders'; break;
- case '_bottom':
- $key = 'bottom'; break;
- case '_diagonal':
- $key = 'diagonal'; break;
- case '_horizontal':
- $key = 'horizontal'; break;
- case '_inside':
- $key = 'inside'; break;
- case '_left':
- $key = 'left'; break;
- case '_outline':
- $key = 'outline'; break;
- case '_right':
- $key = 'right'; break;
- case '_top':
- $key = 'top'; break;
- case '_vertical':
- $key = 'vertical'; break;
- }
- return $this->_parent->getStyleArray(array($key => $array));
- }
+ /**
+ * Build style array from subcomponents
+ *
+ * @param array $array
+ * @return array
+ */
+ public function getStyleArray($array)
+ {
+ switch ($this->_parentPropertyName) {
+ case '_allBorders':
+ $key = 'allborders'; break;
+ case '_bottom':
+ $key = 'bottom'; break;
+ case '_diagonal':
+ $key = 'diagonal'; break;
+ case '_horizontal':
+ $key = 'horizontal'; break;
+ case '_inside':
+ $key = 'inside'; break;
+ case '_left':
+ $key = 'left'; break;
+ case '_outline':
+ $key = 'outline'; break;
+ case '_right':
+ $key = 'right'; break;
+ case '_top':
+ $key = 'top'; break;
+ case '_vertical':
+ $key = 'vertical'; break;
+ }
+ return $this->_parent->getStyleArray(array($key => $array));
+ }
- /**
- * Apply styles from array
- *
- *
- * $objPHPExcel->getActiveSheet()->getStyle('B2')->getBorders()->getTop()->applyFromArray(
- * array(
- * 'style' => PHPExcel\Style_Border::BORDER_DASHDOT,
- * 'color' => array(
- * 'rgb' => '808080'
- * )
- * )
- * );
- *
- *
- * @param array $pStyles Array containing style information
- * @throws PHPExcel\Exception
- * @return PHPExcel\Style_Border
- */
- public function applyFromArray($pStyles = null) {
- if (is_array($pStyles)) {
- if ($this->_isSupervisor) {
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles));
- } else {
- if (isset($pStyles['style'])) {
- $this->setBorderStyle($pStyles['style']);
- }
- if (isset($pStyles['color'])) {
- $this->getColor()->applyFromArray($pStyles['color']);
- }
- }
- } else {
- throw new Exception("Invalid style array passed.");
- }
- return $this;
- }
+ /**
+ * Apply styles from array
+ *
+ *
+ * $objPHPExcel->getActiveSheet()->getStyle('B2')->getBorders()->getTop()->applyFromArray(
+ * array(
+ * 'style' => PHPExcel\Style_Border::BORDER_DASHDOT,
+ * 'color' => array(
+ * 'rgb' => '808080'
+ * )
+ * )
+ * );
+ *
+ *
+ * @param array $pStyles Array containing style information
+ * @throws PHPExcel\Exception
+ * @return PHPExcel\Style_Border
+ */
+ public function applyFromArray($pStyles = null) {
+ if (is_array($pStyles)) {
+ if ($this->_isSupervisor) {
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles));
+ } else {
+ if (isset($pStyles['style'])) {
+ $this->setBorderStyle($pStyles['style']);
+ }
+ if (isset($pStyles['color'])) {
+ $this->getColor()->applyFromArray($pStyles['color']);
+ }
+ }
+ } else {
+ throw new Exception("Invalid style array passed.");
+ }
+ return $this;
+ }
- /**
- * Get Border style
- *
- * @return string
- */
- public function getBorderStyle() {
- if ($this->_isSupervisor) {
- return $this->getSharedComponent()->getBorderStyle();
- }
- return $this->_borderStyle;
- }
+ /**
+ * Get Border style
+ *
+ * @return string
+ */
+ public function getBorderStyle() {
+ if ($this->_isSupervisor) {
+ return $this->getSharedComponent()->getBorderStyle();
+ }
+ return $this->_borderStyle;
+ }
- /**
- * Set Border style
- *
- * @param string|boolean $pValue
- * When passing a boolean, FALSE equates PHPExcel\Style_Border::BORDER_NONE
- * and TRUE to PHPExcel\Style_Border::BORDER_MEDIUM
- * @return PHPExcel\Style_Border
- */
- public function setBorderStyle($pValue = Style_Border::BORDER_NONE) {
+ /**
+ * Set Border style
+ *
+ * @param string|boolean $pValue
+ * When passing a boolean, FALSE equates PHPExcel\Style_Border::BORDER_NONE
+ * and TRUE to PHPExcel\Style_Border::BORDER_MEDIUM
+ * @return PHPExcel\Style_Border
+ */
+ public function setBorderStyle($pValue = Style_Border::BORDER_NONE) {
- if (empty($pValue)) {
- $pValue = Style_Border::BORDER_NONE;
- } elseif(is_bool($pValue) && $pValue) {
- $pValue = Style_Border::BORDER_MEDIUM;
- }
- if ($this->_isSupervisor) {
- $styleArray = $this->getStyleArray(array('style' => $pValue));
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
- } else {
- $this->_borderStyle = $pValue;
- }
- return $this;
- }
+ if (empty($pValue)) {
+ $pValue = Style_Border::BORDER_NONE;
+ } elseif(is_bool($pValue) && $pValue) {
+ $pValue = Style_Border::BORDER_MEDIUM;
+ }
+ if ($this->_isSupervisor) {
+ $styleArray = $this->getStyleArray(array('style' => $pValue));
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
+ } else {
+ $this->_borderStyle = $pValue;
+ }
+ return $this;
+ }
- /**
- * Get Border Color
- *
- * @return PHPExcel\Style_Color
- */
- public function getColor() {
- return $this->_color;
- }
+ /**
+ * Get Border Color
+ *
+ * @return PHPExcel\Style_Color
+ */
+ public function getColor() {
+ return $this->_color;
+ }
- /**
- * Set Border Color
- *
- * @param PHPExcel\Style_Color $pValue
- * @throws PHPExcel\Exception
- * @return PHPExcel\Style_Border
- */
- public function setColor(Style_Color $pValue = null) {
- // make sure parameter is a real color and not a supervisor
- $color = $pValue->getIsSupervisor() ? $pValue->getSharedComponent() : $pValue;
+ /**
+ * Set Border Color
+ *
+ * @param PHPExcel\Style_Color $pValue
+ * @throws PHPExcel\Exception
+ * @return PHPExcel\Style_Border
+ */
+ public function setColor(Style_Color $pValue = null) {
+ // make sure parameter is a real color and not a supervisor
+ $color = $pValue->getIsSupervisor() ? $pValue->getSharedComponent() : $pValue;
- if ($this->_isSupervisor) {
- $styleArray = $this->getColor()->getStyleArray(array('argb' => $color->getARGB()));
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
- } else {
- $this->_color = $color;
- }
- return $this;
- }
-
- /**
- * Get hash code
- *
- * @return string Hash code
- */
- public function getHashCode() {
- if ($this->_isSupervisor) {
- return $this->getSharedComponent()->getHashCode();
- }
- return md5(
- $this->_borderStyle
- . $this->_color->getHashCode()
- . __CLASS__
- );
- }
+ if ($this->_isSupervisor) {
+ $styleArray = $this->getColor()->getStyleArray(array('argb' => $color->getARGB()));
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
+ } else {
+ $this->_color = $color;
+ }
+ return $this;
+ }
+ /**
+ * Get hash code
+ *
+ * @return string Hash code
+ */
+ public function getHashCode() {
+ if ($this->_isSupervisor) {
+ return $this->getSharedComponent()->getHashCode();
+ }
+ return md5(
+ $this->_borderStyle
+ . $this->_color->getHashCode()
+ . __CLASS__
+ );
+ }
}
diff --git a/Classes/PHPExcel/Style/Borders.php b/Classes/PHPExcel/Style/Borders.php
index 092bb0b..7f1e204 100644
--- a/Classes/PHPExcel/Style/Borders.php
+++ b/Classes/PHPExcel/Style/Borders.php
@@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\Style
* @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,230 +37,230 @@ namespace PHPExcel;
*/
class Style_Borders extends Style_Supervisor implements IComparable
{
- /* Diagonal directions */
- const DIAGONAL_NONE = 0;
- const DIAGONAL_UP = 1;
- const DIAGONAL_DOWN = 2;
- const DIAGONAL_BOTH = 3;
+ /* Diagonal directions */
+ const DIAGONAL_NONE = 0;
+ const DIAGONAL_UP = 1;
+ const DIAGONAL_DOWN = 2;
+ const DIAGONAL_BOTH = 3;
- /**
- * Left
- *
- * @var PHPExcel\Style_Border
- */
- protected $_left;
-
- /**
- * Right
- *
- * @var PHPExcel\Style_Border
- */
- protected $_right;
-
- /**
- * Top
- *
- * @var PHPExcel\Style_Border
- */
- protected $_top;
-
- /**
- * Bottom
- *
- * @var PHPExcel\Style_Border
- */
- protected $_bottom;
-
- /**
- * Diagonal
- *
- * @var PHPExcel\Style_Border
- */
- protected $_diagonal;
-
- /**
- * DiagonalDirection
- *
- * @var int
- */
- protected $_diagonalDirection;
-
- /**
- * All borders psedo-border. Only applies to supervisor.
- *
- * @var PHPExcel\Style_Border
- */
- protected $_allBorders;
-
- /**
- * Outline psedo-border. Only applies to supervisor.
- *
- * @var PHPExcel\Style_Border
- */
- protected $_outline;
-
- /**
- * Inside psedo-border. Only applies to supervisor.
- *
- * @var PHPExcel\Style_Border
- */
- protected $_inside;
-
- /**
- * Vertical pseudo-border. Only applies to supervisor.
- *
- * @var PHPExcel\Style_Border
- */
- protected $_vertical;
-
- /**
- * Horizontal pseudo-border. Only applies to supervisor.
- *
- * @var PHPExcel\Style_Border
- */
- protected $_horizontal;
-
- /**
- * Create a new PHPExcel\Style_Borders
- *
- * @param boolean $isSupervisor Flag indicating if this is a supervisor or not
- * Leave this value at default unless you understand exactly what
- * its ramifications are
- * @param boolean $isConditional Flag indicating if this is a conditional style or not
- * Leave this value at default unless you understand exactly what
- * its ramifications are
+ /**
+ * Left
+ *
+ * @var PHPExcel\Style_Border
*/
- public function __construct($isSupervisor = FALSE, $isConditional = FALSE)
+ protected $_left;
+
+ /**
+ * Right
+ *
+ * @var PHPExcel\Style_Border
+ */
+ protected $_right;
+
+ /**
+ * Top
+ *
+ * @var PHPExcel\Style_Border
+ */
+ protected $_top;
+
+ /**
+ * Bottom
+ *
+ * @var PHPExcel\Style_Border
+ */
+ protected $_bottom;
+
+ /**
+ * Diagonal
+ *
+ * @var PHPExcel\Style_Border
+ */
+ protected $_diagonal;
+
+ /**
+ * DiagonalDirection
+ *
+ * @var int
+ */
+ protected $_diagonalDirection;
+
+ /**
+ * All borders psedo-border. Only applies to supervisor.
+ *
+ * @var PHPExcel\Style_Border
+ */
+ protected $_allBorders;
+
+ /**
+ * Outline psedo-border. Only applies to supervisor.
+ *
+ * @var PHPExcel\Style_Border
+ */
+ protected $_outline;
+
+ /**
+ * Inside psedo-border. Only applies to supervisor.
+ *
+ * @var PHPExcel\Style_Border
+ */
+ protected $_inside;
+
+ /**
+ * Vertical pseudo-border. Only applies to supervisor.
+ *
+ * @var PHPExcel\Style_Border
+ */
+ protected $_vertical;
+
+ /**
+ * Horizontal pseudo-border. Only applies to supervisor.
+ *
+ * @var PHPExcel\Style_Border
+ */
+ protected $_horizontal;
+
+ /**
+ * Create a new PHPExcel\Style_Borders
+ *
+ * @param boolean $isSupervisor Flag indicating if this is a supervisor or not
+ * Leave this value at default unless you understand exactly what
+ * its ramifications are
+ * @param boolean $isConditional Flag indicating if this is a conditional style or not
+ * Leave this value at default unless you understand exactly what
+ * its ramifications are
+ */
+ public function __construct($isSupervisor = false, $isConditional = false)
{
- // Supervisor?
- parent::__construct($isSupervisor);
+ // Supervisor?
+ parent::__construct($isSupervisor);
- // Initialise values
- $this->_left = new Style_Border($isSupervisor, $isConditional);
- $this->_right = new Style_Border($isSupervisor, $isConditional);
- $this->_top = new Style_Border($isSupervisor, $isConditional);
- $this->_bottom = new Style_Border($isSupervisor, $isConditional);
- $this->_diagonal = new Style_Border($isSupervisor, $isConditional);
- $this->_diagonalDirection = Style_Borders::DIAGONAL_NONE;
+ // Initialise values
+ $this->_left = new Style_Border($isSupervisor, $isConditional);
+ $this->_right = new Style_Border($isSupervisor, $isConditional);
+ $this->_top = new Style_Border($isSupervisor, $isConditional);
+ $this->_bottom = new Style_Border($isSupervisor, $isConditional);
+ $this->_diagonal = new Style_Border($isSupervisor, $isConditional);
+ $this->_diagonalDirection = Style_Borders::DIAGONAL_NONE;
- // Specially for supervisor
- if ($isSupervisor) {
- // Initialize pseudo-borders
- $this->_allBorders = new Style_Border(TRUE);
- $this->_outline = new Style_Border(TRUE);
- $this->_inside = new Style_Border(TRUE);
- $this->_vertical = new Style_Border(TRUE);
- $this->_horizontal = new Style_Border(TRUE);
+ // Specially for supervisor
+ if ($isSupervisor) {
+ // Initialize pseudo-borders
+ $this->_allBorders = new Style_Border(TRUE);
+ $this->_outline = new Style_Border(TRUE);
+ $this->_inside = new Style_Border(TRUE);
+ $this->_vertical = new Style_Border(TRUE);
+ $this->_horizontal = new Style_Border(TRUE);
- // bind parent if we are a supervisor
- $this->_left->bindParent($this, '_left');
- $this->_right->bindParent($this, '_right');
- $this->_top->bindParent($this, '_top');
- $this->_bottom->bindParent($this, '_bottom');
- $this->_diagonal->bindParent($this, '_diagonal');
- $this->_allBorders->bindParent($this, '_allBorders');
- $this->_outline->bindParent($this, '_outline');
- $this->_inside->bindParent($this, '_inside');
- $this->_vertical->bindParent($this, '_vertical');
- $this->_horizontal->bindParent($this, '_horizontal');
- }
+ // bind parent if we are a supervisor
+ $this->_left->bindParent($this, '_left');
+ $this->_right->bindParent($this, '_right');
+ $this->_top->bindParent($this, '_top');
+ $this->_bottom->bindParent($this, '_bottom');
+ $this->_diagonal->bindParent($this, '_diagonal');
+ $this->_allBorders->bindParent($this, '_allBorders');
+ $this->_outline->bindParent($this, '_outline');
+ $this->_inside->bindParent($this, '_inside');
+ $this->_vertical->bindParent($this, '_vertical');
+ $this->_horizontal->bindParent($this, '_horizontal');
+ }
}
- /**
- * Get the shared style component for the currently active cell in currently active sheet.
- * Only used for style supervisor
- *
- * @return PHPExcel\Style_Borders
- */
- public function getSharedComponent()
- {
- return $this->_parent->getSharedComponent()->getBorders();
- }
+ /**
+ * Get the shared style component for the currently active cell in currently active sheet.
+ * Only used for style supervisor
+ *
+ * @return PHPExcel\Style_Borders
+ */
+ public function getSharedComponent()
+ {
+ return $this->_parent->getSharedComponent()->getBorders();
+ }
- /**
- * Build style array from subcomponents
- *
- * @param array $array
- * @return array
- */
- public function getStyleArray($array)
- {
- return array('borders' => $array);
- }
+ /**
+ * Build style array from subcomponents
+ *
+ * @param array $array
+ * @return array
+ */
+ public function getStyleArray($array)
+ {
+ return array('borders' => $array);
+ }
- /**
+ /**
* Apply styles from array
*
*
* $objPHPExcel->getActiveSheet()->getStyle('B2')->getBorders()->applyFromArray(
- * array(
- * 'bottom' => array(
- * 'style' => PHPExcel\Style_Border::BORDER_DASHDOT,
- * 'color' => array(
- * 'rgb' => '808080'
- * )
- * ),
- * 'top' => array(
- * 'style' => PHPExcel\Style_Border::BORDER_DASHDOT,
- * 'color' => array(
- * 'rgb' => '808080'
- * )
- * )
- * )
+ * array(
+ * 'bottom' => array(
+ * 'style' => PHPExcel\Style_Border::BORDER_DASHDOT,
+ * 'color' => array(
+ * 'rgb' => '808080'
+ * )
+ * ),
+ * 'top' => array(
+ * 'style' => PHPExcel\Style_Border::BORDER_DASHDOT,
+ * 'color' => array(
+ * 'rgb' => '808080'
+ * )
+ * )
+ * )
* );
*
*
* $objPHPExcel->getActiveSheet()->getStyle('B2')->getBorders()->applyFromArray(
- * array(
- * 'allborders' => array(
- * 'style' => PHPExcel\Style_Border::BORDER_DASHDOT,
- * 'color' => array(
- * 'rgb' => '808080'
- * )
- * )
- * )
+ * array(
+ * 'allborders' => array(
+ * 'style' => PHPExcel\Style_Border::BORDER_DASHDOT,
+ * 'color' => array(
+ * 'rgb' => '808080'
+ * )
+ * )
+ * )
* );
*
*
- * @param array $pStyles Array containing style information
- * @throws PHPExcel\Exception
+ * @param array $pStyles Array containing style information
+ * @throws PHPExcel\Exception
* @return PHPExcel\Style_Borders
*/
- public function applyFromArray($pStyles = null) {
- if (is_array($pStyles)) {
- if ($this->_isSupervisor) {
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles));
- } else {
- if (array_key_exists('left', $pStyles)) {
- $this->getLeft()->applyFromArray($pStyles['left']);
- }
- if (array_key_exists('right', $pStyles)) {
- $this->getRight()->applyFromArray($pStyles['right']);
- }
- if (array_key_exists('top', $pStyles)) {
- $this->getTop()->applyFromArray($pStyles['top']);
- }
- if (array_key_exists('bottom', $pStyles)) {
- $this->getBottom()->applyFromArray($pStyles['bottom']);
- }
- if (array_key_exists('diagonal', $pStyles)) {
- $this->getDiagonal()->applyFromArray($pStyles['diagonal']);
- }
- if (array_key_exists('diagonaldirection', $pStyles)) {
- $this->setDiagonalDirection($pStyles['diagonaldirection']);
- }
- if (array_key_exists('allborders', $pStyles)) {
- $this->getLeft()->applyFromArray($pStyles['allborders']);
- $this->getRight()->applyFromArray($pStyles['allborders']);
- $this->getTop()->applyFromArray($pStyles['allborders']);
- $this->getBottom()->applyFromArray($pStyles['allborders']);
- }
- }
- } else {
- throw new Exception("Invalid style array passed.");
- }
- return $this;
- }
+ public function applyFromArray($pStyles = null) {
+ if (is_array($pStyles)) {
+ if ($this->_isSupervisor) {
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles));
+ } else {
+ if (array_key_exists('left', $pStyles)) {
+ $this->getLeft()->applyFromArray($pStyles['left']);
+ }
+ if (array_key_exists('right', $pStyles)) {
+ $this->getRight()->applyFromArray($pStyles['right']);
+ }
+ if (array_key_exists('top', $pStyles)) {
+ $this->getTop()->applyFromArray($pStyles['top']);
+ }
+ if (array_key_exists('bottom', $pStyles)) {
+ $this->getBottom()->applyFromArray($pStyles['bottom']);
+ }
+ if (array_key_exists('diagonal', $pStyles)) {
+ $this->getDiagonal()->applyFromArray($pStyles['diagonal']);
+ }
+ if (array_key_exists('diagonaldirection', $pStyles)) {
+ $this->setDiagonalDirection($pStyles['diagonaldirection']);
+ }
+ if (array_key_exists('allborders', $pStyles)) {
+ $this->getLeft()->applyFromArray($pStyles['allborders']);
+ $this->getRight()->applyFromArray($pStyles['allborders']);
+ $this->getTop()->applyFromArray($pStyles['allborders']);
+ $this->getBottom()->applyFromArray($pStyles['allborders']);
+ }
+ }
+ } else {
+ throw new Exception("Invalid style array passed.");
+ }
+ return $this;
+ }
/**
* Get Left
@@ -268,7 +268,7 @@ class Style_Borders extends Style_Supervisor implements IComparable
* @return PHPExcel\Style_Border
*/
public function getLeft() {
- return $this->_left;
+ return $this->_left;
}
/**
@@ -277,7 +277,7 @@ class Style_Borders extends Style_Supervisor implements IComparable
* @return PHPExcel\Style_Border
*/
public function getRight() {
- return $this->_right;
+ return $this->_right;
}
/**
@@ -286,7 +286,7 @@ class Style_Borders extends Style_Supervisor implements IComparable
* @return PHPExcel\Style_Border
*/
public function getTop() {
- return $this->_top;
+ return $this->_top;
}
/**
@@ -295,7 +295,7 @@ class Style_Borders extends Style_Supervisor implements IComparable
* @return PHPExcel\Style_Border
*/
public function getBottom() {
- return $this->_bottom;
+ return $this->_bottom;
}
/**
@@ -304,7 +304,7 @@ class Style_Borders extends Style_Supervisor implements IComparable
* @return PHPExcel\Style_Border
*/
public function getDiagonal() {
- return $this->_diagonal;
+ return $this->_diagonal;
}
/**
@@ -314,10 +314,10 @@ class Style_Borders extends Style_Supervisor implements IComparable
* @throws PHPExcel\Exception
*/
public function getAllBorders() {
- if (!$this->_isSupervisor) {
- throw new Exception('Can only get pseudo-border for supervisor.');
- }
- return $this->_allBorders;
+ if (!$this->_isSupervisor) {
+ throw new Exception('Can only get pseudo-border for supervisor.');
+ }
+ return $this->_allBorders;
}
/**
@@ -327,10 +327,10 @@ class Style_Borders extends Style_Supervisor implements IComparable
* @throws PHPExcel\Exception
*/
public function getOutline() {
- if (!$this->_isSupervisor) {
- throw new Exception('Can only get pseudo-border for supervisor.');
- }
- return $this->_outline;
+ if (!$this->_isSupervisor) {
+ throw new Exception('Can only get pseudo-border for supervisor.');
+ }
+ return $this->_outline;
}
/**
@@ -340,10 +340,10 @@ class Style_Borders extends Style_Supervisor implements IComparable
* @throws PHPExcel\Exception
*/
public function getInside() {
- if (!$this->_isSupervisor) {
- throw new Exception('Can only get pseudo-border for supervisor.');
- }
- return $this->_inside;
+ if (!$this->_isSupervisor) {
+ throw new Exception('Can only get pseudo-border for supervisor.');
+ }
+ return $this->_inside;
}
/**
@@ -353,10 +353,10 @@ class Style_Borders extends Style_Supervisor implements IComparable
* @throws PHPExcel\Exception
*/
public function getVertical() {
- if (!$this->_isSupervisor) {
- throw new Exception('Can only get pseudo-border for supervisor.');
- }
- return $this->_vertical;
+ if (!$this->_isSupervisor) {
+ throw new Exception('Can only get pseudo-border for supervisor.');
+ }
+ return $this->_vertical;
}
/**
@@ -366,10 +366,10 @@ class Style_Borders extends Style_Supervisor implements IComparable
* @throws PHPExcel\Exception
*/
public function getHorizontal() {
- if (!$this->_isSupervisor) {
- throw new Exception('Can only get pseudo-border for supervisor.');
- }
- return $this->_horizontal;
+ if (!$this->_isSupervisor) {
+ throw new Exception('Can only get pseudo-border for supervisor.');
+ }
+ return $this->_horizontal;
}
/**
@@ -378,10 +378,10 @@ class Style_Borders extends Style_Supervisor implements IComparable
* @return int
*/
public function getDiagonalDirection() {
- if ($this->_isSupervisor) {
- return $this->getSharedComponent()->getDiagonalDirection();
- }
- return $this->_diagonalDirection;
+ if ($this->_isSupervisor) {
+ return $this->getSharedComponent()->getDiagonalDirection();
+ }
+ return $this->_diagonalDirection;
}
/**
@@ -392,35 +392,34 @@ class Style_Borders extends Style_Supervisor implements IComparable
*/
public function setDiagonalDirection($pValue = Style_Borders::DIAGONAL_NONE) {
if ($pValue == '') {
- $pValue = Style_Borders::DIAGONAL_NONE;
- }
- if ($this->_isSupervisor) {
- $styleArray = $this->getStyleArray(array('diagonaldirection' => $pValue));
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
- } else {
- $this->_diagonalDirection = $pValue;
- }
- return $this;
+ $pValue = Style_Borders::DIAGONAL_NONE;
+ }
+ if ($this->_isSupervisor) {
+ $styleArray = $this->getStyleArray(array('diagonaldirection' => $pValue));
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
+ } else {
+ $this->_diagonalDirection = $pValue;
+ }
+ return $this;
}
- /**
- * Get hash code
- *
- * @return string Hash code
- */
- public function getHashCode() {
- if ($this->_isSupervisor) {
- return $this->getSharedComponent()->getHashcode();
- }
- return md5(
- $this->getLeft()->getHashCode()
- . $this->getRight()->getHashCode()
- . $this->getTop()->getHashCode()
- . $this->getBottom()->getHashCode()
- . $this->getDiagonal()->getHashCode()
- . $this->getDiagonalDirection()
- . __CLASS__
- );
+ /**
+ * Get hash code
+ *
+ * @return string Hash code
+ */
+ public function getHashCode() {
+ if ($this->_isSupervisor) {
+ return $this->getSharedComponent()->getHashcode();
+ }
+ return md5(
+ $this->getLeft()->getHashCode()
+ . $this->getRight()->getHashCode()
+ . $this->getTop()->getHashCode()
+ . $this->getBottom()->getHashCode()
+ . $this->getDiagonal()->getHashCode()
+ . $this->getDiagonalDirection()
+ . __CLASS__
+ );
}
-
}
diff --git a/Classes/PHPExcel/Style/Color.php b/Classes/PHPExcel/Style/Color.php
index 2ee99ef..7660366 100644
--- a/Classes/PHPExcel/Style/Color.php
+++ b/Classes/PHPExcel/Style/Color.php
@@ -19,9 +19,9 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category PHPExcel
- * @package PHPExcel\Style
+ * @package PHPExcel\Style
* @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##
*/
@@ -32,400 +32,399 @@ namespace PHPExcel;
* PHPExcel\Style_Color
*
* @category PHPExcel
- * @package PHPExcel\Style
+ * @package PHPExcel\Style
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
*/
class Style_Color extends Style_Supervisor implements IComparable
{
- /* Colors */
- const COLOR_BLACK = 'FF000000';
- const COLOR_WHITE = 'FFFFFFFF';
- const COLOR_RED = 'FFFF0000';
- const COLOR_DARKRED = 'FF800000';
- const COLOR_BLUE = 'FF0000FF';
- const COLOR_DARKBLUE = 'FF000080';
- const COLOR_GREEN = 'FF00FF00';
- const COLOR_DARKGREEN = 'FF008000';
- const COLOR_YELLOW = 'FFFFFF00';
- const COLOR_DARKYELLOW = 'FF808000';
+ /* Colors */
+ const COLOR_BLACK = 'FF000000';
+ const COLOR_WHITE = 'FFFFFFFF';
+ const COLOR_RED = 'FFFF0000';
+ const COLOR_DARKRED = 'FF800000';
+ const COLOR_BLUE = 'FF0000FF';
+ const COLOR_DARKBLUE = 'FF000080';
+ const COLOR_GREEN = 'FF00FF00';
+ const COLOR_DARKGREEN = 'FF008000';
+ const COLOR_YELLOW = 'FFFFFF00';
+ const COLOR_DARKYELLOW = 'FF808000';
- /**
- * Indexed colors array
- *
- * @var array
- */
- protected static $_indexedColors;
+ /**
+ * Indexed colors array
+ *
+ * @var array
+ */
+ protected static $_indexedColors;
- /**
- * ARGB - Alpha RGB
- *
- * @var string
- */
- protected $_argb = NULL;
+ /**
+ * ARGB - Alpha RGB
+ *
+ * @var string
+ */
+ protected $_argb = null;
- /**
- * Parent property name
- *
- * @var string
- */
- protected $_parentPropertyName;
+ /**
+ * Parent property name
+ *
+ * @var string
+ */
+ protected $_parentPropertyName;
- /**
- * Create a new PHPExcel\Style_Color
- *
- * @param string $pARGB ARGB value for the colour
- * @param boolean $isSupervisor Flag indicating if this is a supervisor or not
- * Leave this value at default unless you understand exactly what
- * its ramifications are
- * @param boolean $isConditional Flag indicating if this is a conditional style or not
- * Leave this value at default unless you understand exactly what
- * its ramifications are
- */
- public function __construct($pARGB = Style_Color::COLOR_BLACK, $isSupervisor = FALSE, $isConditional = FALSE)
- {
- // Supervisor?
- parent::__construct($isSupervisor);
+ /**
+ * Create a new PHPExcel\Style_Color
+ *
+ * @param string $pARGB ARGB value for the colour
+ * @param boolean $isSupervisor Flag indicating if this is a supervisor or not
+ * Leave this value at default unless you understand exactly what
+ * its ramifications are
+ * @param boolean $isConditional Flag indicating if this is a conditional style or not
+ * Leave this value at default unless you understand exactly what
+ * its ramifications are
+ */
+ public function __construct($pARGB = Style_Color::COLOR_BLACK, $isSupervisor = false, $isConditional = false)
+ {
+ // Supervisor?
+ parent::__construct($isSupervisor);
- // Initialise values
- if (!$isConditional) {
- $this->_argb = $pARGB;
- }
- }
+ // Initialise values
+ if (!$isConditional) {
+ $this->_argb = $pARGB;
+ }
+ }
- /**
- * Bind parent. Only used for supervisor
- *
- * @param mixed $parent
- * @param string $parentPropertyName
- * @return PHPExcel\Style_Color
- */
- public function bindParent($parent, $parentPropertyName=NULL)
- {
- $this->_parent = $parent;
- $this->_parentPropertyName = $parentPropertyName;
- return $this;
- }
+ /**
+ * Bind parent. Only used for supervisor
+ *
+ * @param mixed $parent
+ * @param string $parentPropertyName
+ * @return PHPExcel\Style_Color
+ */
+ public function bindParent($parent, $parentPropertyName=null)
+ {
+ $this->_parent = $parent;
+ $this->_parentPropertyName = $parentPropertyName;
+ return $this;
+ }
- /**
- * Get the shared style component for the currently active cell in currently active sheet.
- * Only used for style supervisor
- *
- * @return PHPExcel\Style_Color
- */
- public function getSharedComponent()
- {
- switch ($this->_parentPropertyName) {
- case '_endColor':
- return $this->_parent->getSharedComponent()->getEndColor(); break;
- case '_color':
- return $this->_parent->getSharedComponent()->getColor(); break;
- case '_startColor':
- return $this->_parent->getSharedComponent()->getStartColor(); break;
- }
- }
+ /**
+ * Get the shared style component for the currently active cell in currently active sheet.
+ * Only used for style supervisor
+ *
+ * @return PHPExcel\Style_Color
+ */
+ public function getSharedComponent()
+ {
+ switch ($this->_parentPropertyName) {
+ case '_endColor':
+ return $this->_parent->getSharedComponent()->getEndColor(); break;
+ case '_color':
+ return $this->_parent->getSharedComponent()->getColor(); break;
+ case '_startColor':
+ return $this->_parent->getSharedComponent()->getStartColor(); break;
+ }
+ }
- /**
- * Build style array from subcomponents
- *
- * @param array $array
- * @return array
- */
- public function getStyleArray($array)
- {
- switch ($this->_parentPropertyName) {
- case '_endColor':
- $key = 'endcolor';
- break;
- case '_color':
- $key = 'color';
- break;
- case '_startColor':
- $key = 'startcolor';
- break;
+ /**
+ * Build style array from subcomponents
+ *
+ * @param array $array
+ * @return array
+ */
+ public function getStyleArray($array)
+ {
+ switch ($this->_parentPropertyName) {
+ case '_endColor':
+ $key = 'endcolor';
+ break;
+ case '_color':
+ $key = 'color';
+ break;
+ case '_startColor':
+ $key = 'startcolor';
+ break;
- }
- return $this->_parent->getStyleArray(array($key => $array));
- }
+ }
+ return $this->_parent->getStyleArray(array($key => $array));
+ }
- /**
- * Apply styles from array
- *
- *
- * $objPHPExcel->getActiveSheet()->getStyle('B2')->getFont()->getColor()->applyFromArray( array('rgb' => '808080') );
- *
- *
- * @param array $pStyles Array containing style information
- * @throws PHPExcel\Exception
- * @return PHPExcel\Style_Color
- */
- public function applyFromArray($pStyles = NULL) {
- if (is_array($pStyles)) {
- if ($this->_isSupervisor) {
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles));
- } else {
- if (array_key_exists('rgb', $pStyles)) {
- $this->setRGB($pStyles['rgb']);
- }
- if (array_key_exists('argb', $pStyles)) {
- $this->setARGB($pStyles['argb']);
- }
- }
- } else {
- throw new Exception("Invalid style array passed.");
- }
- return $this;
- }
+ /**
+ * Apply styles from array
+ *
+ *
+ * $objPHPExcel->getActiveSheet()->getStyle('B2')->getFont()->getColor()->applyFromArray( array('rgb' => '808080') );
+ *
+ *
+ * @param array $pStyles Array containing style information
+ * @throws PHPExcel\Exception
+ * @return PHPExcel\Style_Color
+ */
+ public function applyFromArray($pStyles = null) {
+ if (is_array($pStyles)) {
+ if ($this->_isSupervisor) {
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles));
+ } else {
+ if (array_key_exists('rgb', $pStyles)) {
+ $this->setRGB($pStyles['rgb']);
+ }
+ if (array_key_exists('argb', $pStyles)) {
+ $this->setARGB($pStyles['argb']);
+ }
+ }
+ } else {
+ throw new Exception("Invalid style array passed.");
+ }
+ return $this;
+ }
- /**
- * Get ARGB
- *
- * @return string
- */
- public function getARGB() {
- if ($this->_isSupervisor) {
- return $this->getSharedComponent()->getARGB();
- }
- return $this->_argb;
- }
+ /**
+ * Get ARGB
+ *
+ * @return string
+ */
+ public function getARGB() {
+ if ($this->_isSupervisor) {
+ return $this->getSharedComponent()->getARGB();
+ }
+ return $this->_argb;
+ }
- /**
- * Set ARGB
- *
- * @param string $pValue
- * @return PHPExcel\Style_Color
- */
- public function setARGB($pValue = Style_Color::COLOR_BLACK) {
- if ($pValue == '') {
- $pValue = Style_Color::COLOR_BLACK;
- }
- if ($this->_isSupervisor) {
- $styleArray = $this->getStyleArray(array('argb' => $pValue));
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
- } else {
- $this->_argb = $pValue;
- }
- return $this;
- }
+ /**
+ * Set ARGB
+ *
+ * @param string $pValue
+ * @return PHPExcel\Style_Color
+ */
+ public function setARGB($pValue = Style_Color::COLOR_BLACK) {
+ if ($pValue == '') {
+ $pValue = Style_Color::COLOR_BLACK;
+ }
+ if ($this->_isSupervisor) {
+ $styleArray = $this->getStyleArray(array('argb' => $pValue));
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
+ } else {
+ $this->_argb = $pValue;
+ }
+ return $this;
+ }
- /**
- * Get RGB
- *
- * @return string
- */
- public function getRGB() {
- if ($this->_isSupervisor) {
- return $this->getSharedComponent()->getRGB();
- }
- return substr($this->_argb, 2);
- }
+ /**
+ * Get RGB
+ *
+ * @return string
+ */
+ public function getRGB() {
+ if ($this->_isSupervisor) {
+ return $this->getSharedComponent()->getRGB();
+ }
+ return substr($this->_argb, 2);
+ }
- /**
- * Set RGB
- *
- * @param string $pValue RGB value
- * @return PHPExcel\Style_Color
- */
- public function setRGB($pValue = '000000') {
- if ($pValue == '') {
- $pValue = '000000';
- }
- if ($this->_isSupervisor) {
- $styleArray = $this->getStyleArray(array('argb' => 'FF' . $pValue));
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
- } else {
- $this->_argb = 'FF' . $pValue;
- }
- return $this;
- }
+ /**
+ * Set RGB
+ *
+ * @param string $pValue RGB value
+ * @return PHPExcel\Style_Color
+ */
+ public function setRGB($pValue = '000000') {
+ if ($pValue == '') {
+ $pValue = '000000';
+ }
+ if ($this->_isSupervisor) {
+ $styleArray = $this->getStyleArray(array('argb' => 'FF' . $pValue));
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
+ } else {
+ $this->_argb = 'FF' . $pValue;
+ }
+ return $this;
+ }
- /**
- * Get a specified colour component of an RGB value
- *
- * @private
- * @param string $RGB The colour as an RGB value (e.g. FF00CCCC or CCDDEE
- * @param int $offset Position within the RGB value to extract
- * @param boolean $hex Flag indicating whether the component should be returned as a hex or a
- * decimal value
- * @return string The extracted colour component
- */
- private static function _getColourComponent($RGB,$offset,$hex=TRUE) {
- $colour = substr($RGB, $offset, 2);
- if (!$hex)
- $colour = hexdec($colour);
- return $colour;
- }
+ /**
+ * Get a specified colour component of an RGB value
+ *
+ * @private
+ * @param string $RGB The colour as an RGB value (e.g. FF00CCCC or CCDDEE
+ * @param int $offset Position within the RGB value to extract
+ * @param boolean $hex Flag indicating whether the component should be returned as a hex or a
+ * decimal value
+ * @return string The extracted colour component
+ */
+ private static function _getColourComponent($RGB,$offset,$hex=TRUE) {
+ $colour = substr($RGB, $offset, 2);
+ if (!$hex)
+ $colour = hexdec($colour);
+ return $colour;
+ }
- /**
- * Get the red colour component of an RGB value
- *
- * @param string $RGB The colour as an RGB value (e.g. FF00CCCC or CCDDEE
- * @param boolean $hex Flag indicating whether the component should be returned as a hex or a
- * decimal value
- * @return string The red colour component
- */
- public static function getRed($RGB,$hex=TRUE) {
- return self::_getColourComponent($RGB, strlen($RGB) - 6, $hex);
- }
+ /**
+ * Get the red colour component of an RGB value
+ *
+ * @param string $RGB The colour as an RGB value (e.g. FF00CCCC or CCDDEE
+ * @param boolean $hex Flag indicating whether the component should be returned as a hex or a
+ * decimal value
+ * @return string The red colour component
+ */
+ public static function getRed($RGB,$hex=TRUE) {
+ return self::_getColourComponent($RGB, strlen($RGB) - 6, $hex);
+ }
- /**
- * Get the green colour component of an RGB value
- *
- * @param string $RGB The colour as an RGB value (e.g. FF00CCCC or CCDDEE
- * @param boolean $hex Flag indicating whether the component should be returned as a hex or a
- * decimal value
- * @return string The green colour component
- */
- public static function getGreen($RGB,$hex=TRUE) {
- return self::_getColourComponent($RGB, strlen($RGB) - 4, $hex);
- }
+ /**
+ * Get the green colour component of an RGB value
+ *
+ * @param string $RGB The colour as an RGB value (e.g. FF00CCCC or CCDDEE
+ * @param boolean $hex Flag indicating whether the component should be returned as a hex or a
+ * decimal value
+ * @return string The green colour component
+ */
+ public static function getGreen($RGB,$hex=TRUE) {
+ return self::_getColourComponent($RGB, strlen($RGB) - 4, $hex);
+ }
- /**
- * Get the blue colour component of an RGB value
- *
- * @param string $RGB The colour as an RGB value (e.g. FF00CCCC or CCDDEE
- * @param boolean $hex Flag indicating whether the component should be returned as a hex or a
- * decimal value
- * @return string The blue colour component
- */
- public static function getBlue($RGB,$hex=TRUE) {
- return self::_getColourComponent($RGB, strlen($RGB) - 2, $hex);
- }
+ /**
+ * Get the blue colour component of an RGB value
+ *
+ * @param string $RGB The colour as an RGB value (e.g. FF00CCCC or CCDDEE
+ * @param boolean $hex Flag indicating whether the component should be returned as a hex or a
+ * decimal value
+ * @return string The blue colour component
+ */
+ public static function getBlue($RGB,$hex=TRUE) {
+ return self::_getColourComponent($RGB, strlen($RGB) - 2, $hex);
+ }
- /**
- * Adjust the brightness of a color
- *
- * @param string $hex The colour as an RGBA or RGB value (e.g. FF00CCCC or CCDDEE)
- * @param float $adjustPercentage The percentage by which to adjust the colour as a float from -1 to 1
- * @return string The adjusted colour as an RGBA or RGB value (e.g. FF00CCCC or CCDDEE)
- */
- public static function changeBrightness($hex, $adjustPercentage) {
- $rgba = (strlen($hex) == 8);
+ /**
+ * Adjust the brightness of a color
+ *
+ * @param string $hex The colour as an RGBA or RGB value (e.g. FF00CCCC or CCDDEE)
+ * @param float $adjustPercentage The percentage by which to adjust the colour as a float from -1 to 1
+ * @return string The adjusted colour as an RGBA or RGB value (e.g. FF00CCCC or CCDDEE)
+ */
+ public static function changeBrightness($hex, $adjustPercentage) {
+ $rgba = (strlen($hex) == 8);
- $red = self::getRed($hex, FALSE);
- $green = self::getGreen($hex, FALSE);
- $blue = self::getBlue($hex, FALSE);
- if ($adjustPercentage > 0) {
- $red += (255 - $red) * $adjustPercentage;
- $green += (255 - $green) * $adjustPercentage;
- $blue += (255 - $blue) * $adjustPercentage;
- } else {
- $red += $red * $adjustPercentage;
- $green += $green * $adjustPercentage;
- $blue += $blue * $adjustPercentage;
- }
+ $red = self::getRed($hex, false);
+ $green = self::getGreen($hex, false);
+ $blue = self::getBlue($hex, false);
+ if ($adjustPercentage > 0) {
+ $red += (255 - $red) * $adjustPercentage;
+ $green += (255 - $green) * $adjustPercentage;
+ $blue += (255 - $blue) * $adjustPercentage;
+ } else {
+ $red += $red * $adjustPercentage;
+ $green += $green * $adjustPercentage;
+ $blue += $blue * $adjustPercentage;
+ }
- if ($red < 0) $red = 0;
- elseif ($red > 255) $red = 255;
- if ($green < 0) $green = 0;
- elseif ($green > 255) $green = 255;
- if ($blue < 0) $blue = 0;
- elseif ($blue > 255) $blue = 255;
+ if ($red < 0) $red = 0;
+ elseif ($red > 255) $red = 255;
+ if ($green < 0) $green = 0;
+ elseif ($green > 255) $green = 255;
+ if ($blue < 0) $blue = 0;
+ elseif ($blue > 255) $blue = 255;
- $rgb = strtoupper( str_pad(dechex($red), 2, '0', 0) .
- str_pad(dechex($green), 2, '0', 0) .
- str_pad(dechex($blue), 2, '0', 0)
- );
- return (($rgba) ? 'FF' : '') . $rgb;
- }
+ $rgb = strtoupper( str_pad(dechex($red), 2, '0', 0) .
+ str_pad(dechex($green), 2, '0', 0) .
+ str_pad(dechex($blue), 2, '0', 0)
+ );
+ return (($rgba) ? 'FF' : '') . $rgb;
+ }
- /**
- * Get indexed color
- *
- * @param int $pIndex Index entry point into the colour array
- * @param boolean $background Flag to indicate whether default background or foreground colour
- * should be returned if the indexed colour doesn't exist
- * @return PHPExcel\Style_Color
- */
- public static function indexedColor($pIndex, $background=FALSE) {
- // Clean parameter
- $pIndex = intval($pIndex);
+ /**
+ * Get indexed color
+ *
+ * @param int $pIndex Index entry point into the colour array
+ * @param boolean $background Flag to indicate whether default background or foreground colour
+ * should be returned if the indexed colour doesn't exist
+ * @return PHPExcel\Style_Color
+ */
+ public static function indexedColor($pIndex, $background=false) {
+ // Clean parameter
+ $pIndex = intval($pIndex);
- // Indexed colors
- if (is_null(self::$_indexedColors)) {
- self::$_indexedColors = array(
- 1 => 'FF000000', // System Colour #1 - Black
- 2 => 'FFFFFFFF', // System Colour #2 - White
- 3 => 'FFFF0000', // System Colour #3 - Red
- 4 => 'FF00FF00', // System Colour #4 - Green
- 5 => 'FF0000FF', // System Colour #5 - Blue
- 6 => 'FFFFFF00', // System Colour #6 - Yellow
- 7 => 'FFFF00FF', // System Colour #7- Magenta
- 8 => 'FF00FFFF', // System Colour #8- Cyan
- 9 => 'FF800000', // Standard Colour #9
- 10 => 'FF008000', // Standard Colour #10
- 11 => 'FF000080', // Standard Colour #11
- 12 => 'FF808000', // Standard Colour #12
- 13 => 'FF800080', // Standard Colour #13
- 14 => 'FF008080', // Standard Colour #14
- 15 => 'FFC0C0C0', // Standard Colour #15
- 16 => 'FF808080', // Standard Colour #16
- 17 => 'FF9999FF', // Chart Fill Colour #17
- 18 => 'FF993366', // Chart Fill Colour #18
- 19 => 'FFFFFFCC', // Chart Fill Colour #19
- 20 => 'FFCCFFFF', // Chart Fill Colour #20
- 21 => 'FF660066', // Chart Fill Colour #21
- 22 => 'FFFF8080', // Chart Fill Colour #22
- 23 => 'FF0066CC', // Chart Fill Colour #23
- 24 => 'FFCCCCFF', // Chart Fill Colour #24
- 25 => 'FF000080', // Chart Line Colour #25
- 26 => 'FFFF00FF', // Chart Line Colour #26
- 27 => 'FFFFFF00', // Chart Line Colour #27
- 28 => 'FF00FFFF', // Chart Line Colour #28
- 29 => 'FF800080', // Chart Line Colour #29
- 30 => 'FF800000', // Chart Line Colour #30
- 31 => 'FF008080', // Chart Line Colour #31
- 32 => 'FF0000FF', // Chart Line Colour #32
- 33 => 'FF00CCFF', // Standard Colour #33
- 34 => 'FFCCFFFF', // Standard Colour #34
- 35 => 'FFCCFFCC', // Standard Colour #35
- 36 => 'FFFFFF99', // Standard Colour #36
- 37 => 'FF99CCFF', // Standard Colour #37
- 38 => 'FFFF99CC', // Standard Colour #38
- 39 => 'FFCC99FF', // Standard Colour #39
- 40 => 'FFFFCC99', // Standard Colour #40
- 41 => 'FF3366FF', // Standard Colour #41
- 42 => 'FF33CCCC', // Standard Colour #42
- 43 => 'FF99CC00', // Standard Colour #43
- 44 => 'FFFFCC00', // Standard Colour #44
- 45 => 'FFFF9900', // Standard Colour #45
- 46 => 'FFFF6600', // Standard Colour #46
- 47 => 'FF666699', // Standard Colour #47
- 48 => 'FF969696', // Standard Colour #48
- 49 => 'FF003366', // Standard Colour #49
- 50 => 'FF339966', // Standard Colour #50
- 51 => 'FF003300', // Standard Colour #51
- 52 => 'FF333300', // Standard Colour #52
- 53 => 'FF993300', // Standard Colour #53
- 54 => 'FF993366', // Standard Colour #54
- 55 => 'FF333399', // Standard Colour #55
- 56 => 'FF333333' // Standard Colour #56
- );
- }
+ // Indexed colors
+ if (is_null(self::$_indexedColors)) {
+ self::$_indexedColors = array(
+ 1 => 'FF000000', // System Colour #1 - Black
+ 2 => 'FFFFFFFF', // System Colour #2 - White
+ 3 => 'FFFF0000', // System Colour #3 - Red
+ 4 => 'FF00FF00', // System Colour #4 - Green
+ 5 => 'FF0000FF', // System Colour #5 - Blue
+ 6 => 'FFFFFF00', // System Colour #6 - Yellow
+ 7 => 'FFFF00FF', // System Colour #7- Magenta
+ 8 => 'FF00FFFF', // System Colour #8- Cyan
+ 9 => 'FF800000', // Standard Colour #9
+ 10 => 'FF008000', // Standard Colour #10
+ 11 => 'FF000080', // Standard Colour #11
+ 12 => 'FF808000', // Standard Colour #12
+ 13 => 'FF800080', // Standard Colour #13
+ 14 => 'FF008080', // Standard Colour #14
+ 15 => 'FFC0C0C0', // Standard Colour #15
+ 16 => 'FF808080', // Standard Colour #16
+ 17 => 'FF9999FF', // Chart Fill Colour #17
+ 18 => 'FF993366', // Chart Fill Colour #18
+ 19 => 'FFFFFFCC', // Chart Fill Colour #19
+ 20 => 'FFCCFFFF', // Chart Fill Colour #20
+ 21 => 'FF660066', // Chart Fill Colour #21
+ 22 => 'FFFF8080', // Chart Fill Colour #22
+ 23 => 'FF0066CC', // Chart Fill Colour #23
+ 24 => 'FFCCCCFF', // Chart Fill Colour #24
+ 25 => 'FF000080', // Chart Line Colour #25
+ 26 => 'FFFF00FF', // Chart Line Colour #26
+ 27 => 'FFFFFF00', // Chart Line Colour #27
+ 28 => 'FF00FFFF', // Chart Line Colour #28
+ 29 => 'FF800080', // Chart Line Colour #29
+ 30 => 'FF800000', // Chart Line Colour #30
+ 31 => 'FF008080', // Chart Line Colour #31
+ 32 => 'FF0000FF', // Chart Line Colour #32
+ 33 => 'FF00CCFF', // Standard Colour #33
+ 34 => 'FFCCFFFF', // Standard Colour #34
+ 35 => 'FFCCFFCC', // Standard Colour #35
+ 36 => 'FFFFFF99', // Standard Colour #36
+ 37 => 'FF99CCFF', // Standard Colour #37
+ 38 => 'FFFF99CC', // Standard Colour #38
+ 39 => 'FFCC99FF', // Standard Colour #39
+ 40 => 'FFFFCC99', // Standard Colour #40
+ 41 => 'FF3366FF', // Standard Colour #41
+ 42 => 'FF33CCCC', // Standard Colour #42
+ 43 => 'FF99CC00', // Standard Colour #43
+ 44 => 'FFFFCC00', // Standard Colour #44
+ 45 => 'FFFF9900', // Standard Colour #45
+ 46 => 'FFFF6600', // Standard Colour #46
+ 47 => 'FF666699', // Standard Colour #47
+ 48 => 'FF969696', // Standard Colour #48
+ 49 => 'FF003366', // Standard Colour #49
+ 50 => 'FF339966', // Standard Colour #50
+ 51 => 'FF003300', // Standard Colour #51
+ 52 => 'FF333300', // Standard Colour #52
+ 53 => 'FF993300', // Standard Colour #53
+ 54 => 'FF993366', // Standard Colour #54
+ 55 => 'FF333399', // Standard Colour #55
+ 56 => 'FF333333' // Standard Colour #56
+ );
+ }
- if (array_key_exists($pIndex, self::$_indexedColors)) {
- return new Style_Color(self::$_indexedColors[$pIndex]);
- }
+ if (array_key_exists($pIndex, self::$_indexedColors)) {
+ return new Style_Color(self::$_indexedColors[$pIndex]);
+ }
- if ($background) {
- return new Style_Color('FFFFFFFF');
- }
- return new Style_Color('FF000000');
- }
-
- /**
- * Get hash code
- *
- * @return string Hash code
- */
- public function getHashCode() {
- if ($this->_isSupervisor) {
- return $this->getSharedComponent()->getHashCode();
- }
- return md5(
- $this->_argb
- . __CLASS__
- );
- }
+ if ($background) {
+ return new Style_Color('FFFFFFFF');
+ }
+ return new Style_Color('FF000000');
+ }
+ /**
+ * Get hash code
+ *
+ * @return string Hash code
+ */
+ public function getHashCode() {
+ if ($this->_isSupervisor) {
+ return $this->getSharedComponent()->getHashCode();
+ }
+ return md5(
+ $this->_argb
+ . __CLASS__
+ );
+ }
}
diff --git a/Classes/PHPExcel/Style/Conditional.php b/Classes/PHPExcel/Style/Conditional.php
index 32ffa65..8cf5bef 100644
--- a/Classes/PHPExcel/Style/Conditional.php
+++ b/Classes/PHPExcel/Style/Conditional.php
@@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\Style
* @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,68 +37,68 @@ namespace PHPExcel;
*/
class Style_Conditional implements IComparable
{
- /* Condition types */
- const CONDITION_NONE = 'none';
- const CONDITION_CELLIS = 'cellIs';
- const CONDITION_CONTAINSTEXT = 'containsText';
- const CONDITION_EXPRESSION = 'expression';
+ /* Condition types */
+ const CONDITION_NONE = 'none';
+ const CONDITION_CELLIS = 'cellIs';
+ const CONDITION_CONTAINSTEXT = 'containsText';
+ const CONDITION_EXPRESSION = 'expression';
- /* Operator types */
- const OPERATOR_NONE = '';
- const OPERATOR_BEGINSWITH = 'beginsWith';
- const OPERATOR_ENDSWITH = 'endsWith';
- const OPERATOR_EQUAL = 'equal';
- const OPERATOR_GREATERTHAN = 'greaterThan';
- const OPERATOR_GREATERTHANOREQUAL = 'greaterThanOrEqual';
- const OPERATOR_LESSTHAN = 'lessThan';
- const OPERATOR_LESSTHANOREQUAL = 'lessThanOrEqual';
- const OPERATOR_NOTEQUAL = 'notEqual';
- const OPERATOR_CONTAINSTEXT = 'containsText';
- const OPERATOR_NOTCONTAINS = 'notContains';
- const OPERATOR_BETWEEN = 'between';
+ /* Operator types */
+ const OPERATOR_NONE = '';
+ const OPERATOR_BEGINSWITH = 'beginsWith';
+ const OPERATOR_ENDSWITH = 'endsWith';
+ const OPERATOR_EQUAL = 'equal';
+ const OPERATOR_GREATERTHAN = 'greaterThan';
+ const OPERATOR_GREATERTHANOREQUAL = 'greaterThanOrEqual';
+ const OPERATOR_LESSTHAN = 'lessThan';
+ const OPERATOR_LESSTHANOREQUAL = 'lessThanOrEqual';
+ const OPERATOR_NOTEQUAL = 'notEqual';
+ const OPERATOR_CONTAINSTEXT = 'containsText';
+ const OPERATOR_NOTCONTAINS = 'notContains';
+ const OPERATOR_BETWEEN = 'between';
- /**
- * Condition type
- *
- * @var int
- */
- protected $_conditionType = Style_Conditional::CONDITION_NONE;
+ /**
+ * Condition type
+ *
+ * @var int
+ */
+ protected $_conditionType = Style_Conditional::CONDITION_NONE;
- /**
- * Operator type
- *
- * @var int
- */
- protected $_operatorType = Style_Conditional::OPERATOR_NONE;
+ /**
+ * Operator type
+ *
+ * @var int
+ */
+ protected $_operatorType = Style_Conditional::OPERATOR_NONE;
- /**
- * Text
- *
- * @var string
- */
- protected $_text;
+ /**
+ * Text
+ *
+ * @var string
+ */
+ protected $_text;
- /**
- * Condition
- *
- * @var string[]
- */
- protected $_condition = array();
+ /**
+ * Condition
+ *
+ * @var string[]
+ */
+ protected $_condition = array();
- /**
- * Style
- *
- * @var PHPExcel\Style
- */
- protected $_style;
+ /**
+ * Style
+ *
+ * @var PHPExcel\Style
+ */
+ protected $_style;
/**
* Create a new PHPExcel\Style_Conditional
*/
public function __construct()
{
- // Initialise values
- $this->_style = new Style(FALSE, TRUE);
+ // Initialise values
+ $this->_style = new Style(FALSE, TRUE);
}
/**
@@ -107,18 +107,18 @@ class Style_Conditional implements IComparable
* @return string
*/
public function getConditionType() {
- return $this->_conditionType;
+ return $this->_conditionType;
}
/**
* Set Condition type
*
- * @param string $pValue PHPExcel\Style_Conditional condition type
+ * @param string $pValue PHPExcel\Style_Conditional condition type
* @return PHPExcel\Style_Conditional
*/
public function setConditionType($pValue = Style_Conditional::CONDITION_NONE) {
- $this->_conditionType = $pValue;
- return $this;
+ $this->_conditionType = $pValue;
+ return $this;
}
/**
@@ -127,18 +127,18 @@ class Style_Conditional implements IComparable
* @return string
*/
public function getOperatorType() {
- return $this->_operatorType;
+ return $this->_operatorType;
}
/**
* Set Operator type
*
- * @param string $pValue PHPExcel\Style_Conditional operator type
+ * @param string $pValue PHPExcel\Style_Conditional operator type
* @return PHPExcel\Style_Conditional
*/
public function setOperatorType($pValue = Style_Conditional::OPERATOR_NONE) {
- $this->_operatorType = $pValue;
- return $this;
+ $this->_operatorType = $pValue;
+ return $this;
}
/**
@@ -168,25 +168,25 @@ class Style_Conditional implements IComparable
* @return string
*/
public function getCondition() {
- if (isset($this->_condition[0])) {
- return $this->_condition[0];
- }
+ if (isset($this->_condition[0])) {
+ return $this->_condition[0];
+ }
- return '';
+ return '';
}
/**
* Set Condition
*
* @deprecated Deprecated, use setConditions instead
- * @param string $pValue Condition
+ * @param string $pValue Condition
* @return PHPExcel\Style_Conditional
*/
public function setCondition($pValue = '') {
- if (!is_array($pValue))
- $pValue = array($pValue);
+ if (!is_array($pValue))
+ $pValue = array($pValue);
- return $this->setConditions($pValue);
+ return $this->setConditions($pValue);
}
/**
@@ -195,32 +195,32 @@ class Style_Conditional implements IComparable
* @return string[]
*/
public function getConditions() {
- return $this->_condition;
+ return $this->_condition;
}
/**
* Set Conditions
*
- * @param string[] $pValue Condition
+ * @param string[] $pValue Condition
* @return PHPExcel\Style_Conditional
*/
public function setConditions($pValue) {
- if (!is_array($pValue))
- $pValue = array($pValue);
+ if (!is_array($pValue))
+ $pValue = array($pValue);
- $this->_condition = $pValue;
- return $this;
+ $this->_condition = $pValue;
+ return $this;
}
/**
* Add Condition
*
- * @param string $pValue Condition
+ * @param string $pValue Condition
* @return PHPExcel\Style_Conditional
*/
public function addCondition($pValue = '') {
- $this->_condition[] = $pValue;
- return $this;
+ $this->_condition[] = $pValue;
+ return $this;
}
/**
@@ -229,47 +229,47 @@ class Style_Conditional implements IComparable
* @return PHPExcel\Style
*/
public function getStyle() {
- return $this->_style;
+ return $this->_style;
}
/**
* Set Style
*
- * @param PHPExcel\Style $pValue
- * @throws PHPExcel\Exception
+ * @param PHPExcel\Style $pValue
+ * @throws PHPExcel\Exception
* @return PHPExcel\Style_Conditional
*/
public function setStyle(Style $pValue = null) {
- $this->_style = $pValue;
- return $this;
+ $this->_style = $pValue;
+ return $this;
}
- /**
- * Get hash code
- *
- * @return string Hash code
- */
- public function getHashCode() {
- return md5(
- $this->_conditionType
- . $this->_operatorType
- . implode(';', $this->_condition)
- . $this->_style->getHashCode()
- . __CLASS__
- );
+ /**
+ * Get hash code
+ *
+ * @return string Hash code
+ */
+ public function getHashCode() {
+ return md5(
+ $this->_conditionType
+ . $this->_operatorType
+ . implode(';', $this->_condition)
+ . $this->_style->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;
- }
- }
- }
+ /**
+ * 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;
+ }
+ }
+ }
}
diff --git a/Classes/PHPExcel/Style/Fill.php b/Classes/PHPExcel/Style/Fill.php
index 259d8f7..b6bd4c9 100644
--- a/Classes/PHPExcel/Style/Fill.php
+++ b/Classes/PHPExcel/Style/Fill.php
@@ -19,10 +19,10 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category PHPExcel
- * @package PHPExcel\Style
+ * @package PHPExcel\Style
* @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,292 +32,291 @@ namespace PHPExcel;
* PHPExcel\Style_Fill
*
* @category PHPExcel
- * @package PHPExcel\Style
+ * @package PHPExcel\Style
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
*/
class Style_Fill extends Style_Supervisor implements IComparable
{
- /* Fill types */
- const FILL_NONE = 'none';
- const FILL_SOLID = 'solid';
- const FILL_GRADIENT_LINEAR = 'linear';
- const FILL_GRADIENT_PATH = 'path';
- const FILL_PATTERN_DARKDOWN = 'darkDown';
- const FILL_PATTERN_DARKGRAY = 'darkGray';
- const FILL_PATTERN_DARKGRID = 'darkGrid';
- const FILL_PATTERN_DARKHORIZONTAL = 'darkHorizontal';
- const FILL_PATTERN_DARKTRELLIS = 'darkTrellis';
- const FILL_PATTERN_DARKUP = 'darkUp';
- const FILL_PATTERN_DARKVERTICAL = 'darkVertical';
- const FILL_PATTERN_GRAY0625 = 'gray0625';
- const FILL_PATTERN_GRAY125 = 'gray125';
- const FILL_PATTERN_LIGHTDOWN = 'lightDown';
- const FILL_PATTERN_LIGHTGRAY = 'lightGray';
- const FILL_PATTERN_LIGHTGRID = 'lightGrid';
- const FILL_PATTERN_LIGHTHORIZONTAL = 'lightHorizontal';
- const FILL_PATTERN_LIGHTTRELLIS = 'lightTrellis';
- const FILL_PATTERN_LIGHTUP = 'lightUp';
- const FILL_PATTERN_LIGHTVERTICAL = 'lightVertical';
- const FILL_PATTERN_MEDIUMGRAY = 'mediumGray';
+ /* Fill types */
+ const FILL_NONE = 'none';
+ const FILL_SOLID = 'solid';
+ const FILL_GRADIENT_LINEAR = 'linear';
+ const FILL_GRADIENT_PATH = 'path';
+ const FILL_PATTERN_DARKDOWN = 'darkDown';
+ const FILL_PATTERN_DARKGRAY = 'darkGray';
+ const FILL_PATTERN_DARKGRID = 'darkGrid';
+ const FILL_PATTERN_DARKHORIZONTAL = 'darkHorizontal';
+ const FILL_PATTERN_DARKTRELLIS = 'darkTrellis';
+ const FILL_PATTERN_DARKUP = 'darkUp';
+ const FILL_PATTERN_DARKVERTICAL = 'darkVertical';
+ const FILL_PATTERN_GRAY0625 = 'gray0625';
+ const FILL_PATTERN_GRAY125 = 'gray125';
+ const FILL_PATTERN_LIGHTDOWN = 'lightDown';
+ const FILL_PATTERN_LIGHTGRAY = 'lightGray';
+ const FILL_PATTERN_LIGHTGRID = 'lightGrid';
+ const FILL_PATTERN_LIGHTHORIZONTAL = 'lightHorizontal';
+ const FILL_PATTERN_LIGHTTRELLIS = 'lightTrellis';
+ const FILL_PATTERN_LIGHTUP = 'lightUp';
+ const FILL_PATTERN_LIGHTVERTICAL = 'lightVertical';
+ const FILL_PATTERN_MEDIUMGRAY = 'mediumGray';
- /**
- * Fill type
- *
- * @var string
- */
- protected $_fillType = Style_Fill::FILL_NONE;
+ /**
+ * Fill type
+ *
+ * @var string
+ */
+ protected $_fillType = Style_Fill::FILL_NONE;
- /**
- * Rotation
- *
- * @var double
- */
- protected $_rotation = 0;
+ /**
+ * Rotation
+ *
+ * @var double
+ */
+ protected $_rotation = 0;
- /**
- * Start color
- *
- * @var PHPExcel\Style_Color
- */
- protected $_startColor;
+ /**
+ * Start color
+ *
+ * @var PHPExcel\Style_Color
+ */
+ protected $_startColor;
- /**
- * End color
- *
- * @var PHPExcel\Style_Color
- */
- protected $_endColor;
+ /**
+ * End color
+ *
+ * @var PHPExcel\Style_Color
+ */
+ protected $_endColor;
- /**
- * Create a new PHPExcel\Style_Fill
- *
- * @param boolean $isSupervisor Flag indicating if this is a supervisor or not
- * Leave this value at default unless you understand exactly what
- * its ramifications are
- * @param boolean $isConditional Flag indicating if this is a conditional style or not
- * Leave this value at default unless you understand exactly what
- * its ramifications are
- */
- public function __construct($isSupervisor = FALSE, $isConditional = FALSE)
- {
- // Supervisor?
- parent::__construct($isSupervisor);
+ /**
+ * Create a new PHPExcel\Style_Fill
+ *
+ * @param boolean $isSupervisor Flag indicating if this is a supervisor or not
+ * Leave this value at default unless you understand exactly what
+ * its ramifications are
+ * @param boolean $isConditional Flag indicating if this is a conditional style or not
+ * Leave this value at default unless you understand exactly what
+ * its ramifications are
+ */
+ public function __construct($isSupervisor = false, $isConditional = false)
+ {
+ // Supervisor?
+ parent::__construct($isSupervisor);
- // Initialise values
- if ($isConditional) {
- $this->_fillType = NULL;
- }
- $this->_startColor = new Style_Color(Style_Color::COLOR_WHITE, $isSupervisor, $isConditional);
- $this->_endColor = new Style_Color(Style_Color::COLOR_BLACK, $isSupervisor, $isConditional);
+ // Initialise values
+ if ($isConditional) {
+ $this->_fillType = null;
+ }
+ $this->_startColor = new Style_Color(Style_Color::COLOR_WHITE, $isSupervisor, $isConditional);
+ $this->_endColor = new Style_Color(Style_Color::COLOR_BLACK, $isSupervisor, $isConditional);
- // bind parent if we are a supervisor
- if ($isSupervisor) {
- $this->_startColor->bindParent($this, '_startColor');
- $this->_endColor->bindParent($this, '_endColor');
- }
- }
+ // bind parent if we are a supervisor
+ if ($isSupervisor) {
+ $this->_startColor->bindParent($this, '_startColor');
+ $this->_endColor->bindParent($this, '_endColor');
+ }
+ }
- /**
- * Get the shared style component for the currently active cell in currently active sheet.
- * Only used for style supervisor
- *
- * @return PHPExcel\Style_Fill
- */
- public function getSharedComponent()
- {
- return $this->_parent->getSharedComponent()->getFill();
- }
+ /**
+ * Get the shared style component for the currently active cell in currently active sheet.
+ * Only used for style supervisor
+ *
+ * @return PHPExcel\Style_Fill
+ */
+ public function getSharedComponent()
+ {
+ return $this->_parent->getSharedComponent()->getFill();
+ }
- /**
- * Build style array from subcomponents
- *
- * @param array $array
- * @return array
- */
- public function getStyleArray($array)
- {
- return array('fill' => $array);
- }
+ /**
+ * Build style array from subcomponents
+ *
+ * @param array $array
+ * @return array
+ */
+ public function getStyleArray($array)
+ {
+ return array('fill' => $array);
+ }
- /**
- * Apply styles from array
- *
- *
- * $objPHPExcel->getActiveSheet()->getStyle('B2')->getFill()->applyFromArray(
- * array(
- * 'type' => PHPExcel\Style_Fill::FILL_GRADIENT_LINEAR,
- * 'rotation' => 0,
- * 'startcolor' => array(
- * 'rgb' => '000000'
- * ),
- * 'endcolor' => array(
- * 'argb' => 'FFFFFFFF'
- * )
- * )
- * );
- *
- *
- * @param array $pStyles Array containing style information
- * @throws PHPExcel\Exception
- * @return PHPExcel\Style_Fill
- */
- public function applyFromArray($pStyles = null) {
- if (is_array($pStyles)) {
- if ($this->_isSupervisor) {
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles));
- } else {
- if (array_key_exists('type', $pStyles)) {
- $this->setFillType($pStyles['type']);
- }
- if (array_key_exists('rotation', $pStyles)) {
- $this->setRotation($pStyles['rotation']);
- }
- if (array_key_exists('startcolor', $pStyles)) {
- $this->getStartColor()->applyFromArray($pStyles['startcolor']);
- }
- if (array_key_exists('endcolor', $pStyles)) {
- $this->getEndColor()->applyFromArray($pStyles['endcolor']);
- }
- if (array_key_exists('color', $pStyles)) {
- $this->getStartColor()->applyFromArray($pStyles['color']);
- }
- }
- } else {
- throw new Exception("Invalid style array passed.");
- }
- return $this;
- }
+ /**
+ * Apply styles from array
+ *
+ *
+ * $objPHPExcel->getActiveSheet()->getStyle('B2')->getFill()->applyFromArray(
+ * array(
+ * 'type' => PHPExcel\Style_Fill::FILL_GRADIENT_LINEAR,
+ * 'rotation' => 0,
+ * 'startcolor' => array(
+ * 'rgb' => '000000'
+ * ),
+ * 'endcolor' => array(
+ * 'argb' => 'FFFFFFFF'
+ * )
+ * )
+ * );
+ *
+ *
+ * @param array $pStyles Array containing style information
+ * @throws PHPExcel\Exception
+ * @return PHPExcel\Style_Fill
+ */
+ public function applyFromArray($pStyles = null) {
+ if (is_array($pStyles)) {
+ if ($this->_isSupervisor) {
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles));
+ } else {
+ if (array_key_exists('type', $pStyles)) {
+ $this->setFillType($pStyles['type']);
+ }
+ if (array_key_exists('rotation', $pStyles)) {
+ $this->setRotation($pStyles['rotation']);
+ }
+ if (array_key_exists('startcolor', $pStyles)) {
+ $this->getStartColor()->applyFromArray($pStyles['startcolor']);
+ }
+ if (array_key_exists('endcolor', $pStyles)) {
+ $this->getEndColor()->applyFromArray($pStyles['endcolor']);
+ }
+ if (array_key_exists('color', $pStyles)) {
+ $this->getStartColor()->applyFromArray($pStyles['color']);
+ }
+ }
+ } else {
+ throw new Exception("Invalid style array passed.");
+ }
+ return $this;
+ }
- /**
- * Get Fill Type
- *
- * @return string
- */
- public function getFillType() {
- if ($this->_isSupervisor) {
- return $this->getSharedComponent()->getFillType();
- }
- return $this->_fillType;
- }
+ /**
+ * Get Fill Type
+ *
+ * @return string
+ */
+ public function getFillType() {
+ if ($this->_isSupervisor) {
+ return $this->getSharedComponent()->getFillType();
+ }
+ return $this->_fillType;
+ }
- /**
- * Set Fill Type
- *
- * @param string $pValue PHPExcel\Style_Fill fill type
- * @return PHPExcel\Style_Fill
- */
- public function setFillType($pValue = Style_Fill::FILL_NONE) {
- if ($this->_isSupervisor) {
- $styleArray = $this->getStyleArray(array('type' => $pValue));
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
- } else {
- $this->_fillType = $pValue;
- }
- return $this;
- }
+ /**
+ * Set Fill Type
+ *
+ * @param string $pValue PHPExcel\Style_Fill fill type
+ * @return PHPExcel\Style_Fill
+ */
+ public function setFillType($pValue = Style_Fill::FILL_NONE) {
+ if ($this->_isSupervisor) {
+ $styleArray = $this->getStyleArray(array('type' => $pValue));
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
+ } else {
+ $this->_fillType = $pValue;
+ }
+ return $this;
+ }
- /**
- * Get Rotation
- *
- * @return double
- */
- public function getRotation() {
- if ($this->_isSupervisor) {
- return $this->getSharedComponent()->getRotation();
- }
- return $this->_rotation;
- }
+ /**
+ * Get Rotation
+ *
+ * @return double
+ */
+ public function getRotation() {
+ if ($this->_isSupervisor) {
+ return $this->getSharedComponent()->getRotation();
+ }
+ return $this->_rotation;
+ }
- /**
- * Set Rotation
- *
- * @param double $pValue
- * @return PHPExcel\Style_Fill
- */
- public function setRotation($pValue = 0) {
- if ($this->_isSupervisor) {
- $styleArray = $this->getStyleArray(array('rotation' => $pValue));
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
- } else {
- $this->_rotation = $pValue;
- }
- return $this;
- }
+ /**
+ * Set Rotation
+ *
+ * @param double $pValue
+ * @return PHPExcel\Style_Fill
+ */
+ public function setRotation($pValue = 0) {
+ if ($this->_isSupervisor) {
+ $styleArray = $this->getStyleArray(array('rotation' => $pValue));
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
+ } else {
+ $this->_rotation = $pValue;
+ }
+ return $this;
+ }
- /**
- * Get Start Color
- *
- * @return PHPExcel\Style_Color
- */
- public function getStartColor() {
- return $this->_startColor;
- }
+ /**
+ * Get Start Color
+ *
+ * @return PHPExcel\Style_Color
+ */
+ public function getStartColor() {
+ return $this->_startColor;
+ }
- /**
- * Set Start Color
- *
- * @param PHPExcel\Style_Color $pValue
- * @throws PHPExcel\Exception
- * @return PHPExcel\Style_Fill
- */
- public function setStartColor(Style_Color $pValue = null) {
- // make sure parameter is a real color and not a supervisor
- $color = $pValue->getIsSupervisor() ? $pValue->getSharedComponent() : $pValue;
+ /**
+ * Set Start Color
+ *
+ * @param PHPExcel\Style_Color $pValue
+ * @throws PHPExcel\Exception
+ * @return PHPExcel\Style_Fill
+ */
+ public function setStartColor(Style_Color $pValue = null) {
+ // make sure parameter is a real color and not a supervisor
+ $color = $pValue->getIsSupervisor() ? $pValue->getSharedComponent() : $pValue;
- if ($this->_isSupervisor) {
- $styleArray = $this->getStartColor()->getStyleArray(array('argb' => $color->getARGB()));
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
- } else {
- $this->_startColor = $color;
- }
- return $this;
- }
+ if ($this->_isSupervisor) {
+ $styleArray = $this->getStartColor()->getStyleArray(array('argb' => $color->getARGB()));
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
+ } else {
+ $this->_startColor = $color;
+ }
+ return $this;
+ }
- /**
- * Get End Color
- *
- * @return PHPExcel\Style_Color
- */
- public function getEndColor() {
- return $this->_endColor;
- }
+ /**
+ * Get End Color
+ *
+ * @return PHPExcel\Style_Color
+ */
+ public function getEndColor() {
+ return $this->_endColor;
+ }
- /**
- * Set End Color
- *
- * @param PHPExcel\Style_Color $pValue
- * @throws PHPExcel\Exception
- * @return PHPExcel\Style_Fill
- */
- public function setEndColor(Style_Color $pValue = null) {
- // make sure parameter is a real color and not a supervisor
- $color = $pValue->getIsSupervisor() ? $pValue->getSharedComponent() : $pValue;
+ /**
+ * Set End Color
+ *
+ * @param PHPExcel\Style_Color $pValue
+ * @throws PHPExcel\Exception
+ * @return PHPExcel\Style_Fill
+ */
+ public function setEndColor(Style_Color $pValue = null) {
+ // make sure parameter is a real color and not a supervisor
+ $color = $pValue->getIsSupervisor() ? $pValue->getSharedComponent() : $pValue;
- if ($this->_isSupervisor) {
- $styleArray = $this->getEndColor()->getStyleArray(array('argb' => $color->getARGB()));
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
- } else {
- $this->_endColor = $color;
- }
- return $this;
- }
-
- /**
- * Get hash code
- *
- * @return string Hash code
- */
- public function getHashCode() {
- if ($this->_isSupervisor) {
- return $this->getSharedComponent()->getHashCode();
- }
- return md5(
- $this->getFillType()
- . $this->getRotation()
- . $this->getStartColor()->getHashCode()
- . $this->getEndColor()->getHashCode()
- . __CLASS__
- );
- }
+ if ($this->_isSupervisor) {
+ $styleArray = $this->getEndColor()->getStyleArray(array('argb' => $color->getARGB()));
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
+ } else {
+ $this->_endColor = $color;
+ }
+ return $this;
+ }
+ /**
+ * Get hash code
+ *
+ * @return string Hash code
+ */
+ public function getHashCode() {
+ if ($this->_isSupervisor) {
+ return $this->getSharedComponent()->getHashCode();
+ }
+ return md5(
+ $this->getFillType()
+ . $this->getRotation()
+ . $this->getStartColor()->getHashCode()
+ . $this->getEndColor()->getHashCode()
+ . __CLASS__
+ );
+ }
}
diff --git a/Classes/PHPExcel/Style/Font.php b/Classes/PHPExcel/Style/Font.php
index 0c1a860..56fc10c 100644
--- a/Classes/PHPExcel/Style/Font.php
+++ b/Classes/PHPExcel/Style/Font.php
@@ -19,10 +19,10 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category PHPExcel
- * @package PHPExcel\Style
+ * @package PHPExcel\Style
* @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,503 +32,502 @@ namespace PHPExcel;
* PHPExcel\Style\Font
*
* @category PHPExcel
- * @package PHPExcel\Style
+ * @package PHPExcel\Style
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
*/
class Style_Font extends Style_Supervisor implements IComparable
{
- /* Underline types */
- const UNDERLINE_NONE = 'none';
- const UNDERLINE_DOUBLE = 'double';
- const UNDERLINE_DOUBLEACCOUNTING = 'doubleAccounting';
- const UNDERLINE_SINGLE = 'single';
- const UNDERLINE_SINGLEACCOUNTING = 'singleAccounting';
+ /* Underline types */
+ const UNDERLINE_NONE = 'none';
+ const UNDERLINE_DOUBLE = 'double';
+ const UNDERLINE_DOUBLEACCOUNTING = 'doubleAccounting';
+ const UNDERLINE_SINGLE = 'single';
+ const UNDERLINE_SINGLEACCOUNTING = 'singleAccounting';
- /**
- * Font Name
- *
- * @var string
- */
- protected $_name = 'Calibri';
+ /**
+ * Font Name
+ *
+ * @var string
+ */
+ protected $_name = 'Calibri';
- /**
- * Font Size
- *
- * @var float
- */
- protected $_size = 11;
+ /**
+ * Font Size
+ *
+ * @var float
+ */
+ protected $_size = 11;
- /**
- * Bold
- *
- * @var boolean
- */
- protected $_bold = FALSE;
+ /**
+ * Bold
+ *
+ * @var boolean
+ */
+ protected $_bold = false;
- /**
- * Italic
- *
- * @var boolean
- */
- protected $_italic = FALSE;
+ /**
+ * Italic
+ *
+ * @var boolean
+ */
+ protected $_italic = false;
- /**
- * Superscript
- *
- * @var boolean
- */
- protected $_superScript = FALSE;
+ /**
+ * Superscript
+ *
+ * @var boolean
+ */
+ protected $_superScript = false;
- /**
- * Subscript
- *
- * @var boolean
- */
- protected $_subScript = FALSE;
+ /**
+ * Subscript
+ *
+ * @var boolean
+ */
+ protected $_subScript = false;
- /**
- * Underline
- *
- * @var string
- */
- protected $_underline = self::UNDERLINE_NONE;
+ /**
+ * Underline
+ *
+ * @var string
+ */
+ protected $_underline = self::UNDERLINE_NONE;
- /**
- * Strikethrough
- *
- * @var boolean
- */
- protected $_strikethrough = FALSE;
+ /**
+ * Strikethrough
+ *
+ * @var boolean
+ */
+ protected $_strikethrough = false;
- /**
- * Foreground color
- *
- * @var PHPExcel\Style_Color
- */
- protected $_color;
+ /**
+ * Foreground color
+ *
+ * @var PHPExcel\Style_Color
+ */
+ protected $_color;
- /**
- * Create a new PHPExcel\Style_Font
- *
- * @param boolean $isSupervisor Flag indicating if this is a supervisor or not
- * Leave this value at default unless you understand exactly what
- * its ramifications are
- * @param boolean $isConditional Flag indicating if this is a conditional style or not
- * Leave this value at default unless you understand exactly what
- * its ramifications are
- */
- public function __construct($isSupervisor = FALSE, $isConditional = FALSE)
- {
- // Supervisor?
- parent::__construct($isSupervisor);
+ /**
+ * Create a new PHPExcel\Style_Font
+ *
+ * @param boolean $isSupervisor Flag indicating if this is a supervisor or not
+ * Leave this value at default unless you understand exactly what
+ * its ramifications are
+ * @param boolean $isConditional Flag indicating if this is a conditional style or not
+ * Leave this value at default unless you understand exactly what
+ * its ramifications are
+ */
+ public function __construct($isSupervisor = false, $isConditional = false)
+ {
+ // Supervisor?
+ parent::__construct($isSupervisor);
- // Initialise values
- if ($isConditional) {
- $this->_name = NULL;
- $this->_size = NULL;
- $this->_bold = NULL;
- $this->_italic = NULL;
- $this->_superScript = NULL;
- $this->_subScript = NULL;
- $this->_underline = NULL;
- $this->_strikethrough = NULL;
- $this->_color = new Style_Color(Style_Color::COLOR_BLACK, $isSupervisor, $isConditional);
- } else {
- $this->_color = new Style_Color(Style_Color::COLOR_BLACK, $isSupervisor);
- }
- // bind parent if we are a supervisor
- if ($isSupervisor) {
- $this->_color->bindParent($this, '_color');
- }
- }
+ // Initialise values
+ if ($isConditional) {
+ $this->_name = null;
+ $this->_size = null;
+ $this->_bold = null;
+ $this->_italic = null;
+ $this->_superScript = null;
+ $this->_subScript = null;
+ $this->_underline = null;
+ $this->_strikethrough = null;
+ $this->_color = new Style_Color(Style_Color::COLOR_BLACK, $isSupervisor, $isConditional);
+ } else {
+ $this->_color = new Style_Color(Style_Color::COLOR_BLACK, $isSupervisor);
+ }
+ // bind parent if we are a supervisor
+ if ($isSupervisor) {
+ $this->_color->bindParent($this, '_color');
+ }
+ }
- /**
- * Get the shared style component for the currently active cell in currently active sheet.
- * Only used for style supervisor
- *
- * @return PHPExcel\Style_Font
- */
- public function getSharedComponent()
- {
- return $this->_parent->getSharedComponent()->getFont();
- }
+ /**
+ * Get the shared style component for the currently active cell in currently active sheet.
+ * Only used for style supervisor
+ *
+ * @return PHPExcel\Style_Font
+ */
+ public function getSharedComponent()
+ {
+ return $this->_parent->getSharedComponent()->getFont();
+ }
- /**
- * Build style array from subcomponents
- *
- * @param array $array
- * @return array
- */
- public function getStyleArray($array)
- {
- return array('font' => $array);
- }
+ /**
+ * Build style array from subcomponents
+ *
+ * @param array $array
+ * @return array
+ */
+ public function getStyleArray($array)
+ {
+ return array('font' => $array);
+ }
- /**
- * Apply styles from array
- *
- *
- * $objPHPExcel->getActiveSheet()->getStyle('B2')->getFont()->applyFromArray(
- * array(
- * 'name' => 'Arial',
- * 'bold' => TRUE,
- * 'italic' => FALSE,
- * 'underline' => PHPExcel\Style_Font::UNDERLINE_DOUBLE,
- * 'strike' => FALSE,
- * 'color' => array(
- * 'rgb' => '808080'
- * )
- * )
- * );
- *
- *
- * @param array $pStyles Array containing style information
- * @throws PHPExcel\Exception
- * @return PHPExcel\Style_Font
- */
- public function applyFromArray($pStyles = null) {
- if (is_array($pStyles)) {
- if ($this->_isSupervisor) {
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles));
- } else {
- if (array_key_exists('name', $pStyles)) {
- $this->setName($pStyles['name']);
- }
- if (array_key_exists('bold', $pStyles)) {
- $this->setBold($pStyles['bold']);
- }
- if (array_key_exists('italic', $pStyles)) {
- $this->setItalic($pStyles['italic']);
- }
- if (array_key_exists('superScript', $pStyles)) {
- $this->setSuperScript($pStyles['superScript']);
- }
- if (array_key_exists('subScript', $pStyles)) {
- $this->setSubScript($pStyles['subScript']);
- }
- if (array_key_exists('underline', $pStyles)) {
- $this->setUnderline($pStyles['underline']);
- }
- if (array_key_exists('strike', $pStyles)) {
- $this->setStrikethrough($pStyles['strike']);
- }
- if (array_key_exists('color', $pStyles)) {
- $this->getColor()->applyFromArray($pStyles['color']);
- }
- if (array_key_exists('size', $pStyles)) {
- $this->setSize($pStyles['size']);
- }
- }
- } else {
- throw new Exception("Invalid style array passed.");
- }
- return $this;
- }
+ /**
+ * Apply styles from array
+ *
+ *
+ * $objPHPExcel->getActiveSheet()->getStyle('B2')->getFont()->applyFromArray(
+ * array(
+ * 'name' => 'Arial',
+ * 'bold' => true,
+ * 'italic' => false,
+ * 'underline' => PHPExcel\Style_Font::UNDERLINE_DOUBLE,
+ * 'strike' => false,
+ * 'color' => array(
+ * 'rgb' => '808080'
+ * )
+ * )
+ * );
+ *
+ *
+ * @param array $pStyles Array containing style information
+ * @throws PHPExcel\Exception
+ * @return PHPExcel\Style_Font
+ */
+ public function applyFromArray($pStyles = null) {
+ if (is_array($pStyles)) {
+ if ($this->_isSupervisor) {
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles));
+ } else {
+ if (array_key_exists('name', $pStyles)) {
+ $this->setName($pStyles['name']);
+ }
+ if (array_key_exists('bold', $pStyles)) {
+ $this->setBold($pStyles['bold']);
+ }
+ if (array_key_exists('italic', $pStyles)) {
+ $this->setItalic($pStyles['italic']);
+ }
+ if (array_key_exists('superScript', $pStyles)) {
+ $this->setSuperScript($pStyles['superScript']);
+ }
+ if (array_key_exists('subScript', $pStyles)) {
+ $this->setSubScript($pStyles['subScript']);
+ }
+ if (array_key_exists('underline', $pStyles)) {
+ $this->setUnderline($pStyles['underline']);
+ }
+ if (array_key_exists('strike', $pStyles)) {
+ $this->setStrikethrough($pStyles['strike']);
+ }
+ if (array_key_exists('color', $pStyles)) {
+ $this->getColor()->applyFromArray($pStyles['color']);
+ }
+ if (array_key_exists('size', $pStyles)) {
+ $this->setSize($pStyles['size']);
+ }
+ }
+ } else {
+ throw new Exception("Invalid style array passed.");
+ }
+ return $this;
+ }
- /**
- * Get Name
- *
- * @return string
- */
- public function getName() {
- if ($this->_isSupervisor) {
- return $this->getSharedComponent()->getName();
- }
- return $this->_name;
- }
+ /**
+ * Get Name
+ *
+ * @return string
+ */
+ public function getName() {
+ if ($this->_isSupervisor) {
+ return $this->getSharedComponent()->getName();
+ }
+ return $this->_name;
+ }
- /**
- * Set Name
- *
- * @param string $pValue
- * @return PHPExcel\Style_Font
- */
- public function setName($pValue = 'Calibri') {
- if ($pValue == '') {
- $pValue = 'Calibri';
- }
- if ($this->_isSupervisor) {
- $styleArray = $this->getStyleArray(array('name' => $pValue));
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
- } else {
- $this->_name = $pValue;
- }
- return $this;
- }
+ /**
+ * Set Name
+ *
+ * @param string $pValue
+ * @return PHPExcel\Style_Font
+ */
+ public function setName($pValue = 'Calibri') {
+ if ($pValue == '') {
+ $pValue = 'Calibri';
+ }
+ if ($this->_isSupervisor) {
+ $styleArray = $this->getStyleArray(array('name' => $pValue));
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
+ } else {
+ $this->_name = $pValue;
+ }
+ return $this;
+ }
- /**
- * Get Size
- *
- * @return double
- */
- public function getSize() {
- if ($this->_isSupervisor) {
- return $this->getSharedComponent()->getSize();
- }
- return $this->_size;
- }
+ /**
+ * Get Size
+ *
+ * @return double
+ */
+ public function getSize() {
+ if ($this->_isSupervisor) {
+ return $this->getSharedComponent()->getSize();
+ }
+ return $this->_size;
+ }
- /**
- * Set Size
- *
- * @param double $pValue
- * @return PHPExcel\Style_Font
- */
- public function setSize($pValue = 10) {
- if ($pValue == '') {
- $pValue = 10;
- }
- if ($this->_isSupervisor) {
- $styleArray = $this->getStyleArray(array('size' => $pValue));
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
- } else {
- $this->_size = $pValue;
- }
- return $this;
- }
+ /**
+ * Set Size
+ *
+ * @param double $pValue
+ * @return PHPExcel\Style_Font
+ */
+ public function setSize($pValue = 10) {
+ if ($pValue == '') {
+ $pValue = 10;
+ }
+ if ($this->_isSupervisor) {
+ $styleArray = $this->getStyleArray(array('size' => $pValue));
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
+ } else {
+ $this->_size = $pValue;
+ }
+ return $this;
+ }
- /**
- * Get Bold
- *
- * @return boolean
- */
- public function getBold() {
- if ($this->_isSupervisor) {
- return $this->getSharedComponent()->getBold();
- }
- return $this->_bold;
- }
+ /**
+ * Get Bold
+ *
+ * @return boolean
+ */
+ public function getBold() {
+ if ($this->_isSupervisor) {
+ return $this->getSharedComponent()->getBold();
+ }
+ return $this->_bold;
+ }
- /**
- * Set Bold
- *
- * @param boolean $pValue
- * @return PHPExcel\Style_Font
- */
- public function setBold($pValue = false) {
- if ($pValue == '') {
- $pValue = false;
- }
- if ($this->_isSupervisor) {
- $styleArray = $this->getStyleArray(array('bold' => $pValue));
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
- } else {
- $this->_bold = $pValue;
- }
- return $this;
- }
+ /**
+ * Set Bold
+ *
+ * @param boolean $pValue
+ * @return PHPExcel\Style_Font
+ */
+ public function setBold($pValue = false) {
+ if ($pValue == '') {
+ $pValue = false;
+ }
+ if ($this->_isSupervisor) {
+ $styleArray = $this->getStyleArray(array('bold' => $pValue));
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
+ } else {
+ $this->_bold = $pValue;
+ }
+ return $this;
+ }
- /**
- * Get Italic
- *
- * @return boolean
- */
- public function getItalic() {
- if ($this->_isSupervisor) {
- return $this->getSharedComponent()->getItalic();
- }
- return $this->_italic;
- }
+ /**
+ * Get Italic
+ *
+ * @return boolean
+ */
+ public function getItalic() {
+ if ($this->_isSupervisor) {
+ return $this->getSharedComponent()->getItalic();
+ }
+ return $this->_italic;
+ }
- /**
- * Set Italic
- *
- * @param boolean $pValue
- * @return PHPExcel\Style_Font
- */
- public function setItalic($pValue = false) {
- if ($pValue == '') {
- $pValue = false;
- }
- if ($this->_isSupervisor) {
- $styleArray = $this->getStyleArray(array('italic' => $pValue));
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
- } else {
- $this->_italic = $pValue;
- }
- return $this;
- }
+ /**
+ * Set Italic
+ *
+ * @param boolean $pValue
+ * @return PHPExcel\Style_Font
+ */
+ public function setItalic($pValue = false) {
+ if ($pValue == '') {
+ $pValue = false;
+ }
+ if ($this->_isSupervisor) {
+ $styleArray = $this->getStyleArray(array('italic' => $pValue));
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
+ } else {
+ $this->_italic = $pValue;
+ }
+ return $this;
+ }
- /**
- * Get SuperScript
- *
- * @return boolean
- */
- public function getSuperScript() {
- if ($this->_isSupervisor) {
- return $this->getSharedComponent()->getSuperScript();
- }
- return $this->_superScript;
- }
+ /**
+ * Get SuperScript
+ *
+ * @return boolean
+ */
+ public function getSuperScript() {
+ if ($this->_isSupervisor) {
+ return $this->getSharedComponent()->getSuperScript();
+ }
+ return $this->_superScript;
+ }
- /**
- * Set SuperScript
- *
- * @param boolean $pValue
- * @return PHPExcel\Style_Font
- */
- public function setSuperScript($pValue = false) {
- if ($pValue == '') {
- $pValue = false;
- }
- if ($this->_isSupervisor) {
- $styleArray = $this->getStyleArray(array('superScript' => $pValue));
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
- } else {
- $this->_superScript = $pValue;
- $this->_subScript = !$pValue;
- }
- return $this;
- }
+ /**
+ * Set SuperScript
+ *
+ * @param boolean $pValue
+ * @return PHPExcel\Style_Font
+ */
+ public function setSuperScript($pValue = false) {
+ if ($pValue == '') {
+ $pValue = false;
+ }
+ if ($this->_isSupervisor) {
+ $styleArray = $this->getStyleArray(array('superScript' => $pValue));
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
+ } else {
+ $this->_superScript = $pValue;
+ $this->_subScript = !$pValue;
+ }
+ return $this;
+ }
- /**
- * Get SubScript
- *
- * @return boolean
- */
- public function getSubScript() {
- if ($this->_isSupervisor) {
- return $this->getSharedComponent()->getSubScript();
- }
- return $this->_subScript;
- }
+ /**
+ * Get SubScript
+ *
+ * @return boolean
+ */
+ public function getSubScript() {
+ if ($this->_isSupervisor) {
+ return $this->getSharedComponent()->getSubScript();
+ }
+ return $this->_subScript;
+ }
- /**
- * Set SubScript
- *
- * @param boolean $pValue
- * @return PHPExcel\Style_Font
- */
- public function setSubScript($pValue = false) {
- if ($pValue == '') {
- $pValue = false;
- }
- if ($this->_isSupervisor) {
- $styleArray = $this->getStyleArray(array('subScript' => $pValue));
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
- } else {
- $this->_subScript = $pValue;
- $this->_superScript = !$pValue;
- }
- return $this;
- }
+ /**
+ * Set SubScript
+ *
+ * @param boolean $pValue
+ * @return PHPExcel\Style_Font
+ */
+ public function setSubScript($pValue = false) {
+ if ($pValue == '') {
+ $pValue = false;
+ }
+ if ($this->_isSupervisor) {
+ $styleArray = $this->getStyleArray(array('subScript' => $pValue));
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
+ } else {
+ $this->_subScript = $pValue;
+ $this->_superScript = !$pValue;
+ }
+ return $this;
+ }
- /**
- * Get Underline
- *
- * @return string
- */
- public function getUnderline() {
- if ($this->_isSupervisor) {
- return $this->getSharedComponent()->getUnderline();
- }
- return $this->_underline;
- }
+ /**
+ * Get Underline
+ *
+ * @return string
+ */
+ public function getUnderline() {
+ if ($this->_isSupervisor) {
+ return $this->getSharedComponent()->getUnderline();
+ }
+ return $this->_underline;
+ }
- /**
- * Set Underline
- *
- * @param string|boolean $pValue PHPExcel\Style_Font underline type
- * If a boolean is passed, then TRUE equates to UNDERLINE_SINGLE,
- * false equates to UNDERLINE_NONE
- * @return PHPExcel\Style_Font
- */
- public function setUnderline($pValue = self::UNDERLINE_NONE) {
- if (is_bool($pValue)) {
- $pValue = ($pValue) ? self::UNDERLINE_SINGLE : self::UNDERLINE_NONE;
- } elseif ($pValue == '') {
- $pValue = self::UNDERLINE_NONE;
- }
- if ($this->_isSupervisor) {
- $styleArray = $this->getStyleArray(array('underline' => $pValue));
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
- } else {
- $this->_underline = $pValue;
- }
- return $this;
- }
+ /**
+ * Set Underline
+ *
+ * @param string|boolean $pValue PHPExcel\Style_Font underline type
+ * If a boolean is passed, then TRUE equates to UNDERLINE_SINGLE,
+ * false equates to UNDERLINE_NONE
+ * @return PHPExcel\Style_Font
+ */
+ public function setUnderline($pValue = self::UNDERLINE_NONE) {
+ if (is_bool($pValue)) {
+ $pValue = ($pValue) ? self::UNDERLINE_SINGLE : self::UNDERLINE_NONE;
+ } elseif ($pValue == '') {
+ $pValue = self::UNDERLINE_NONE;
+ }
+ if ($this->_isSupervisor) {
+ $styleArray = $this->getStyleArray(array('underline' => $pValue));
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
+ } else {
+ $this->_underline = $pValue;
+ }
+ return $this;
+ }
- /**
- * Get Strikethrough
- *
- * @return boolean
- */
- public function getStrikethrough() {
- if ($this->_isSupervisor) {
- return $this->getSharedComponent()->getStrikethrough();
- }
- return $this->_strikethrough;
- }
+ /**
+ * Get Strikethrough
+ *
+ * @return boolean
+ */
+ public function getStrikethrough() {
+ if ($this->_isSupervisor) {
+ return $this->getSharedComponent()->getStrikethrough();
+ }
+ return $this->_strikethrough;
+ }
- /**
- * Set Strikethrough
- *
- * @param boolean $pValue
- * @return PHPExcel\Style_Font
- */
- public function setStrikethrough($pValue = false) {
- if ($pValue == '') {
- $pValue = false;
- }
- if ($this->_isSupervisor) {
- $styleArray = $this->getStyleArray(array('strike' => $pValue));
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
- } else {
- $this->_strikethrough = $pValue;
- }
- return $this;
- }
+ /**
+ * Set Strikethrough
+ *
+ * @param boolean $pValue
+ * @return PHPExcel\Style_Font
+ */
+ public function setStrikethrough($pValue = false) {
+ if ($pValue == '') {
+ $pValue = false;
+ }
+ if ($this->_isSupervisor) {
+ $styleArray = $this->getStyleArray(array('strike' => $pValue));
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
+ } else {
+ $this->_strikethrough = $pValue;
+ }
+ return $this;
+ }
- /**
- * Get Color
- *
- * @return PHPExcel\Style_Color
- */
- public function getColor() {
- return $this->_color;
- }
+ /**
+ * Get Color
+ *
+ * @return PHPExcel\Style_Color
+ */
+ public function getColor() {
+ return $this->_color;
+ }
- /**
- * Set Color
- *
- * @param PHPExcel\Style_Color $pValue
- * @throws PHPExcel\Exception
- * @return PHPExcel\Style_Font
- */
- public function setColor(Style_Color $pValue = null) {
- // make sure parameter is a real color and not a supervisor
- $color = $pValue->getIsSupervisor() ? $pValue->getSharedComponent() : $pValue;
+ /**
+ * Set Color
+ *
+ * @param PHPExcel\Style_Color $pValue
+ * @throws PHPExcel\Exception
+ * @return PHPExcel\Style_Font
+ */
+ public function setColor(Style_Color $pValue = null) {
+ // make sure parameter is a real color and not a supervisor
+ $color = $pValue->getIsSupervisor() ? $pValue->getSharedComponent() : $pValue;
- if ($this->_isSupervisor) {
- $styleArray = $this->getColor()->getStyleArray(array('argb' => $color->getARGB()));
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
- } else {
- $this->_color = $color;
- }
- return $this;
- }
-
- /**
- * Get hash code
- *
- * @return string Hash code
- */
- public function getHashCode() {
- if ($this->_isSupervisor) {
- return $this->getSharedComponent()->getHashCode();
- }
- return md5(
- $this->_name
- . $this->_size
- . ($this->_bold ? 't' : 'f')
- . ($this->_italic ? 't' : 'f')
- . ($this->_superScript ? 't' : 'f')
- . ($this->_subScript ? 't' : 'f')
- . $this->_underline
- . ($this->_strikethrough ? 't' : 'f')
- . $this->_color->getHashCode()
- . __CLASS__
- );
- }
+ if ($this->_isSupervisor) {
+ $styleArray = $this->getColor()->getStyleArray(array('argb' => $color->getARGB()));
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
+ } else {
+ $this->_color = $color;
+ }
+ return $this;
+ }
+ /**
+ * Get hash code
+ *
+ * @return string Hash code
+ */
+ public function getHashCode() {
+ if ($this->_isSupervisor) {
+ return $this->getSharedComponent()->getHashCode();
+ }
+ return md5(
+ $this->_name
+ . $this->_size
+ . ($this->_bold ? 't' : 'f')
+ . ($this->_italic ? 't' : 'f')
+ . ($this->_superScript ? 't' : 'f')
+ . ($this->_subScript ? 't' : 'f')
+ . $this->_underline
+ . ($this->_strikethrough ? 't' : 'f')
+ . $this->_color->getHashCode()
+ . __CLASS__
+ );
+ }
}
diff --git a/Classes/PHPExcel/Style/NumberFormat.php b/Classes/PHPExcel/Style/NumberFormat.php
index b40b1ac..ba340ca 100644
--- a/Classes/PHPExcel/Style/NumberFormat.php
+++ b/Classes/PHPExcel/Style/NumberFormat.php
@@ -19,10 +19,10 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category PHPExcel
- * @package PHPExcel\Style
+ * @package PHPExcel\Style
* @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,682 +32,681 @@ namespace PHPExcel;
* PHPExcel\Style_NumberFormat
*
* @category PHPExcel
- * @package PHPExcel\Style
+ * @package PHPExcel\Style
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
*/
class Style_NumberFormat extends Style_Supervisor implements IComparable
{
- /* Pre-defined formats */
- const FORMAT_GENERAL = 'General';
-
- const FORMAT_TEXT = '@';
-
- const FORMAT_NUMBER = '0';
- const FORMAT_NUMBER_00 = '0.00';
- const FORMAT_NUMBER_COMMA_SEPARATED1 = '#,##0.00';
- const FORMAT_NUMBER_COMMA_SEPARATED2 = '#,##0.00_-';
-
- const FORMAT_PERCENTAGE = '0%';
- const FORMAT_PERCENTAGE_00 = '0.00%';
-
- const FORMAT_DATE_YYYYMMDD2 = 'yyyy-mm-dd';
- const FORMAT_DATE_YYYYMMDD = 'yy-mm-dd';
- const FORMAT_DATE_DDMMYYYY = 'dd/mm/yy';
- const FORMAT_DATE_DMYSLASH = 'd/m/y';
- const FORMAT_DATE_DMYMINUS = 'd-m-y';
- const FORMAT_DATE_DMMINUS = 'd-m';
- const FORMAT_DATE_MYMINUS = 'm-y';
- const FORMAT_DATE_XLSX14 = 'mm-dd-yy';
- const FORMAT_DATE_XLSX15 = 'd-mmm-yy';
- const FORMAT_DATE_XLSX16 = 'd-mmm';
- const FORMAT_DATE_XLSX17 = 'mmm-yy';
- const FORMAT_DATE_XLSX22 = 'm/d/yy h:mm';
- const FORMAT_DATE_DATETIME = 'd/m/y h:mm';
- const FORMAT_DATE_TIME1 = 'h:mm AM/PM';
- const FORMAT_DATE_TIME2 = 'h:mm:ss AM/PM';
- const FORMAT_DATE_TIME3 = 'h:mm';
- const FORMAT_DATE_TIME4 = 'h:mm:ss';
- const FORMAT_DATE_TIME5 = 'mm:ss';
- const FORMAT_DATE_TIME6 = 'h:mm:ss';
- const FORMAT_DATE_TIME7 = 'i:s.S';
- const FORMAT_DATE_TIME8 = 'h:mm:ss;@';
- const FORMAT_DATE_YYYYMMDDSLASH = 'yy/mm/dd;@';
-
- const FORMAT_CURRENCY_USD_SIMPLE = '"$"#,##0.00_-';
- const FORMAT_CURRENCY_USD = '$#,##0_-';
- const FORMAT_CURRENCY_EUR_SIMPLE = '[$EUR ]#,##0.00_-';
-
- /**
- * Excel built-in number formats
- *
- * @var array
- */
- protected static $_builtInFormats;
-
- /**
- * Excel built-in number formats (flipped, for faster lookups)
- *
- * @var array
- */
- protected static $_flippedBuiltInFormats;
-
- /**
- * Format Code
- *
- * @var string
- */
- protected $_formatCode = Style_NumberFormat::FORMAT_GENERAL;
-
- /**
- * Built-in format Code
- *
- * @var string
- */
- protected $_builtInFormatCode = 0;
-
- /**
- * Create a new PHPExcel\Style_NumberFormat
- *
- * @param boolean $isSupervisor Flag indicating if this is a supervisor or not
- * Leave this value at default unless you understand exactly what
- * its ramifications are
- * @param boolean $isConditional Flag indicating if this is a conditional style or not
- * Leave this value at default unless you understand exactly what
- * its ramifications are
- */
- public function __construct($isSupervisor = FALSE, $isConditional = FALSE)
- {
- // Supervisor?
- parent::__construct($isSupervisor);
-
- if ($isConditional) {
- $this->_formatCode = NULL;
- }
- }
-
- /**
- * Get the shared style component for the currently active cell in currently active sheet.
- * Only used for style supervisor
- *
- * @return PHPExcel\Style_NumberFormat
- */
- public function getSharedComponent()
- {
- return $this->_parent->getSharedComponent()->getNumberFormat();
- }
-
- /**
- * Build style array from subcomponents
- *
- * @param array $array
- * @return array
- */
- public function getStyleArray($array)
- {
- return array('numberformat' => $array);
- }
-
- /**
- * Apply styles from array
- *
- *
- * $objPHPExcel->getActiveSheet()->getStyle('B2')->getNumberFormat()->applyFromArray(
- * array(
- * 'code' => PHPExcel\Style_NumberFormat::FORMAT_CURRENCY_EUR_SIMPLE
- * )
- * );
- *
- *
- * @param array $pStyles Array containing style information
- * @throws PHPExcel\Exception
- * @return PHPExcel\Style_NumberFormat
- */
- public function applyFromArray($pStyles = null)
- {
- if (is_array($pStyles)) {
- if ($this->_isSupervisor) {
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles));
- } else {
- if (array_key_exists('code', $pStyles)) {
- $this->setFormatCode($pStyles['code']);
- }
- }
- } else {
- throw new Exception("Invalid style array passed.");
- }
- return $this;
- }
-
- /**
- * Get Format Code
- *
- * @return string
- */
- public function getFormatCode()
- {
- if ($this->_isSupervisor) {
- return $this->getSharedComponent()->getFormatCode();
- }
- if ($this->_builtInFormatCode !== false)
- {
- return self::builtInFormatCode($this->_builtInFormatCode);
- }
- return $this->_formatCode;
- }
-
- /**
- * Set Format Code
- *
- * @param string $pValue
- * @return PHPExcel\Style_NumberFormat
- */
- public function setFormatCode($pValue = Style_NumberFormat::FORMAT_GENERAL)
- {
- if ($pValue == '') {
- $pValue = Style_NumberFormat::FORMAT_GENERAL;
- }
- if ($this->_isSupervisor) {
- $styleArray = $this->getStyleArray(array('code' => $pValue));
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
- } else {
- $this->_formatCode = $pValue;
- $this->_builtInFormatCode = self::builtInFormatCodeIndex($pValue);
- }
- return $this;
- }
-
- /**
- * Get Built-In Format Code
- *
- * @return int
- */
- public function getBuiltInFormatCode()
- {
- if ($this->_isSupervisor) {
- return $this->getSharedComponent()->getBuiltInFormatCode();
- }
- return $this->_builtInFormatCode;
- }
-
- /**
- * Set Built-In Format Code
- *
- * @param int $pValue
- * @return PHPExcel\Style_NumberFormat
- */
- public function setBuiltInFormatCode($pValue = 0)
- {
-
- if ($this->_isSupervisor) {
- $styleArray = $this->getStyleArray(array('code' => self::builtInFormatCode($pValue)));
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
- } else {
- $this->_builtInFormatCode = $pValue;
- $this->_formatCode = self::builtInFormatCode($pValue);
- }
- return $this;
- }
-
- /**
- * Fill built-in format codes
- */
- protected static function fillBuiltInFormatCodes()
- {
- // Built-in format codes
- if (is_null(self::$_builtInFormats)) {
- self::$_builtInFormats = array();
-
- // General
- self::$_builtInFormats[0] = Style_NumberFormat::FORMAT_GENERAL;
- self::$_builtInFormats[1] = '0';
- self::$_builtInFormats[2] = '0.00';
- self::$_builtInFormats[3] = '#,##0';
- self::$_builtInFormats[4] = '#,##0.00';
-
- self::$_builtInFormats[9] = '0%';
- self::$_builtInFormats[10] = '0.00%';
- self::$_builtInFormats[11] = '0.00E+00';
- self::$_builtInFormats[12] = '# ?/?';
- self::$_builtInFormats[13] = '# ??/??';
- self::$_builtInFormats[14] = 'mm-dd-yy';
- self::$_builtInFormats[15] = 'd-mmm-yy';
- self::$_builtInFormats[16] = 'd-mmm';
- self::$_builtInFormats[17] = 'mmm-yy';
- self::$_builtInFormats[18] = 'h:mm AM/PM';
- self::$_builtInFormats[19] = 'h:mm:ss AM/PM';
- self::$_builtInFormats[20] = 'h:mm';
- self::$_builtInFormats[21] = 'h:mm:ss';
- self::$_builtInFormats[22] = 'm/d/yy h:mm';
-
- self::$_builtInFormats[37] = '#,##0 ;(#,##0)';
- self::$_builtInFormats[38] = '#,##0 ;[Red](#,##0)';
- self::$_builtInFormats[39] = '#,##0.00;(#,##0.00)';
- self::$_builtInFormats[40] = '#,##0.00;[Red](#,##0.00)';
-
- self::$_builtInFormats[44] = '_("$"* #,##0.00_);_("$"* \(#,##0.00\);_("$"* "-"??_);_(@_)';
- self::$_builtInFormats[45] = 'mm:ss';
- self::$_builtInFormats[46] = '[h]:mm:ss';
- self::$_builtInFormats[47] = 'mmss.0';
- self::$_builtInFormats[48] = '##0.0E+0';
- self::$_builtInFormats[49] = '@';
-
- // CHT
- self::$_builtInFormats[27] = '[$-404]e/m/d';
- self::$_builtInFormats[30] = 'm/d/yy';
- self::$_builtInFormats[36] = '[$-404]e/m/d';
- self::$_builtInFormats[50] = '[$-404]e/m/d';
- self::$_builtInFormats[57] = '[$-404]e/m/d';
-
- // THA
- self::$_builtInFormats[59] = 't0';
- self::$_builtInFormats[60] = 't0.00';
- self::$_builtInFormats[61] = 't#,##0';
- self::$_builtInFormats[62] = 't#,##0.00';
- self::$_builtInFormats[67] = 't0%';
- self::$_builtInFormats[68] = 't0.00%';
- self::$_builtInFormats[69] = 't# ?/?';
- self::$_builtInFormats[70] = 't# ??/??';
-
- // Flip array (for faster lookups)
- self::$_flippedBuiltInFormats = array_flip(self::$_builtInFormats);
- }
- }
-
- /**
- * Get built-in format code
- *
- * @param int $pIndex
- * @return string
- */
- public static function builtInFormatCode($pIndex)
- {
- // Clean parameter
- $pIndex = intval($pIndex);
-
- // Ensure built-in format codes are available
- self::fillBuiltInFormatCodes();
-
- // Lookup format code
- if (isset(self::$_builtInFormats[$pIndex])) {
- return self::$_builtInFormats[$pIndex];
- }
-
- return '';
- }
-
- /**
- * Get built-in format code index
- *
- * @param string $formatCode
- * @return int|boolean
- */
- public static function builtInFormatCodeIndex($formatCode)
- {
- // Ensure built-in format codes are available
- self::fillBuiltInFormatCodes();
-
- // Lookup format code
- if (isset(self::$_flippedBuiltInFormats[$formatCode])) {
- return self::$_flippedBuiltInFormats[$formatCode];
- }
-
- return false;
- }
-
- /**
- * Get hash code
- *
- * @return string Hash code
- */
- public function getHashCode()
- {
- if ($this->_isSupervisor) {
- return $this->getSharedComponent()->getHashCode();
- }
- return md5(
- $this->_formatCode
- . $this->_builtInFormatCode
- . __CLASS__
- );
- }
-
- /**
- * Search/replace values to convert Excel date/time format masks to PHP format masks
- *
- * @var array
- */
- protected static $_dateFormatReplacements = array(
- // first remove escapes related to non-format characters
- '\\' => '',
- // 12-hour suffix
- 'am/pm' => 'A',
- // 4-digit year
- 'e' => 'Y',
- 'yyyy' => 'Y',
- // 2-digit year
- 'yy' => 'y',
- // first letter of month - no php equivalent
- 'mmmmm' => 'M',
- // full month name
- 'mmmm' => 'F',
- // short month name
- 'mmm' => 'M',
- // mm is minutes if time, but can also be month w/leading zero
- // so we try to identify times be the inclusion of a : separator in the mask
- // It isn't perfect, but the best way I know how
- ':mm' => ':i',
- 'mm:' => 'i:',
- // month leading zero
- 'mm' => 'm',
- // month no leading zero
- 'm' => 'n',
- // full day of week name
- 'dddd' => 'l',
- // short day of week name
- 'ddd' => 'D',
- // days leading zero
- 'dd' => 'd',
- // days no leading zero
- 'd' => 'j',
- // seconds
- 'ss' => 's',
- // fractional seconds - no php equivalent
- '.s' => ''
- );
- /**
- * Search/replace values to convert Excel date/time format masks hours to PHP format masks (24 hr clock)
- *
- * @var array
- */
- protected static $_dateFormatReplacements24 = array(
- 'hh' => 'H',
- 'h' => 'G'
- );
- /**
- * Search/replace values to convert Excel date/time format masks hours to PHP format masks (12 hr clock)
- *
- * @var array
- */
- protected static $_dateFormatReplacements12 = array(
- 'hh' => 'h',
- 'h' => 'g'
- );
-
- protected static function _formatAsDate(&$value, &$format)
- {
- // dvc: convert Excel formats to PHP date formats
-
- // strip off first part containing e.g. [$-F800] or [$USD-409]
- // general syntax: [$
';
- if ($value != (int)$value) {
- self::_formatAsFraction($value, $format);
- }
-
- } else {
- // Handle the number itself
-
- // scale number
- $value = $value / $scale;
-
- // Strip #
- $format = preg_replace('/\\#/', '0', $format);
-
- $n = "/\[[^\]]+\]/";
- $m = preg_replace($n, '', $format);
- $number_regex = "/(0+)(\.?)(0*)/";
- if (preg_match($number_regex, $m, $matches)) {
- $left = $matches[1];
- $dec = $matches[2];
- $right = $matches[3];
-
- // minimun width of formatted number (including dot)
- $minWidth = strlen($left) + strlen($dec) + strlen($right);
- if ($useThousands) {
- $value = number_format(
- $value
- , strlen($right)
- , Shared_String::getDecimalSeparator()
- , Shared_String::getThousandsSeparator()
- );
- $value = preg_replace($number_regex, $value, $format);
- } else {
- if (preg_match('/0E[+-]0/i', $format)) {
- // Scientific format
- $value = sprintf('%5.2E', $value);
- } elseif (preg_match('/0([^\d\.]+)0/', $format)) {
- $value = self::_complexNumberFormatMask($value, $format);
- } else {
- $sprintf_pattern = "%0$minWidth." . strlen($right) . "f";
- $value = sprintf($sprintf_pattern, $value);
- $value = preg_replace($number_regex, $value, $format);
- }
- }
- }
- }
- if (preg_match('/\[\$(.*)\]/u', $format, $m)) {
- // Currency or Accounting
- $currencyFormat = $m[0];
- $currencyCode = $m[1];
- list($currencyCode) = explode('-',$currencyCode);
- if ($currencyCode == '') {
- $currencyCode = Shared_String::getCurrencyCode();
- }
- $value = preg_replace('/\[\$([^\]]*)\]/u',$currencyCode,$value);
- }
- }
- }
-
- // Additional formatting provided by callback function
- if ($callBack !== null) {
- list($writerInstance, $function) = $callBack;
- $value = $writerInstance->$function($value, $formatColor);
- }
-
- return $value;
- }
-
+ /* Pre-defined formats */
+ const FORMAT_GENERAL = 'General';
+
+ const FORMAT_TEXT = '@';
+
+ const FORMAT_NUMBER = '0';
+ const FORMAT_NUMBER_00 = '0.00';
+ const FORMAT_NUMBER_COMMA_SEPARATED1 = '#,##0.00';
+ const FORMAT_NUMBER_COMMA_SEPARATED2 = '#,##0.00_-';
+
+ const FORMAT_PERCENTAGE = '0%';
+ const FORMAT_PERCENTAGE_00 = '0.00%';
+
+ const FORMAT_DATE_YYYYMMDD2 = 'yyyy-mm-dd';
+ const FORMAT_DATE_YYYYMMDD = 'yy-mm-dd';
+ const FORMAT_DATE_DDMMYYYY = 'dd/mm/yy';
+ const FORMAT_DATE_DMYSLASH = 'd/m/y';
+ const FORMAT_DATE_DMYMINUS = 'd-m-y';
+ const FORMAT_DATE_DMMINUS = 'd-m';
+ const FORMAT_DATE_MYMINUS = 'm-y';
+ const FORMAT_DATE_XLSX14 = 'mm-dd-yy';
+ const FORMAT_DATE_XLSX15 = 'd-mmm-yy';
+ const FORMAT_DATE_XLSX16 = 'd-mmm';
+ const FORMAT_DATE_XLSX17 = 'mmm-yy';
+ const FORMAT_DATE_XLSX22 = 'm/d/yy h:mm';
+ const FORMAT_DATE_DATETIME = 'd/m/y h:mm';
+ const FORMAT_DATE_TIME1 = 'h:mm AM/PM';
+ const FORMAT_DATE_TIME2 = 'h:mm:ss AM/PM';
+ const FORMAT_DATE_TIME3 = 'h:mm';
+ const FORMAT_DATE_TIME4 = 'h:mm:ss';
+ const FORMAT_DATE_TIME5 = 'mm:ss';
+ const FORMAT_DATE_TIME6 = 'h:mm:ss';
+ const FORMAT_DATE_TIME7 = 'i:s.S';
+ const FORMAT_DATE_TIME8 = 'h:mm:ss;@';
+ const FORMAT_DATE_YYYYMMDDSLASH = 'yy/mm/dd;@';
+
+ const FORMAT_CURRENCY_USD_SIMPLE = '"$"#,##0.00_-';
+ const FORMAT_CURRENCY_USD = '$#,##0_-';
+ const FORMAT_CURRENCY_EUR_SIMPLE = '[$EUR ]#,##0.00_-';
+
+ /**
+ * Excel built-in number formats
+ *
+ * @var array
+ */
+ protected static $_builtInFormats;
+
+ /**
+ * Excel built-in number formats (flipped, for faster lookups)
+ *
+ * @var array
+ */
+ protected static $_flippedBuiltInFormats;
+
+ /**
+ * Format Code
+ *
+ * @var string
+ */
+ protected $_formatCode = Style_NumberFormat::FORMAT_GENERAL;
+
+ /**
+ * Built-in format Code
+ *
+ * @var string
+ */
+ protected $_builtInFormatCode = 0;
+
+ /**
+ * Create a new PHPExcel\Style_NumberFormat
+ *
+ * @param boolean $isSupervisor Flag indicating if this is a supervisor or not
+ * Leave this value at default unless you understand exactly what
+ * its ramifications are
+ * @param boolean $isConditional Flag indicating if this is a conditional style or not
+ * Leave this value at default unless you understand exactly what
+ * its ramifications are
+ */
+ public function __construct($isSupervisor = false, $isConditional = false)
+ {
+ // Supervisor?
+ parent::__construct($isSupervisor);
+
+ if ($isConditional) {
+ $this->_formatCode = null;
+ }
+ }
+
+ /**
+ * Get the shared style component for the currently active cell in currently active sheet.
+ * Only used for style supervisor
+ *
+ * @return PHPExcel\Style_NumberFormat
+ */
+ public function getSharedComponent()
+ {
+ return $this->_parent->getSharedComponent()->getNumberFormat();
+ }
+
+ /**
+ * Build style array from subcomponents
+ *
+ * @param array $array
+ * @return array
+ */
+ public function getStyleArray($array)
+ {
+ return array('numberformat' => $array);
+ }
+
+ /**
+ * Apply styles from array
+ *
+ *
+ * $objPHPExcel->getActiveSheet()->getStyle('B2')->getNumberFormat()->applyFromArray(
+ * array(
+ * 'code' => PHPExcel\Style_NumberFormat::FORMAT_CURRENCY_EUR_SIMPLE
+ * )
+ * );
+ *
+ *
+ * @param array $pStyles Array containing style information
+ * @throws PHPExcel\Exception
+ * @return PHPExcel\Style_NumberFormat
+ */
+ public function applyFromArray($pStyles = null)
+ {
+ if (is_array($pStyles)) {
+ if ($this->_isSupervisor) {
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles));
+ } else {
+ if (array_key_exists('code', $pStyles)) {
+ $this->setFormatCode($pStyles['code']);
+ }
+ }
+ } else {
+ throw new Exception("Invalid style array passed.");
+ }
+ return $this;
+ }
+
+ /**
+ * Get Format Code
+ *
+ * @return string
+ */
+ public function getFormatCode()
+ {
+ if ($this->_isSupervisor) {
+ return $this->getSharedComponent()->getFormatCode();
+ }
+ if ($this->_builtInFormatCode !== false)
+ {
+ return self::builtInFormatCode($this->_builtInFormatCode);
+ }
+ return $this->_formatCode;
+ }
+
+ /**
+ * Set Format Code
+ *
+ * @param string $pValue
+ * @return PHPExcel\Style_NumberFormat
+ */
+ public function setFormatCode($pValue = Style_NumberFormat::FORMAT_GENERAL)
+ {
+ if ($pValue == '') {
+ $pValue = Style_NumberFormat::FORMAT_GENERAL;
+ }
+ if ($this->_isSupervisor) {
+ $styleArray = $this->getStyleArray(array('code' => $pValue));
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
+ } else {
+ $this->_formatCode = $pValue;
+ $this->_builtInFormatCode = self::builtInFormatCodeIndex($pValue);
+ }
+ return $this;
+ }
+
+ /**
+ * Get Built-In Format Code
+ *
+ * @return int
+ */
+ public function getBuiltInFormatCode()
+ {
+ if ($this->_isSupervisor) {
+ return $this->getSharedComponent()->getBuiltInFormatCode();
+ }
+ return $this->_builtInFormatCode;
+ }
+
+ /**
+ * Set Built-In Format Code
+ *
+ * @param int $pValue
+ * @return PHPExcel\Style_NumberFormat
+ */
+ public function setBuiltInFormatCode($pValue = 0)
+ {
+
+ if ($this->_isSupervisor) {
+ $styleArray = $this->getStyleArray(array('code' => self::builtInFormatCode($pValue)));
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
+ } else {
+ $this->_builtInFormatCode = $pValue;
+ $this->_formatCode = self::builtInFormatCode($pValue);
+ }
+ return $this;
+ }
+
+ /**
+ * Fill built-in format codes
+ */
+ protected static function fillBuiltInFormatCodes()
+ {
+ // Built-in format codes
+ if (is_null(self::$_builtInFormats)) {
+ self::$_builtInFormats = array();
+
+ // General
+ self::$_builtInFormats[0] = Style_NumberFormat::FORMAT_GENERAL;
+ self::$_builtInFormats[1] = '0';
+ self::$_builtInFormats[2] = '0.00';
+ self::$_builtInFormats[3] = '#,##0';
+ self::$_builtInFormats[4] = '#,##0.00';
+
+ self::$_builtInFormats[9] = '0%';
+ self::$_builtInFormats[10] = '0.00%';
+ self::$_builtInFormats[11] = '0.00E+00';
+ self::$_builtInFormats[12] = '# ?/?';
+ self::$_builtInFormats[13] = '# ??/??';
+ self::$_builtInFormats[14] = 'mm-dd-yy';
+ self::$_builtInFormats[15] = 'd-mmm-yy';
+ self::$_builtInFormats[16] = 'd-mmm';
+ self::$_builtInFormats[17] = 'mmm-yy';
+ self::$_builtInFormats[18] = 'h:mm AM/PM';
+ self::$_builtInFormats[19] = 'h:mm:ss AM/PM';
+ self::$_builtInFormats[20] = 'h:mm';
+ self::$_builtInFormats[21] = 'h:mm:ss';
+ self::$_builtInFormats[22] = 'm/d/yy h:mm';
+
+ self::$_builtInFormats[37] = '#,##0 ;(#,##0)';
+ self::$_builtInFormats[38] = '#,##0 ;[Red](#,##0)';
+ self::$_builtInFormats[39] = '#,##0.00;(#,##0.00)';
+ self::$_builtInFormats[40] = '#,##0.00;[Red](#,##0.00)';
+
+ self::$_builtInFormats[44] = '_("$"* #,##0.00_);_("$"* \(#,##0.00\);_("$"* "-"??_);_(@_)';
+ self::$_builtInFormats[45] = 'mm:ss';
+ self::$_builtInFormats[46] = '[h]:mm:ss';
+ self::$_builtInFormats[47] = 'mmss.0';
+ self::$_builtInFormats[48] = '##0.0E+0';
+ self::$_builtInFormats[49] = '@';
+
+ // CHT
+ self::$_builtInFormats[27] = '[$-404]e/m/d';
+ self::$_builtInFormats[30] = 'm/d/yy';
+ self::$_builtInFormats[36] = '[$-404]e/m/d';
+ self::$_builtInFormats[50] = '[$-404]e/m/d';
+ self::$_builtInFormats[57] = '[$-404]e/m/d';
+
+ // THA
+ self::$_builtInFormats[59] = 't0';
+ self::$_builtInFormats[60] = 't0.00';
+ self::$_builtInFormats[61] = 't#,##0';
+ self::$_builtInFormats[62] = 't#,##0.00';
+ self::$_builtInFormats[67] = 't0%';
+ self::$_builtInFormats[68] = 't0.00%';
+ self::$_builtInFormats[69] = 't# ?/?';
+ self::$_builtInFormats[70] = 't# ??/??';
+
+ // Flip array (for faster lookups)
+ self::$_flippedBuiltInFormats = array_flip(self::$_builtInFormats);
+ }
+ }
+
+ /**
+ * Get built-in format code
+ *
+ * @param int $pIndex
+ * @return string
+ */
+ public static function builtInFormatCode($pIndex)
+ {
+ // Clean parameter
+ $pIndex = intval($pIndex);
+
+ // Ensure built-in format codes are available
+ self::fillBuiltInFormatCodes();
+
+ // Lookup format code
+ if (isset(self::$_builtInFormats[$pIndex])) {
+ return self::$_builtInFormats[$pIndex];
+ }
+
+ return '';
+ }
+
+ /**
+ * Get built-in format code index
+ *
+ * @param string $formatCode
+ * @return int|boolean
+ */
+ public static function builtInFormatCodeIndex($formatCode)
+ {
+ // Ensure built-in format codes are available
+ self::fillBuiltInFormatCodes();
+
+ // Lookup format code
+ if (isset(self::$_flippedBuiltInFormats[$formatCode])) {
+ return self::$_flippedBuiltInFormats[$formatCode];
+ }
+
+ return false;
+ }
+
+ /**
+ * Get hash code
+ *
+ * @return string Hash code
+ */
+ public function getHashCode()
+ {
+ if ($this->_isSupervisor) {
+ return $this->getSharedComponent()->getHashCode();
+ }
+ return md5(
+ $this->_formatCode
+ . $this->_builtInFormatCode
+ . __CLASS__
+ );
+ }
+
+ /**
+ * Search/replace values to convert Excel date/time format masks to PHP format masks
+ *
+ * @var array
+ */
+ protected static $_dateFormatReplacements = array(
+ // first remove escapes related to non-format characters
+ '\\' => '',
+ // 12-hour suffix
+ 'am/pm' => 'A',
+ // 4-digit year
+ 'e' => 'Y',
+ 'yyyy' => 'Y',
+ // 2-digit year
+ 'yy' => 'y',
+ // first letter of month - no php equivalent
+ 'mmmmm' => 'M',
+ // full month name
+ 'mmmm' => 'F',
+ // short month name
+ 'mmm' => 'M',
+ // mm is minutes if time, but can also be month w/leading zero
+ // so we try to identify times be the inclusion of a : separator in the mask
+ // It isn't perfect, but the best way I know how
+ ':mm' => ':i',
+ 'mm:' => 'i:',
+ // month leading zero
+ 'mm' => 'm',
+ // month no leading zero
+ 'm' => 'n',
+ // full day of week name
+ 'dddd' => 'l',
+ // short day of week name
+ 'ddd' => 'D',
+ // days leading zero
+ 'dd' => 'd',
+ // days no leading zero
+ 'd' => 'j',
+ // seconds
+ 'ss' => 's',
+ // fractional seconds - no php equivalent
+ '.s' => ''
+ );
+ /**
+ * Search/replace values to convert Excel date/time format masks hours to PHP format masks (24 hr clock)
+ *
+ * @var array
+ */
+ protected static $_dateFormatReplacements24 = array(
+ 'hh' => 'H',
+ 'h' => 'G'
+ );
+ /**
+ * Search/replace values to convert Excel date/time format masks hours to PHP format masks (12 hr clock)
+ *
+ * @var array
+ */
+ protected static $_dateFormatReplacements12 = array(
+ 'hh' => 'h',
+ 'h' => 'g'
+ );
+
+ protected static function _formatAsDate(&$value, &$format)
+ {
+ // dvc: convert Excel formats to PHP date formats
+
+ // strip off first part containing e.g. [$-F800] or [$USD-409]
+ // general syntax: [$
';
+ if ($value != (int)$value) {
+ self::_formatAsFraction($value, $format);
+ }
+
+ } else {
+ // Handle the number itself
+
+ // scale number
+ $value = $value / $scale;
+
+ // Strip #
+ $format = preg_replace('/\\#/', '0', $format);
+
+ $n = "/\[[^\]]+\]/";
+ $m = preg_replace($n, '', $format);
+ $number_regex = "/(0+)(\.?)(0*)/";
+ if (preg_match($number_regex, $m, $matches)) {
+ $left = $matches[1];
+ $dec = $matches[2];
+ $right = $matches[3];
+
+ // minimun width of formatted number (including dot)
+ $minWidth = strlen($left) + strlen($dec) + strlen($right);
+ if ($useThousands) {
+ $value = number_format(
+ $value
+ , strlen($right)
+ , Shared_String::getDecimalSeparator()
+ , Shared_String::getThousandsSeparator()
+ );
+ $value = preg_replace($number_regex, $value, $format);
+ } else {
+ if (preg_match('/0E[+-]0/i', $format)) {
+ // Scientific format
+ $value = sprintf('%5.2E', $value);
+ } elseif (preg_match('/0([^\d\.]+)0/', $format)) {
+ $value = self::_complexNumberFormatMask($value, $format);
+ } else {
+ $sprintf_pattern = "%0$minWidth." . strlen($right) . "f";
+ $value = sprintf($sprintf_pattern, $value);
+ $value = preg_replace($number_regex, $value, $format);
+ }
+ }
+ }
+ }
+ if (preg_match('/\[\$(.*)\]/u', $format, $m)) {
+ // Currency or Accounting
+ $currencyFormat = $m[0];
+ $currencyCode = $m[1];
+ list($currencyCode) = explode('-',$currencyCode);
+ if ($currencyCode == '') {
+ $currencyCode = Shared_String::getCurrencyCode();
+ }
+ $value = preg_replace('/\[\$([^\]]*)\]/u',$currencyCode,$value);
+ }
+ }
+ }
+
+ // Additional formatting provided by callback function
+ if ($callBack !== null) {
+ list($writerInstance, $function) = $callBack;
+ $value = $writerInstance->$function($value, $formatColor);
+ }
+
+ return $value;
+ }
}
diff --git a/Classes/PHPExcel/Style/Protection.php b/Classes/PHPExcel/Style/Protection.php
index 21f3dac..49cf9de 100644
--- a/Classes/PHPExcel/Style/Protection.php
+++ b/Classes/PHPExcel/Style/Protection.php
@@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\Style
* @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 1.4.5, 2007-08-23
*/
@@ -37,102 +37,102 @@ namespace PHPExcel;
*/
class Style_Protection extends Style_Supervisor implements IComparable
{
- /** Protection styles */
- const PROTECTION_INHERIT = 'inherit';
- const PROTECTION_PROTECTED = 'protected';
- const PROTECTION_UNPROTECTED = 'unprotected';
+ /** Protection styles */
+ const PROTECTION_INHERIT = 'inherit';
+ const PROTECTION_PROTECTED = 'protected';
+ const PROTECTION_UNPROTECTED = 'unprotected';
- /**
- * Locked
- *
- * @var string
- */
- protected $_locked;
-
- /**
- * Hidden
- *
- * @var string
- */
- protected $_hidden;
-
- /**
- * Create a new PHPExcel\Style_Protection
- *
- * @param boolean $isSupervisor Flag indicating if this is a supervisor or not
- * Leave this value at default unless you understand exactly what
- * its ramifications are
- * @param boolean $isConditional Flag indicating if this is a conditional style or not
- * Leave this value at default unless you understand exactly what
- * its ramifications are
+ /**
+ * Locked
+ *
+ * @var string
*/
- public function __construct($isSupervisor = FALSE, $isConditional = FALSE)
- {
- // Supervisor?
- parent::__construct($isSupervisor);
+ protected $_locked;
- // Initialise values
- if (!$isConditional) {
- $this->_locked = self::PROTECTION_INHERIT;
- $this->_hidden = self::PROTECTION_INHERIT;
- }
+ /**
+ * Hidden
+ *
+ * @var string
+ */
+ protected $_hidden;
+
+ /**
+ * Create a new PHPExcel\Style_Protection
+ *
+ * @param boolean $isSupervisor Flag indicating if this is a supervisor or not
+ * Leave this value at default unless you understand exactly what
+ * its ramifications are
+ * @param boolean $isConditional Flag indicating if this is a conditional style or not
+ * Leave this value at default unless you understand exactly what
+ * its ramifications are
+ */
+ public function __construct($isSupervisor = false, $isConditional = false)
+ {
+ // Supervisor?
+ parent::__construct($isSupervisor);
+
+ // Initialise values
+ if (!$isConditional) {
+ $this->_locked = self::PROTECTION_INHERIT;
+ $this->_hidden = self::PROTECTION_INHERIT;
+ }
}
- /**
- * Get the shared style component for the currently active cell in currently active sheet.
- * Only used for style supervisor
- *
- * @return PHPExcel\Style_Protection
- */
- public function getSharedComponent()
- {
- return $this->_parent->getSharedComponent()->getProtection();
- }
+ /**
+ * Get the shared style component for the currently active cell in currently active sheet.
+ * Only used for style supervisor
+ *
+ * @return PHPExcel\Style_Protection
+ */
+ public function getSharedComponent()
+ {
+ return $this->_parent->getSharedComponent()->getProtection();
+ }
- /**
- * Build style array from subcomponents
- *
- * @param array $array
- * @return array
- */
- public function getStyleArray($array)
- {
- return array('protection' => $array);
- }
+ /**
+ * Build style array from subcomponents
+ *
+ * @param array $array
+ * @return array
+ */
+ public function getStyleArray($array)
+ {
+ return array('protection' => $array);
+ }
/**
* Apply styles from array
*
*
* $objPHPExcel->getActiveSheet()->getStyle('B2')->getLocked()->applyFromArray(
- * array(
- * 'locked' => TRUE,
- * 'hidden' => FALSE
- * )
+ * array(
+ * 'locked' => TRUE,
+ * 'hidden' => FALSE
+ * )
* );
*
*
- * @param array $pStyles Array containing style information
- * @throws PHPExcel\Exception
+ * @param array $pStyles Array containing style information
+ * @throws PHPExcel\Exception
* @return PHPExcel\Style_Protection
*/
- public function applyFromArray($pStyles = NULL) {
- if (is_array($pStyles)) {
- if ($this->_isSupervisor) {
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles));
- } else {
- if (isset($pStyles['locked'])) {
- $this->setLocked($pStyles['locked']);
- }
- if (isset($pStyles['hidden'])) {
- $this->setHidden($pStyles['hidden']);
- }
- }
- } else {
- throw new Exception("Invalid style array passed.");
- }
- return $this;
- }
+ public function applyFromArray($pStyles = null) {
+ if (is_array($pStyles)) {
+ if ($this->_isSupervisor) {
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles));
+ } else {
+ if (isset($pStyles['locked'])) {
+ $this->setLocked($pStyles['locked']);
+ }
+ if (isset($pStyles['hidden'])) {
+ $this->setHidden($pStyles['hidden']);
+ }
+ }
+ } else {
+ throw new Exception("Invalid style array passed.");
+ }
+ return $this;
+ }
/**
* Get locked
@@ -140,10 +140,10 @@ class Style_Protection extends Style_Supervisor implements IComparable
* @return string
*/
public function getLocked() {
- if ($this->_isSupervisor) {
- return $this->getSharedComponent()->getLocked();
- }
- return $this->_locked;
+ if ($this->_isSupervisor) {
+ return $this->getSharedComponent()->getLocked();
+ }
+ return $this->_locked;
}
/**
@@ -153,13 +153,13 @@ class Style_Protection extends Style_Supervisor implements IComparable
* @return PHPExcel\Style_Protection
*/
public function setLocked($pValue = self::PROTECTION_INHERIT) {
- if ($this->_isSupervisor) {
- $styleArray = $this->getStyleArray(array('locked' => $pValue));
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
- } else {
- $this->_locked = $pValue;
- }
- return $this;
+ if ($this->_isSupervisor) {
+ $styleArray = $this->getStyleArray(array('locked' => $pValue));
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
+ } else {
+ $this->_locked = $pValue;
+ }
+ return $this;
}
/**
@@ -168,10 +168,10 @@ class Style_Protection extends Style_Supervisor implements IComparable
* @return string
*/
public function getHidden() {
- if ($this->_isSupervisor) {
- return $this->getSharedComponent()->getHidden();
- }
- return $this->_hidden;
+ if ($this->_isSupervisor) {
+ return $this->getSharedComponent()->getHidden();
+ }
+ return $this->_hidden;
}
/**
@@ -181,29 +181,28 @@ class Style_Protection extends Style_Supervisor implements IComparable
* @return PHPExcel\Style_Protection
*/
public function setHidden($pValue = self::PROTECTION_INHERIT) {
- if ($this->_isSupervisor) {
- $styleArray = $this->getStyleArray(array('hidden' => $pValue));
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
- } else {
- $this->_hidden = $pValue;
- }
- return $this;
+ if ($this->_isSupervisor) {
+ $styleArray = $this->getStyleArray(array('hidden' => $pValue));
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
+ } else {
+ $this->_hidden = $pValue;
+ }
+ return $this;
}
- /**
- * Get hash code
- *
- * @return string Hash code
- */
- public function getHashCode() {
- if ($this->_isSupervisor) {
- return $this->getSharedComponent()->getHashCode();
- }
- return md5(
- $this->_locked
- . $this->_hidden
- . __CLASS__
- );
+ /**
+ * Get hash code
+ *
+ * @return string Hash code
+ */
+ public function getHashCode() {
+ if ($this->_isSupervisor) {
+ return $this->getSharedComponent()->getHashCode();
+ }
+ return md5(
+ $this->_locked
+ . $this->_hidden
+ . __CLASS__
+ );
}
-
}
diff --git a/Classes/PHPExcel/Style/Supervisor.php b/Classes/PHPExcel/Style/Supervisor.php
index 61c68ad..e7a82e0 100644
--- a/Classes/PHPExcel/Style/Supervisor.php
+++ b/Classes/PHPExcel/Style/Supervisor.php
@@ -19,10 +19,10 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category PHPExcel
- * @package PHPExcel\Style
+ * @package PHPExcel\Style
* @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,103 +32,103 @@ namespace PHPExcel;
* PHPExcel\Style\Supervisor
*
* @category PHPExcel
- * @package PHPExcel\Style
+ * @package PHPExcel\Style
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
*/
abstract class Style_Supervisor
{
- /**
- * Supervisor?
- *
- * @var boolean
- */
- protected $_isSupervisor;
+ /**
+ * Supervisor?
+ *
+ * @var boolean
+ */
+ protected $_isSupervisor;
- /**
- * Parent. Only used for supervisor
- *
- * @var PHPExcel\Style
- */
- protected $_parent;
+ /**
+ * Parent. Only used for supervisor
+ *
+ * @var PHPExcel\Style
+ */
+ protected $_parent;
- /**
- * Create a new PHPExcel\Style_Alignment
- *
- * @param boolean $isSupervisor Flag indicating if this is a supervisor or not
- * Leave this value at default unless you understand exactly what
- * its ramifications are
- */
- public function __construct($isSupervisor = FALSE)
- {
- // Supervisor?
- $this->_isSupervisor = $isSupervisor;
- }
+ /**
+ * Create a new PHPExcel\Style_Alignment
+ *
+ * @param boolean $isSupervisor Flag indicating if this is a supervisor or not
+ * Leave this value at default unless you understand exactly what
+ * its ramifications are
+ */
+ public function __construct($isSupervisor = false)
+ {
+ // Supervisor?
+ $this->_isSupervisor = $isSupervisor;
+ }
- /**
- * Bind parent. Only used for supervisor
- *
- * @param PHPExcel $parent
- * @return PHPExcel\Style_Supervisor
- */
- public function bindParent($parent, $parentPropertyName=NULL)
- {
- $this->_parent = $parent;
- return $this;
- }
+ /**
+ * Bind parent. Only used for supervisor
+ *
+ * @param PHPExcel $parent
+ * @return PHPExcel\Style_Supervisor
+ */
+ public function bindParent($parent, $parentPropertyName=null)
+ {
+ $this->_parent = $parent;
+ return $this;
+ }
- /**
- * Is this a supervisor or a cell style component?
- *
- * @return boolean
- */
- public function getIsSupervisor()
- {
- return $this->_isSupervisor;
- }
+ /**
+ * Is this a supervisor or a cell style component?
+ *
+ * @return boolean
+ */
+ public function getIsSupervisor()
+ {
+ return $this->_isSupervisor;
+ }
- /**
- * Get the currently active sheet. Only used for supervisor
- *
- * @return PHPExcel\Worksheet
- */
- public function getActiveSheet()
- {
- return $this->_parent->getActiveSheet();
- }
+ /**
+ * Get the currently active sheet. Only used for supervisor
+ *
+ * @return PHPExcel\Worksheet
+ */
+ public function getActiveSheet()
+ {
+ return $this->_parent->getActiveSheet();
+ }
- /**
- * Get the currently active cell coordinate in currently active sheet.
- * Only used for supervisor
- *
- * @return string E.g. 'A1'
- */
- public function getSelectedCells()
- {
- return $this->getActiveSheet()->getSelectedCells();
- }
+ /**
+ * Get the currently active cell coordinate in currently active sheet.
+ * Only used for supervisor
+ *
+ * @return string E.g. 'A1'
+ */
+ public function getSelectedCells()
+ {
+ return $this->getActiveSheet()->getSelectedCells();
+ }
- /**
- * Get the currently active cell coordinate in currently active sheet.
- * Only used for supervisor
- *
- * @return string E.g. 'A1'
- */
- public function getActiveCell()
- {
- return $this->getActiveSheet()->getActiveCell();
- }
+ /**
+ * Get the currently active cell coordinate in currently active sheet.
+ * Only used for supervisor
+ *
+ * @return string E.g. 'A1'
+ */
+ public function getActiveCell()
+ {
+ return $this->getActiveSheet()->getActiveCell();
+ }
- /**
- * 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;
+ }
+ }
+ }
}
diff --git a/Classes/PHPExcel/Workbook.php b/Classes/PHPExcel/Workbook.php
index 77fc911..46acdec 100644
--- a/Classes/PHPExcel/Workbook.php
+++ b/Classes/PHPExcel/Workbook.php
@@ -65,11 +65,11 @@ class Workbook
protected $_workSheetCollection = array();
/**
- * Calculation Engine
- *
- * @var PHPExcel\Calculation
- */
- protected $_calculationEngine = NULL;
+ * Calculation Engine
+ *
+ * @var PHPExcel\Calculation
+ */
+ protected $_calculationEngine = null;
/**
* Active sheet index
@@ -111,8 +111,8 @@ class Workbook
*/
public function __construct()
{
- $this->_uniqueID = uniqid();
- $this->_calculationEngine = Calculation::getInstance($this);
+ $this->_uniqueID = uniqid();
+ $this->_calculationEngine = Calculation::getInstance($this);
// Initialise worksheet collection and add one worksheet
$this->_workSheetCollection = array();
@@ -153,7 +153,7 @@ class Workbook
*/
public function disconnectWorksheets()
{
- $worksheet = NULL;
+ $worksheet = null;
foreach($this->_workSheetCollection as $k => &$worksheet) {
$worksheet->disconnectCells();
$this->_workSheetCollection[$k] = null;
@@ -162,15 +162,15 @@ class Workbook
$this->_workSheetCollection = array();
}
- /**
- * Return the calculation engine for this worksheet
- *
- * @return PHPExcel\Calculation
- */
- public function getCalculationEngine()
- {
- return $this->_calculationEngine;
- } // function getCellCacheController()
+ /**
+ * Return the calculation engine for this worksheet
+ *
+ * @return PHPExcel\Calculation
+ */
+ public function getCalculationEngine()
+ {
+ return $this->_calculationEngine;
+ } // function getCellCacheController()
/**
* Get properties
@@ -229,7 +229,7 @@ class Workbook
* @return PHPExcel\Worksheet
* @throws PHPExcel\Exception
*/
- public function createSheet($iSheetIndex = NULL)
+ public function createSheet($iSheetIndex = null)
{
$newSheet = new Worksheet($this);
$this->addSheet($newSheet, $iSheetIndex);
@@ -244,7 +244,7 @@ class Workbook
*/
public function sheetNameExists($pSheetName)
{
- return ($this->getSheetByName($pSheetName) !== NULL);
+ return ($this->getSheetByName($pSheetName) !== null);
}
/**
@@ -255,15 +255,15 @@ class Workbook
* @return PHPExcel\Worksheet
* @throws PHPExcel\Exception
*/
- public function addSheet(Worksheet $pSheet, $iSheetIndex = NULL)
+ public function addSheet(Worksheet $pSheet, $iSheetIndex = null)
{
if ($this->sheetNameExists($pSheet->getTitle())) {
throw new Exception(
- "Workbook already contains a worksheet named '{$pSheet->getTitle()}'. Rename this worksheet first."
+ "Workbook already contains a worksheet named '{$pSheet->getTitle()}'. Rename this worksheet first."
);
}
- if($iSheetIndex === NULL) {
+ if($iSheetIndex === null) {
if ($this->_activeSheetIndex < 0) {
$this->_activeSheetIndex = 0;
}
@@ -298,7 +298,7 @@ class Workbook
if ($pIndex > $numSheets - 1) {
throw new Exception(
- "You tried to remove a sheet by the out of bounds index: {$pIndex}. The actual number of sheets is {$numSheets}."
+ "You tried to remove a sheet by the out of bounds index: {$pIndex}. The actual number of sheets is {$numSheets}."
);
} else {
array_splice($this->_workSheetCollection, $pIndex, 1);
@@ -325,8 +325,8 @@ class Workbook
if ($pIndex > $numSheets - 1) {
throw new Exception(
- "Your requested sheet index: {$pIndex} is out of bounds. The actual number of sheets is {$numSheets}."
- );
+ "Your requested sheet index: {$pIndex} is out of bounds. The actual number of sheets is {$numSheets}."
+ );
} else {
return $this->_workSheetCollection[$pIndex];
}
@@ -357,7 +357,7 @@ class Workbook
}
}
- return NULL;
+ return null;
}
/**
@@ -432,11 +432,11 @@ class Workbook
*/
public function setActiveSheetIndex($pIndex = 0)
{
- $numSheets = count($this->_workSheetCollection);
+ $numSheets = count($this->_workSheetCollection);
if ($pIndex > $numSheets - 1) {
throw new Exception(
- "You tried to set a sheet active by the out of bounds index: {$pIndex}. The actual number of sheets is {$numSheets}."
+ "You tried to set a sheet active by the out of bounds index: {$pIndex}. The actual number of sheets is {$numSheets}."
);
} else {
$this->_activeSheetIndex = $pIndex;
@@ -546,14 +546,14 @@ class Workbook
public function getNamedRange($namedRange, Worksheet $pSheet = null) {
$returnValue = null;
- if ($namedRange != '' && ($namedRange !== NULL)) {
+ if ($namedRange != '' && ($namedRange !== null)) {
// first look for global defined name
if (isset($this->_namedRanges[$namedRange])) {
$returnValue = $this->_namedRanges[$namedRange];
}
// then look for local defined name (has priority over global defined name if both names exist)
- if (($pSheet !== NULL) && isset($this->_namedRanges[$pSheet->getTitle() . '!' . $namedRange])) {
+ if (($pSheet !== null) && isset($this->_namedRanges[$pSheet->getTitle() . '!' . $namedRange])) {
$returnValue = $this->_namedRanges[$pSheet->getTitle() . '!' . $namedRange];
}
}
@@ -569,7 +569,7 @@ class Workbook
* @return PHPExcel
*/
public function removeNamedRange($namedRange, Worksheet $pSheet = null) {
- if ($pSheet === NULL) {
+ if ($pSheet === null) {
if (isset($this->_namedRanges[$namedRange])) {
unset($this->_namedRanges[$namedRange]);
}
@@ -872,7 +872,7 @@ class Workbook
$columnDimension->setXfIndex( $map[$columnDimension->getXfIndex()] );
}
- // also do garbage collection for all the sheets
+ // also do garbage collection for all the sheets
$sheet->garbageCollect();
}
}
@@ -885,5 +885,4 @@ class Workbook
public function getID() {
return $this->_uniqueID;
}
-
}
diff --git a/Classes/PHPExcel/Worksheet.php b/Classes/PHPExcel/Worksheet.php
index ac39f58..41424f9 100644
--- a/Classes/PHPExcel/Worksheet.php
+++ b/Classes/PHPExcel/Worksheet.php
@@ -206,7 +206,7 @@ class Worksheet implements IComparable
*
* @var PHPExcel\Worksheet_AutoFilter
*/
- protected $_autoFilter = NULL;
+ protected $_autoFilter = null;
/**
* Freeze pane
@@ -337,7 +337,7 @@ class Worksheet implements IComparable
{
// Set parent and title
$this->_parent = $pParent;
- $this->setTitle($pTitle, FALSE);
+ $this->setTitle($pTitle, false);
$this->setSheetState(Worksheet::SHEETSTATE_VISIBLE);
$this->_cellCollection = CachedObjectStorageFactory::getInstance($this);
@@ -364,12 +364,12 @@ class Worksheet implements IComparable
$this->_protection = new Worksheet_Protection();
// Default row dimension
- $this->_defaultRowDimension = new Worksheet_RowDimension(NULL);
+ $this->_defaultRowDimension = new Worksheet_RowDimension(null);
// Default column dimension
- $this->_defaultColumnDimension = new Worksheet_ColumnDimension(NULL);
+ $this->_defaultColumnDimension = new Worksheet_ColumnDimension(null);
- $this->_autoFilter = new Worksheet_AutoFilter(NULL, $this);
+ $this->_autoFilter = new Worksheet_AutoFilter(null, $this);
}
@@ -378,11 +378,11 @@ class Worksheet implements IComparable
* typically so that the worksheet object can be unset
*
*/
- public function disconnectCells() {
- if ( $this->_cellCollection !== NULL){
+ public function disconnectCells() {
+ if ( $this->_cellCollection !== null){
$this->_cellCollection->unsetWorksheetCells();
- $this->_cellCollection = NULL;
- }
+ $this->_cellCollection = null;
+ }
// detach ourself from the workbook, so that it can then delete this worksheet successfully
$this->_parent = null;
}
@@ -391,19 +391,19 @@ class Worksheet implements IComparable
* Code to execute when this worksheet is unset()
*
*/
- function __destruct() {
- Calculation::getInstance($this->_parent)
- ->clearCalculationCacheForWorksheet($this->_title);
+ function __destruct() {
+ Calculation::getInstance($this->_parent)
+ ->clearCalculationCacheForWorksheet($this->_title);
- $this->disconnectCells();
- }
+ $this->disconnectCells();
+ }
/**
* Return the cache controller for the cell collection
*
* @return PHPExcel\CachedObjectStorage_xxx
*/
- public function getCellCacheController() {
+ public function getCellCacheController() {
return $this->_cellCollection;
} // function getCellCacheController()
@@ -452,7 +452,7 @@ class Worksheet implements IComparable
// Re-order cell collection
return $this->sortCellCollection();
}
- if ($this->_cellCollection !== NULL) {
+ if ($this->_cellCollection !== null) {
return $this->_cellCollection->getCellList();
}
return array();
@@ -465,7 +465,7 @@ class Worksheet implements IComparable
*/
public function sortCellCollection()
{
- if ($this->_cellCollection !== NULL) {
+ if ($this->_cellCollection !== null) {
return $this->_cellCollection->getSortedCellList();
}
return array();
@@ -710,22 +710,22 @@ class Worksheet implements IComparable
// loop through all cells in the worksheet
foreach ($this->getCellCollection(false) as $cellID) {
$cell = $this->getCell($cellID);
- if (isset($autoSizes[$this->_cellCollection->getCurrentColumn()])) {
+ if (isset($autoSizes[$this->_cellCollection->getCurrentColumn()])) {
// Determine width if cell does not participate in a merge
- if (!isset($isMergeCell[$this->_cellCollection->getCurrentAddress()])) {
+ if (!isset($isMergeCell[$this->_cellCollection->getCurrentAddress()])) {
// Calculated value
// To formatted string
- $cellValue = Style_NumberFormat::toFormattedString(
- $cell->getCalculatedValue(),
- $this->getParent()->getCellXfByIndex($cell->getXfIndex())->getNumberFormat()->getFormatCode()
- );
+ $cellValue = Style_NumberFormat::toFormattedString(
+ $cell->getCalculatedValue(),
+ $this->getParent()->getCellXfByIndex($cell->getXfIndex())->getNumberFormat()->getFormatCode()
+ );
- $autoSizes[$this->_cellCollection->getCurrentColumn()] = max(
- (float) $autoSizes[$this->_cellCollection->getCurrentColumn()],
+ $autoSizes[$this->_cellCollection->getCurrentColumn()] = max(
+ (float) $autoSizes[$this->_cellCollection->getCurrentColumn()],
(float) Shared_Font::calculateColumnWidth(
- $this->getParent()->getCellXfByIndex($cell->getXfIndex())->getFont(),
+ $this->getParent()->getCellXfByIndex($cell->getXfIndex())->getFont(),
$cellValue,
- $this->getParent()->getCellXfByIndex($cell->getXfIndex())->getAlignment()->getTextRotation(),
+ $this->getParent()->getCellXfByIndex($cell->getXfIndex())->getAlignment()->getTextRotation(),
$this->getDefaultStyle()->getFont()
)
);
@@ -748,7 +748,7 @@ class Worksheet implements IComparable
*
* @return PHPExcel\Workbook
*/
- public function getParent() {
+ public function getParent() {
return $this->_parent;
}
@@ -758,7 +758,7 @@ class Worksheet implements IComparable
* @param PHPExcel\Workbook $parent
* @return PHPExcel\Worksheet
*/
- public function rebindParent(Workbook $parent) {
+ public function rebindParent(Workbook $parent) {
$namedRanges = $this->_parent->getNamedRanges();
foreach ($namedRanges as $namedRange) {
$parent->addNamedRange($namedRange);
@@ -787,7 +787,7 @@ class Worksheet implements IComparable
*
* @param string $pValue String containing the dimension of this worksheet
* @param string $updateFormulaCellReferences boolean Flag indicating whether cell references in formulae should
- * be updated to reflect the new sheet name.
+ * be updated to reflect the new sheet name.
* This should be left as the default true, unless you are
* certain that no formula cells on any worksheet contain
* references to this worksheet
@@ -808,14 +808,14 @@ class Worksheet implements IComparable
if ($this->_parent) {
// Is there already such sheet name?
- if ($this->_parent->sheetNameExists($pValue)) {
+ if ($this->_parent->sheetNameExists($pValue)) {
// Use name, but append with lowest possible integer
if (Shared_String::CountCharacters($pValue) > 29) {
$pValue = Shared_String::Substring($pValue,0,29);
}
$i = 1;
- while ($this->_parent->sheetNameExists($pValue . ' ' . $i)) {
+ while ($this->_parent->sheetNameExists($pValue . ' ' . $i)) {
++$i;
if ($i == 10) {
if (Shared_String::CountCharacters($pValue) > 28) {
@@ -840,10 +840,10 @@ class Worksheet implements IComparable
if ($this->_parent) {
// New title
$newTitle = $this->getTitle();
- Calculation::getInstance($this->_parent)
- ->renameCalculationCacheForWorksheet($oldTitle, $newTitle);
+ Calculation::getInstance($this->_parent)
+ ->renameCalculationCacheForWorksheet($oldTitle, $newTitle);
if ($updateFormulaCellReferences)
- ReferenceHelper::getInstance()->updateNamedFormulas($this->_parent, $oldTitle, $newTitle);
+ ReferenceHelper::getInstance()->updateNamedFormulas($this->_parent, $oldTitle, $newTitle);
}
return $this;
@@ -854,7 +854,7 @@ class Worksheet implements IComparable
*
* @return string Sheet state (visible, hidden, veryHidden)
*/
- public function getSheetState() {
+ public function getSheetState() {
return $this->_sheetState;
}
@@ -864,7 +864,7 @@ class Worksheet implements IComparable
* @param string $value Sheet state (visible, hidden, veryHidden)
* @return PHPExcel\Worksheet
*/
- public function setSheetState($value = Worksheet::SHEETSTATE_VISIBLE) {
+ public function setSheetState($value = Worksheet::SHEETSTATE_VISIBLE) {
$this->_sheetState = $value;
return $this;
}
@@ -1109,14 +1109,14 @@ class Worksheet implements IComparable
// Worksheet reference?
if (strpos($pCoordinate, '!') !== false) {
$worksheetReference = Worksheet::extractSheetTitle($pCoordinate, true);
- return $this->_parent->getSheetByName($worksheetReference[0])->getCell($worksheetReference[1]);
+ return $this->_parent->getSheetByName($worksheetReference[0])->getCell($worksheetReference[1]);
}
// Named range?
if ((!preg_match('/^'.Calculation::CALCULATION_REGEXP_CELLREF.'$/i', $pCoordinate, $matches)) &&
(preg_match('/^'.Calculation::CALCULATION_REGEXP_NAMEDRANGE.'$/i', $pCoordinate, $matches))) {
$namedRange = NamedRange::resolveRange($pCoordinate, $this);
- if ($namedRange !== NULL) {
+ if ($namedRange !== null) {
$pCoordinate = $namedRange->getRange();
return $namedRange->getWorksheet()->getCell($pCoordinate);
}
@@ -1151,7 +1151,7 @@ class Worksheet implements IComparable
return $this->_cellCollection->getCacheData($coordinate);
}
- return $this->_createNewCell($coordinate);
+ return $this->_createNewCell($coordinate);
}
/**
@@ -1160,16 +1160,16 @@ class Worksheet implements IComparable
* @param string $pCoordinate Coordinate of the cell
* @return PHPExcel\Cell Cell that was created
*/
- private function _createNewCell($pCoordinate)
- {
- $cell = $this->_cellCollection->addCacheData(
- $pCoordinate,
- new Cell(
- NULL,
- Cell_DataType::TYPE_NULL,
- $this
- )
- );
+ private function _createNewCell($pCoordinate)
+ {
+ $cell = $this->_cellCollection->addCacheData(
+ $pCoordinate,
+ new Cell(
+ null,
+ Cell_DataType::TYPE_NULL,
+ $this
+ )
+ );
$this->_cellCollectionIsSorted = false;
// Coordinates
@@ -1179,21 +1179,21 @@ class Worksheet implements IComparable
$this->_cachedHighestRow = max($this->_cachedHighestRow, $aCoordinates[1]);
// Cell needs appropriate xfIndex from dimensions records
- // but don't create dimension records if they don't already exist
- $rowDimension = $this->getRowDimension($aCoordinates[1], FALSE);
- $columnDimension = $this->getColumnDimension($aCoordinates[0], FALSE);
+ // but don't create dimension records if they don't already exist
+ $rowDimension = $this->getRowDimension($aCoordinates[1], false);
+ $columnDimension = $this->getColumnDimension($aCoordinates[0], false);
- if ($rowDimension !== NULL && $rowDimension->getXfIndex() > 0) {
+ if ($rowDimension !== null && $rowDimension->getXfIndex() > 0) {
// then there is a row dimension with explicit style, assign it to the cell
$cell->setXfIndex($rowDimension->getXfIndex());
- } elseif ($columnDimension !== NULL && $columnDimension->getXfIndex() > 0) {
+ } elseif ($columnDimension !== null && $columnDimension->getXfIndex() > 0) {
// then there is a column dimension, assign it to the cell
$cell->setXfIndex($columnDimension->getXfIndex());
}
return $cell;
- }
-
+ }
+
/**
* Does the cell at a specific coordinate exist?
*
@@ -1206,14 +1206,14 @@ class Worksheet implements IComparable
// Worksheet reference?
if (strpos($pCoordinate, '!') !== false) {
$worksheetReference = self::extractSheetTitle($pCoordinate, true);
- return $this->_parent->getSheetByName($worksheetReference[0])->cellExists($worksheetReference[1]);
+ return $this->_parent->getSheetByName($worksheetReference[0])->cellExists($worksheetReference[1]);
}
// Named range?
if ((!preg_match('/^'.Calculation::CALCULATION_REGEXP_CELLREF.'$/i', $pCoordinate, $matches)) &&
(preg_match('/^'.Calculation::CALCULATION_REGEXP_NAMEDRANGE.'$/i', $pCoordinate, $matches))) {
$namedRange = NamedRange::resolveRange($pCoordinate, $this);
- if ($namedRange !== NULL) {
+ if ($namedRange !== null) {
$pCoordinate = $namedRange->getRange();
if ($this->getHashCode() != $namedRange->getWorksheet()->getHashCode()) {
if (!$namedRange->getLocalOnly()) {
@@ -1267,8 +1267,8 @@ class Worksheet implements IComparable
// Get row dimension
if (!isset($this->_rowDimensions[$pRow])) {
- if (!$create)
- return NULL;
+ if (!$create)
+ return null;
$this->_rowDimensions[$pRow] = new Worksheet_RowDimension($pRow);
$this->_cachedHighestRow = max($this->_cachedHighestRow,$pRow);
@@ -1289,8 +1289,8 @@ class Worksheet implements IComparable
// Fetch dimensions
if (!isset($this->_columnDimensions[$pColumn])) {
- if (!$create)
- return NULL;
+ if (!$create)
+ return null;
$this->_columnDimensions[$pColumn] = new Worksheet_ColumnDimension($pColumn);
if (Cell::columnIndexFromString($this->_cachedHighestColumn) < Cell::columnIndexFromString($pColumn))
@@ -1530,7 +1530,7 @@ class Worksheet implements IComparable
*
* Please note that this will overwrite existing cell styles for cells in range!
*
- * @param array of PHPExcel\Style_Conditional $pCellStyle Cell style to duplicate
+ * @param array of PHPExcel\Style_Conditional $pCellStyle Cell style to duplicate
* @param string $pRange Range of cells (i.e. "A1:B10"), or just one cell (i.e. "A1")
* @throws PHPExcel\Exception
* @return PHPExcel\Worksheet
@@ -1615,13 +1615,13 @@ class Worksheet implements IComparable
$pCell = strtoupper($pCell);
if ($pCell != '') {
- if ($pBreak == self::BREAK_NONE) {
- if (isset($this->_breaks[$pCell])) {
- unset($this->_breaks[$pCell]);
- }
- } else {
- $this->_breaks[$pCell] = $pBreak;
- }
+ if ($pBreak == self::BREAK_NONE) {
+ if (isset($this->_breaks[$pCell])) {
+ unset($this->_breaks[$pCell]);
+ }
+ } else {
+ $this->_breaks[$pCell] = $pBreak;
+ }
} else {
throw new Exception('No cell coordinate specified.');
}
@@ -1913,7 +1913,7 @@ class Worksheet implements IComparable
*/
public function removeAutoFilter()
{
- $this->_autoFilter->setRange(NULL);
+ $this->_autoFilter->setRange(null);
return $this;
}
@@ -2193,7 +2193,7 @@ class Worksheet implements IComparable
/**
* Set comments array for the entire sheet.
*
- * @param array of PHPExcel\Comment
+ * @param array of PHPExcel\Comment
* @return PHPExcel\Worksheet
*/
public function setComments($pValue = array())
@@ -2411,7 +2411,7 @@ class Worksheet implements IComparable
* True - Return rows and columns indexed by their actual row and column IDs
* @return array
*/
- public function rangeToArray($pRange = 'A1', $nullValue = null, $calculateFormulas = true, $formatData = true, $returnCellRef = false) {
+ public function rangeToArray($pRange = 'A1', $nullValue = null, $calculateFormulas = true, $formatData = true, $returnCellRef = false) {
// Returnvalue
$returnValue = array();
// Identify the range that we need to extract from the worksheet
@@ -2449,14 +2449,14 @@ class Worksheet implements IComparable
if ($formatData) {
$style = $this->_parent->getCellXfByIndex($cell->getXfIndex());
$returnValue[$rRef][$cRef] = Style_NumberFormat::toFormattedString(
- $returnValue[$rRef][$cRef],
- ($style->getNumberFormat()) ?
- $style->getNumberFormat()->getFormatCode() :
- Style_NumberFormat::FORMAT_GENERAL
+ $returnValue[$rRef][$cRef],
+ ($style->getNumberFormat()) ?
+ $style->getNumberFormat()->getFormatCode() :
+ Style_NumberFormat::FORMAT_GENERAL
);
}
} else {
- // Cell holds a NULL
+ // Cell holds a null
$returnValue[$rRef][$cRef] = $nullValue;
}
} else {
@@ -2483,14 +2483,14 @@ class Worksheet implements IComparable
* @return array
* @throws PHPExcel\Exception
*/
- public function namedRangeToArray($pNamedRange = '', $nullValue = null, $calculateFormulas = true, $formatData = true, $returnCellRef = false) {
+ public function namedRangeToArray($pNamedRange = '', $nullValue = null, $calculateFormulas = true, $formatData = true, $returnCellRef = false) {
$namedRange = NamedRange::resolveRange($pNamedRange, $this);
- if ($namedRange !== NULL) {
+ if ($namedRange !== null) {
$pWorkSheet = $namedRange->getWorksheet();
$pCellRange = $namedRange->getRange();
- return $pWorkSheet->rangeToArray( $pCellRange,
- $nullValue, $calculateFormulas, $formatData, $returnCellRef);
+ return $pWorkSheet->rangeToArray( $pCellRange,
+ $nullValue, $calculateFormulas, $formatData, $returnCellRef);
}
throw new Exception('Named Range '.$pNamedRange.' does not exist.');
@@ -2507,7 +2507,7 @@ class Worksheet implements IComparable
* True - Return rows and columns indexed by their actual row and column IDs
* @return array
*/
- public function toArray($nullValue = null, $calculateFormulas = true, $formatData = true, $returnCellRef = false) {
+ public function toArray($nullValue = null, $calculateFormulas = true, $formatData = true, $returnCellRef = false) {
// Garbage collect...
$this->garbageCollect();
@@ -2515,8 +2515,8 @@ class Worksheet implements IComparable
$maxCol = $this->getHighestColumn();
$maxRow = $this->getHighestRow();
// Return
- return $this->rangeToArray( 'A1:'.$maxCol.$maxRow,
- $nullValue, $calculateFormulas, $formatData, $returnCellRef);
+ return $this->rangeToArray( 'A1:'.$maxCol.$maxRow,
+ $nullValue, $calculateFormulas, $formatData, $returnCellRef);
}
/**
@@ -2525,7 +2525,7 @@ class Worksheet implements IComparable
* @param integer $startRow The row number at which to start iterating
* @return PHPExcel\Worksheet_RowIterator
*/
- public function getRowIterator($startRow = 1) {
+ public function getRowIterator($startRow = 1) {
return new Worksheet_RowIterator($this,$startRow);
}
@@ -2534,7 +2534,7 @@ class Worksheet implements IComparable
*
* @return PHPExcel\Worksheet
*/
- public function garbageCollect() {
+ public function garbageCollect() {
// Flush cache
$this->_cellCollection->getCacheData('A1');
// Build a reference table from images
@@ -2578,7 +2578,7 @@ class Worksheet implements IComparable
*
* @return string Hash code
*/
- public function getHashCode() {
+ public function getHashCode() {
if ($this->_dirty) {
$this->_hash = md5( $this->_title .
$this->_autoFilter .
@@ -2600,7 +2600,7 @@ class Worksheet implements IComparable
* @param bool $returnRange Return range? (see example)
* @return mixed
*/
- public static function extractSheetTitle($pRange, $returnRange = false) {
+ public static function extractSheetTitle($pRange, $returnRange = false) {
// Sheet title included?
if (($sep = strpos($pRange, '!')) === false) {
return '';
@@ -2731,7 +2731,7 @@ class Worksheet implements IComparable
* @param string $range
* @return string Adjusted range value
*/
- public function shrinkRangeToFit($range) {
+ public function shrinkRangeToFit($range) {
$maxCol = $this->getHighestColumn();
$maxRow = $this->getHighestRow();
$maxCol = Cell::columnIndexFromString($maxCol);
@@ -2759,7 +2759,7 @@ class Worksheet implements IComparable
*/
public function getTabColor()
{
- if ($this->_tabColor === NULL)
+ if ($this->_tabColor === null)
$this->_tabColor = new Style_Color();
return $this->_tabColor;
@@ -2785,7 +2785,7 @@ class Worksheet implements IComparable
*/
public function isTabColorSet()
{
- return ($this->_tabColor !== NULL);
+ return ($this->_tabColor !== null);
}
/**
@@ -2793,7 +2793,7 @@ class Worksheet implements IComparable
*
* @return PHPExcel\Worksheet
*/
- public function copy() {
+ public function copy() {
$copied = clone $this;
return $copied;
@@ -2802,7 +2802,7 @@ class Worksheet implements IComparable
/**
* Implement PHP __clone to create a deep clone, not just a shallow copy.
*/
- public function __clone() {
+ public function __clone() {
foreach ($this as $key => $val) {
if ($key == '_parent') {
continue;
diff --git a/Classes/PHPExcel/Worksheet/AutoFilter.php b/Classes/PHPExcel/Worksheet/AutoFilter.php
index 637b283..608d426 100644
--- a/Classes/PHPExcel/Worksheet/AutoFilter.php
+++ b/Classes/PHPExcel/Worksheet/AutoFilter.php
@@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\Worksheet
* @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,824 +37,823 @@ namespace PHPExcel;
*/
class Worksheet_AutoFilter
{
- /**
- * Autofilter Worksheet
- *
- * @var PHPExcel\Worksheet
- */
- protected $_workSheet = NULL;
+ /**
+ * Autofilter Worksheet
+ *
+ * @var PHPExcel\Worksheet
+ */
+ protected $_workSheet = null;
- /**
- * Autofilter Range
- *
- * @var string
- */
- protected $_range = '';
+ /**
+ * Autofilter Range
+ *
+ * @var string
+ */
+ protected $_range = '';
- /**
- * Autofilter Column Ruleset
- *
- * @var array of PHPExcel\Worksheet_AutoFilter_Column
- */
- protected $_columns = array();
+ /**
+ * Autofilter Column Ruleset
+ *
+ * @var array of PHPExcel\Worksheet_AutoFilter_Column
+ */
+ protected $_columns = array();
/**
* Create a new PHPExcel\Worksheet_AutoFilter
- *
- * @param string $pRange Cell range (i.e. A1:E10)
- * @param PHPExcel\Worksheet $pSheet
+ *
+ * @param string $pRange Cell range (i.e. A1:E10)
+ * @param PHPExcel\Worksheet $pSheet
*/
- public function __construct($pRange = '', Worksheet $pSheet = NULL)
+ public function __construct($pRange = '', Worksheet $pSheet = null)
{
- $this->_range = $pRange;
- $this->_workSheet = $pSheet;
+ $this->_range = $pRange;
+ $this->_workSheet = $pSheet;
}
- /**
- * Get AutoFilter Parent Worksheet
- *
- * @return PHPExcel\Worksheet
- */
- public function getParent() {
- return $this->_workSheet;
- }
+ /**
+ * Get AutoFilter Parent Worksheet
+ *
+ * @return PHPExcel\Worksheet
+ */
+ public function getParent() {
+ return $this->_workSheet;
+ }
- /**
- * Set AutoFilter Parent Worksheet
- *
- * @param PHPExcel\Worksheet $pSheet
- * @return PHPExcel\Worksheet_AutoFilter
- */
- public function setParent(Worksheet $pSheet = NULL) {
- $this->_workSheet = $pSheet;
+ /**
+ * Set AutoFilter Parent Worksheet
+ *
+ * @param PHPExcel\Worksheet $pSheet
+ * @return PHPExcel\Worksheet_AutoFilter
+ */
+ public function setParent(Worksheet $pSheet = null) {
+ $this->_workSheet = $pSheet;
- return $this;
- }
+ return $this;
+ }
- /**
- * Get AutoFilter Range
- *
- * @return string
- */
- public function getRange() {
- return $this->_range;
- }
+ /**
+ * Get AutoFilter Range
+ *
+ * @return string
+ */
+ public function getRange() {
+ return $this->_range;
+ }
- /**
- * Set AutoFilter Range
- *
- * @param string $pRange Cell range (i.e. A1:E10)
- * @throws PHPExcel\Exception
- * @return PHPExcel\Worksheet_AutoFilter
- */
- public function setRange($pRange = '') {
- // Uppercase coordinate
- $cellAddress = explode('!',strtoupper($pRange));
- if (count($cellAddress) > 1) {
- list($worksheet,$pRange) = $cellAddress;
- }
+ /**
+ * Set AutoFilter Range
+ *
+ * @param string $pRange Cell range (i.e. A1:E10)
+ * @throws PHPExcel\Exception
+ * @return PHPExcel\Worksheet_AutoFilter
+ */
+ public function setRange($pRange = '') {
+ // Uppercase coordinate
+ $cellAddress = explode('!',strtoupper($pRange));
+ if (count($cellAddress) > 1) {
+ list($worksheet,$pRange) = $cellAddress;
+ }
- if (strpos($pRange,':') !== FALSE) {
- $this->_range = $pRange;
- } elseif(empty($pRange)) {
- $this->_range = '';
- } else {
- throw new Exception('Autofilter must be set on a range of cells.');
- }
+ if (strpos($pRange,':') !== false) {
+ $this->_range = $pRange;
+ } elseif(empty($pRange)) {
+ $this->_range = '';
+ } else {
+ throw new Exception('Autofilter must be set on a range of cells.');
+ }
- if (empty($pRange)) {
- // Discard all column rules
- $this->_columns = array();
- } else {
- // Discard any column rules that are no longer valid within this range
- list($rangeStart,$rangeEnd) = Cell::rangeBoundaries($this->_range);
- foreach($this->_columns as $key => $value) {
- $colIndex = Cell::columnIndexFromString($key);
- if (($rangeStart[0] > $colIndex) || ($rangeEnd[0] < $colIndex)) {
- unset($this->_columns[$key]);
- }
- }
- }
+ if (empty($pRange)) {
+ // Discard all column rules
+ $this->_columns = array();
+ } else {
+ // Discard any column rules that are no longer valid within this range
+ list($rangeStart,$rangeEnd) = Cell::rangeBoundaries($this->_range);
+ foreach($this->_columns as $key => $value) {
+ $colIndex = Cell::columnIndexFromString($key);
+ if (($rangeStart[0] > $colIndex) || ($rangeEnd[0] < $colIndex)) {
+ unset($this->_columns[$key]);
+ }
+ }
+ }
- return $this;
- }
+ return $this;
+ }
- /**
- * Get all AutoFilter Columns
- *
- * @throws PHPExcel\Exception
- * @return array of PHPExcel\Worksheet_AutoFilter_Column
- */
- public function getColumns() {
- return $this->_columns;
- }
+ /**
+ * Get all AutoFilter Columns
+ *
+ * @throws PHPExcel\Exception
+ * @return array of PHPExcel\Worksheet_AutoFilter_Column
+ */
+ public function getColumns() {
+ return $this->_columns;
+ }
- /**
- * Validate that the specified column is in the AutoFilter range
- *
- * @param string $column Column name (e.g. A)
- * @throws PHPExcel\Exception
- * @return integer The column offset within the autofilter range
- */
- public function testColumnInRange($column) {
- if (empty($this->_range)) {
- throw new Exception("No autofilter range is defined.");
- }
+ /**
+ * Validate that the specified column is in the AutoFilter range
+ *
+ * @param string $column Column name (e.g. A)
+ * @throws PHPExcel\Exception
+ * @return integer The column offset within the autofilter range
+ */
+ public function testColumnInRange($column) {
+ if (empty($this->_range)) {
+ throw new Exception("No autofilter range is defined.");
+ }
- $columnIndex = Cell::columnIndexFromString($column);
- list($rangeStart,$rangeEnd) = Cell::rangeBoundaries($this->_range);
- if (($rangeStart[0] > $columnIndex) || ($rangeEnd[0] < $columnIndex)) {
- throw new Exception("Column is outside of current autofilter range.");
- }
+ $columnIndex = Cell::columnIndexFromString($column);
+ list($rangeStart,$rangeEnd) = Cell::rangeBoundaries($this->_range);
+ if (($rangeStart[0] > $columnIndex) || ($rangeEnd[0] < $columnIndex)) {
+ throw new Exception("Column is outside of current autofilter range.");
+ }
- return $columnIndex - $rangeStart[0];
- }
+ return $columnIndex - $rangeStart[0];
+ }
- /**
- * Get a specified AutoFilter Column Offset within the defined AutoFilter range
- *
- * @param string $pColumn Column name (e.g. A)
- * @throws PHPExcel\Exception
- * @return integer The offset of the specified column within the autofilter range
- */
- public function getColumnOffset($pColumn) {
- return $this->testColumnInRange($pColumn);
- }
+ /**
+ * Get a specified AutoFilter Column Offset within the defined AutoFilter range
+ *
+ * @param string $pColumn Column name (e.g. A)
+ * @throws PHPExcel\Exception
+ * @return integer The offset of the specified column within the autofilter range
+ */
+ public function getColumnOffset($pColumn) {
+ return $this->testColumnInRange($pColumn);
+ }
- /**
- * Get a specified AutoFilter Column
- *
- * @param string $pColumn Column name (e.g. A)
- * @throws PHPExcel\Exception
- * @return PHPExcel\Worksheet_AutoFilter_Column
- */
- public function getColumn($pColumn) {
- $this->testColumnInRange($pColumn);
+ /**
+ * Get a specified AutoFilter Column
+ *
+ * @param string $pColumn Column name (e.g. A)
+ * @throws PHPExcel\Exception
+ * @return PHPExcel\Worksheet_AutoFilter_Column
+ */
+ public function getColumn($pColumn) {
+ $this->testColumnInRange($pColumn);
- if (!isset($this->_columns[$pColumn])) {
- $this->_columns[$pColumn] = new Worksheet_AutoFilter_Column($pColumn, $this);
- }
+ if (!isset($this->_columns[$pColumn])) {
+ $this->_columns[$pColumn] = new Worksheet_AutoFilter_Column($pColumn, $this);
+ }
- return $this->_columns[$pColumn];
- }
+ return $this->_columns[$pColumn];
+ }
- /**
- * Get a specified AutoFilter Column by it's offset
- *
- * @param integer $pColumnOffset Column offset within range (starting from 0)
- * @throws PHPExcel\Exception
- * @return PHPExcel\Worksheet_AutoFilter_Column
- */
- public function getColumnByOffset($pColumnOffset = 0) {
- list($rangeStart,$rangeEnd) = Cell::rangeBoundaries($this->_range);
- $pColumn = Cell::stringFromColumnIndex($rangeStart[0] + $pColumnOffset - 1);
+ /**
+ * Get a specified AutoFilter Column by it's offset
+ *
+ * @param integer $pColumnOffset Column offset within range (starting from 0)
+ * @throws PHPExcel\Exception
+ * @return PHPExcel\Worksheet_AutoFilter_Column
+ */
+ public function getColumnByOffset($pColumnOffset = 0) {
+ list($rangeStart,$rangeEnd) = Cell::rangeBoundaries($this->_range);
+ $pColumn = Cell::stringFromColumnIndex($rangeStart[0] + $pColumnOffset - 1);
- return $this->getColumn($pColumn);
- }
+ return $this->getColumn($pColumn);
+ }
- /**
- * Set AutoFilter
- *
- * @param PHPExcel\Worksheet_AutoFilter_Column|string $pColumn
- * A simple string containing a Column ID like 'A' is permitted
- * @throws PHPExcel\Exception
- * @return PHPExcel\Worksheet_AutoFilter
- */
- public function setColumn($pColumn)
- {
- if ((is_string($pColumn)) && (!empty($pColumn))) {
- $column = $pColumn;
- } elseif(is_object($pColumn) && ($pColumn instanceof Worksheet_AutoFilter_Column)) {
- $column = $pColumn->getColumnIndex();
- } else {
- throw new Exception("Column is not within the autofilter range.");
- }
- $this->testColumnInRange($column);
+ /**
+ * Set AutoFilter
+ *
+ * @param PHPExcel\Worksheet_AutoFilter_Column|string $pColumn
+ * A simple string containing a Column ID like 'A' is permitted
+ * @throws PHPExcel\Exception
+ * @return PHPExcel\Worksheet_AutoFilter
+ */
+ public function setColumn($pColumn)
+ {
+ if ((is_string($pColumn)) && (!empty($pColumn))) {
+ $column = $pColumn;
+ } elseif(is_object($pColumn) && ($pColumn instanceof Worksheet_AutoFilter_Column)) {
+ $column = $pColumn->getColumnIndex();
+ } else {
+ throw new Exception("Column is not within the autofilter range.");
+ }
+ $this->testColumnInRange($column);
- if (is_string($pColumn)) {
- $this->_columns[$pColumn] = new Worksheet_AutoFilter_Column($pColumn, $this);
- } elseif(is_object($pColumn) && ($pColumn instanceof Worksheet_AutoFilter_Column)) {
- $pColumn->setParent($this);
- $this->_columns[$column] = $pColumn;
- }
- ksort($this->_columns);
+ if (is_string($pColumn)) {
+ $this->_columns[$pColumn] = new Worksheet_AutoFilter_Column($pColumn, $this);
+ } elseif(is_object($pColumn) && ($pColumn instanceof Worksheet_AutoFilter_Column)) {
+ $pColumn->setParent($this);
+ $this->_columns[$column] = $pColumn;
+ }
+ ksort($this->_columns);
- return $this;
- }
+ return $this;
+ }
- /**
- * Clear a specified AutoFilter Column
- *
- * @param string $pColumn Column name (e.g. A)
- * @throws PHPExcel\Exception
- * @return PHPExcel\Worksheet_AutoFilter
- */
- public function clearColumn($pColumn) {
- $this->testColumnInRange($pColumn);
+ /**
+ * Clear a specified AutoFilter Column
+ *
+ * @param string $pColumn Column name (e.g. A)
+ * @throws PHPExcel\Exception
+ * @return PHPExcel\Worksheet_AutoFilter
+ */
+ public function clearColumn($pColumn) {
+ $this->testColumnInRange($pColumn);
- if (isset($this->_columns[$pColumn])) {
- unset($this->_columns[$pColumn]);
- }
+ if (isset($this->_columns[$pColumn])) {
+ unset($this->_columns[$pColumn]);
+ }
- return $this;
- }
+ return $this;
+ }
- /**
- * Shift an AutoFilter Column Rule to a different column
- *
- * Note: This method bypasses validation of the destination column to ensure it is within this AutoFilter range.
- * Nor does it verify whether any column rule already exists at $toColumn, but will simply overrideany existing value.
- * Use with caution.
- *
- * @param string $fromColumn Column name (e.g. A)
- * @param string $toColumn Column name (e.g. B)
- * @return PHPExcel\Worksheet_AutoFilter
- */
- public function shiftColumn($fromColumn=NULL,$toColumn=NULL) {
- $fromColumn = strtoupper($fromColumn);
- $toColumn = strtoupper($toColumn);
+ /**
+ * Shift an AutoFilter Column Rule to a different column
+ *
+ * Note: This method bypasses validation of the destination column to ensure it is within this AutoFilter range.
+ * Nor does it verify whether any column rule already exists at $toColumn, but will simply overrideany existing value.
+ * Use with caution.
+ *
+ * @param string $fromColumn Column name (e.g. A)
+ * @param string $toColumn Column name (e.g. B)
+ * @return PHPExcel\Worksheet_AutoFilter
+ */
+ public function shiftColumn($fromColumn=null, $toColumn=null) {
+ $fromColumn = strtoupper($fromColumn);
+ $toColumn = strtoupper($toColumn);
- if (($fromColumn !== NULL) && (isset($this->_columns[$fromColumn])) && ($toColumn !== NULL)) {
- $this->_columns[$fromColumn]->setParent();
- $this->_columns[$fromColumn]->setColumnIndex($toColumn);
- $this->_columns[$toColumn] = $this->_columns[$fromColumn];
- $this->_columns[$toColumn]->setParent($this);
- unset($this->_columns[$fromColumn]);
+ if (($fromColumn !== null) && (isset($this->_columns[$fromColumn])) && ($toColumn !== null)) {
+ $this->_columns[$fromColumn]->setParent();
+ $this->_columns[$fromColumn]->setColumnIndex($toColumn);
+ $this->_columns[$toColumn] = $this->_columns[$fromColumn];
+ $this->_columns[$toColumn]->setParent($this);
+ unset($this->_columns[$fromColumn]);
- ksort($this->_columns);
- }
+ ksort($this->_columns);
+ }
- return $this;
- }
+ return $this;
+ }
- /**
- * Test if cell value is in the defined set of values
- *
- * @param mixed $cellValue
- * @param mixed[] $dataSet
- * @return boolean
- */
- private static function _filterTestInSimpleDataSet($cellValue,$dataSet)
- {
- $dataSetValues = $dataSet['filterValues'];
- $blanks = $dataSet['blanks'];
- if (($cellValue == '') || ($cellValue === NULL)) {
- return $blanks;
- }
- return in_array($cellValue,$dataSetValues);
- }
+ /**
+ * Test if cell value is in the defined set of values
+ *
+ * @param mixed $cellValue
+ * @param mixed[] $dataSet
+ * @return boolean
+ */
+ private static function _filterTestInSimpleDataSet($cellValue,$dataSet)
+ {
+ $dataSetValues = $dataSet['filterValues'];
+ $blanks = $dataSet['blanks'];
+ if (($cellValue == '') || ($cellValue === null)) {
+ return $blanks;
+ }
+ return in_array($cellValue,$dataSetValues);
+ }
- /**
- * Test if cell value is in the defined set of Excel date values
- *
- * @param mixed $cellValue
- * @param mixed[] $dataSet
- * @return boolean
- */
- private static function _filterTestInDateGroupSet($cellValue,$dataSet)
- {
- $dateSet = $dataSet['filterValues'];
- $blanks = $dataSet['blanks'];
- if (($cellValue == '') || ($cellValue === NULL)) {
- return $blanks;
- }
+ /**
+ * Test if cell value is in the defined set of Excel date values
+ *
+ * @param mixed $cellValue
+ * @param mixed[] $dataSet
+ * @return boolean
+ */
+ private static function _filterTestInDateGroupSet($cellValue,$dataSet)
+ {
+ $dateSet = $dataSet['filterValues'];
+ $blanks = $dataSet['blanks'];
+ if (($cellValue == '') || ($cellValue === null)) {
+ return $blanks;
+ }
- if (is_numeric($cellValue)) {
- $dateValue = Shared_Date::ExcelToPHP($cellValue);
- if ($cellValue < 1) {
- // Just the time part
- $dtVal = date('His',$dateValue);
- $dateSet = $dateSet['time'];
- } elseif($cellValue == floor($cellValue)) {
- // Just the date part
- $dtVal = date('Ymd',$dateValue);
- $dateSet = $dateSet['date'];
- } else {
- // date and time parts
- $dtVal = date('YmdHis',$dateValue);
- $dateSet = $dateSet['dateTime'];
- }
- foreach($dateSet as $dateValue) {
- // Use of substr to extract value at the appropriate group level
- if (substr($dtVal,0,strlen($dateValue)) == $dateValue)
- return TRUE;
- }
- }
+ if (is_numeric($cellValue)) {
+ $dateValue = Shared_Date::ExcelToPHP($cellValue);
+ if ($cellValue < 1) {
+ // Just the time part
+ $dtVal = date('His',$dateValue);
+ $dateSet = $dateSet['time'];
+ } elseif($cellValue == floor($cellValue)) {
+ // Just the date part
+ $dtVal = date('Ymd',$dateValue);
+ $dateSet = $dateSet['date'];
+ } else {
+ // date and time parts
+ $dtVal = date('YmdHis',$dateValue);
+ $dateSet = $dateSet['dateTime'];
+ }
+ foreach($dateSet as $dateValue) {
+ // Use of substr to extract value at the appropriate group level
+ if (substr($dtVal,0,strlen($dateValue)) == $dateValue)
+ return TRUE;
+ }
+ }
- return FALSE;
- }
+ return false;
+ }
- /**
- * Test if cell value is within a set of values defined by a ruleset
- *
- * @param mixed $cellValue
- * @param mixed[] $ruleSet
- * @return boolean
- */
- private static function _filterTestInCustomDataSet($cellValue, $ruleSet)
- {
- $dataSet = $ruleSet['filterRules'];
- $join = $ruleSet['join'];
- $customRuleForBlanks = isset($ruleSet['customRuleForBlanks']) ? $ruleSet['customRuleForBlanks'] : FALSE;
+ /**
+ * Test if cell value is within a set of values defined by a ruleset
+ *
+ * @param mixed $cellValue
+ * @param mixed[] $ruleSet
+ * @return boolean
+ */
+ private static function _filterTestInCustomDataSet($cellValue, $ruleSet)
+ {
+ $dataSet = $ruleSet['filterRules'];
+ $join = $ruleSet['join'];
+ $customRuleForBlanks = isset($ruleSet['customRuleForBlanks']) ? $ruleSet['customRuleForBlanks'] : false;
- if (!$customRuleForBlanks) {
- // Blank cells are always ignored, so return a FALSE
- if (($cellValue == '') || ($cellValue === NULL)) {
- return FALSE;
- }
- }
- $returnVal = ($join == Worksheet_AutoFilter_Column::AUTOFILTER_COLUMN_JOIN_AND);
- foreach($dataSet as $rule) {
- if (is_numeric($rule['value'])) {
- // Numeric values are tested using the appropriate operator
- switch ($rule['operator']) {
- case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_EQUAL :
- $retVal = ($cellValue == $rule['value']);
- break;
- case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_NOTEQUAL :
- $retVal = ($cellValue != $rule['value']);
- break;
- case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_GREATERTHAN :
- $retVal = ($cellValue > $rule['value']);
- break;
- case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL :
- $retVal = ($cellValue >= $rule['value']);
- break;
- case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_LESSTHAN :
- $retVal = ($cellValue < $rule['value']);
- break;
- case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_LESSTHANOREQUAL :
- $retVal = ($cellValue <= $rule['value']);
- break;
- }
- } elseif($rule['value'] == '') {
- switch ($rule['operator']) {
- case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_EQUAL :
- $retVal = (($cellValue == '') || ($cellValue === NULL));
- break;
- case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_NOTEQUAL :
- $retVal = (($cellValue != '') && ($cellValue !== NULL));
- break;
- default :
- $retVal = TRUE;
- break;
- }
- } else {
- // String values are always tested for equality, factoring in for wildcards (hence a regexp test)
- $retVal = preg_match('/^'.$rule['value'].'$/i',$cellValue);
- }
- // If there are multiple conditions, then we need to test both using the appropriate join operator
- switch ($join) {
- case Worksheet_AutoFilter_Column::AUTOFILTER_COLUMN_JOIN_OR :
- $returnVal = $returnVal || $retVal;
- // Break as soon as we have a TRUE match for OR joins,
- // to avoid unnecessary additional code execution
- if ($returnVal)
- return $returnVal;
- break;
- case Worksheet_AutoFilter_Column::AUTOFILTER_COLUMN_JOIN_AND :
- $returnVal = $returnVal && $retVal;
- break;
- }
- }
+ if (!$customRuleForBlanks) {
+ // Blank cells are always ignored, so return a FALSE
+ if (($cellValue == '') || ($cellValue === null)) {
+ return false;
+ }
+ }
+ $returnVal = ($join == Worksheet_AutoFilter_Column::AUTOFILTER_COLUMN_JOIN_AND);
+ foreach($dataSet as $rule) {
+ if (is_numeric($rule['value'])) {
+ // Numeric values are tested using the appropriate operator
+ switch ($rule['operator']) {
+ case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_EQUAL :
+ $retVal = ($cellValue == $rule['value']);
+ break;
+ case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_NOTEQUAL :
+ $retVal = ($cellValue != $rule['value']);
+ break;
+ case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_GREATERTHAN :
+ $retVal = ($cellValue > $rule['value']);
+ break;
+ case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL :
+ $retVal = ($cellValue >= $rule['value']);
+ break;
+ case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_LESSTHAN :
+ $retVal = ($cellValue < $rule['value']);
+ break;
+ case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_LESSTHANOREQUAL :
+ $retVal = ($cellValue <= $rule['value']);
+ break;
+ }
+ } elseif($rule['value'] == '') {
+ switch ($rule['operator']) {
+ case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_EQUAL :
+ $retVal = (($cellValue == '') || ($cellValue === null));
+ break;
+ case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_NOTEQUAL :
+ $retVal = (($cellValue != '') && ($cellValue !== null));
+ break;
+ default :
+ $retVal = TRUE;
+ break;
+ }
+ } else {
+ // String values are always tested for equality, factoring in for wildcards (hence a regexp test)
+ $retVal = preg_match('/^'.$rule['value'].'$/i',$cellValue);
+ }
+ // If there are multiple conditions, then we need to test both using the appropriate join operator
+ switch ($join) {
+ case Worksheet_AutoFilter_Column::AUTOFILTER_COLUMN_JOIN_OR :
+ $returnVal = $returnVal || $retVal;
+ // Break as soon as we have a TRUE match for OR joins,
+ // to avoid unnecessary additional code execution
+ if ($returnVal)
+ return $returnVal;
+ break;
+ case Worksheet_AutoFilter_Column::AUTOFILTER_COLUMN_JOIN_AND :
+ $returnVal = $returnVal && $retVal;
+ break;
+ }
+ }
- return $returnVal;
- }
+ return $returnVal;
+ }
- /**
- * Test if cell date value is matches a set of values defined by a set of months
- *
- * @param mixed $cellValue
- * @param mixed[] $monthSet
- * @return boolean
- */
- private static function _filterTestInPeriodDateSet($cellValue, $monthSet)
- {
- // Blank cells are always ignored, so return a FALSE
- if (($cellValue == '') || ($cellValue === NULL)) {
- return FALSE;
- }
+ /**
+ * Test if cell date value is matches a set of values defined by a set of months
+ *
+ * @param mixed $cellValue
+ * @param mixed[] $monthSet
+ * @return boolean
+ */
+ private static function _filterTestInPeriodDateSet($cellValue, $monthSet)
+ {
+ // Blank cells are always ignored, so return a FALSE
+ if (($cellValue == '') || ($cellValue === null)) {
+ return false;
+ }
- if (is_numeric($cellValue)) {
- $dateValue = date('m',Shared_Date::ExcelToPHP($cellValue));
- if (in_array($dateValue,$monthSet)) {
- return TRUE;
- }
- }
+ if (is_numeric($cellValue)) {
+ $dateValue = date('m',Shared_Date::ExcelToPHP($cellValue));
+ if (in_array($dateValue,$monthSet)) {
+ return TRUE;
+ }
+ }
- return FALSE;
- }
+ return false;
+ }
- /**
- * Search/Replace arrays to convert Excel wildcard syntax to a regexp syntax for preg_matching
- *
- * @var array
- */
- private static $_fromReplace = array('\*', '\?', '~~', '~.*', '~.?');
- private static $_toReplace = array('.*', '.', '~', '\*', '\?');
+ /**
+ * Search/Replace arrays to convert Excel wildcard syntax to a regexp syntax for preg_matching
+ *
+ * @var array
+ */
+ private static $_fromReplace = array('\*', '\?', '~~', '~.*', '~.?');
+ private static $_toReplace = array('.*', '.', '~', '\*', '\?');
- /**
- * Convert a dynamic rule daterange to a custom filter range expression for ease of calculation
- *
- * @param string $dynamicRuleType
- * @param PHPExcel\Worksheet_AutoFilter_Column &$filterColumn
- * @return mixed[]
- */
- private function _dynamicFilterDateRange($dynamicRuleType, &$filterColumn)
- {
- $rDateType = Calculation_Functions::getReturnDateType();
- Calculation_Functions::setReturnDateType(Calculation_Functions::RETURNDATE_PHP_NUMERIC);
- $val = $maxVal = NULL;
+ /**
+ * Convert a dynamic rule daterange to a custom filter range expression for ease of calculation
+ *
+ * @param string $dynamicRuleType
+ * @param PHPExcel\Worksheet_AutoFilter_Column &$filterColumn
+ * @return mixed[]
+ */
+ private function _dynamicFilterDateRange($dynamicRuleType, &$filterColumn)
+ {
+ $rDateType = Calculation_Functions::getReturnDateType();
+ Calculation_Functions::setReturnDateType(Calculation_Functions::RETURNDATE_PHP_NUMERIC);
+ $val = $maxVal = null;
- $ruleValues = array();
- $baseDate = Calculation_DateTime::DATENOW();
- // Calculate start/end dates for the required date range based on current date
- switch ($dynamicRuleType) {
- case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTWEEK :
- $baseDate = strtotime('-7 days',$baseDate);
- break;
- case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTWEEK :
- $baseDate = strtotime('-7 days',$baseDate);
- break;
- case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTMONTH :
- $baseDate = strtotime('-1 month',gmmktime(0,0,0,1,date('m',$baseDate),date('Y',$baseDate)));
- break;
- case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTMONTH :
- $baseDate = strtotime('+1 month',gmmktime(0,0,0,1,date('m',$baseDate),date('Y',$baseDate)));
- break;
- case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTQUARTER :
- $baseDate = strtotime('-3 month',gmmktime(0,0,0,1,date('m',$baseDate),date('Y',$baseDate)));
- break;
- case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTQUARTER :
- $baseDate = strtotime('+3 month',gmmktime(0,0,0,1,date('m',$baseDate),date('Y',$baseDate)));
- break;
- case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTYEAR :
- $baseDate = strtotime('-1 year',gmmktime(0,0,0,1,date('m',$baseDate),date('Y',$baseDate)));
- break;
- case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTYEAR :
- $baseDate = strtotime('+1 year',gmmktime(0,0,0,1,date('m',$baseDate),date('Y',$baseDate)));
- break;
- }
+ $ruleValues = array();
+ $baseDate = Calculation_DateTime::DATENOW();
+ // Calculate start/end dates for the required date range based on current date
+ switch ($dynamicRuleType) {
+ case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTWEEK :
+ $baseDate = strtotime('-7 days',$baseDate);
+ break;
+ case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTWEEK :
+ $baseDate = strtotime('-7 days',$baseDate);
+ break;
+ case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTMONTH :
+ $baseDate = strtotime('-1 month',gmmktime(0,0,0,1,date('m',$baseDate),date('Y',$baseDate)));
+ break;
+ case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTMONTH :
+ $baseDate = strtotime('+1 month',gmmktime(0,0,0,1,date('m',$baseDate),date('Y',$baseDate)));
+ break;
+ case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTQUARTER :
+ $baseDate = strtotime('-3 month',gmmktime(0,0,0,1,date('m',$baseDate),date('Y',$baseDate)));
+ break;
+ case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTQUARTER :
+ $baseDate = strtotime('+3 month',gmmktime(0,0,0,1,date('m',$baseDate),date('Y',$baseDate)));
+ break;
+ case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTYEAR :
+ $baseDate = strtotime('-1 year',gmmktime(0,0,0,1,date('m',$baseDate),date('Y',$baseDate)));
+ break;
+ case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTYEAR :
+ $baseDate = strtotime('+1 year',gmmktime(0,0,0,1,date('m',$baseDate),date('Y',$baseDate)));
+ break;
+ }
- switch ($dynamicRuleType) {
- case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_TODAY :
- case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_YESTERDAY :
- case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_TOMORROW :
- $maxVal = (int) Shared_Date::PHPtoExcel(strtotime('+1 day',$baseDate));
- $val = (int) Shared_Date::PHPToExcel($baseDate);
- break;
- case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_YEARTODATE :
- $maxVal = (int) Shared_Date::PHPtoExcel(strtotime('+1 day',$baseDate));
- $val = (int) Shared_Date::PHPToExcel(gmmktime(0,0,0,1,1,date('Y',$baseDate)));
- break;
- case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISYEAR :
- case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTYEAR :
- case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTYEAR :
- $maxVal = (int) Shared_Date::PHPToExcel(gmmktime(0,0,0,31,12,date('Y',$baseDate)));
- ++$maxVal;
- $val = (int) Shared_Date::PHPToExcel(gmmktime(0,0,0,1,1,date('Y',$baseDate)));
- break;
- case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISQUARTER :
- case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTQUARTER :
- case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTQUARTER :
- $thisMonth = date('m',$baseDate);
- $thisQuarter = floor(--$thisMonth / 3);
- $maxVal = (int) Shared_Date::PHPtoExcel(gmmktime(0,0,0,date('t',$baseDate),(1+$thisQuarter)*3,date('Y',$baseDate)));
- ++$maxVal;
- $val = (int) Shared_Date::PHPToExcel(gmmktime(0,0,0,1,1+$thisQuarter*3,date('Y',$baseDate)));
- break;
- case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISMONTH :
- case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTMONTH :
- case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTMONTH :
- $maxVal = (int) Shared_Date::PHPtoExcel(gmmktime(0,0,0,date('t',$baseDate),date('m',$baseDate),date('Y',$baseDate)));
- ++$maxVal;
- $val = (int) Shared_Date::PHPToExcel(gmmktime(0,0,0,1,date('m',$baseDate),date('Y',$baseDate)));
- break;
- case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISWEEK :
- case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTWEEK :
- case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTWEEK :
- $dayOfWeek = date('w',$baseDate);
- $val = (int) Shared_Date::PHPToExcel($baseDate) - $dayOfWeek;
- $maxVal = $val + 7;
- break;
- }
+ switch ($dynamicRuleType) {
+ case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_TODAY :
+ case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_YESTERDAY :
+ case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_TOMORROW :
+ $maxVal = (int) Shared_Date::PHPtoExcel(strtotime('+1 day',$baseDate));
+ $val = (int) Shared_Date::PHPToExcel($baseDate);
+ break;
+ case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_YEARTODATE :
+ $maxVal = (int) Shared_Date::PHPtoExcel(strtotime('+1 day',$baseDate));
+ $val = (int) Shared_Date::PHPToExcel(gmmktime(0,0,0,1,1,date('Y',$baseDate)));
+ break;
+ case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISYEAR :
+ case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTYEAR :
+ case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTYEAR :
+ $maxVal = (int) Shared_Date::PHPToExcel(gmmktime(0,0,0,31,12,date('Y',$baseDate)));
+ ++$maxVal;
+ $val = (int) Shared_Date::PHPToExcel(gmmktime(0,0,0,1,1,date('Y',$baseDate)));
+ break;
+ case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISQUARTER :
+ case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTQUARTER :
+ case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTQUARTER :
+ $thisMonth = date('m',$baseDate);
+ $thisQuarter = floor(--$thisMonth / 3);
+ $maxVal = (int) Shared_Date::PHPtoExcel(gmmktime(0,0,0,date('t',$baseDate),(1+$thisQuarter)*3,date('Y',$baseDate)));
+ ++$maxVal;
+ $val = (int) Shared_Date::PHPToExcel(gmmktime(0,0,0,1,1+$thisQuarter*3,date('Y',$baseDate)));
+ break;
+ case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISMONTH :
+ case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTMONTH :
+ case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTMONTH :
+ $maxVal = (int) Shared_Date::PHPtoExcel(gmmktime(0,0,0,date('t',$baseDate),date('m',$baseDate),date('Y',$baseDate)));
+ ++$maxVal;
+ $val = (int) Shared_Date::PHPToExcel(gmmktime(0,0,0,1,date('m',$baseDate),date('Y',$baseDate)));
+ break;
+ case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISWEEK :
+ case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTWEEK :
+ case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTWEEK :
+ $dayOfWeek = date('w',$baseDate);
+ $val = (int) Shared_Date::PHPToExcel($baseDate) - $dayOfWeek;
+ $maxVal = $val + 7;
+ break;
+ }
- switch ($dynamicRuleType) {
- // Adjust Today dates for Yesterday and Tomorrow
- case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_YESTERDAY :
- --$maxVal;
- --$val;
- break;
- case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_TOMORROW :
- ++$maxVal;
- ++$val;
- break;
- }
+ switch ($dynamicRuleType) {
+ // Adjust Today dates for Yesterday and Tomorrow
+ case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_YESTERDAY :
+ --$maxVal;
+ --$val;
+ break;
+ case Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_TOMORROW :
+ ++$maxVal;
+ ++$val;
+ break;
+ }
- // Set the filter column rule attributes ready for writing
- $filterColumn->setAttributes(array( 'val' => $val,
- 'maxVal' => $maxVal
- )
- );
+ // Set the filter column rule attributes ready for writing
+ $filterColumn->setAttributes(array( 'val' => $val,
+ 'maxVal' => $maxVal
+ )
+ );
- // Set the rules for identifying rows for hide/show
- $ruleValues[] = array( 'operator' => Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL,
- 'value' => $val
- );
- $ruleValues[] = array( 'operator' => Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_LESSTHAN,
- 'value' => $maxVal
- );
- Calculation_Functions::setReturnDateType($rDateType);
+ // Set the rules for identifying rows for hide/show
+ $ruleValues[] = array( 'operator' => Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL,
+ 'value' => $val
+ );
+ $ruleValues[] = array( 'operator' => Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_LESSTHAN,
+ 'value' => $maxVal
+ );
+ Calculation_Functions::setReturnDateType($rDateType);
- return array(
- 'method' => '_filterTestInCustomDataSet',
- 'arguments' => array( 'filterRules' => $ruleValues,
- 'join' => Worksheet_AutoFilter_Column::AUTOFILTER_COLUMN_JOIN_AND
- )
- );
- }
+ return array(
+ 'method' => '_filterTestInCustomDataSet',
+ 'arguments' => array( 'filterRules' => $ruleValues,
+ 'join' => Worksheet_AutoFilter_Column::AUTOFILTER_COLUMN_JOIN_AND
+ )
+ );
+ }
- private function _calculateTopTenValue($columnID,$startRow,$endRow,$ruleType,$ruleValue) {
- $range = $columnID.$startRow.':'.$columnID.$endRow;
- $dataValues = Calculation_Functions::flattenArray(
- $this->_workSheet->rangeToArray($range,NULL,TRUE,FALSE)
- );
+ private function _calculateTopTenValue($columnID,$startRow,$endRow,$ruleType,$ruleValue) {
+ $range = $columnID.$startRow.':'.$columnID.$endRow;
+ $dataValues = Calculation_Functions::flattenArray(
+ $this->_workSheet->rangeToArray($range,null,true,false)
+ );
- $dataValues = array_filter($dataValues);
- if ($ruleType == Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP) {
- rsort($dataValues);
- } else {
- sort($dataValues);
- }
+ $dataValues = array_filter($dataValues);
+ if ($ruleType == Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP) {
+ rsort($dataValues);
+ } else {
+ sort($dataValues);
+ }
- return array_pop(array_slice($dataValues,0,$ruleValue));
- }
+ return array_pop(array_slice($dataValues,0,$ruleValue));
+ }
- /**
- * Apply the AutoFilter rules to the AutoFilter Range
- *
- * @throws PHPExcel\Exception
- * @return PHPExcel\Worksheet_AutoFilter
- */
- public function showHideRows()
- {
- list($rangeStart,$rangeEnd) = Cell::rangeBoundaries($this->_range);
+ /**
+ * Apply the AutoFilter rules to the AutoFilter Range
+ *
+ * @throws PHPExcel\Exception
+ * @return PHPExcel\Worksheet_AutoFilter
+ */
+ public function showHideRows()
+ {
+ list($rangeStart,$rangeEnd) = Cell::rangeBoundaries($this->_range);
- // The heading row should always be visible
-// echo 'AutoFilter Heading Row ',$rangeStart[1],' is always SHOWN',PHP_EOL;
- $this->_workSheet->getRowDimension($rangeStart[1])->setVisible(TRUE);
+ // The heading row should always be visible
+// echo 'AutoFilter Heading Row ',$rangeStart[1],' is always SHOWN',PHP_EOL;
+ $this->_workSheet->getRowDimension($rangeStart[1])->setVisible(TRUE);
- $columnFilterTests = array();
- foreach($this->_columns as $columnID => $filterColumn) {
- $rules = $filterColumn->getRules();
- switch ($filterColumn->getFilterType()) {
- case Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_FILTER :
- $ruleValues = array();
- // Build a list of the filter value selections
- foreach($rules as $rule) {
- $ruleType = $rule->getRuleType();
- $ruleValues[] = $rule->getValue();
- }
- // Test if we want to include blanks in our filter criteria
- $blanks = FALSE;
- $ruleDataSet = array_filter($ruleValues);
- if (count($ruleValues) != count($ruleDataSet))
- $blanks = TRUE;
- if ($ruleType == Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_FILTER) {
- // Filter on absolute values
- $columnFilterTests[$columnID] = array(
- 'method' => '_filterTestInSimpleDataSet',
- 'arguments' => array( 'filterValues' => $ruleDataSet,
- 'blanks' => $blanks
- )
- );
- } else {
- // Filter on date group values
- $arguments = array();
- foreach($ruleDataSet as $ruleValue) {
- $date = $time = '';
- if ((isset($ruleValue[Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_YEAR])) &&
- ($ruleValue[Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_YEAR] !== ''))
- $date .= sprintf('%04d',$ruleValue[Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_YEAR]);
- if ((isset($ruleValue[Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_MONTH])) &&
- ($ruleValue[Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_MONTH] != ''))
- $date .= sprintf('%02d',$ruleValue[Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_MONTH]);
- if ((isset($ruleValue[Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_DAY])) &&
- ($ruleValue[Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_DAY] !== ''))
- $date .= sprintf('%02d',$ruleValue[Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_DAY]);
- if ((isset($ruleValue[Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_HOUR])) &&
- ($ruleValue[Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_HOUR] !== ''))
- $time .= sprintf('%02d',$ruleValue[Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_HOUR]);
- if ((isset($ruleValue[Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_MINUTE])) &&
- ($ruleValue[Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_MINUTE] !== ''))
- $time .= sprintf('%02d',$ruleValue[Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_MINUTE]);
- if ((isset($ruleValue[Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_SECOND])) &&
- ($ruleValue[Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_SECOND] !== ''))
- $time .= sprintf('%02d',$ruleValue[Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_SECOND]);
- $dateTime = $date . $time;
- $arguments['date'][] = $date;
- $arguments['time'][] = $time;
- $arguments['dateTime'][] = $dateTime;
- }
- // Remove empty elements
- $arguments['date'] = array_filter($arguments['date']);
- $arguments['time'] = array_filter($arguments['time']);
- $arguments['dateTime'] = array_filter($arguments['dateTime']);
- $columnFilterTests[$columnID] = array(
- 'method' => '_filterTestInDateGroupSet',
- 'arguments' => array( 'filterValues' => $arguments,
- 'blanks' => $blanks
- )
- );
- }
- break;
- case Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_CUSTOMFILTER :
- $customRuleForBlanks = FALSE;
- $ruleValues = array();
- // Build a list of the filter value selections
- foreach($rules as $rule) {
- $ruleType = $rule->getRuleType();
- $ruleValue = $rule->getValue();
- if (!is_numeric($ruleValue)) {
- // Convert to a regexp allowing for regexp reserved characters, wildcards and escaped wildcards
- $ruleValue = preg_quote($ruleValue);
- $ruleValue = str_replace(self::$_fromReplace,self::$_toReplace,$ruleValue);
- if (trim($ruleValue) == '') {
- $customRuleForBlanks = TRUE;
- $ruleValue = trim($ruleValue);
- }
- }
- $ruleValues[] = array( 'operator' => $rule->getOperator(),
- 'value' => $ruleValue
- );
- }
- $join = $filterColumn->getJoin();
- $columnFilterTests[$columnID] = array(
- 'method' => '_filterTestInCustomDataSet',
- 'arguments' => array( 'filterRules' => $ruleValues,
- 'join' => $join,
- 'customRuleForBlanks' => $customRuleForBlanks
- )
- );
- break;
- case Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_DYNAMICFILTER :
- $ruleValues = array();
- foreach($rules as $rule) {
- // We should only ever have one Dynamic Filter Rule anyway
- $dynamicRuleType = $rule->getGrouping();
- if (($dynamicRuleType == Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_ABOVEAVERAGE) ||
- ($dynamicRuleType == Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_BELOWAVERAGE)) {
- // Number (Average) based
- // Calculate the average
- $averageFormula = '=AVERAGE('.$columnID.($rangeStart[1]+1).':'.$columnID.$rangeEnd[1].')';
- $average = Calculation::getInstance()->calculateFormula($averageFormula,NULL,$this->_workSheet->getCell('A1'));
- // Set above/below rule based on greaterThan or LessTan
- $operator = ($dynamicRuleType === Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_ABOVEAVERAGE)
- ? Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_GREATERTHAN
- : Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_LESSTHAN;
- $ruleValues[] = array( 'operator' => $operator,
- 'value' => $average
- );
- $columnFilterTests[$columnID] = array(
- 'method' => '_filterTestInCustomDataSet',
- 'arguments' => array( 'filterRules' => $ruleValues,
- 'join' => Worksheet_AutoFilter_Column::AUTOFILTER_COLUMN_JOIN_OR
- )
- );
- } else {
- // Date based
- if ($dynamicRuleType{0} == 'M' || $dynamicRuleType{0} == 'Q') {
- // Month or Quarter
- sscanf($dynamicRuleType,'%[A-Z]%d', $periodType, $period);
- if ($periodType == 'M') {
- $ruleValues = array($period);
- } else {
- --$period;
- $periodEnd = (1+$period)*3;
- $periodStart = 1+$period*3;
- $ruleValues = range($periodStart,periodEnd);
- }
- $columnFilterTests[$columnID] = array(
- 'method' => '_filterTestInPeriodDateSet',
- 'arguments' => $ruleValues
- );
- $filterColumn->setAttributes(array());
- } else {
- // Date Range
- $columnFilterTests[$columnID] = $this->_dynamicFilterDateRange($dynamicRuleType, $filterColumn);
- break;
- }
- }
- }
- break;
- case Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_TOPTENFILTER :
- $ruleValues = array();
- $dataRowCount = $rangeEnd[1] - $rangeStart[1];
- foreach($rules as $rule) {
- // We should only ever have one Dynamic Filter Rule anyway
- $toptenRuleType = $rule->getGrouping();
- $ruleValue = $rule->getValue();
- $ruleOperator = $rule->getOperator();
- }
- if ($ruleOperator === Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT) {
- $ruleValue = floor($ruleValue * ($dataRowCount / 100));
- }
- if ($ruleValue < 1) $ruleValue = 1;
- if ($ruleValue > 500) $ruleValue = 500;
+ $columnFilterTests = array();
+ foreach($this->_columns as $columnID => $filterColumn) {
+ $rules = $filterColumn->getRules();
+ switch ($filterColumn->getFilterType()) {
+ case Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_FILTER :
+ $ruleValues = array();
+ // Build a list of the filter value selections
+ foreach($rules as $rule) {
+ $ruleType = $rule->getRuleType();
+ $ruleValues[] = $rule->getValue();
+ }
+ // Test if we want to include blanks in our filter criteria
+ $blanks = false;
+ $ruleDataSet = array_filter($ruleValues);
+ if (count($ruleValues) != count($ruleDataSet))
+ $blanks = TRUE;
+ if ($ruleType == Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_FILTER) {
+ // Filter on absolute values
+ $columnFilterTests[$columnID] = array(
+ 'method' => '_filterTestInSimpleDataSet',
+ 'arguments' => array( 'filterValues' => $ruleDataSet,
+ 'blanks' => $blanks
+ )
+ );
+ } else {
+ // Filter on date group values
+ $arguments = array();
+ foreach($ruleDataSet as $ruleValue) {
+ $date = $time = '';
+ if ((isset($ruleValue[Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_YEAR])) &&
+ ($ruleValue[Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_YEAR] !== ''))
+ $date .= sprintf('%04d',$ruleValue[Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_YEAR]);
+ if ((isset($ruleValue[Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_MONTH])) &&
+ ($ruleValue[Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_MONTH] != ''))
+ $date .= sprintf('%02d',$ruleValue[Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_MONTH]);
+ if ((isset($ruleValue[Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_DAY])) &&
+ ($ruleValue[Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_DAY] !== ''))
+ $date .= sprintf('%02d',$ruleValue[Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_DAY]);
+ if ((isset($ruleValue[Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_HOUR])) &&
+ ($ruleValue[Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_HOUR] !== ''))
+ $time .= sprintf('%02d',$ruleValue[Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_HOUR]);
+ if ((isset($ruleValue[Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_MINUTE])) &&
+ ($ruleValue[Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_MINUTE] !== ''))
+ $time .= sprintf('%02d',$ruleValue[Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_MINUTE]);
+ if ((isset($ruleValue[Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_SECOND])) &&
+ ($ruleValue[Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_SECOND] !== ''))
+ $time .= sprintf('%02d',$ruleValue[Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_SECOND]);
+ $dateTime = $date . $time;
+ $arguments['date'][] = $date;
+ $arguments['time'][] = $time;
+ $arguments['dateTime'][] = $dateTime;
+ }
+ // Remove empty elements
+ $arguments['date'] = array_filter($arguments['date']);
+ $arguments['time'] = array_filter($arguments['time']);
+ $arguments['dateTime'] = array_filter($arguments['dateTime']);
+ $columnFilterTests[$columnID] = array(
+ 'method' => '_filterTestInDateGroupSet',
+ 'arguments' => array( 'filterValues' => $arguments,
+ 'blanks' => $blanks
+ )
+ );
+ }
+ break;
+ case Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_CUSTOMFILTER :
+ $customRuleForBlanks = false;
+ $ruleValues = array();
+ // Build a list of the filter value selections
+ foreach($rules as $rule) {
+ $ruleType = $rule->getRuleType();
+ $ruleValue = $rule->getValue();
+ if (!is_numeric($ruleValue)) {
+ // Convert to a regexp allowing for regexp reserved characters, wildcards and escaped wildcards
+ $ruleValue = preg_quote($ruleValue);
+ $ruleValue = str_replace(self::$_fromReplace,self::$_toReplace,$ruleValue);
+ if (trim($ruleValue) == '') {
+ $customRuleForBlanks = TRUE;
+ $ruleValue = trim($ruleValue);
+ }
+ }
+ $ruleValues[] = array( 'operator' => $rule->getOperator(),
+ 'value' => $ruleValue
+ );
+ }
+ $join = $filterColumn->getJoin();
+ $columnFilterTests[$columnID] = array(
+ 'method' => '_filterTestInCustomDataSet',
+ 'arguments' => array( 'filterRules' => $ruleValues,
+ 'join' => $join,
+ 'customRuleForBlanks' => $customRuleForBlanks
+ )
+ );
+ break;
+ case Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_DYNAMICFILTER :
+ $ruleValues = array();
+ foreach($rules as $rule) {
+ // We should only ever have one Dynamic Filter Rule anyway
+ $dynamicRuleType = $rule->getGrouping();
+ if (($dynamicRuleType == Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_ABOVEAVERAGE) ||
+ ($dynamicRuleType == Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_BELOWAVERAGE)) {
+ // Number (Average) based
+ // Calculate the average
+ $averageFormula = '=AVERAGE('.$columnID.($rangeStart[1]+1).':'.$columnID.$rangeEnd[1].')';
+ $average = Calculation::getInstance()->calculateFormula($averageFormula,null,$this->_workSheet->getCell('A1'));
+ // Set above/below rule based on greaterThan or LessTan
+ $operator = ($dynamicRuleType === Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_ABOVEAVERAGE)
+ ? Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_GREATERTHAN
+ : Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_LESSTHAN;
+ $ruleValues[] = array( 'operator' => $operator,
+ 'value' => $average
+ );
+ $columnFilterTests[$columnID] = array(
+ 'method' => '_filterTestInCustomDataSet',
+ 'arguments' => array( 'filterRules' => $ruleValues,
+ 'join' => Worksheet_AutoFilter_Column::AUTOFILTER_COLUMN_JOIN_OR
+ )
+ );
+ } else {
+ // Date based
+ if ($dynamicRuleType{0} == 'M' || $dynamicRuleType{0} == 'Q') {
+ // Month or Quarter
+ sscanf($dynamicRuleType,'%[A-Z]%d', $periodType, $period);
+ if ($periodType == 'M') {
+ $ruleValues = array($period);
+ } else {
+ --$period;
+ $periodEnd = (1+$period)*3;
+ $periodStart = 1+$period*3;
+ $ruleValues = range($periodStart,periodEnd);
+ }
+ $columnFilterTests[$columnID] = array(
+ 'method' => '_filterTestInPeriodDateSet',
+ 'arguments' => $ruleValues
+ );
+ $filterColumn->setAttributes(array());
+ } else {
+ // Date Range
+ $columnFilterTests[$columnID] = $this->_dynamicFilterDateRange($dynamicRuleType, $filterColumn);
+ break;
+ }
+ }
+ }
+ break;
+ case Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_TOPTENFILTER :
+ $ruleValues = array();
+ $dataRowCount = $rangeEnd[1] - $rangeStart[1];
+ foreach($rules as $rule) {
+ // We should only ever have one Dynamic Filter Rule anyway
+ $toptenRuleType = $rule->getGrouping();
+ $ruleValue = $rule->getValue();
+ $ruleOperator = $rule->getOperator();
+ }
+ if ($ruleOperator === Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT) {
+ $ruleValue = floor($ruleValue * ($dataRowCount / 100));
+ }
+ if ($ruleValue < 1) $ruleValue = 1;
+ if ($ruleValue > 500) $ruleValue = 500;
- $maxVal = $this->_calculateTopTenValue($columnID,$rangeStart[1]+1,$rangeEnd[1],$toptenRuleType,$ruleValue);
+ $maxVal = $this->_calculateTopTenValue($columnID,$rangeStart[1]+1,$rangeEnd[1],$toptenRuleType,$ruleValue);
- $operator = ($toptenRuleType == Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP)
- ? Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL
- : Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_LESSTHANOREQUAL;
- $ruleValues[] = array( 'operator' => $operator,
- 'value' => $maxVal
- );
- $columnFilterTests[$columnID] = array(
- 'method' => '_filterTestInCustomDataSet',
- 'arguments' => array( 'filterRules' => $ruleValues,
- 'join' => Worksheet_AutoFilter_Column::AUTOFILTER_COLUMN_JOIN_OR
- )
- );
- $filterColumn->setAttributes(
- array('maxVal' => $maxVal)
- );
- break;
- }
- }
+ $operator = ($toptenRuleType == Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP)
+ ? Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL
+ : Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_LESSTHANOREQUAL;
+ $ruleValues[] = array( 'operator' => $operator,
+ 'value' => $maxVal
+ );
+ $columnFilterTests[$columnID] = array(
+ 'method' => '_filterTestInCustomDataSet',
+ 'arguments' => array( 'filterRules' => $ruleValues,
+ 'join' => Worksheet_AutoFilter_Column::AUTOFILTER_COLUMN_JOIN_OR
+ )
+ );
+ $filterColumn->setAttributes(
+ array('maxVal' => $maxVal)
+ );
+ break;
+ }
+ }
-// echo 'Column Filter Test CRITERIA',PHP_EOL;
-// var_dump($columnFilterTests);
+// echo 'Column Filter Test CRITERIA',PHP_EOL;
+// var_dump($columnFilterTests);
//
- // Execute the column tests for each row in the autoFilter range to determine show/hide,
- for ($row = $rangeStart[1]+1; $row <= $rangeEnd[1]; ++$row) {
-// echo 'Testing Row = ',$row,PHP_EOL;
- $result = TRUE;
- foreach($columnFilterTests as $columnID => $columnFilterTest) {
-// echo 'Testing cell ',$columnID.$row,PHP_EOL;
- $cellValue = $this->_workSheet->getCell($columnID.$row)->getCalculatedValue();
-// echo 'Value is ',$cellValue,PHP_EOL;
- // Execute the filter test
- $result = $result &&
- call_user_func_array(
- array(__NAMESPACE__ . '\Worksheet_AutoFilter',$columnFilterTest['method']),
- array(
- $cellValue,
- $columnFilterTest['arguments']
- )
- );
-// echo (($result) ? 'VALID' : 'INVALID'),PHP_EOL;
- // If filter test has resulted in FALSE, exit the loop straightaway rather than running any more tests
- if (!$result)
- break;
- }
- // Set show/hide for the row based on the result of the autoFilter result
-// echo (($result) ? 'SHOW' : 'HIDE'),PHP_EOL;
- $this->_workSheet->getRowDimension($row)->setVisible($result);
- }
+ // Execute the column tests for each row in the autoFilter range to determine show/hide,
+ for ($row = $rangeStart[1]+1; $row <= $rangeEnd[1]; ++$row) {
+// echo 'Testing Row = ',$row,PHP_EOL;
+ $result = TRUE;
+ foreach($columnFilterTests as $columnID => $columnFilterTest) {
+// echo 'Testing cell ',$columnID.$row,PHP_EOL;
+ $cellValue = $this->_workSheet->getCell($columnID.$row)->getCalculatedValue();
+// echo 'Value is ',$cellValue,PHP_EOL;
+ // Execute the filter test
+ $result = $result &&
+ call_user_func_array(
+ array(__NAMESPACE__ . '\Worksheet_AutoFilter',$columnFilterTest['method']),
+ array(
+ $cellValue,
+ $columnFilterTest['arguments']
+ )
+ );
+// echo (($result) ? 'VALID' : 'INVALID'),PHP_EOL;
+ // If filter test has resulted in FALSE, exit the loop straightaway rather than running any more tests
+ if (!$result)
+ break;
+ }
+ // Set show/hide for the row based on the result of the autoFilter result
+// echo (($result) ? 'SHOW' : 'HIDE'),PHP_EOL;
+ $this->_workSheet->getRowDimension($row)->setVisible($result);
+ }
- return $this;
- }
+ return $this;
+ }
- /**
- * Implement PHP __clone to create a deep clone, not just a shallow copy.
- */
- public function __clone() {
- $vars = get_object_vars($this);
- foreach ($vars as $key => $value) {
- if (is_object($value)) {
- if ($key == '_workSheet') {
- // Detach from worksheet
- $this->{$key} = NULL;
- } else {
- $this->{$key} = clone $value;
- }
- } elseif ((is_array($value)) && ($key == '_columns')) {
- // The columns array of PHPExcel\Worksheet_AutoFilter objects
- $this->{$key} = array();
- foreach ($value as $k => $v) {
- $this->{$key}[$k] = clone $v;
- // attach the new cloned Column to this new cloned Autofilter object
- $this->{$key}[$k]->setParent($this);
- }
- } else {
- $this->{$key} = $value;
- }
- }
- }
-
- /**
- * toString method replicates previous behavior by returning the range if object is
- * referenced as a property of its parent.
- */
- public function __toString() {
- return (string) $this->_range;
- }
+ /**
+ * Implement PHP __clone to create a deep clone, not just a shallow copy.
+ */
+ public function __clone() {
+ $vars = get_object_vars($this);
+ foreach ($vars as $key => $value) {
+ if (is_object($value)) {
+ if ($key == '_workSheet') {
+ // Detach from worksheet
+ $this->{$key} = null;
+ } else {
+ $this->{$key} = clone $value;
+ }
+ } elseif ((is_array($value)) && ($key == '_columns')) {
+ // The columns array of PHPExcel\Worksheet_AutoFilter objects
+ $this->{$key} = array();
+ foreach ($value as $k => $v) {
+ $this->{$key}[$k] = clone $v;
+ // attach the new cloned Column to this new cloned Autofilter object
+ $this->{$key}[$k]->setParent($this);
+ }
+ } else {
+ $this->{$key} = $value;
+ }
+ }
+ }
+ /**
+ * toString method replicates previous behavior by returning the range if object is
+ * referenced as a property of its parent.
+ */
+ public function __toString() {
+ return (string) $this->_range;
+ }
}
diff --git a/Classes/PHPExcel/Worksheet/AutoFilter/Column.php b/Classes/PHPExcel/Worksheet/AutoFilter/Column.php
index b8e4b2a..6b4a468 100644
--- a/Classes/PHPExcel/Worksheet/AutoFilter/Column.php
+++ b/Classes/PHPExcel/Worksheet/AutoFilter/Column.php
@@ -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\Worksheet
- * @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\Worksheet
+ * @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,366 +31,365 @@ namespace PHPExcel;
/**
* PHPExcel\Worksheet_AutoFilter_Column
*
- * @category PHPExcel
- * @package PHPExcel\Worksheet
- * @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @category PHPExcel
+ * @package PHPExcel\Worksheet
+ * @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
*/
class Worksheet_AutoFilter_Column
{
- const AUTOFILTER_FILTERTYPE_FILTER = 'filters';
- const AUTOFILTER_FILTERTYPE_CUSTOMFILTER = 'customFilters';
- // Supports no more than 2 rules, with an And/Or join criteria
- // if more than 1 rule is defined
- const AUTOFILTER_FILTERTYPE_DYNAMICFILTER = 'dynamicFilter';
- // Even though the filter rule is constant, the filtered data can vary
- // e.g. filtered by date = TODAY
- const AUTOFILTER_FILTERTYPE_TOPTENFILTER = 'top10';
+ const AUTOFILTER_FILTERTYPE_FILTER = 'filters';
+ const AUTOFILTER_FILTERTYPE_CUSTOMFILTER = 'customFilters';
+ // Supports no more than 2 rules, with an And/Or join criteria
+ // if more than 1 rule is defined
+ const AUTOFILTER_FILTERTYPE_DYNAMICFILTER = 'dynamicFilter';
+ // Even though the filter rule is constant, the filtered data can vary
+ // e.g. filtered by date = TODAY
+ const AUTOFILTER_FILTERTYPE_TOPTENFILTER = 'top10';
- /**
- * Types of autofilter rules
- *
- * @var string[]
- */
- private static $_filterTypes = array(
- // Currently we're not handling
- // colorFilter
- // extLst
- // iconFilter
- self::AUTOFILTER_FILTERTYPE_FILTER,
- self::AUTOFILTER_FILTERTYPE_CUSTOMFILTER,
- self::AUTOFILTER_FILTERTYPE_DYNAMICFILTER,
- self::AUTOFILTER_FILTERTYPE_TOPTENFILTER,
- );
+ /**
+ * Types of autofilter rules
+ *
+ * @var string[]
+ */
+ private static $_filterTypes = array(
+ // Currently we're not handling
+ // colorFilter
+ // extLst
+ // iconFilter
+ self::AUTOFILTER_FILTERTYPE_FILTER,
+ self::AUTOFILTER_FILTERTYPE_CUSTOMFILTER,
+ self::AUTOFILTER_FILTERTYPE_DYNAMICFILTER,
+ self::AUTOFILTER_FILTERTYPE_TOPTENFILTER,
+ );
- /* Multiple Rule Connections */
- const AUTOFILTER_COLUMN_JOIN_AND = 'and';
- const AUTOFILTER_COLUMN_JOIN_OR = 'or';
+ /* Multiple Rule Connections */
+ const AUTOFILTER_COLUMN_JOIN_AND = 'and';
+ const AUTOFILTER_COLUMN_JOIN_OR = 'or';
- /**
- * Join options for autofilter rules
- *
- * @var string[]
- */
- private static $_ruleJoins = array(
- self::AUTOFILTER_COLUMN_JOIN_AND,
- self::AUTOFILTER_COLUMN_JOIN_OR,
- );
+ /**
+ * Join options for autofilter rules
+ *
+ * @var string[]
+ */
+ private static $_ruleJoins = array(
+ self::AUTOFILTER_COLUMN_JOIN_AND,
+ self::AUTOFILTER_COLUMN_JOIN_OR,
+ );
- /**
- * Autofilter
- *
- * @var PHPExcel\Worksheet_AutoFilter
- */
- private $_parent = NULL;
+ /**
+ * Autofilter
+ *
+ * @var PHPExcel\Worksheet_AutoFilter
+ */
+ private $_parent = null;
- /**
- * Autofilter Column Index
- *
- * @var string
- */
- private $_columnIndex = '';
+ /**
+ * Autofilter Column Index
+ *
+ * @var string
+ */
+ private $_columnIndex = '';
- /**
- * Autofilter Column Filter Type
- *
- * @var string
- */
- private $_filterType = self::AUTOFILTER_FILTERTYPE_FILTER;
+ /**
+ * Autofilter Column Filter Type
+ *
+ * @var string
+ */
+ private $_filterType = self::AUTOFILTER_FILTERTYPE_FILTER;
- /**
- * Autofilter Multiple Rules And/Or
- *
- * @var string
- */
- private $_join = self::AUTOFILTER_COLUMN_JOIN_OR;
+ /**
+ * Autofilter Multiple Rules And/Or
+ *
+ * @var string
+ */
+ private $_join = self::AUTOFILTER_COLUMN_JOIN_OR;
- /**
- * Autofilter Column Rules
- *
- * @var array of PHPExcel\Worksheet_AutoFilter_Column_Rule
- */
- private $_ruleset = array();
+ /**
+ * Autofilter Column Rules
+ *
+ * @var array of PHPExcel\Worksheet_AutoFilter_Column_Rule
+ */
+ private $_ruleset = array();
- /**
- * Autofilter Column Dynamic Attributes
- *
- * @var array of mixed
- */
- private $_attributes = array();
+ /**
+ * Autofilter Column Dynamic Attributes
+ *
+ * @var array of mixed
+ */
+ private $_attributes = array();
- /**
- * Create a new PHPExcel\Worksheet_AutoFilter_Column
- *
- * @param string $pColumn Column (e.g. A)
- * @param PHPExcel\Worksheet_AutoFilter $pParent Autofilter for this column
- */
- public function __construct($pColumn, Worksheet_AutoFilter $pParent = NULL)
- {
- $this->_columnIndex = $pColumn;
- $this->_parent = $pParent;
- }
+ /**
+ * Create a new PHPExcel\Worksheet_AutoFilter_Column
+ *
+ * @param string $pColumn Column (e.g. A)
+ * @param PHPExcel\Worksheet_AutoFilter $pParent Autofilter for this column
+ */
+ public function __construct($pColumn, Worksheet_AutoFilter $pParent = null)
+ {
+ $this->_columnIndex = $pColumn;
+ $this->_parent = $pParent;
+ }
- /**
- * Get AutoFilter Column Index
- *
- * @return string
- */
- public function getColumnIndex() {
- return $this->_columnIndex;
- }
+ /**
+ * Get AutoFilter Column Index
+ *
+ * @return string
+ */
+ public function getColumnIndex() {
+ return $this->_columnIndex;
+ }
- /**
- * Set AutoFilter Column Index
- *
- * @param string $pColumn Column (e.g. A)
- * @throws PHPExcel\Exception
- * @return PHPExcel\Worksheet_AutoFilter_Column
- */
- public function setColumnIndex($pColumn) {
- // Uppercase coordinate
- $pColumn = strtoupper($pColumn);
- if ($this->_parent !== NULL) {
- $this->_parent->testColumnInRange($pColumn);
- }
+ /**
+ * Set AutoFilter Column Index
+ *
+ * @param string $pColumn Column (e.g. A)
+ * @throws PHPExcel\Exception
+ * @return PHPExcel\Worksheet_AutoFilter_Column
+ */
+ public function setColumnIndex($pColumn) {
+ // Uppercase coordinate
+ $pColumn = strtoupper($pColumn);
+ if ($this->_parent !== null) {
+ $this->_parent->testColumnInRange($pColumn);
+ }
- $this->_columnIndex = $pColumn;
+ $this->_columnIndex = $pColumn;
- return $this;
- }
+ return $this;
+ }
- /**
- * Get this Column's AutoFilter Parent
- *
- * @return PHPExcel\Worksheet_AutoFilter
- */
- public function getParent() {
- return $this->_parent;
- }
+ /**
+ * Get this Column's AutoFilter Parent
+ *
+ * @return PHPExcel\Worksheet_AutoFilter
+ */
+ public function getParent() {
+ return $this->_parent;
+ }
- /**
- * Set this Column's AutoFilter Parent
- *
- * @param PHPExcel\Worksheet_AutoFilter
- * @return PHPExcel\Worksheet_AutoFilter_Column
- */
- public function setParent(PHPExcel\Worksheet_AutoFilter $pParent = NULL) {
- $this->_parent = $pParent;
+ /**
+ * Set this Column's AutoFilter Parent
+ *
+ * @param PHPExcel\Worksheet_AutoFilter
+ * @return PHPExcel\Worksheet_AutoFilter_Column
+ */
+ public function setParent(PHPExcel\Worksheet_AutoFilter $pParent = null) {
+ $this->_parent = $pParent;
- return $this;
- }
+ return $this;
+ }
- /**
- * Get AutoFilter Type
- *
- * @return string
- */
- public function getFilterType() {
- return $this->_filterType;
- }
+ /**
+ * Get AutoFilter Type
+ *
+ * @return string
+ */
+ public function getFilterType() {
+ return $this->_filterType;
+ }
- /**
- * Set AutoFilter Type
- *
- * @param string $pFilterType
- * @throws PHPExcel\Exception
- * @return PHPExcel\Worksheet_AutoFilter_Column
- */
- public function setFilterType($pFilterType = self::AUTOFILTER_FILTERTYPE_FILTER) {
- if (!in_array($pFilterType,self::$_filterTypes)) {
- throw new Exception('Invalid filter type for column AutoFilter.');
- }
+ /**
+ * Set AutoFilter Type
+ *
+ * @param string $pFilterType
+ * @throws PHPExcel\Exception
+ * @return PHPExcel\Worksheet_AutoFilter_Column
+ */
+ public function setFilterType($pFilterType = self::AUTOFILTER_FILTERTYPE_FILTER) {
+ if (!in_array($pFilterType,self::$_filterTypes)) {
+ throw new Exception('Invalid filter type for column AutoFilter.');
+ }
- $this->_filterType = $pFilterType;
+ $this->_filterType = $pFilterType;
- return $this;
- }
+ return $this;
+ }
- /**
- * Get AutoFilter Multiple Rules And/Or Join
- *
- * @return string
- */
- public function getJoin() {
- return $this->_join;
- }
+ /**
+ * Get AutoFilter Multiple Rules And/Or Join
+ *
+ * @return string
+ */
+ public function getJoin() {
+ return $this->_join;
+ }
- /**
- * Set AutoFilter Multiple Rules And/Or
- *
- * @param string $pJoin And/Or
- * @throws PHPExcel\Exception
- * @return PHPExcel\Worksheet_AutoFilter_Column
- */
- public function setJoin($pJoin = self::AUTOFILTER_COLUMN_JOIN_OR) {
- // Lowercase And/Or
- $pJoin = strtolower($pJoin);
- if (!in_array($pJoin,self::$_ruleJoins)) {
- throw new Exception('Invalid rule connection for column AutoFilter.');
- }
+ /**
+ * Set AutoFilter Multiple Rules And/Or
+ *
+ * @param string $pJoin And/Or
+ * @throws PHPExcel\Exception
+ * @return PHPExcel\Worksheet_AutoFilter_Column
+ */
+ public function setJoin($pJoin = self::AUTOFILTER_COLUMN_JOIN_OR) {
+ // Lowercase And/Or
+ $pJoin = strtolower($pJoin);
+ if (!in_array($pJoin,self::$_ruleJoins)) {
+ throw new Exception('Invalid rule connection for column AutoFilter.');
+ }
- $this->_join = $pJoin;
+ $this->_join = $pJoin;
- return $this;
- }
+ return $this;
+ }
- /**
- * Set AutoFilter Attributes
- *
- * @param string[] $pAttributes
- * @throws PHPExcel\Exception
- * @return PHPExcel\Worksheet_AutoFilter_Column
- */
- public function setAttributes($pAttributes = array()) {
- $this->_attributes = $pAttributes;
+ /**
+ * Set AutoFilter Attributes
+ *
+ * @param string[] $pAttributes
+ * @throws PHPExcel\Exception
+ * @return PHPExcel\Worksheet_AutoFilter_Column
+ */
+ public function setAttributes($pAttributes = array()) {
+ $this->_attributes = $pAttributes;
- return $this;
- }
+ return $this;
+ }
- /**
- * Set An AutoFilter Attribute
- *
- * @param string $pName Attribute Name
- * @param string $pValue Attribute Value
- * @throws PHPExcel\Exception
- * @return PHPExcel\Worksheet_AutoFilter_Column
- */
- public function setAttribute($pName, $pValue) {
- $this->_attributes[$pName] = $pValue;
+ /**
+ * Set An AutoFilter Attribute
+ *
+ * @param string $pName Attribute Name
+ * @param string $pValue Attribute Value
+ * @throws PHPExcel\Exception
+ * @return PHPExcel\Worksheet_AutoFilter_Column
+ */
+ public function setAttribute($pName, $pValue) {
+ $this->_attributes[$pName] = $pValue;
- return $this;
- }
+ return $this;
+ }
- /**
- * Get AutoFilter Column Attributes
- *
- * @return string
- */
- public function getAttributes() {
- return $this->_attributes;
- }
+ /**
+ * Get AutoFilter Column Attributes
+ *
+ * @return string
+ */
+ public function getAttributes() {
+ return $this->_attributes;
+ }
- /**
- * Get specific AutoFilter Column Attribute
- *
- * @param string $pName Attribute Name
- * @return string
- */
- public function getAttribute($pName) {
- if (isset($this->_attributes[$pName]))
- return $this->_attributes[$pName];
- return NULL;
- }
+ /**
+ * Get specific AutoFilter Column Attribute
+ *
+ * @param string $pName Attribute Name
+ * @return string
+ */
+ public function getAttribute($pName) {
+ if (isset($this->_attributes[$pName]))
+ return $this->_attributes[$pName];
+ return null;
+ }
- /**
- * Get all AutoFilter Column Rules
- *
- * @throws PHPExcel\Exception
- * @return array of PHPExcel\Worksheet_AutoFilter_Column_Rule
- */
- public function getRules() {
- return $this->_ruleset;
- }
+ /**
+ * Get all AutoFilter Column Rules
+ *
+ * @throws PHPExcel\Exception
+ * @return array of PHPExcel\Worksheet_AutoFilter_Column_Rule
+ */
+ public function getRules() {
+ return $this->_ruleset;
+ }
- /**
- * Get a specified AutoFilter Column Rule
- *
- * @param integer $pIndex Rule index in the ruleset array
- * @return PHPExcel\Worksheet_AutoFilter_Column_Rule
- */
- public function getRule($pIndex) {
- if (!isset($this->_ruleset[$pIndex])) {
- $this->_ruleset[$pIndex] = new Worksheet_AutoFilter_Column_Rule($this);
- }
- return $this->_ruleset[$pIndex];
- }
+ /**
+ * Get a specified AutoFilter Column Rule
+ *
+ * @param integer $pIndex Rule index in the ruleset array
+ * @return PHPExcel\Worksheet_AutoFilter_Column_Rule
+ */
+ public function getRule($pIndex) {
+ if (!isset($this->_ruleset[$pIndex])) {
+ $this->_ruleset[$pIndex] = new Worksheet_AutoFilter_Column_Rule($this);
+ }
+ return $this->_ruleset[$pIndex];
+ }
- /**
- * Create a new AutoFilter Column Rule in the ruleset
- *
- * @return PHPExcel\Worksheet_AutoFilter_Column_Rule
- */
- public function createRule() {
- $this->_ruleset[] = new Worksheet_AutoFilter_Column_Rule($this);
+ /**
+ * Create a new AutoFilter Column Rule in the ruleset
+ *
+ * @return PHPExcel\Worksheet_AutoFilter_Column_Rule
+ */
+ public function createRule() {
+ $this->_ruleset[] = new Worksheet_AutoFilter_Column_Rule($this);
- return end($this->_ruleset);
- }
+ return end($this->_ruleset);
+ }
- /**
- * Add a new AutoFilter Column Rule to the ruleset
- *
- * @param PHPExcel\Worksheet_AutoFilter_Column_Rule $pRule
- * @param boolean $returnRule Flag indicating whether the rule object or the column object should be returned
- * @return PHPExcel\Worksheet_AutoFilter_Column|PHPExcel\Worksheet_AutoFilter_Column_Rule
- */
- public function addRule(Worksheet_AutoFilter_Column_Rule $pRule, $returnRule=TRUE) {
- $pRule->setParent($this);
- $this->_ruleset[] = $pRule;
+ /**
+ * Add a new AutoFilter Column Rule to the ruleset
+ *
+ * @param PHPExcel\Worksheet_AutoFilter_Column_Rule $pRule
+ * @param boolean $returnRule Flag indicating whether the rule object or the column object should be returned
+ * @return PHPExcel\Worksheet_AutoFilter_Column|PHPExcel\Worksheet_AutoFilter_Column_Rule
+ */
+ public function addRule(Worksheet_AutoFilter_Column_Rule $pRule, $returnRule=TRUE) {
+ $pRule->setParent($this);
+ $this->_ruleset[] = $pRule;
- return ($returnRule) ? $pRule : $this;
- }
+ return ($returnRule) ? $pRule : $this;
+ }
- /**
- * Delete a specified AutoFilter Column Rule
- * If the number of rules is reduced to 1, then we reset And/Or logic to Or
- *
- * @param integer $pIndex Rule index in the ruleset array
- * @return PHPExcel\Worksheet_AutoFilter_Column
- */
- public function deleteRule($pIndex) {
- if (isset($this->_ruleset[$pIndex])) {
- unset($this->_ruleset[$pIndex]);
- // If we've just deleted down to a single rule, then reset And/Or joining to Or
- if (count($this->_ruleset) <= 1) {
- $this->setJoin(self::AUTOFILTER_COLUMN_JOIN_OR);
- }
- }
+ /**
+ * Delete a specified AutoFilter Column Rule
+ * If the number of rules is reduced to 1, then we reset And/Or logic to Or
+ *
+ * @param integer $pIndex Rule index in the ruleset array
+ * @return PHPExcel\Worksheet_AutoFilter_Column
+ */
+ public function deleteRule($pIndex) {
+ if (isset($this->_ruleset[$pIndex])) {
+ unset($this->_ruleset[$pIndex]);
+ // If we've just deleted down to a single rule, then reset And/Or joining to Or
+ if (count($this->_ruleset) <= 1) {
+ $this->setJoin(self::AUTOFILTER_COLUMN_JOIN_OR);
+ }
+ }
- return $this;
- }
+ return $this;
+ }
- /**
- * Delete all AutoFilter Column Rules
- *
- * @return PHPExcel\Worksheet_AutoFilter_Column
- */
- public function clearRules() {
- $this->_ruleset = array();
- $this->setJoin(self::AUTOFILTER_COLUMN_JOIN_OR);
+ /**
+ * Delete all AutoFilter Column Rules
+ *
+ * @return PHPExcel\Worksheet_AutoFilter_Column
+ */
+ public function clearRules() {
+ $this->_ruleset = array();
+ $this->setJoin(self::AUTOFILTER_COLUMN_JOIN_OR);
- return $this;
- }
-
- /**
- * Implement PHP __clone to create a deep clone, not just a shallow copy.
- */
- public function __clone() {
- $vars = get_object_vars($this);
- foreach ($vars as $key => $value) {
- if (is_object($value)) {
- if ($key == '_parent') {
- // Detach from autofilter parent
- $this->$key = NULL;
- } else {
- $this->$key = clone $value;
- }
- } elseif ((is_array($value)) && ($key == '_ruleset')) {
- // The columns array of PHPExcel\Worksheet_AutoFilter objects
- $this->$key = array();
- foreach ($value as $k => $v) {
- $this->$key[$k] = clone $v;
- // attach the new cloned Rule to this new cloned Autofilter Cloned object
- $this->$key[$k]->setParent($this);
- }
- } else {
- $this->$key = $value;
- }
- }
- }
+ return $this;
+ }
+ /**
+ * Implement PHP __clone to create a deep clone, not just a shallow copy.
+ */
+ public function __clone() {
+ $vars = get_object_vars($this);
+ foreach ($vars as $key => $value) {
+ if (is_object($value)) {
+ if ($key == '_parent') {
+ // Detach from autofilter parent
+ $this->$key = null;
+ } else {
+ $this->$key = clone $value;
+ }
+ } elseif ((is_array($value)) && ($key == '_ruleset')) {
+ // The columns array of PHPExcel\Worksheet_AutoFilter objects
+ $this->$key = array();
+ foreach ($value as $k => $v) {
+ $this->$key[$k] = clone $v;
+ // attach the new cloned Rule to this new cloned Autofilter Cloned object
+ $this->$key[$k]->setParent($this);
+ }
+ } else {
+ $this->$key = $value;
+ }
+ }
+ }
}
diff --git a/Classes/PHPExcel/Worksheet/AutoFilter/Column/Rule.php b/Classes/PHPExcel/Worksheet/AutoFilter/Column/Rule.php
index 391993e..df4257e 100644
--- a/Classes/PHPExcel/Worksheet/AutoFilter/Column/Rule.php
+++ b/Classes/PHPExcel/Worksheet/AutoFilter/Column/Rule.php
@@ -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\Worksheet
- * @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\Worksheet
+ * @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,436 +31,435 @@ namespace PHPExcel;
/**
* PHPExcel\Worksheet_AutoFilter_Column_Rule
*
- * @category PHPExcel
- * @package PHPExcel\Worksheet
- * @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @category PHPExcel
+ * @package PHPExcel\Worksheet
+ * @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
*/
class Worksheet_AutoFilter_Column_Rule
{
- const AUTOFILTER_RULETYPE_FILTER = 'filter';
- const AUTOFILTER_RULETYPE_DATEGROUP = 'dateGroupItem';
- const AUTOFILTER_RULETYPE_CUSTOMFILTER = 'customFilter';
- const AUTOFILTER_RULETYPE_DYNAMICFILTER = 'dynamicFilter';
- const AUTOFILTER_RULETYPE_TOPTENFILTER = 'top10Filter';
+ const AUTOFILTER_RULETYPE_FILTER = 'filter';
+ const AUTOFILTER_RULETYPE_DATEGROUP = 'dateGroupItem';
+ const AUTOFILTER_RULETYPE_CUSTOMFILTER = 'customFilter';
+ const AUTOFILTER_RULETYPE_DYNAMICFILTER = 'dynamicFilter';
+ const AUTOFILTER_RULETYPE_TOPTENFILTER = 'top10Filter';
- private static $_ruleTypes = array(
- // Currently we're not handling
- // colorFilter
- // extLst
- // iconFilter
- self::AUTOFILTER_RULETYPE_FILTER,
- self::AUTOFILTER_RULETYPE_DATEGROUP,
- self::AUTOFILTER_RULETYPE_CUSTOMFILTER,
- self::AUTOFILTER_RULETYPE_DYNAMICFILTER,
- self::AUTOFILTER_RULETYPE_TOPTENFILTER,
- );
+ private static $_ruleTypes = array(
+ // Currently we're not handling
+ // colorFilter
+ // extLst
+ // iconFilter
+ self::AUTOFILTER_RULETYPE_FILTER,
+ self::AUTOFILTER_RULETYPE_DATEGROUP,
+ self::AUTOFILTER_RULETYPE_CUSTOMFILTER,
+ self::AUTOFILTER_RULETYPE_DYNAMICFILTER,
+ self::AUTOFILTER_RULETYPE_TOPTENFILTER,
+ );
- const AUTOFILTER_RULETYPE_DATEGROUP_YEAR = 'year';
- const AUTOFILTER_RULETYPE_DATEGROUP_MONTH = 'month';
- const AUTOFILTER_RULETYPE_DATEGROUP_DAY = 'day';
- const AUTOFILTER_RULETYPE_DATEGROUP_HOUR = 'hour';
- const AUTOFILTER_RULETYPE_DATEGROUP_MINUTE = 'minute';
- const AUTOFILTER_RULETYPE_DATEGROUP_SECOND = 'second';
+ const AUTOFILTER_RULETYPE_DATEGROUP_YEAR = 'year';
+ const AUTOFILTER_RULETYPE_DATEGROUP_MONTH = 'month';
+ const AUTOFILTER_RULETYPE_DATEGROUP_DAY = 'day';
+ const AUTOFILTER_RULETYPE_DATEGROUP_HOUR = 'hour';
+ const AUTOFILTER_RULETYPE_DATEGROUP_MINUTE = 'minute';
+ const AUTOFILTER_RULETYPE_DATEGROUP_SECOND = 'second';
- private static $_dateTimeGroups = array(
- self::AUTOFILTER_RULETYPE_DATEGROUP_YEAR,
- self::AUTOFILTER_RULETYPE_DATEGROUP_MONTH,
- self::AUTOFILTER_RULETYPE_DATEGROUP_DAY,
- self::AUTOFILTER_RULETYPE_DATEGROUP_HOUR,
- self::AUTOFILTER_RULETYPE_DATEGROUP_MINUTE,
- self::AUTOFILTER_RULETYPE_DATEGROUP_SECOND,
- );
+ private static $_dateTimeGroups = array(
+ self::AUTOFILTER_RULETYPE_DATEGROUP_YEAR,
+ self::AUTOFILTER_RULETYPE_DATEGROUP_MONTH,
+ self::AUTOFILTER_RULETYPE_DATEGROUP_DAY,
+ self::AUTOFILTER_RULETYPE_DATEGROUP_HOUR,
+ self::AUTOFILTER_RULETYPE_DATEGROUP_MINUTE,
+ self::AUTOFILTER_RULETYPE_DATEGROUP_SECOND,
+ );
- const AUTOFILTER_RULETYPE_DYNAMIC_YESTERDAY = 'yesterday';
- const AUTOFILTER_RULETYPE_DYNAMIC_TODAY = 'today';
- const AUTOFILTER_RULETYPE_DYNAMIC_TOMORROW = 'tomorrow';
- const AUTOFILTER_RULETYPE_DYNAMIC_YEARTODATE = 'yearToDate';
- const AUTOFILTER_RULETYPE_DYNAMIC_THISYEAR = 'thisYear';
- const AUTOFILTER_RULETYPE_DYNAMIC_THISQUARTER = 'thisQuarter';
- const AUTOFILTER_RULETYPE_DYNAMIC_THISMONTH = 'thisMonth';
- const AUTOFILTER_RULETYPE_DYNAMIC_THISWEEK = 'thisWeek';
- const AUTOFILTER_RULETYPE_DYNAMIC_LASTYEAR = 'lastYear';
- const AUTOFILTER_RULETYPE_DYNAMIC_LASTQUARTER = 'lastQuarter';
- const AUTOFILTER_RULETYPE_DYNAMIC_LASTMONTH = 'lastMonth';
- const AUTOFILTER_RULETYPE_DYNAMIC_LASTWEEK = 'lastWeek';
- const AUTOFILTER_RULETYPE_DYNAMIC_NEXTYEAR = 'nextYear';
- const AUTOFILTER_RULETYPE_DYNAMIC_NEXTQUARTER = 'nextQuarter';
- const AUTOFILTER_RULETYPE_DYNAMIC_NEXTMONTH = 'nextMonth';
- const AUTOFILTER_RULETYPE_DYNAMIC_NEXTWEEK = 'nextWeek';
- const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_1 = 'M1';
- const AUTOFILTER_RULETYPE_DYNAMIC_JANUARY = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_1;
- const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_2 = 'M2';
- const AUTOFILTER_RULETYPE_DYNAMIC_FEBRUARY = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_2;
- const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_3 = 'M3';
- const AUTOFILTER_RULETYPE_DYNAMIC_MARCH = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_3;
- const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_4 = 'M4';
- const AUTOFILTER_RULETYPE_DYNAMIC_APRIL = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_4;
- const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_5 = 'M5';
- const AUTOFILTER_RULETYPE_DYNAMIC_MAY = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_5;
- const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_6 = 'M6';
- const AUTOFILTER_RULETYPE_DYNAMIC_JUNE = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_6;
- const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_7 = 'M7';
- const AUTOFILTER_RULETYPE_DYNAMIC_JULY = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_7;
- const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_8 = 'M8';
- const AUTOFILTER_RULETYPE_DYNAMIC_AUGUST = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_8;
- const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_9 = 'M9';
- const AUTOFILTER_RULETYPE_DYNAMIC_SEPTEMBER = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_9;
- const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_10 = 'M10';
- const AUTOFILTER_RULETYPE_DYNAMIC_OCTOBER = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_10;
- const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_11 = 'M11';
- const AUTOFILTER_RULETYPE_DYNAMIC_NOVEMBER = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_11;
- const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_12 = 'M12';
- const AUTOFILTER_RULETYPE_DYNAMIC_DECEMBER = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_12;
- const AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_1 = 'Q1';
- const AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_2 = 'Q2';
- const AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_3 = 'Q3';
- const AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_4 = 'Q4';
- const AUTOFILTER_RULETYPE_DYNAMIC_ABOVEAVERAGE = 'aboveAverage';
- const AUTOFILTER_RULETYPE_DYNAMIC_BELOWAVERAGE = 'belowAverage';
+ const AUTOFILTER_RULETYPE_DYNAMIC_YESTERDAY = 'yesterday';
+ const AUTOFILTER_RULETYPE_DYNAMIC_TODAY = 'today';
+ const AUTOFILTER_RULETYPE_DYNAMIC_TOMORROW = 'tomorrow';
+ const AUTOFILTER_RULETYPE_DYNAMIC_YEARTODATE = 'yearToDate';
+ const AUTOFILTER_RULETYPE_DYNAMIC_THISYEAR = 'thisYear';
+ const AUTOFILTER_RULETYPE_DYNAMIC_THISQUARTER = 'thisQuarter';
+ const AUTOFILTER_RULETYPE_DYNAMIC_THISMONTH = 'thisMonth';
+ const AUTOFILTER_RULETYPE_DYNAMIC_THISWEEK = 'thisWeek';
+ const AUTOFILTER_RULETYPE_DYNAMIC_LASTYEAR = 'lastYear';
+ const AUTOFILTER_RULETYPE_DYNAMIC_LASTQUARTER = 'lastQuarter';
+ const AUTOFILTER_RULETYPE_DYNAMIC_LASTMONTH = 'lastMonth';
+ const AUTOFILTER_RULETYPE_DYNAMIC_LASTWEEK = 'lastWeek';
+ const AUTOFILTER_RULETYPE_DYNAMIC_NEXTYEAR = 'nextYear';
+ const AUTOFILTER_RULETYPE_DYNAMIC_NEXTQUARTER = 'nextQuarter';
+ const AUTOFILTER_RULETYPE_DYNAMIC_NEXTMONTH = 'nextMonth';
+ const AUTOFILTER_RULETYPE_DYNAMIC_NEXTWEEK = 'nextWeek';
+ const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_1 = 'M1';
+ const AUTOFILTER_RULETYPE_DYNAMIC_JANUARY = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_1;
+ const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_2 = 'M2';
+ const AUTOFILTER_RULETYPE_DYNAMIC_FEBRUARY = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_2;
+ const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_3 = 'M3';
+ const AUTOFILTER_RULETYPE_DYNAMIC_MARCH = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_3;
+ const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_4 = 'M4';
+ const AUTOFILTER_RULETYPE_DYNAMIC_APRIL = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_4;
+ const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_5 = 'M5';
+ const AUTOFILTER_RULETYPE_DYNAMIC_MAY = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_5;
+ const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_6 = 'M6';
+ const AUTOFILTER_RULETYPE_DYNAMIC_JUNE = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_6;
+ const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_7 = 'M7';
+ const AUTOFILTER_RULETYPE_DYNAMIC_JULY = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_7;
+ const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_8 = 'M8';
+ const AUTOFILTER_RULETYPE_DYNAMIC_AUGUST = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_8;
+ const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_9 = 'M9';
+ const AUTOFILTER_RULETYPE_DYNAMIC_SEPTEMBER = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_9;
+ const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_10 = 'M10';
+ const AUTOFILTER_RULETYPE_DYNAMIC_OCTOBER = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_10;
+ const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_11 = 'M11';
+ const AUTOFILTER_RULETYPE_DYNAMIC_NOVEMBER = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_11;
+ const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_12 = 'M12';
+ const AUTOFILTER_RULETYPE_DYNAMIC_DECEMBER = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_12;
+ const AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_1 = 'Q1';
+ const AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_2 = 'Q2';
+ const AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_3 = 'Q3';
+ const AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_4 = 'Q4';
+ const AUTOFILTER_RULETYPE_DYNAMIC_ABOVEAVERAGE = 'aboveAverage';
+ const AUTOFILTER_RULETYPE_DYNAMIC_BELOWAVERAGE = 'belowAverage';
- private static $_dynamicTypes = array(
- self::AUTOFILTER_RULETYPE_DYNAMIC_YESTERDAY,
- self::AUTOFILTER_RULETYPE_DYNAMIC_TODAY,
- self::AUTOFILTER_RULETYPE_DYNAMIC_TOMORROW,
- self::AUTOFILTER_RULETYPE_DYNAMIC_YEARTODATE,
- self::AUTOFILTER_RULETYPE_DYNAMIC_THISYEAR,
- self::AUTOFILTER_RULETYPE_DYNAMIC_THISQUARTER,
- self::AUTOFILTER_RULETYPE_DYNAMIC_THISMONTH,
- self::AUTOFILTER_RULETYPE_DYNAMIC_THISWEEK,
- self::AUTOFILTER_RULETYPE_DYNAMIC_LASTYEAR,
- self::AUTOFILTER_RULETYPE_DYNAMIC_LASTQUARTER,
- self::AUTOFILTER_RULETYPE_DYNAMIC_LASTMONTH,
- self::AUTOFILTER_RULETYPE_DYNAMIC_LASTWEEK,
- self::AUTOFILTER_RULETYPE_DYNAMIC_NEXTYEAR,
- self::AUTOFILTER_RULETYPE_DYNAMIC_NEXTQUARTER,
- self::AUTOFILTER_RULETYPE_DYNAMIC_NEXTMONTH,
- self::AUTOFILTER_RULETYPE_DYNAMIC_NEXTWEEK,
- self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_1,
- self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_2,
- self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_3,
- self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_4,
- self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_5,
- self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_6,
- self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_7,
- self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_8,
- self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_9,
- self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_10,
- self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_11,
- self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_12,
- self::AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_1,
- self::AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_2,
- self::AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_3,
- self::AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_4,
- self::AUTOFILTER_RULETYPE_DYNAMIC_ABOVEAVERAGE,
- self::AUTOFILTER_RULETYPE_DYNAMIC_BELOWAVERAGE,
- );
+ private static $_dynamicTypes = array(
+ self::AUTOFILTER_RULETYPE_DYNAMIC_YESTERDAY,
+ self::AUTOFILTER_RULETYPE_DYNAMIC_TODAY,
+ self::AUTOFILTER_RULETYPE_DYNAMIC_TOMORROW,
+ self::AUTOFILTER_RULETYPE_DYNAMIC_YEARTODATE,
+ self::AUTOFILTER_RULETYPE_DYNAMIC_THISYEAR,
+ self::AUTOFILTER_RULETYPE_DYNAMIC_THISQUARTER,
+ self::AUTOFILTER_RULETYPE_DYNAMIC_THISMONTH,
+ self::AUTOFILTER_RULETYPE_DYNAMIC_THISWEEK,
+ self::AUTOFILTER_RULETYPE_DYNAMIC_LASTYEAR,
+ self::AUTOFILTER_RULETYPE_DYNAMIC_LASTQUARTER,
+ self::AUTOFILTER_RULETYPE_DYNAMIC_LASTMONTH,
+ self::AUTOFILTER_RULETYPE_DYNAMIC_LASTWEEK,
+ self::AUTOFILTER_RULETYPE_DYNAMIC_NEXTYEAR,
+ self::AUTOFILTER_RULETYPE_DYNAMIC_NEXTQUARTER,
+ self::AUTOFILTER_RULETYPE_DYNAMIC_NEXTMONTH,
+ self::AUTOFILTER_RULETYPE_DYNAMIC_NEXTWEEK,
+ self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_1,
+ self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_2,
+ self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_3,
+ self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_4,
+ self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_5,
+ self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_6,
+ self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_7,
+ self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_8,
+ self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_9,
+ self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_10,
+ self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_11,
+ self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_12,
+ self::AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_1,
+ self::AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_2,
+ self::AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_3,
+ self::AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_4,
+ self::AUTOFILTER_RULETYPE_DYNAMIC_ABOVEAVERAGE,
+ self::AUTOFILTER_RULETYPE_DYNAMIC_BELOWAVERAGE,
+ );
- /*
- * The only valid filter rule operators for filter and customFilter types are:
- *
- * $objDrawing->setResizeProportional(true);
- * $objDrawing->setWidthAndHeight(160,120);
- *
- *
+ * Example:
+ *
+ * $objDrawing->setResizeProportional(true);
+ * $objDrawing->setWidthAndHeight(160,120);
+ *
+ *
* @author Vincent@luo MSN:kele_100@hotmail.com
* @param int $width
* @param int $height
* @return PHPExcel\Worksheet_BaseDrawing
*/
- public function setWidthAndHeight($width = 0, $height = 0) {
- $xratio = $width / $this->_width;
- $yratio = $height / $this->_height;
- if ($this->_resizeProportional && !($width == 0 || $height == 0)) {
- if (($xratio * $this->_height) < $height) {
- $this->_height = ceil($xratio * $this->_height);
- $this->_width = $width;
- } else {
- $this->_width = ceil($yratio * $this->_width);
- $this->_height = $height;
- }
- }
- return $this;
- }
+ public function setWidthAndHeight($width = 0, $height = 0) {
+ $xratio = $width / $this->_width;
+ $yratio = $height / $this->_height;
+ if ($this->_resizeProportional && !($width == 0 || $height == 0)) {
+ if (($xratio * $this->_height) < $height) {
+ $this->_height = ceil($xratio * $this->_height);
+ $this->_width = $width;
+ } else {
+ $this->_width = ceil($yratio * $this->_width);
+ $this->_height = $height;
+ }
+ }
+ return $this;
+ }
/**
* Get ResizeProportional
@@ -385,7 +385,7 @@ class Worksheet_BaseDrawing implements IComparable
* @return boolean
*/
public function getResizeProportional() {
- return $this->_resizeProportional;
+ return $this->_resizeProportional;
}
/**
@@ -395,8 +395,8 @@ class Worksheet_BaseDrawing implements IComparable
* @return PHPExcel\Worksheet_BaseDrawing
*/
public function setResizeProportional($pValue = true) {
- $this->_resizeProportional = $pValue;
- return $this;
+ $this->_resizeProportional = $pValue;
+ return $this;
}
/**
@@ -405,7 +405,7 @@ class Worksheet_BaseDrawing implements IComparable
* @return int
*/
public function getRotation() {
- return $this->_rotation;
+ return $this->_rotation;
}
/**
@@ -415,8 +415,8 @@ class Worksheet_BaseDrawing implements IComparable
* @return PHPExcel\Worksheet_BaseDrawing
*/
public function setRotation($pValue = 0) {
- $this->_rotation = $pValue;
- return $this;
+ $this->_rotation = $pValue;
+ return $this;
}
/**
@@ -425,53 +425,53 @@ class Worksheet_BaseDrawing implements IComparable
* @return PHPExcel\Worksheet_Drawing_Shadow
*/
public function getShadow() {
- return $this->_shadow;
+ return $this->_shadow;
}
/**
* Set Shadow
*
- * @param PHPExcel\Worksheet_Drawing_Shadow $pValue
- * @throws PHPExcel\Exception
+ * @param PHPExcel\Worksheet_Drawing_Shadow $pValue
+ * @throws PHPExcel\Exception
* @return PHPExcel\Worksheet_BaseDrawing
*/
public function setShadow(Worksheet_Drawing_Shadow $pValue = null) {
- $this->_shadow = $pValue;
- return $this;
+ $this->_shadow = $pValue;
+ return $this;
}
- /**
- * Get hash code
- *
- * @return string Hash code
- */
- public function getHashCode() {
- return md5(
- $this->_name
- . $this->_description
- . $this->_worksheet->getHashCode()
- . $this->_coordinates
- . $this->_offsetX
- . $this->_offsetY
- . $this->_width
- . $this->_height
- . $this->_rotation
- . $this->_shadow->getHashCode()
- . __CLASS__
- );
+ /**
+ * Get hash code
+ *
+ * @return string Hash code
+ */
+ public function getHashCode() {
+ return md5(
+ $this->_name
+ . $this->_description
+ . $this->_worksheet->getHashCode()
+ . $this->_coordinates
+ . $this->_offsetX
+ . $this->_offsetY
+ . $this->_width
+ . $this->_height
+ . $this->_rotation
+ . $this->_shadow->getHashCode()
+ . __CLASS__
+ );
}
- /**
- * Implement PHP __clone to create a deep clone, not just a shallow copy.
- */
- public function __clone() {
- $vars = get_object_vars($this);
- foreach ($vars as $key => $value) {
- if (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;
+ }
+ }
+ }
}
diff --git a/Classes/PHPExcel/Worksheet/CellIterator.php b/Classes/PHPExcel/Worksheet/CellIterator.php
index 022e259..988bf82 100644
--- a/Classes/PHPExcel/Worksheet/CellIterator.php
+++ b/Classes/PHPExcel/Worksheet/CellIterator.php
@@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\Worksheet
* @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##
*/
@@ -39,56 +39,56 @@ namespace PHPExcel;
*/
class Worksheet_CellIterator implements \Iterator
{
- /**
- * PHPExcel\Worksheet to iterate
- *
- * @var PHPExcel\Worksheet
- */
- protected $_subject;
+ /**
+ * PHPExcel\Worksheet to iterate
+ *
+ * @var PHPExcel\Worksheet
+ */
+ protected $_subject;
- /**
- * Row index
- *
- * @var int
- */
- protected $_rowIndex;
+ /**
+ * Row index
+ *
+ * @var int
+ */
+ protected $_rowIndex;
- /**
- * Current iterator position
- *
- * @var int
- */
- protected $_position = 0;
+ /**
+ * Current iterator position
+ *
+ * @var int
+ */
+ protected $_position = 0;
- /**
- * Loop only existing cells
- *
- * @var boolean
- */
- protected $_onlyExistingCells = true;
+ /**
+ * Loop only existing cells
+ *
+ * @var boolean
+ */
+ protected $_onlyExistingCells = true;
- /**
- * Create a new cell iterator
- *
- * @param PHPExcel\Worksheet $subject
- * @param int $rowIndex
- */
- public function __construct(Worksheet $subject = null, $rowIndex = 1) {
- // Set subject and row index
- $this->_subject = $subject;
- $this->_rowIndex = $rowIndex;
- }
+ /**
+ * Create a new cell iterator
+ *
+ * @param PHPExcel\Worksheet $subject
+ * @param int $rowIndex
+ */
+ public function __construct(Worksheet $subject = null, $rowIndex = 1) {
+ // Set subject and row index
+ $this->_subject = $subject;
+ $this->_rowIndex = $rowIndex;
+ }
- /**
- * Destructor
- */
- public function __destruct() {
- unset($this->_subject);
- }
+ /**
+ * Destructor
+ */
+ public function __destruct() {
+ unset($this->_subject);
+ }
- /**
- * Rewind iterator
- */
+ /**
+ * Rewind iterator
+ */
public function rewind() {
$this->_position = 0;
}
@@ -99,7 +99,7 @@ class Worksheet_CellIterator implements \Iterator
* @return PHPExcel\Cell
*/
public function current() {
- return $this->_subject->getCellByColumnAndRow($this->_position, $this->_rowIndex);
+ return $this->_subject->getCellByColumnAndRow($this->_position, $this->_rowIndex);
}
/**
@@ -143,21 +143,21 @@ class Worksheet_CellIterator implements \Iterator
return $this->_position < $columnCount;
}
- /**
- * Get loop only existing cells
- *
- * @return boolean
- */
+ /**
+ * Get loop only existing cells
+ *
+ * @return boolean
+ */
public function getIterateOnlyExistingCells() {
- return $this->_onlyExistingCells;
+ return $this->_onlyExistingCells;
}
- /**
- * Set the iterator to loop only existing cells
- *
- * @param boolean $value
- */
+ /**
+ * Set the iterator to loop only existing cells
+ *
+ * @param boolean $value
+ */
public function setIterateOnlyExistingCells($value = true) {
- $this->_onlyExistingCells = $value;
+ $this->_onlyExistingCells = $value;
}
}
diff --git a/Classes/PHPExcel/Worksheet/ColumnDimension.php b/Classes/PHPExcel/Worksheet/ColumnDimension.php
index 3af8333..ba5e6fc 100644
--- a/Classes/PHPExcel/Worksheet/ColumnDimension.php
+++ b/Classes/PHPExcel/Worksheet/ColumnDimension.php
@@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\Worksheet
* @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,56 +37,56 @@ namespace PHPExcel;
*/
class Worksheet_ColumnDimension
{
- /**
- * Column index
- *
- * @var int
- */
- protected $_columnIndex;
+ /**
+ * Column index
+ *
+ * @var int
+ */
+ protected $_columnIndex;
- /**
- * Column width
- *
- * When this is set to a negative value, the column width should be ignored by IWriter
- *
- * @var double
- */
- protected $_width = -1;
+ /**
+ * Column width
+ *
+ * When this is set to a negative value, the column width should be ignored by IWriter
+ *
+ * @var double
+ */
+ protected $_width = -1;
- /**
- * Auto size?
- *
- * @var bool
- */
- protected $_autoSize = false;
+ /**
+ * Auto size?
+ *
+ * @var bool
+ */
+ protected $_autoSize = false;
- /**
- * Visible?
- *
- * @var bool
- */
- protected $_visible = true;
+ /**
+ * Visible?
+ *
+ * @var bool
+ */
+ protected $_visible = true;
- /**
- * Outline level
- *
- * @var int
- */
- protected $_outlineLevel = 0;
+ /**
+ * Outline level
+ *
+ * @var int
+ */
+ protected $_outlineLevel = 0;
- /**
- * Collapsed
- *
- * @var bool
- */
- protected $_collapsed = false;
+ /**
+ * Collapsed
+ *
+ * @var bool
+ */
+ protected $_collapsed = false;
- /**
- * Index to cellXf
- *
- * @var int
- */
- protected $_xfIndex = 0;
+ /**
+ * Index to cellXf
+ *
+ * @var int
+ */
+ protected $_xfIndex = 0;
/**
* Create a new PHPExcel\Worksheet_ColumnDimension
@@ -95,8 +95,8 @@ class Worksheet_ColumnDimension
*/
public function __construct($pIndex = 'A')
{
- // Initialise values
- $this->_columnIndex = $pIndex;
+ // Initialise values
+ $this->_columnIndex = $pIndex;
}
/**
@@ -105,7 +105,7 @@ class Worksheet_ColumnDimension
* @return string
*/
public function getColumnIndex() {
- return $this->_columnIndex;
+ return $this->_columnIndex;
}
/**
@@ -115,8 +115,8 @@ class Worksheet_ColumnDimension
* @return PHPExcel\Worksheet_ColumnDimension
*/
public function setColumnIndex($pValue) {
- $this->_columnIndex = $pValue;
- return $this;
+ $this->_columnIndex = $pValue;
+ return $this;
}
/**
@@ -125,7 +125,7 @@ class Worksheet_ColumnDimension
* @return double
*/
public function getWidth() {
- return $this->_width;
+ return $this->_width;
}
/**
@@ -135,8 +135,8 @@ class Worksheet_ColumnDimension
* @return PHPExcel\Worksheet_ColumnDimension
*/
public function setWidth($pValue = -1) {
- $this->_width = $pValue;
- return $this;
+ $this->_width = $pValue;
+ return $this;
}
/**
@@ -145,7 +145,7 @@ class Worksheet_ColumnDimension
* @return bool
*/
public function getAutoSize() {
- return $this->_autoSize;
+ return $this->_autoSize;
}
/**
@@ -155,8 +155,8 @@ class Worksheet_ColumnDimension
* @return PHPExcel\Worksheet_ColumnDimension
*/
public function setAutoSize($pValue = false) {
- $this->_autoSize = $pValue;
- return $this;
+ $this->_autoSize = $pValue;
+ return $this;
}
/**
@@ -165,7 +165,7 @@ class Worksheet_ColumnDimension
* @return bool
*/
public function getVisible() {
- return $this->_visible;
+ return $this->_visible;
}
/**
@@ -175,8 +175,8 @@ class Worksheet_ColumnDimension
* @return PHPExcel\Worksheet_ColumnDimension
*/
public function setVisible($pValue = true) {
- $this->_visible = $pValue;
- return $this;
+ $this->_visible = $pValue;
+ return $this;
}
/**
@@ -185,7 +185,7 @@ class Worksheet_ColumnDimension
* @return int
*/
public function getOutlineLevel() {
- return $this->_outlineLevel;
+ return $this->_outlineLevel;
}
/**
@@ -198,12 +198,12 @@ class Worksheet_ColumnDimension
* @return PHPExcel\Worksheet_ColumnDimension
*/
public function setOutlineLevel($pValue) {
- if ($pValue < 0 || $pValue > 7) {
- throw new Exception("Outline level must range between 0 and 7.");
- }
+ if ($pValue < 0 || $pValue > 7) {
+ throw new Exception("Outline level must range between 0 and 7.");
+ }
- $this->_outlineLevel = $pValue;
- return $this;
+ $this->_outlineLevel = $pValue;
+ return $this;
}
/**
@@ -212,7 +212,7 @@ class Worksheet_ColumnDimension
* @return bool
*/
public function getCollapsed() {
- return $this->_collapsed;
+ return $this->_collapsed;
}
/**
@@ -222,44 +222,44 @@ class Worksheet_ColumnDimension
* @return PHPExcel\Worksheet_ColumnDimension
*/
public function setCollapsed($pValue = true) {
- $this->_collapsed = $pValue;
- return $this;
+ $this->_collapsed = $pValue;
+ return $this;
}
- /**
- * Get index to cellXf
- *
- * @return int
- */
- public function getXfIndex()
- {
- return $this->_xfIndex;
- }
+ /**
+ * Get index to cellXf
+ *
+ * @return int
+ */
+ public function getXfIndex()
+ {
+ return $this->_xfIndex;
+ }
- /**
- * Set index to cellXf
- *
- * @param int $pValue
- * @return PHPExcel\Worksheet_ColumnDimension
- */
- public function setXfIndex($pValue = 0)
- {
- $this->_xfIndex = $pValue;
- return $this;
- }
+ /**
+ * Set index to cellXf
+ *
+ * @param int $pValue
+ * @return PHPExcel\Worksheet_ColumnDimension
+ */
+ public function setXfIndex($pValue = 0)
+ {
+ $this->_xfIndex = $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;
+ }
+ }
+ }
}
diff --git a/Classes/PHPExcel/Worksheet/Drawing.php b/Classes/PHPExcel/Worksheet/Drawing.php
index 418794d..a406e0b 100644
--- a/Classes/PHPExcel/Worksheet/Drawing.php
+++ b/Classes/PHPExcel/Worksheet/Drawing.php
@@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\Worksheet_Drawing
* @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,20 +37,20 @@ namespace PHPExcel;
*/
class Worksheet_Drawing extends Worksheet_BaseDrawing implements IComparable
{
- /**
- * Path
- *
- * @var string
- */
- protected $_path = '';
+ /**
+ * Path
+ *
+ * @var string
+ */
+ protected $_path = '';
/**
* Create a new PHPExcel\Worksheet_Drawing
*/
public function __construct()
{
- // Initialize parent
- parent::__construct();
+ // Initialize parent
+ parent::__construct();
}
/**
@@ -59,7 +59,7 @@ class Worksheet_Drawing extends Worksheet_BaseDrawing implements IComparable
* @return string
*/
public function getFilename() {
- return basename($this->_path);
+ return basename($this->_path);
}
/**
@@ -68,9 +68,9 @@ class Worksheet_Drawing extends Worksheet_BaseDrawing implements IComparable
* @return string
*/
public function getIndexedFilename() {
- $fileName = $this->getFilename();
- $fileName = str_replace(' ', '_', $fileName);
- return str_replace('.' . $this->getExtension(), '', $fileName) . $this->getImageIndex() . '.' . $this->getExtension();
+ $fileName = $this->getFilename();
+ $fileName = str_replace(' ', '_', $fileName);
+ return str_replace('.' . $this->getExtension(), '', $fileName) . $this->getImageIndex() . '.' . $this->getExtension();
}
/**
@@ -79,8 +79,8 @@ class Worksheet_Drawing extends Worksheet_BaseDrawing implements IComparable
* @return string
*/
public function getExtension() {
- $exploded = explode(".", basename($this->_path));
- return $exploded[count($exploded) - 1];
+ $exploded = explode(".", basename($this->_path));
+ return $exploded[count($exploded) - 1];
}
/**
@@ -89,59 +89,59 @@ class Worksheet_Drawing extends Worksheet_BaseDrawing implements IComparable
* @return string
*/
public function getPath() {
- return $this->_path;
+ return $this->_path;
}
/**
* Set Path
*
- * @param string $pValue File path
- * @param boolean $pVerifyFile Verify file
- * @throws PHPExcel\Exception
+ * @param string $pValue File path
+ * @param boolean $pVerifyFile Verify file
+ * @throws PHPExcel\Exception
* @return PHPExcel\Worksheet_Drawing
*/
public function setPath($pValue = '', $pVerifyFile = true) {
- if ($pVerifyFile) {
- if (file_exists($pValue)) {
- $this->_path = $pValue;
+ if ($pVerifyFile) {
+ if (file_exists($pValue)) {
+ $this->_path = $pValue;
- if ($this->_width == 0 && $this->_height == 0) {
- // Get width/height
- list($this->_width, $this->_height) = getimagesize($pValue);
- }
- } else {
- throw new Exception("File $pValue not found!");
- }
- } else {
- $this->_path = $pValue;
- }
- return $this;
+ if ($this->_width == 0 && $this->_height == 0) {
+ // Get width/height
+ list($this->_width, $this->_height) = getimagesize($pValue);
+ }
+ } else {
+ throw new Exception("File $pValue not found!");
+ }
+ } else {
+ $this->_path = $pValue;
+ }
+ return $this;
}
- /**
- * Get hash code
- *
- * @return string Hash code
- */
- public function getHashCode() {
- return md5(
- $this->_path
- . parent::getHashCode()
- . __CLASS__
- );
+ /**
+ * Get hash code
+ *
+ * @return string Hash code
+ */
+ public function getHashCode() {
+ return md5(
+ $this->_path
+ . parent::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;
- }
- }
- }
+ /**
+ * 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;
+ }
+ }
+ }
}
diff --git a/Classes/PHPExcel/Worksheet/Drawing/Shadow.php b/Classes/PHPExcel/Worksheet/Drawing/Shadow.php
index d63455d..4950117 100644
--- a/Classes/PHPExcel/Worksheet/Drawing/Shadow.php
+++ b/Classes/PHPExcel/Worksheet/Drawing/Shadow.php
@@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\Worksheet_Drawing
* @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,82 +37,82 @@ namespace PHPExcel;
*/
class Worksheet_Drawing_Shadow implements IComparable
{
- /* Shadow alignment */
- const SHADOW_BOTTOM = 'b';
- const SHADOW_BOTTOM_LEFT = 'bl';
- const SHADOW_BOTTOM_RIGHT = 'br';
- const SHADOW_CENTER = 'ctr';
- const SHADOW_LEFT = 'l';
- const SHADOW_TOP = 't';
- const SHADOW_TOP_LEFT = 'tl';
- const SHADOW_TOP_RIGHT = 'tr';
+ /* Shadow alignment */
+ const SHADOW_BOTTOM = 'b';
+ const SHADOW_BOTTOM_LEFT = 'bl';
+ const SHADOW_BOTTOM_RIGHT = 'br';
+ const SHADOW_CENTER = 'ctr';
+ const SHADOW_LEFT = 'l';
+ const SHADOW_TOP = 't';
+ const SHADOW_TOP_LEFT = 'tl';
+ const SHADOW_TOP_RIGHT = 'tr';
- /**
- * Visible
- *
- * @var boolean
- */
- private $_visible;
+ /**
+ * Visible
+ *
+ * @var boolean
+ */
+ private $_visible;
- /**
- * Blur radius
- *
- * Defaults to 6
- *
- * @var int
- */
- private $_blurRadius;
+ /**
+ * Blur radius
+ *
+ * Defaults to 6
+ *
+ * @var int
+ */
+ private $_blurRadius;
- /**
- * Shadow distance
- *
- * Defaults to 2
- *
- * @var int
- */
- private $_distance;
+ /**
+ * Shadow distance
+ *
+ * Defaults to 2
+ *
+ * @var int
+ */
+ private $_distance;
- /**
- * Shadow direction (in degrees)
- *
- * @var int
- */
- private $_direction;
+ /**
+ * Shadow direction (in degrees)
+ *
+ * @var int
+ */
+ private $_direction;
- /**
- * Shadow alignment
- *
- * @var int
- */
- private $_alignment;
+ /**
+ * Shadow alignment
+ *
+ * @var int
+ */
+ private $_alignment;
- /**
- * Color
- *
- * @var PHPExcel\Style_Color
- */
- private $_color;
+ /**
+ * Color
+ *
+ * @var PHPExcel\Style_Color
+ */
+ private $_color;
- /**
- * Alpha
- *
- * @var int
- */
- private $_alpha;
+ /**
+ * Alpha
+ *
+ * @var int
+ */
+ private $_alpha;
/**
* Create a new PHPExcel\Worksheet_Drawing_Shadow
*/
public function __construct()
{
- // Initialise values
- $this->_visible = false;
- $this->_blurRadius = 6;
- $this->_distance = 2;
- $this->_direction = 0;
- $this->_alignment = Worksheet_Drawing_Shadow::SHADOW_BOTTOM_RIGHT;
- $this->_color = new Style_Color(Style_Color::COLOR_BLACK);
- $this->_alpha = 50;
+ // Initialise values
+ $this->_visible = false;
+ $this->_blurRadius = 6;
+ $this->_distance = 2;
+ $this->_direction = 0;
+ $this->_alignment = Worksheet_Drawing_Shadow::SHADOW_BOTTOM_RIGHT;
+ $this->_color = new Style_Color(Style_Color::COLOR_BLACK);
+ $this->_alpha = 50;
}
/**
@@ -121,7 +121,7 @@ class Worksheet_Drawing_Shadow implements IComparable
* @return boolean
*/
public function getVisible() {
- return $this->_visible;
+ return $this->_visible;
}
/**
@@ -131,8 +131,8 @@ class Worksheet_Drawing_Shadow implements IComparable
* @return PHPExcel\Worksheet_Drawing_Shadow
*/
public function setVisible($pValue = false) {
- $this->_visible = $pValue;
- return $this;
+ $this->_visible = $pValue;
+ return $this;
}
/**
@@ -141,7 +141,7 @@ class Worksheet_Drawing_Shadow implements IComparable
* @return int
*/
public function getBlurRadius() {
- return $this->_blurRadius;
+ return $this->_blurRadius;
}
/**
@@ -151,8 +151,8 @@ class Worksheet_Drawing_Shadow implements IComparable
* @return PHPExcel\Worksheet_Drawing_Shadow
*/
public function setBlurRadius($pValue = 6) {
- $this->_blurRadius = $pValue;
- return $this;
+ $this->_blurRadius = $pValue;
+ return $this;
}
/**
@@ -161,7 +161,7 @@ class Worksheet_Drawing_Shadow implements IComparable
* @return int
*/
public function getDistance() {
- return $this->_distance;
+ return $this->_distance;
}
/**
@@ -171,8 +171,8 @@ class Worksheet_Drawing_Shadow implements IComparable
* @return PHPExcel\Worksheet_Drawing_Shadow
*/
public function setDistance($pValue = 2) {
- $this->_distance = $pValue;
- return $this;
+ $this->_distance = $pValue;
+ return $this;
}
/**
@@ -181,7 +181,7 @@ class Worksheet_Drawing_Shadow implements IComparable
* @return int
*/
public function getDirection() {
- return $this->_direction;
+ return $this->_direction;
}
/**
@@ -191,8 +191,8 @@ class Worksheet_Drawing_Shadow implements IComparable
* @return PHPExcel\Worksheet_Drawing_Shadow
*/
public function setDirection($pValue = 0) {
- $this->_direction = $pValue;
- return $this;
+ $this->_direction = $pValue;
+ return $this;
}
/**
@@ -201,7 +201,7 @@ class Worksheet_Drawing_Shadow implements IComparable
* @return int
*/
public function getAlignment() {
- return $this->_alignment;
+ return $this->_alignment;
}
/**
@@ -211,8 +211,8 @@ class Worksheet_Drawing_Shadow implements IComparable
* @return PHPExcel\Worksheet_Drawing_Shadow
*/
public function setAlignment($pValue = 0) {
- $this->_alignment = $pValue;
- return $this;
+ $this->_alignment = $pValue;
+ return $this;
}
/**
@@ -221,19 +221,19 @@ class Worksheet_Drawing_Shadow implements IComparable
* @return PHPExcel\Style_Color
*/
public function getColor() {
- return $this->_color;
+ return $this->_color;
}
/**
* Set Color
*
- * @param PHPExcel\Style_Color $pValue
- * @throws PHPExcel\Exception
+ * @param PHPExcel\Style_Color $pValue
+ * @throws PHPExcel\Exception
* @return PHPExcel\Worksheet_Drawing_Shadow
*/
public function setColor(Style_Color $pValue = null) {
- $this->_color = $pValue;
- return $this;
+ $this->_color = $pValue;
+ return $this;
}
/**
@@ -242,7 +242,7 @@ class Worksheet_Drawing_Shadow implements IComparable
* @return int
*/
public function getAlpha() {
- return $this->_alpha;
+ return $this->_alpha;
}
/**
@@ -252,39 +252,39 @@ class Worksheet_Drawing_Shadow implements IComparable
* @return PHPExcel\Worksheet_Drawing_Shadow
*/
public function setAlpha($pValue = 0) {
- $this->_alpha = $pValue;
- return $this;
+ $this->_alpha = $pValue;
+ return $this;
}
- /**
- * Get hash code
- *
- * @return string Hash code
- */
- public function getHashCode() {
- return md5(
- ($this->_visible ? 't' : 'f')
- . $this->_blurRadius
- . $this->_distance
- . $this->_direction
- . $this->_alignment
- . $this->_color->getHashCode()
- . $this->_alpha
- . __CLASS__
- );
+ /**
+ * Get hash code
+ *
+ * @return string Hash code
+ */
+ public function getHashCode() {
+ return md5(
+ ($this->_visible ? 't' : 'f')
+ . $this->_blurRadius
+ . $this->_distance
+ . $this->_direction
+ . $this->_alignment
+ . $this->_color->getHashCode()
+ . $this->_alpha
+ . __CLASS__
+ );
}
- /**
- * Implement PHP __clone to create a deep clone, not just a shallow copy.
- */
- public function __clone() {
- $vars = get_object_vars($this);
- foreach ($vars as $key => $value) {
- if (is_object($value)) {
- $this->$key = clone $value;
- } else {
- $this->$key = $value;
- }
- }
- }
+ /**
+ * 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;
+ }
+ }
+ }
}
diff --git a/Classes/PHPExcel/Worksheet/HeaderFooter.php b/Classes/PHPExcel/Worksheet/HeaderFooter.php
index 52cfb5b..e083457 100644
--- a/Classes/PHPExcel/Worksheet/HeaderFooter.php
+++ b/Classes/PHPExcel/Worksheet/HeaderFooter.php
@@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\Worksheet
* @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##
*/
@@ -39,7 +39,7 @@ namespace PHPExcel;
*
* Example: This example shows the text "Center Bold Header" on the first line (center section), and the date on
* the second line (center section).
- * &CCenter &"-,Bold"Bold&"-,Regular"Header_x000A_&D
+ * &CCenter &"-,Bold"Bold&"-,Regular"Header_x000A_&D
*
* General Rules:
* There is no required order in which these codes must appear.
@@ -97,90 +97,90 @@ namespace PHPExcel;
*/
class Worksheet_HeaderFooter
{
- /* Header/footer image location */
- const IMAGE_HEADER_LEFT = 'LH';
- const IMAGE_HEADER_CENTER = 'CH';
- const IMAGE_HEADER_RIGHT = 'RH';
- const IMAGE_FOOTER_LEFT = 'LF';
- const IMAGE_FOOTER_CENTER = 'CF';
- const IMAGE_FOOTER_RIGHT = 'RF';
+ /* Header/footer image location */
+ const IMAGE_HEADER_LEFT = 'LH';
+ const IMAGE_HEADER_CENTER = 'CH';
+ const IMAGE_HEADER_RIGHT = 'RH';
+ const IMAGE_FOOTER_LEFT = 'LF';
+ const IMAGE_FOOTER_CENTER = 'CF';
+ const IMAGE_FOOTER_RIGHT = 'RF';
- /**
- * OddHeader
- *
- * @var string
- */
- protected $_oddHeader = '';
+ /**
+ * OddHeader
+ *
+ * @var string
+ */
+ protected $_oddHeader = '';
- /**
- * OddFooter
- *
- * @var string
- */
- protected $_oddFooter = '';
+ /**
+ * OddFooter
+ *
+ * @var string
+ */
+ protected $_oddFooter = '';
- /**
- * EvenHeader
- *
- * @var string
- */
- protected $_evenHeader = '';
+ /**
+ * EvenHeader
+ *
+ * @var string
+ */
+ protected $_evenHeader = '';
- /**
- * EvenFooter
- *
- * @var string
- */
- protected $_evenFooter = '';
+ /**
+ * EvenFooter
+ *
+ * @var string
+ */
+ protected $_evenFooter = '';
- /**
- * FirstHeader
- *
- * @var string
- */
- protected $_firstHeader = '';
+ /**
+ * FirstHeader
+ *
+ * @var string
+ */
+ protected $_firstHeader = '';
- /**
- * FirstFooter
- *
- * @var string
- */
- protected $_firstFooter = '';
+ /**
+ * FirstFooter
+ *
+ * @var string
+ */
+ protected $_firstFooter = '';
- /**
- * Different header for Odd/Even, defaults to false
- *
- * @var boolean
- */
- protected $_differentOddEven = false;
+ /**
+ * Different header for Odd/Even, defaults to false
+ *
+ * @var boolean
+ */
+ protected $_differentOddEven = false;
- /**
- * Different header for first page, defaults to false
- *
- * @var boolean
- */
- protected $_differentFirst = false;
+ /**
+ * Different header for first page, defaults to false
+ *
+ * @var boolean
+ */
+ protected $_differentFirst = false;
- /**
- * Scale with document, defaults to true
- *
- * @var boolean
- */
- protected $_scaleWithDocument = true;
+ /**
+ * Scale with document, defaults to true
+ *
+ * @var boolean
+ */
+ protected $_scaleWithDocument = true;
- /**
- * Align with margins, defaults to true
- *
- * @var boolean
- */
- protected $_alignWithMargins = true;
+ /**
+ * Align with margins, defaults to true
+ *
+ * @var boolean
+ */
+ protected $_alignWithMargins = true;
- /**
- * Header/footer images
- *
- * @var PHPExcel\Worksheet_HeaderFooterDrawing[]
- */
- protected $_headerFooterImages = array();
+ /**
+ * Header/footer images
+ *
+ * @var PHPExcel\Worksheet_HeaderFooterDrawing[]
+ */
+ protected $_headerFooterImages = array();
/**
* Create a new PHPExcel\Worksheet_HeaderFooter
@@ -195,7 +195,7 @@ class Worksheet_HeaderFooter
* @return string
*/
public function getOddHeader() {
- return $this->_oddHeader;
+ return $this->_oddHeader;
}
/**
@@ -205,8 +205,8 @@ class Worksheet_HeaderFooter
* @return PHPExcel\Worksheet_HeaderFooter
*/
public function setOddHeader($pValue) {
- $this->_oddHeader = $pValue;
- return $this;
+ $this->_oddHeader = $pValue;
+ return $this;
}
/**
@@ -215,7 +215,7 @@ class Worksheet_HeaderFooter
* @return string
*/
public function getOddFooter() {
- return $this->_oddFooter;
+ return $this->_oddFooter;
}
/**
@@ -225,8 +225,8 @@ class Worksheet_HeaderFooter
* @return PHPExcel\Worksheet_HeaderFooter
*/
public function setOddFooter($pValue) {
- $this->_oddFooter = $pValue;
- return $this;
+ $this->_oddFooter = $pValue;
+ return $this;
}
/**
@@ -235,7 +235,7 @@ class Worksheet_HeaderFooter
* @return string
*/
public function getEvenHeader() {
- return $this->_evenHeader;
+ return $this->_evenHeader;
}
/**
@@ -245,8 +245,8 @@ class Worksheet_HeaderFooter
* @return PHPExcel\Worksheet_HeaderFooter
*/
public function setEvenHeader($pValue) {
- $this->_evenHeader = $pValue;
- return $this;
+ $this->_evenHeader = $pValue;
+ return $this;
}
/**
@@ -255,7 +255,7 @@ class Worksheet_HeaderFooter
* @return string
*/
public function getEvenFooter() {
- return $this->_evenFooter;
+ return $this->_evenFooter;
}
/**
@@ -265,8 +265,8 @@ class Worksheet_HeaderFooter
* @return PHPExcel\Worksheet_HeaderFooter
*/
public function setEvenFooter($pValue) {
- $this->_evenFooter = $pValue;
- return $this;
+ $this->_evenFooter = $pValue;
+ return $this;
}
/**
@@ -275,7 +275,7 @@ class Worksheet_HeaderFooter
* @return string
*/
public function getFirstHeader() {
- return $this->_firstHeader;
+ return $this->_firstHeader;
}
/**
@@ -285,8 +285,8 @@ class Worksheet_HeaderFooter
* @return PHPExcel\Worksheet_HeaderFooter
*/
public function setFirstHeader($pValue) {
- $this->_firstHeader = $pValue;
- return $this;
+ $this->_firstHeader = $pValue;
+ return $this;
}
/**
@@ -295,7 +295,7 @@ class Worksheet_HeaderFooter
* @return string
*/
public function getFirstFooter() {
- return $this->_firstFooter;
+ return $this->_firstFooter;
}
/**
@@ -305,8 +305,8 @@ class Worksheet_HeaderFooter
* @return PHPExcel\Worksheet_HeaderFooter
*/
public function setFirstFooter($pValue) {
- $this->_firstFooter = $pValue;
- return $this;
+ $this->_firstFooter = $pValue;
+ return $this;
}
/**
@@ -315,7 +315,7 @@ class Worksheet_HeaderFooter
* @return boolean
*/
public function getDifferentOddEven() {
- return $this->_differentOddEven;
+ return $this->_differentOddEven;
}
/**
@@ -325,8 +325,8 @@ class Worksheet_HeaderFooter
* @return PHPExcel\Worksheet_HeaderFooter
*/
public function setDifferentOddEven($pValue = false) {
- $this->_differentOddEven = $pValue;
- return $this;
+ $this->_differentOddEven = $pValue;
+ return $this;
}
/**
@@ -335,7 +335,7 @@ class Worksheet_HeaderFooter
* @return boolean
*/
public function getDifferentFirst() {
- return $this->_differentFirst;
+ return $this->_differentFirst;
}
/**
@@ -345,8 +345,8 @@ class Worksheet_HeaderFooter
* @return PHPExcel\Worksheet_HeaderFooter
*/
public function setDifferentFirst($pValue = false) {
- $this->_differentFirst = $pValue;
- return $this;
+ $this->_differentFirst = $pValue;
+ return $this;
}
/**
@@ -355,7 +355,7 @@ class Worksheet_HeaderFooter
* @return boolean
*/
public function getScaleWithDocument() {
- return $this->_scaleWithDocument;
+ return $this->_scaleWithDocument;
}
/**
@@ -365,8 +365,8 @@ class Worksheet_HeaderFooter
* @return PHPExcel\Worksheet_HeaderFooter
*/
public function setScaleWithDocument($pValue = true) {
- $this->_scaleWithDocument = $pValue;
- return $this;
+ $this->_scaleWithDocument = $pValue;
+ return $this;
}
/**
@@ -375,7 +375,7 @@ class Worksheet_HeaderFooter
* @return boolean
*/
public function getAlignWithMargins() {
- return $this->_alignWithMargins;
+ return $this->_alignWithMargins;
}
/**
@@ -385,8 +385,8 @@ class Worksheet_HeaderFooter
* @return PHPExcel\Worksheet_HeaderFooter
*/
public function setAlignWithMargins($pValue = true) {
- $this->_alignWithMargins = $pValue;
- return $this;
+ $this->_alignWithMargins = $pValue;
+ return $this;
}
/**
@@ -398,8 +398,8 @@ class Worksheet_HeaderFooter
* @return PHPExcel\Worksheet_HeaderFooter
*/
public function addImage(Worksheet_HeaderFooterDrawing $image = null, $location = self::IMAGE_HEADER_LEFT) {
- $this->_headerFooterImages[$location] = $image;
- return $this;
+ $this->_headerFooterImages[$location] = $image;
+ return $this;
}
/**
@@ -410,10 +410,10 @@ class Worksheet_HeaderFooter
* @return PHPExcel\Worksheet_HeaderFooter
*/
public function removeImage($location = self::IMAGE_HEADER_LEFT) {
- if (isset($this->_headerFooterImages[$location])) {
- unset($this->_headerFooterImages[$location]);
- }
- return $this;
+ if (isset($this->_headerFooterImages[$location])) {
+ unset($this->_headerFooterImages[$location]);
+ }
+ return $this;
}
/**
@@ -424,12 +424,12 @@ class Worksheet_HeaderFooter
* @return PHPExcel\Worksheet_HeaderFooter
*/
public function setImages($images) {
- if (!is_array($images)) {
- throw new Exception('Invalid parameter!');
- }
+ if (!is_array($images)) {
+ throw new Exception('Invalid parameter!');
+ }
- $this->_headerFooterImages = $images;
- return $this;
+ $this->_headerFooterImages = $images;
+ return $this;
}
/**
@@ -438,30 +438,30 @@ class Worksheet_HeaderFooter
* @return PHPExcel\Worksheet_HeaderFooterDrawing[]
*/
public function getImages() {
- // Sort array
- $images = array();
- if (isset($this->_headerFooterImages[self::IMAGE_HEADER_LEFT])) $images[self::IMAGE_HEADER_LEFT] = $this->_headerFooterImages[self::IMAGE_HEADER_LEFT];
- if (isset($this->_headerFooterImages[self::IMAGE_HEADER_CENTER])) $images[self::IMAGE_HEADER_CENTER] = $this->_headerFooterImages[self::IMAGE_HEADER_CENTER];
- if (isset($this->_headerFooterImages[self::IMAGE_HEADER_RIGHT])) $images[self::IMAGE_HEADER_RIGHT] = $this->_headerFooterImages[self::IMAGE_HEADER_RIGHT];
- if (isset($this->_headerFooterImages[self::IMAGE_FOOTER_LEFT])) $images[self::IMAGE_FOOTER_LEFT] = $this->_headerFooterImages[self::IMAGE_FOOTER_LEFT];
- if (isset($this->_headerFooterImages[self::IMAGE_FOOTER_CENTER])) $images[self::IMAGE_FOOTER_CENTER] = $this->_headerFooterImages[self::IMAGE_FOOTER_CENTER];
- if (isset($this->_headerFooterImages[self::IMAGE_FOOTER_RIGHT])) $images[self::IMAGE_FOOTER_RIGHT] = $this->_headerFooterImages[self::IMAGE_FOOTER_RIGHT];
- $this->_headerFooterImages = $images;
+ // Sort array
+ $images = array();
+ if (isset($this->_headerFooterImages[self::IMAGE_HEADER_LEFT])) $images[self::IMAGE_HEADER_LEFT] = $this->_headerFooterImages[self::IMAGE_HEADER_LEFT];
+ if (isset($this->_headerFooterImages[self::IMAGE_HEADER_CENTER])) $images[self::IMAGE_HEADER_CENTER] = $this->_headerFooterImages[self::IMAGE_HEADER_CENTER];
+ if (isset($this->_headerFooterImages[self::IMAGE_HEADER_RIGHT])) $images[self::IMAGE_HEADER_RIGHT] = $this->_headerFooterImages[self::IMAGE_HEADER_RIGHT];
+ if (isset($this->_headerFooterImages[self::IMAGE_FOOTER_LEFT])) $images[self::IMAGE_FOOTER_LEFT] = $this->_headerFooterImages[self::IMAGE_FOOTER_LEFT];
+ if (isset($this->_headerFooterImages[self::IMAGE_FOOTER_CENTER])) $images[self::IMAGE_FOOTER_CENTER] = $this->_headerFooterImages[self::IMAGE_FOOTER_CENTER];
+ if (isset($this->_headerFooterImages[self::IMAGE_FOOTER_RIGHT])) $images[self::IMAGE_FOOTER_RIGHT] = $this->_headerFooterImages[self::IMAGE_FOOTER_RIGHT];
+ $this->_headerFooterImages = $images;
- return $this->_headerFooterImages;
+ return $this->_headerFooterImages;
}
- /**
- * Implement PHP __clone to create a deep clone, not just a shallow copy.
- */
- public function __clone() {
- $vars = get_object_vars($this);
- foreach ($vars as $key => $value) {
- if (is_object($value)) {
- $this->$key = clone $value;
- } else {
- $this->$key = $value;
- }
- }
- }
+ /**
+ * 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;
+ }
+ }
+ }
}
diff --git a/Classes/PHPExcel/Worksheet/HeaderFooterDrawing.php b/Classes/PHPExcel/Worksheet/HeaderFooterDrawing.php
index 3d9b245..53a7c55 100644
--- a/Classes/PHPExcel/Worksheet/HeaderFooterDrawing.php
+++ b/Classes/PHPExcel/Worksheet/HeaderFooterDrawing.php
@@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\Worksheet
* @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,54 +37,54 @@ namespace PHPExcel;
*/
class Worksheet_HeaderFooterDrawing extends Worksheet_Drawing implements IComparable
{
- /**
- * Path
- *
- * @var string
- */
- protected $_path = '';
+ /**
+ * Path
+ *
+ * @var string
+ */
+ protected $_path = '';
- /**
- * Name
- *
- * @var string
- */
- protected $_name = '';
+ /**
+ * Name
+ *
+ * @var string
+ */
+ protected $_name = '';
- /**
- * Offset X
- *
- * @var int
- */
- protected $_offsetX = 0;
+ /**
+ * Offset X
+ *
+ * @var int
+ */
+ protected $_offsetX = 0;
- /**
- * Offset Y
- *
- * @var int
- */
- protected $_offsetY = 0;
+ /**
+ * Offset Y
+ *
+ * @var int
+ */
+ protected $_offsetY = 0;
- /**
- * Width
- *
- * @var int
- */
- protected $_width = 0;
+ /**
+ * Width
+ *
+ * @var int
+ */
+ protected $_width = 0;
- /**
- * Height
- *
- * @var int
- */
- protected $_height = 0;
+ /**
+ * Height
+ *
+ * @var int
+ */
+ protected $_height = 0;
- /**
- * Proportional resize
- *
- * @var boolean
- */
- protected $_resizeProportional = true;
+ /**
+ * Proportional resize
+ *
+ * @var boolean
+ */
+ protected $_resizeProportional = true;
/**
* Create a new PHPExcel\Worksheet_HeaderFooterDrawing
@@ -99,7 +99,7 @@ class Worksheet_HeaderFooterDrawing extends Worksheet_Drawing implements ICompar
* @return string
*/
public function getName() {
- return $this->_name;
+ return $this->_name;
}
/**
@@ -109,8 +109,8 @@ class Worksheet_HeaderFooterDrawing extends Worksheet_Drawing implements ICompar
* @return PHPExcel\Worksheet_HeaderFooterDrawing
*/
public function setName($pValue = '') {
- $this->_name = $pValue;
- return $this;
+ $this->_name = $pValue;
+ return $this;
}
/**
@@ -119,7 +119,7 @@ class Worksheet_HeaderFooterDrawing extends Worksheet_Drawing implements ICompar
* @return int
*/
public function getOffsetX() {
- return $this->_offsetX;
+ return $this->_offsetX;
}
/**
@@ -129,8 +129,8 @@ class Worksheet_HeaderFooterDrawing extends Worksheet_Drawing implements ICompar
* @return PHPExcel\Worksheet_HeaderFooterDrawing
*/
public function setOffsetX($pValue = 0) {
- $this->_offsetX = $pValue;
- return $this;
+ $this->_offsetX = $pValue;
+ return $this;
}
/**
@@ -139,7 +139,7 @@ class Worksheet_HeaderFooterDrawing extends Worksheet_Drawing implements ICompar
* @return int
*/
public function getOffsetY() {
- return $this->_offsetY;
+ return $this->_offsetY;
}
/**
@@ -149,8 +149,8 @@ class Worksheet_HeaderFooterDrawing extends Worksheet_Drawing implements ICompar
* @return PHPExcel\Worksheet_HeaderFooterDrawing
*/
public function setOffsetY($pValue = 0) {
- $this->_offsetY = $pValue;
- return $this;
+ $this->_offsetY = $pValue;
+ return $this;
}
/**
@@ -159,7 +159,7 @@ class Worksheet_HeaderFooterDrawing extends Worksheet_Drawing implements ICompar
* @return int
*/
public function getWidth() {
- return $this->_width;
+ return $this->_width;
}
/**
@@ -169,16 +169,16 @@ class Worksheet_HeaderFooterDrawing extends Worksheet_Drawing implements ICompar
* @return PHPExcel\Worksheet_HeaderFooterDrawing
*/
public function setWidth($pValue = 0) {
- // Resize proportional?
- if ($this->_resizeProportional && $pValue != 0) {
- $ratio = $this->_width / $this->_height;
- $this->_height = round($ratio * $pValue);
- }
+ // Resize proportional?
+ if ($this->_resizeProportional && $pValue != 0) {
+ $ratio = $this->_width / $this->_height;
+ $this->_height = round($ratio * $pValue);
+ }
- // Set width
- $this->_width = $pValue;
+ // Set width
+ $this->_width = $pValue;
- return $this;
+ return $this;
}
/**
@@ -187,7 +187,7 @@ class Worksheet_HeaderFooterDrawing extends Worksheet_Drawing implements ICompar
* @return int
*/
public function getHeight() {
- return $this->_height;
+ return $this->_height;
}
/**
@@ -197,45 +197,45 @@ class Worksheet_HeaderFooterDrawing extends Worksheet_Drawing implements ICompar
* @return PHPExcel\Worksheet_HeaderFooterDrawing
*/
public function setHeight($pValue = 0) {
- // Resize proportional?
- if ($this->_resizeProportional && $pValue != 0) {
- $ratio = $this->_width / $this->_height;
- $this->_width = round($ratio * $pValue);
- }
+ // Resize proportional?
+ if ($this->_resizeProportional && $pValue != 0) {
+ $ratio = $this->_width / $this->_height;
+ $this->_width = round($ratio * $pValue);
+ }
- // Set height
- $this->_height = $pValue;
+ // Set height
+ $this->_height = $pValue;
- return $this;
+ return $this;
}
/**
* Set width and height with proportional resize
- * Example:
- *
+ * Example:
+ *
+ *
* @author Vincent@luo MSN:kele_100@hotmail.com
* @param int $width
* @param int $height
* @return PHPExcel\Worksheet_HeaderFooterDrawing
*/
- public function setWidthAndHeight($width = 0, $height = 0) {
- $xratio = $width / $this->_width;
- $yratio = $height / $this->_height;
- if ($this->_resizeProportional && !($width == 0 || $height == 0)) {
- if (($xratio * $this->_height) < $height) {
- $this->_height = ceil($xratio * $this->_height);
- $this->_width = $width;
- } else {
- $this->_width = ceil($yratio * $this->_width);
- $this->_height = $height;
- }
- }
- return $this;
- }
+ public function setWidthAndHeight($width = 0, $height = 0) {
+ $xratio = $width / $this->_width;
+ $yratio = $height / $this->_height;
+ if ($this->_resizeProportional && !($width == 0 || $height == 0)) {
+ if (($xratio * $this->_height) < $height) {
+ $this->_height = ceil($xratio * $this->_height);
+ $this->_width = $width;
+ } else {
+ $this->_width = ceil($yratio * $this->_width);
+ $this->_height = $height;
+ }
+ }
+ return $this;
+ }
/**
* Get ResizeProportional
@@ -243,7 +243,7 @@ class Worksheet_HeaderFooterDrawing extends Worksheet_Drawing implements ICompar
* @return boolean
*/
public function getResizeProportional() {
- return $this->_resizeProportional;
+ return $this->_resizeProportional;
}
/**
@@ -253,8 +253,8 @@ class Worksheet_HeaderFooterDrawing extends Worksheet_Drawing implements ICompar
* @return PHPExcel\Worksheet_HeaderFooterDrawing
*/
public function setResizeProportional($pValue = true) {
- $this->_resizeProportional = $pValue;
- return $this;
+ $this->_resizeProportional = $pValue;
+ return $this;
}
/**
@@ -263,7 +263,7 @@ class Worksheet_HeaderFooterDrawing extends Worksheet_Drawing implements ICompar
* @return string
*/
public function getFilename() {
- return basename($this->_path);
+ return basename($this->_path);
}
/**
@@ -282,63 +282,63 @@ class Worksheet_HeaderFooterDrawing extends Worksheet_Drawing implements ICompar
* @return string
*/
public function getPath() {
- return $this->_path;
+ return $this->_path;
}
/**
* Set Path
*
- * @param string $pValue File path
- * @param boolean $pVerifyFile Verify file
- * @throws PHPExcel\Exception
+ * @param string $pValue File path
+ * @param boolean $pVerifyFile Verify file
+ * @throws PHPExcel\Exception
* @return PHPExcel\Worksheet_HeaderFooterDrawing
*/
public function setPath($pValue = '', $pVerifyFile = true) {
- if ($pVerifyFile) {
- if (file_exists($pValue)) {
- $this->_path = $pValue;
+ if ($pVerifyFile) {
+ if (file_exists($pValue)) {
+ $this->_path = $pValue;
- if ($this->_width == 0 && $this->_height == 0) {
- // Get width/height
- list($this->_width, $this->_height) = getimagesize($pValue);
- }
- } else {
- throw new Exception("File $pValue not found!");
- }
- } else {
- $this->_path = $pValue;
- }
- return $this;
+ if ($this->_width == 0 && $this->_height == 0) {
+ // Get width/height
+ list($this->_width, $this->_height) = getimagesize($pValue);
+ }
+ } else {
+ throw new Exception("File $pValue not found!");
+ }
+ } else {
+ $this->_path = $pValue;
+ }
+ return $this;
}
- /**
- * Get hash code
- *
- * @return string Hash code
- */
- public function getHashCode() {
- return md5(
- $this->_path
- . $this->_name
- . $this->_offsetX
- . $this->_offsetY
- . $this->_width
- . $this->_height
- . __CLASS__
- );
+ /**
+ * Get hash code
+ *
+ * @return string Hash code
+ */
+ public function getHashCode() {
+ return md5(
+ $this->_path
+ . $this->_name
+ . $this->_offsetX
+ . $this->_offsetY
+ . $this->_width
+ . $this->_height
+ . __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;
- }
- }
- }
+ /**
+ * 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;
+ }
+ }
+ }
}
diff --git a/Classes/PHPExcel/Worksheet/MemoryDrawing.php b/Classes/PHPExcel/Worksheet/MemoryDrawing.php
index b6fe9cb..8fe58ec 100644
--- a/Classes/PHPExcel/Worksheet/MemoryDrawing.php
+++ b/Classes/PHPExcel/Worksheet/MemoryDrawing.php
@@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\Worksheet
* @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,56 +37,56 @@ namespace PHPExcel;
*/
class Worksheet_MemoryDrawing extends Worksheet_BaseDrawing implements IComparable
{
- /* Rendering functions */
- const RENDERING_DEFAULT = 'imagepng';
- const RENDERING_PNG = 'imagepng';
- const RENDERING_GIF = 'imagegif';
- const RENDERING_JPEG = 'imagejpeg';
+ /* Rendering functions */
+ const RENDERING_DEFAULT = 'imagepng';
+ const RENDERING_PNG = 'imagepng';
+ const RENDERING_GIF = 'imagegif';
+ const RENDERING_JPEG = 'imagejpeg';
- /* MIME types */
- const MIMETYPE_DEFAULT = 'image/png';
- const MIMETYPE_PNG = 'image/png';
- const MIMETYPE_GIF = 'image/gif';
- const MIMETYPE_JPEG = 'image/jpeg';
+ /* MIME types */
+ const MIMETYPE_DEFAULT = 'image/png';
+ const MIMETYPE_PNG = 'image/png';
+ const MIMETYPE_GIF = 'image/gif';
+ const MIMETYPE_JPEG = 'image/jpeg';
- /**
- * Image resource
- *
- * @var resource
- */
- protected $_imageResource;
+ /**
+ * Image resource
+ *
+ * @var resource
+ */
+ protected $_imageResource;
- /**
- * Rendering function
- *
- * @var string
- */
- protected $_renderingFunction = self::RENDERING_DEFAULT;
+ /**
+ * Rendering function
+ *
+ * @var string
+ */
+ protected $_renderingFunction = self::RENDERING_DEFAULT;
- /**
- * Mime type
- *
- * @var string
- */
- protected $_mimeType = self::MIMETYPE_DEFAULT;
+ /**
+ * Mime type
+ *
+ * @var string
+ */
+ protected $_mimeType = self::MIMETYPE_DEFAULT;
- /**
- * Unique name
- *
- * @var string
- */
- protected $_uniqueName;
+ /**
+ * Unique name
+ *
+ * @var string
+ */
+ protected $_uniqueName;
/**
* Create a new PHPExcel\Worksheet_MemoryDrawing
*/
public function __construct()
{
- // Initialise values
- $this->_uniqueName = md5(rand(0, 9999). time() . rand(0, 9999));
+ // Initialise values
+ $this->_uniqueName = md5(rand(0, 9999). time() . rand(0, 9999));
- // Initialize parent
- parent::__construct();
+ // Initialize parent
+ parent::__construct();
}
/**
@@ -95,24 +95,24 @@ class Worksheet_MemoryDrawing extends Worksheet_BaseDrawing implements IComparab
* @return resource
*/
public function getImageResource() {
- return $this->_imageResource;
+ return $this->_imageResource;
}
/**
* Set image resource
*
- * @param $value resource
+ * @param $value resource
* @return PHPExcel\Worksheet_MemoryDrawing
*/
public function setImageResource($value = null) {
- $this->_imageResource = $value;
+ $this->_imageResource = $value;
- if (!is_null($this->_imageResource)) {
- // Get width/height
- $this->_width = imagesx($this->_imageResource);
- $this->_height = imagesy($this->_imageResource);
- }
- return $this;
+ if (!is_null($this->_imageResource)) {
+ // Get width/height
+ $this->_width = imagesx($this->_imageResource);
+ $this->_height = imagesy($this->_imageResource);
+ }
+ return $this;
}
/**
@@ -121,7 +121,7 @@ class Worksheet_MemoryDrawing extends Worksheet_BaseDrawing implements IComparab
* @return string
*/
public function getRenderingFunction() {
- return $this->_renderingFunction;
+ return $this->_renderingFunction;
}
/**
@@ -131,8 +131,8 @@ class Worksheet_MemoryDrawing extends Worksheet_BaseDrawing implements IComparab
* @return PHPExcel\Worksheet_MemoryDrawing
*/
public function setRenderingFunction($value = Worksheet_MemoryDrawing::RENDERING_DEFAULT) {
- $this->_renderingFunction = $value;
- return $this;
+ $this->_renderingFunction = $value;
+ return $this;
}
/**
@@ -141,7 +141,7 @@ class Worksheet_MemoryDrawing extends Worksheet_BaseDrawing implements IComparab
* @return string
*/
public function getMimeType() {
- return $this->_mimeType;
+ return $this->_mimeType;
}
/**
@@ -151,8 +151,8 @@ class Worksheet_MemoryDrawing extends Worksheet_BaseDrawing implements IComparab
* @return PHPExcel\Worksheet_MemoryDrawing
*/
public function setMimeType($value = Worksheet_MemoryDrawing::MIMETYPE_DEFAULT) {
- $this->_mimeType = $value;
- return $this;
+ $this->_mimeType = $value;
+ return $this;
}
/**
@@ -161,39 +161,39 @@ class Worksheet_MemoryDrawing extends Worksheet_BaseDrawing implements IComparab
* @return string
*/
public function getIndexedFilename() {
- $extension = strtolower($this->getMimeType());
- $extension = explode('/', $extension);
- $extension = $extension[1];
+ $extension = strtolower($this->getMimeType());
+ $extension = explode('/', $extension);
+ $extension = $extension[1];
- return $this->_uniqueName . $this->getImageIndex() . '.' . $extension;
+ return $this->_uniqueName . $this->getImageIndex() . '.' . $extension;
}
- /**
- * Get hash code
- *
- * @return string Hash code
- */
- public function getHashCode() {
- return md5(
- $this->_renderingFunction
- . $this->_mimeType
- . $this->_uniqueName
- . parent::getHashCode()
- . __CLASS__
- );
+ /**
+ * Get hash code
+ *
+ * @return string Hash code
+ */
+ public function getHashCode() {
+ return md5(
+ $this->_renderingFunction
+ . $this->_mimeType
+ . $this->_uniqueName
+ . parent::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;
- }
- }
- }
+ /**
+ * 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;
+ }
+ }
+ }
}
diff --git a/Classes/PHPExcel/Worksheet/PageMargins.php b/Classes/PHPExcel/Worksheet/PageMargins.php
index e7e278c..6e1118b 100644
--- a/Classes/PHPExcel/Worksheet/PageMargins.php
+++ b/Classes/PHPExcel/Worksheet/PageMargins.php
@@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\Worksheet
* @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,47 +37,47 @@ namespace PHPExcel;
*/
class Worksheet_PageMargins
{
- /**
- * Left
- *
- * @var double
- */
- protected $_left = 0.7;
+ /**
+ * Left
+ *
+ * @var double
+ */
+ protected $_left = 0.7;
- /**
- * Right
- *
- * @var double
- */
- protected $_right = 0.7;
+ /**
+ * Right
+ *
+ * @var double
+ */
+ protected $_right = 0.7;
- /**
- * Top
- *
- * @var double
- */
- protected $_top = 0.75;
+ /**
+ * Top
+ *
+ * @var double
+ */
+ protected $_top = 0.75;
- /**
- * Bottom
- *
- * @var double
- */
- protected $_bottom = 0.75;
+ /**
+ * Bottom
+ *
+ * @var double
+ */
+ protected $_bottom = 0.75;
- /**
- * Header
- *
- * @var double
- */
- protected $_header = 0.3;
+ /**
+ * Header
+ *
+ * @var double
+ */
+ protected $_header = 0.3;
- /**
- * Footer
- *
- * @var double
- */
- protected $_footer = 0.3;
+ /**
+ * Footer
+ *
+ * @var double
+ */
+ protected $_footer = 0.3;
/**
* Create a new PHPExcel\Worksheet_PageMargins
@@ -92,7 +92,7 @@ class Worksheet_PageMargins
* @return double
*/
public function getLeft() {
- return $this->_left;
+ return $this->_left;
}
/**
@@ -102,8 +102,8 @@ class Worksheet_PageMargins
* @return PHPExcel\Worksheet_PageMargins
*/
public function setLeft($pValue) {
- $this->_left = $pValue;
- return $this;
+ $this->_left = $pValue;
+ return $this;
}
/**
@@ -112,7 +112,7 @@ class Worksheet_PageMargins
* @return double
*/
public function getRight() {
- return $this->_right;
+ return $this->_right;
}
/**
@@ -122,8 +122,8 @@ class Worksheet_PageMargins
* @return PHPExcel\Worksheet_PageMargins
*/
public function setRight($pValue) {
- $this->_right = $pValue;
- return $this;
+ $this->_right = $pValue;
+ return $this;
}
/**
@@ -132,7 +132,7 @@ class Worksheet_PageMargins
* @return double
*/
public function getTop() {
- return $this->_top;
+ return $this->_top;
}
/**
@@ -142,8 +142,8 @@ class Worksheet_PageMargins
* @return PHPExcel\Worksheet_PageMargins
*/
public function setTop($pValue) {
- $this->_top = $pValue;
- return $this;
+ $this->_top = $pValue;
+ return $this;
}
/**
@@ -152,7 +152,7 @@ class Worksheet_PageMargins
* @return double
*/
public function getBottom() {
- return $this->_bottom;
+ return $this->_bottom;
}
/**
@@ -162,8 +162,8 @@ class Worksheet_PageMargins
* @return PHPExcel\Worksheet_PageMargins
*/
public function setBottom($pValue) {
- $this->_bottom = $pValue;
- return $this;
+ $this->_bottom = $pValue;
+ return $this;
}
/**
@@ -172,7 +172,7 @@ class Worksheet_PageMargins
* @return double
*/
public function getHeader() {
- return $this->_header;
+ return $this->_header;
}
/**
@@ -182,8 +182,8 @@ class Worksheet_PageMargins
* @return PHPExcel\Worksheet_PageMargins
*/
public function setHeader($pValue) {
- $this->_header = $pValue;
- return $this;
+ $this->_header = $pValue;
+ return $this;
}
/**
@@ -192,7 +192,7 @@ class Worksheet_PageMargins
* @return double
*/
public function getFooter() {
- return $this->_footer;
+ return $this->_footer;
}
/**
@@ -202,21 +202,21 @@ class Worksheet_PageMargins
* @return PHPExcel\Worksheet_PageMargins
*/
public function setFooter($pValue) {
- $this->_footer = $pValue;
- return $this;
+ $this->_footer = $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;
+ }
+ }
+ }
}
diff --git a/Classes/PHPExcel/Worksheet/PageSetup.php b/Classes/PHPExcel/Worksheet/PageSetup.php
index bcee357..1cf1da1 100644
--- a/Classes/PHPExcel/Worksheet/PageSetup.php
+++ b/Classes/PHPExcel/Worksheet/PageSetup.php
@@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\Worksheet
* @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##
*/
@@ -108,173 +108,173 @@ namespace PHPExcel;
*/
class Worksheet_PageSetup
{
- /* Paper size */
- const PAPERSIZE_LETTER = 1;
- const PAPERSIZE_LETTER_SMALL = 2;
- const PAPERSIZE_TABLOID = 3;
- const PAPERSIZE_LEDGER = 4;
- const PAPERSIZE_LEGAL = 5;
- const PAPERSIZE_STATEMENT = 6;
- const PAPERSIZE_EXECUTIVE = 7;
- const PAPERSIZE_A3 = 8;
- const PAPERSIZE_A4 = 9;
- const PAPERSIZE_A4_SMALL = 10;
- const PAPERSIZE_A5 = 11;
- const PAPERSIZE_B4 = 12;
- const PAPERSIZE_B5 = 13;
- const PAPERSIZE_FOLIO = 14;
- const PAPERSIZE_QUARTO = 15;
- const PAPERSIZE_STANDARD_1 = 16;
- const PAPERSIZE_STANDARD_2 = 17;
- const PAPERSIZE_NOTE = 18;
- const PAPERSIZE_NO9_ENVELOPE = 19;
- const PAPERSIZE_NO10_ENVELOPE = 20;
- const PAPERSIZE_NO11_ENVELOPE = 21;
- const PAPERSIZE_NO12_ENVELOPE = 22;
- const PAPERSIZE_NO14_ENVELOPE = 23;
- const PAPERSIZE_C = 24;
- const PAPERSIZE_D = 25;
- const PAPERSIZE_E = 26;
- const PAPERSIZE_DL_ENVELOPE = 27;
- const PAPERSIZE_C5_ENVELOPE = 28;
- const PAPERSIZE_C3_ENVELOPE = 29;
- const PAPERSIZE_C4_ENVELOPE = 30;
- const PAPERSIZE_C6_ENVELOPE = 31;
- const PAPERSIZE_C65_ENVELOPE = 32;
- const PAPERSIZE_B4_ENVELOPE = 33;
- const PAPERSIZE_B5_ENVELOPE = 34;
- const PAPERSIZE_B6_ENVELOPE = 35;
- const PAPERSIZE_ITALY_ENVELOPE = 36;
- const PAPERSIZE_MONARCH_ENVELOPE = 37;
- const PAPERSIZE_6_3_4_ENVELOPE = 38;
- const PAPERSIZE_US_STANDARD_FANFOLD = 39;
- const PAPERSIZE_GERMAN_STANDARD_FANFOLD = 40;
- const PAPERSIZE_GERMAN_LEGAL_FANFOLD = 41;
- const PAPERSIZE_ISO_B4 = 42;
- const PAPERSIZE_JAPANESE_DOUBLE_POSTCARD = 43;
- const PAPERSIZE_STANDARD_PAPER_1 = 44;
- const PAPERSIZE_STANDARD_PAPER_2 = 45;
- const PAPERSIZE_STANDARD_PAPER_3 = 46;
- const PAPERSIZE_INVITE_ENVELOPE = 47;
- const PAPERSIZE_LETTER_EXTRA_PAPER = 48;
- const PAPERSIZE_LEGAL_EXTRA_PAPER = 49;
- const PAPERSIZE_TABLOID_EXTRA_PAPER = 50;
- const PAPERSIZE_A4_EXTRA_PAPER = 51;
- const PAPERSIZE_LETTER_TRANSVERSE_PAPER = 52;
- const PAPERSIZE_A4_TRANSVERSE_PAPER = 53;
- const PAPERSIZE_LETTER_EXTRA_TRANSVERSE_PAPER = 54;
- const PAPERSIZE_SUPERA_SUPERA_A4_PAPER = 55;
- const PAPERSIZE_SUPERB_SUPERB_A3_PAPER = 56;
- const PAPERSIZE_LETTER_PLUS_PAPER = 57;
- const PAPERSIZE_A4_PLUS_PAPER = 58;
- const PAPERSIZE_A5_TRANSVERSE_PAPER = 59;
- const PAPERSIZE_JIS_B5_TRANSVERSE_PAPER = 60;
- const PAPERSIZE_A3_EXTRA_PAPER = 61;
- const PAPERSIZE_A5_EXTRA_PAPER = 62;
- const PAPERSIZE_ISO_B5_EXTRA_PAPER = 63;
- const PAPERSIZE_A2_PAPER = 64;
- const PAPERSIZE_A3_TRANSVERSE_PAPER = 65;
- const PAPERSIZE_A3_EXTRA_TRANSVERSE_PAPER = 66;
+ /* Paper size */
+ const PAPERSIZE_LETTER = 1;
+ const PAPERSIZE_LETTER_SMALL = 2;
+ const PAPERSIZE_TABLOID = 3;
+ const PAPERSIZE_LEDGER = 4;
+ const PAPERSIZE_LEGAL = 5;
+ const PAPERSIZE_STATEMENT = 6;
+ const PAPERSIZE_EXECUTIVE = 7;
+ const PAPERSIZE_A3 = 8;
+ const PAPERSIZE_A4 = 9;
+ const PAPERSIZE_A4_SMALL = 10;
+ const PAPERSIZE_A5 = 11;
+ const PAPERSIZE_B4 = 12;
+ const PAPERSIZE_B5 = 13;
+ const PAPERSIZE_FOLIO = 14;
+ const PAPERSIZE_QUARTO = 15;
+ const PAPERSIZE_STANDARD_1 = 16;
+ const PAPERSIZE_STANDARD_2 = 17;
+ const PAPERSIZE_NOTE = 18;
+ const PAPERSIZE_NO9_ENVELOPE = 19;
+ const PAPERSIZE_NO10_ENVELOPE = 20;
+ const PAPERSIZE_NO11_ENVELOPE = 21;
+ const PAPERSIZE_NO12_ENVELOPE = 22;
+ const PAPERSIZE_NO14_ENVELOPE = 23;
+ const PAPERSIZE_C = 24;
+ const PAPERSIZE_D = 25;
+ const PAPERSIZE_E = 26;
+ const PAPERSIZE_DL_ENVELOPE = 27;
+ const PAPERSIZE_C5_ENVELOPE = 28;
+ const PAPERSIZE_C3_ENVELOPE = 29;
+ const PAPERSIZE_C4_ENVELOPE = 30;
+ const PAPERSIZE_C6_ENVELOPE = 31;
+ const PAPERSIZE_C65_ENVELOPE = 32;
+ const PAPERSIZE_B4_ENVELOPE = 33;
+ const PAPERSIZE_B5_ENVELOPE = 34;
+ const PAPERSIZE_B6_ENVELOPE = 35;
+ const PAPERSIZE_ITALY_ENVELOPE = 36;
+ const PAPERSIZE_MONARCH_ENVELOPE = 37;
+ const PAPERSIZE_6_3_4_ENVELOPE = 38;
+ const PAPERSIZE_US_STANDARD_FANFOLD = 39;
+ const PAPERSIZE_GERMAN_STANDARD_FANFOLD = 40;
+ const PAPERSIZE_GERMAN_LEGAL_FANFOLD = 41;
+ const PAPERSIZE_ISO_B4 = 42;
+ const PAPERSIZE_JAPANESE_DOUBLE_POSTCARD = 43;
+ const PAPERSIZE_STANDARD_PAPER_1 = 44;
+ const PAPERSIZE_STANDARD_PAPER_2 = 45;
+ const PAPERSIZE_STANDARD_PAPER_3 = 46;
+ const PAPERSIZE_INVITE_ENVELOPE = 47;
+ const PAPERSIZE_LETTER_EXTRA_PAPER = 48;
+ const PAPERSIZE_LEGAL_EXTRA_PAPER = 49;
+ const PAPERSIZE_TABLOID_EXTRA_PAPER = 50;
+ const PAPERSIZE_A4_EXTRA_PAPER = 51;
+ const PAPERSIZE_LETTER_TRANSVERSE_PAPER = 52;
+ const PAPERSIZE_A4_TRANSVERSE_PAPER = 53;
+ const PAPERSIZE_LETTER_EXTRA_TRANSVERSE_PAPER = 54;
+ const PAPERSIZE_SUPERA_SUPERA_A4_PAPER = 55;
+ const PAPERSIZE_SUPERB_SUPERB_A3_PAPER = 56;
+ const PAPERSIZE_LETTER_PLUS_PAPER = 57;
+ const PAPERSIZE_A4_PLUS_PAPER = 58;
+ const PAPERSIZE_A5_TRANSVERSE_PAPER = 59;
+ const PAPERSIZE_JIS_B5_TRANSVERSE_PAPER = 60;
+ const PAPERSIZE_A3_EXTRA_PAPER = 61;
+ const PAPERSIZE_A5_EXTRA_PAPER = 62;
+ const PAPERSIZE_ISO_B5_EXTRA_PAPER = 63;
+ const PAPERSIZE_A2_PAPER = 64;
+ const PAPERSIZE_A3_TRANSVERSE_PAPER = 65;
+ const PAPERSIZE_A3_EXTRA_TRANSVERSE_PAPER = 66;
- /* Page orientation */
- const ORIENTATION_DEFAULT = 'default';
- const ORIENTATION_LANDSCAPE = 'landscape';
- const ORIENTATION_PORTRAIT = 'portrait';
+ /* Page orientation */
+ const ORIENTATION_DEFAULT = 'default';
+ const ORIENTATION_LANDSCAPE = 'landscape';
+ const ORIENTATION_PORTRAIT = 'portrait';
- /* Print Range Set Method */
- const SETPRINTRANGE_OVERWRITE = 'O';
- const SETPRINTRANGE_INSERT = 'I';
+ /* Print Range Set Method */
+ const SETPRINTRANGE_OVERWRITE = 'O';
+ const SETPRINTRANGE_INSERT = 'I';
- /**
- * Paper size
- *
- * @var int
- */
- protected $_paperSize = Worksheet_PageSetup::PAPERSIZE_LETTER;
+ /**
+ * Paper size
+ *
+ * @var int
+ */
+ protected $_paperSize = Worksheet_PageSetup::PAPERSIZE_LETTER;
- /**
- * Orientation
- *
- * @var string
- */
- protected $_orientation = Worksheet_PageSetup::ORIENTATION_DEFAULT;
+ /**
+ * Orientation
+ *
+ * @var string
+ */
+ protected $_orientation = Worksheet_PageSetup::ORIENTATION_DEFAULT;
- /**
- * Scale (Print Scale)
- *
- * Print scaling. Valid values range from 10 to 400
- * This setting is overridden when fitToWidth and/or fitToHeight are in use
- *
- * @var int?
- */
- protected $_scale = 100;
+ /**
+ * Scale (Print Scale)
+ *
+ * Print scaling. Valid values range from 10 to 400
+ * This setting is overridden when fitToWidth and/or fitToHeight are in use
+ *
+ * @var int?
+ */
+ protected $_scale = 100;
- /**
- * Fit To Page
- * Whether scale or fitToWith / fitToHeight applies
- *
- * @var boolean
- */
- protected $_fitToPage = FALSE;
+ /**
+ * Fit To Page
+ * Whether scale or fitToWith / fitToHeight applies
+ *
+ * @var boolean
+ */
+ protected $_fitToPage = false;
- /**
- * Fit To Height
- * Number of vertical pages to fit on
- *
- * @var int?
- */
- protected $_fitToHeight = 1;
+ /**
+ * Fit To Height
+ * Number of vertical pages to fit on
+ *
+ * @var int?
+ */
+ protected $_fitToHeight = 1;
- /**
- * Fit To Width
- * Number of horizontal pages to fit on
- *
- * @var int?
- */
- protected $_fitToWidth = 1;
+ /**
+ * Fit To Width
+ * Number of horizontal pages to fit on
+ *
+ * @var int?
+ */
+ protected $_fitToWidth = 1;
- /**
- * Columns to repeat at left
- *
- * @var array Containing start column and end column, empty array if option unset
- */
- protected $_columnsToRepeatAtLeft = array('', '');
+ /**
+ * Columns to repeat at left
+ *
+ * @var array Containing start column and end column, empty array if option unset
+ */
+ protected $_columnsToRepeatAtLeft = array('', '');
- /**
- * Rows to repeat at top
- *
- * @var array Containing start row number and end row number, empty array if option unset
- */
- protected $_rowsToRepeatAtTop = array(0, 0);
+ /**
+ * Rows to repeat at top
+ *
+ * @var array Containing start row number and end row number, empty array if option unset
+ */
+ protected $_rowsToRepeatAtTop = array(0, 0);
- /**
- * Center page horizontally
- *
- * @var boolean
- */
- protected $_horizontalCentered = FALSE;
+ /**
+ * Center page horizontally
+ *
+ * @var boolean
+ */
+ protected $_horizontalCentered = false;
- /**
- * Center page vertically
- *
- * @var boolean
- */
- protected $_verticalCentered = FALSE;
+ /**
+ * Center page vertically
+ *
+ * @var boolean
+ */
+ protected $_verticalCentered = false;
- /**
- * Print area
- *
- * @var string
- */
- protected $_printArea = NULL;
+ /**
+ * Print area
+ *
+ * @var string
+ */
+ protected $_printArea = null;
- /**
- * First page number
- *
- * @var int
- */
- protected $_firstPageNumber = NULL;
+ /**
+ * First page number
+ *
+ * @var int
+ */
+ protected $_firstPageNumber = null;
/**
* Create a new PHPExcel\Worksheet_PageSetup
@@ -289,7 +289,7 @@ class Worksheet_PageSetup
* @return int
*/
public function getPaperSize() {
- return $this->_paperSize;
+ return $this->_paperSize;
}
/**
@@ -299,8 +299,8 @@ class Worksheet_PageSetup
* @return PHPExcel\Worksheet_PageSetup
*/
public function setPaperSize($pValue = Worksheet_PageSetup::PAPERSIZE_LETTER) {
- $this->_paperSize = $pValue;
- return $this;
+ $this->_paperSize = $pValue;
+ return $this;
}
/**
@@ -309,7 +309,7 @@ class Worksheet_PageSetup
* @return string
*/
public function getOrientation() {
- return $this->_orientation;
+ return $this->_orientation;
}
/**
@@ -319,449 +319,449 @@ class Worksheet_PageSetup
* @return PHPExcel\Worksheet_PageSetup
*/
public function setOrientation($pValue = Worksheet_PageSetup::ORIENTATION_DEFAULT) {
- $this->_orientation = $pValue;
- return $this;
+ $this->_orientation = $pValue;
+ return $this;
}
- /**
- * Get Scale
- *
- * @return int?
- */
- public function getScale() {
- return $this->_scale;
- }
+ /**
+ * Get Scale
+ *
+ * @return int?
+ */
+ public function getScale() {
+ return $this->_scale;
+ }
- /**
- * Set Scale
- *
- * Print scaling. Valid values range from 10 to 400
- * This setting is overridden when fitToWidth and/or fitToHeight are in use
- *
- * @param int? $pValue
- * @param boolean $pUpdate Update fitToPage so scaling applies rather than fitToHeight / fitToWidth
- * @return PHPExcel\Worksheet_PageSetup
- * @throws PHPExcel\Exception
- */
- public function setScale($pValue = 100, $pUpdate = true) {
- // Microsoft Office Excel 2007 only allows setting a scale between 10 and 400 via the user interface,
- // but it is apparently still able to handle any scale >= 0, where 0 results in 100
- if (($pValue >= 0) || is_null($pValue)) {
- $this->_scale = $pValue;
- if ($pUpdate) {
- $this->_fitToPage = false;
- }
- } else {
- throw new Exception("Scale must not be negative");
- }
- return $this;
- }
+ /**
+ * Set Scale
+ *
+ * Print scaling. Valid values range from 10 to 400
+ * This setting is overridden when fitToWidth and/or fitToHeight are in use
+ *
+ * @param int? $pValue
+ * @param boolean $pUpdate Update fitToPage so scaling applies rather than fitToHeight / fitToWidth
+ * @return PHPExcel\Worksheet_PageSetup
+ * @throws PHPExcel\Exception
+ */
+ public function setScale($pValue = 100, $pUpdate = true) {
+ // Microsoft Office Excel 2007 only allows setting a scale between 10 and 400 via the user interface,
+ // but it is apparently still able to handle any scale >= 0, where 0 results in 100
+ if (($pValue >= 0) || is_null($pValue)) {
+ $this->_scale = $pValue;
+ if ($pUpdate) {
+ $this->_fitToPage = false;
+ }
+ } else {
+ throw new Exception("Scale must not be negative");
+ }
+ return $this;
+ }
- /**
- * Get Fit To Page
- *
- * @return boolean
- */
- public function getFitToPage() {
- return $this->_fitToPage;
- }
+ /**
+ * Get Fit To Page
+ *
+ * @return boolean
+ */
+ public function getFitToPage() {
+ return $this->_fitToPage;
+ }
- /**
- * Set Fit To Page
- *
- * @param boolean $pValue
- * @return PHPExcel\Worksheet_PageSetup
- */
- public function setFitToPage($pValue = TRUE) {
- $this->_fitToPage = $pValue;
- return $this;
- }
+ /**
+ * Set Fit To Page
+ *
+ * @param boolean $pValue
+ * @return PHPExcel\Worksheet_PageSetup
+ */
+ public function setFitToPage($pValue = TRUE) {
+ $this->_fitToPage = $pValue;
+ return $this;
+ }
- /**
- * Get Fit To Height
- *
- * @return int?
- */
- public function getFitToHeight() {
- return $this->_fitToHeight;
- }
+ /**
+ * Get Fit To Height
+ *
+ * @return int?
+ */
+ public function getFitToHeight() {
+ return $this->_fitToHeight;
+ }
- /**
- * Set Fit To Height
- *
- * @param int? $pValue
- * @param boolean $pUpdate Update fitToPage so it applies rather than scaling
- * @return PHPExcel\Worksheet_PageSetup
- */
- public function setFitToHeight($pValue = 1, $pUpdate = TRUE) {
- $this->_fitToHeight = $pValue;
- if ($pUpdate) {
- $this->_fitToPage = TRUE;
- }
- return $this;
- }
+ /**
+ * Set Fit To Height
+ *
+ * @param int? $pValue
+ * @param boolean $pUpdate Update fitToPage so it applies rather than scaling
+ * @return PHPExcel\Worksheet_PageSetup
+ */
+ public function setFitToHeight($pValue = 1, $pUpdate = TRUE) {
+ $this->_fitToHeight = $pValue;
+ if ($pUpdate) {
+ $this->_fitToPage = TRUE;
+ }
+ return $this;
+ }
- /**
- * Get Fit To Width
- *
- * @return int?
- */
- public function getFitToWidth() {
- return $this->_fitToWidth;
- }
+ /**
+ * Get Fit To Width
+ *
+ * @return int?
+ */
+ public function getFitToWidth() {
+ return $this->_fitToWidth;
+ }
- /**
- * Set Fit To Width
- *
- * @param int? $pValue
- * @param boolean $pUpdate Update fitToPage so it applies rather than scaling
- * @return PHPExcel\Worksheet_PageSetup
- */
- public function setFitToWidth($pValue = 1, $pUpdate = TRUE) {
- $this->_fitToWidth = $pValue;
- if ($pUpdate) {
- $this->_fitToPage = TRUE;
- }
- return $this;
- }
+ /**
+ * Set Fit To Width
+ *
+ * @param int? $pValue
+ * @param boolean $pUpdate Update fitToPage so it applies rather than scaling
+ * @return PHPExcel\Worksheet_PageSetup
+ */
+ public function setFitToWidth($pValue = 1, $pUpdate = TRUE) {
+ $this->_fitToWidth = $pValue;
+ if ($pUpdate) {
+ $this->_fitToPage = TRUE;
+ }
+ return $this;
+ }
- /**
- * Is Columns to repeat at left set?
- *
- * @return boolean
- */
- public function isColumnsToRepeatAtLeftSet() {
- if (is_array($this->_columnsToRepeatAtLeft)) {
- if ($this->_columnsToRepeatAtLeft[0] != '' && $this->_columnsToRepeatAtLeft[1] != '') {
- return true;
- }
- }
+ /**
+ * Is Columns to repeat at left set?
+ *
+ * @return boolean
+ */
+ public function isColumnsToRepeatAtLeftSet() {
+ if (is_array($this->_columnsToRepeatAtLeft)) {
+ if ($this->_columnsToRepeatAtLeft[0] != '' && $this->_columnsToRepeatAtLeft[1] != '') {
+ return true;
+ }
+ }
- return false;
- }
+ return false;
+ }
- /**
- * Get Columns to repeat at left
- *
- * @return array Containing start column and end column, empty array if option unset
- */
- public function getColumnsToRepeatAtLeft() {
- return $this->_columnsToRepeatAtLeft;
- }
+ /**
+ * Get Columns to repeat at left
+ *
+ * @return array Containing start column and end column, empty array if option unset
+ */
+ public function getColumnsToRepeatAtLeft() {
+ return $this->_columnsToRepeatAtLeft;
+ }
- /**
- * Set Columns to repeat at left
- *
- * @param array $pValue Containing start column and end column, empty array if option unset
- * @return PHPExcel\Worksheet_PageSetup
- */
- public function setColumnsToRepeatAtLeft($pValue = null) {
- if (is_array($pValue)) {
- $this->_columnsToRepeatAtLeft = $pValue;
- }
- return $this;
- }
+ /**
+ * Set Columns to repeat at left
+ *
+ * @param array $pValue Containing start column and end column, empty array if option unset
+ * @return PHPExcel\Worksheet_PageSetup
+ */
+ public function setColumnsToRepeatAtLeft($pValue = null) {
+ if (is_array($pValue)) {
+ $this->_columnsToRepeatAtLeft = $pValue;
+ }
+ return $this;
+ }
- /**
- * Set Columns to repeat at left by start and end
- *
- * @param string $pStart
- * @param string $pEnd
- * @return PHPExcel\Worksheet_PageSetup
- */
- public function setColumnsToRepeatAtLeftByStartAndEnd($pStart = 'A', $pEnd = 'A') {
- $this->_columnsToRepeatAtLeft = array($pStart, $pEnd);
- return $this;
- }
+ /**
+ * Set Columns to repeat at left by start and end
+ *
+ * @param string $pStart
+ * @param string $pEnd
+ * @return PHPExcel\Worksheet_PageSetup
+ */
+ public function setColumnsToRepeatAtLeftByStartAndEnd($pStart = 'A', $pEnd = 'A') {
+ $this->_columnsToRepeatAtLeft = array($pStart, $pEnd);
+ return $this;
+ }
- /**
- * Is Rows to repeat at top set?
- *
- * @return boolean
- */
- public function isRowsToRepeatAtTopSet() {
- if (is_array($this->_rowsToRepeatAtTop)) {
- if ($this->_rowsToRepeatAtTop[0] != 0 && $this->_rowsToRepeatAtTop[1] != 0) {
- return true;
- }
- }
+ /**
+ * Is Rows to repeat at top set?
+ *
+ * @return boolean
+ */
+ public function isRowsToRepeatAtTopSet() {
+ if (is_array($this->_rowsToRepeatAtTop)) {
+ if ($this->_rowsToRepeatAtTop[0] != 0 && $this->_rowsToRepeatAtTop[1] != 0) {
+ return true;
+ }
+ }
- return false;
- }
+ return false;
+ }
- /**
- * Get Rows to repeat at top
- *
- * @return array Containing start column and end column, empty array if option unset
- */
- public function getRowsToRepeatAtTop() {
- return $this->_rowsToRepeatAtTop;
- }
+ /**
+ * Get Rows to repeat at top
+ *
+ * @return array Containing start column and end column, empty array if option unset
+ */
+ public function getRowsToRepeatAtTop() {
+ return $this->_rowsToRepeatAtTop;
+ }
- /**
- * Set Rows to repeat at top
- *
- * @param array $pValue Containing start column and end column, empty array if option unset
- * @return PHPExcel\Worksheet_PageSetup
- */
- public function setRowsToRepeatAtTop($pValue = null) {
- if (is_array($pValue)) {
- $this->_rowsToRepeatAtTop = $pValue;
- }
- return $this;
- }
+ /**
+ * Set Rows to repeat at top
+ *
+ * @param array $pValue Containing start column and end column, empty array if option unset
+ * @return PHPExcel\Worksheet_PageSetup
+ */
+ public function setRowsToRepeatAtTop($pValue = null) {
+ if (is_array($pValue)) {
+ $this->_rowsToRepeatAtTop = $pValue;
+ }
+ return $this;
+ }
- /**
- * Set Rows to repeat at top by start and end
- *
- * @param int $pStart
- * @param int $pEnd
- * @return PHPExcel\Worksheet_PageSetup
- */
- public function setRowsToRepeatAtTopByStartAndEnd($pStart = 1, $pEnd = 1) {
- $this->_rowsToRepeatAtTop = array($pStart, $pEnd);
- return $this;
- }
+ /**
+ * Set Rows to repeat at top by start and end
+ *
+ * @param int $pStart
+ * @param int $pEnd
+ * @return PHPExcel\Worksheet_PageSetup
+ */
+ public function setRowsToRepeatAtTopByStartAndEnd($pStart = 1, $pEnd = 1) {
+ $this->_rowsToRepeatAtTop = array($pStart, $pEnd);
+ return $this;
+ }
- /**
- * Get center page horizontally
- *
- * @return bool
- */
- public function getHorizontalCentered() {
- return $this->_horizontalCentered;
- }
+ /**
+ * Get center page horizontally
+ *
+ * @return bool
+ */
+ public function getHorizontalCentered() {
+ return $this->_horizontalCentered;
+ }
- /**
- * Set center page horizontally
- *
- * @param bool $value
- * @return PHPExcel\Worksheet_PageSetup
- */
- public function setHorizontalCentered($value = false) {
- $this->_horizontalCentered = $value;
- return $this;
- }
+ /**
+ * Set center page horizontally
+ *
+ * @param bool $value
+ * @return PHPExcel\Worksheet_PageSetup
+ */
+ public function setHorizontalCentered($value = false) {
+ $this->_horizontalCentered = $value;
+ return $this;
+ }
- /**
- * Get center page vertically
- *
- * @return bool
- */
- public function getVerticalCentered() {
- return $this->_verticalCentered;
- }
+ /**
+ * Get center page vertically
+ *
+ * @return bool
+ */
+ public function getVerticalCentered() {
+ return $this->_verticalCentered;
+ }
- /**
- * Set center page vertically
- *
- * @param bool $value
- * @return PHPExcel\Worksheet_PageSetup
- */
- public function setVerticalCentered($value = false) {
- $this->_verticalCentered = $value;
- return $this;
- }
+ /**
+ * Set center page vertically
+ *
+ * @param bool $value
+ * @return PHPExcel\Worksheet_PageSetup
+ */
+ public function setVerticalCentered($value = false) {
+ $this->_verticalCentered = $value;
+ return $this;
+ }
- /**
- * Get print area
- *
- * @param int $index Identifier for a specific print area range if several ranges have been set
- * Default behaviour, or a index value of 0, will return all ranges as a comma-separated string
- * Otherwise, the specific range identified by the value of $index will be returned
- * Print areas are numbered from 1
- * @throws PHPExcel\Exception
- * @return string
- */
- public function getPrintArea($index = 0) {
- if ($index == 0) {
- return $this->_printArea;
- }
- $printAreas = explode(',',$this->_printArea);
- if (isset($printAreas[$index-1])) {
- return $printAreas[$index-1];
- }
- throw new Exception("Requested Print Area does not exist");
- }
+ /**
+ * Get print area
+ *
+ * @param int $index Identifier for a specific print area range if several ranges have been set
+ * Default behaviour, or a index value of 0, will return all ranges as a comma-separated string
+ * Otherwise, the specific range identified by the value of $index will be returned
+ * Print areas are numbered from 1
+ * @throws PHPExcel\Exception
+ * @return string
+ */
+ public function getPrintArea($index = 0) {
+ if ($index == 0) {
+ return $this->_printArea;
+ }
+ $printAreas = explode(',',$this->_printArea);
+ if (isset($printAreas[$index-1])) {
+ return $printAreas[$index-1];
+ }
+ throw new Exception("Requested Print Area does not exist");
+ }
- /**
- * Is print area set?
- *
- * @param int $index Identifier for a specific print area range if several ranges have been set
- * Default behaviour, or an index value of 0, will identify whether any print range is set
- * Otherwise, existence of the range identified by the value of $index will be returned
- * Print areas are numbered from 1
- * @return boolean
- */
- public function isPrintAreaSet($index = 0) {
- if ($index == 0) {
- return !is_null($this->_printArea);
- }
- $printAreas = explode(',',$this->_printArea);
- return isset($printAreas[$index-1]);
- }
+ /**
+ * Is print area set?
+ *
+ * @param int $index Identifier for a specific print area range if several ranges have been set
+ * Default behaviour, or an index value of 0, will identify whether any print range is set
+ * Otherwise, existence of the range identified by the value of $index will be returned
+ * Print areas are numbered from 1
+ * @return boolean
+ */
+ public function isPrintAreaSet($index = 0) {
+ if ($index == 0) {
+ return !is_null($this->_printArea);
+ }
+ $printAreas = explode(',',$this->_printArea);
+ return isset($printAreas[$index-1]);
+ }
- /**
- * Clear a print area
- *
- * @param int $index Identifier for a specific print area range if several ranges have been set
- * Default behaviour, or an index value of 0, will clear all print ranges that are set
- * Otherwise, the range identified by the value of $index will be removed from the series
- * Print areas are numbered from 1
- * @return PHPExcel\Worksheet_PageSetup
- */
- public function clearPrintArea($index = 0) {
- if ($index == 0) {
- $this->_printArea = NULL;
- } else {
- $printAreas = explode(',',$this->_printArea);
- if (isset($printAreas[$index-1])) {
- unset($printAreas[$index-1]);
- $this->_printArea = implode(',',$printAreas);
- }
- }
+ /**
+ * Clear a print area
+ *
+ * @param int $index Identifier for a specific print area range if several ranges have been set
+ * Default behaviour, or an index value of 0, will clear all print ranges that are set
+ * Otherwise, the range identified by the value of $index will be removed from the series
+ * Print areas are numbered from 1
+ * @return PHPExcel\Worksheet_PageSetup
+ */
+ public function clearPrintArea($index = 0) {
+ if ($index == 0) {
+ $this->_printArea = null;
+ } else {
+ $printAreas = explode(',',$this->_printArea);
+ if (isset($printAreas[$index-1])) {
+ unset($printAreas[$index-1]);
+ $this->_printArea = implode(',',$printAreas);
+ }
+ }
- return $this;
- }
+ return $this;
+ }
- /**
- * Set print area. e.g. 'A1:D10' or 'A1:D10,G5:M20'
- *
- * @param string $value
- * @param int $index Identifier for a specific print area range allowing several ranges to be set
- * When the method is "O"verwrite, then a positive integer index will overwrite that indexed
- * entry in the print areas list; a negative index value will identify which entry to
- * overwrite working bacward through the print area to the list, with the last entry as -1.
- * Specifying an index value of 0, will overwrite all existing print ranges.
- * When the method is "I"nsert, then a positive index will insert after that indexed entry in
- * the print areas list, while a negative index will insert before the indexed entry.
- * Specifying an index value of 0, will always append the new print range at the end of the
- * list.
- * Print areas are numbered from 1
- * @param string $method Determines the method used when setting multiple print areas
- * Default behaviour, or the "O" method, overwrites existing print area
- * The "I" method, inserts the new print area before any specified index, or at the end of the list
- * @return PHPExcel\Worksheet_PageSetup
- * @throws PHPExcel\Exception
- */
- public function setPrintArea($value, $index = 0, $method = self::SETPRINTRANGE_OVERWRITE) {
- if (strpos($value,'!') !== false) {
- throw new Exception('Cell coordinate must not specify a worksheet.');
- } elseif (strpos($value,':') === false) {
- throw new Exception('Cell coordinate must be a range of cells.');
- } elseif (strpos($value,'$') !== false) {
- throw new Exception('Cell coordinate must not be absolute.');
- }
- $value = strtoupper($value);
+ /**
+ * Set print area. e.g. 'A1:D10' or 'A1:D10,G5:M20'
+ *
+ * @param string $value
+ * @param int $index Identifier for a specific print area range allowing several ranges to be set
+ * When the method is "O"verwrite, then a positive integer index will overwrite that indexed
+ * entry in the print areas list; a negative index value will identify which entry to
+ * overwrite working bacward through the print area to the list, with the last entry as -1.
+ * Specifying an index value of 0, will overwrite all existing print ranges.
+ * When the method is "I"nsert, then a positive index will insert after that indexed entry in
+ * the print areas list, while a negative index will insert before the indexed entry.
+ * Specifying an index value of 0, will always append the new print range at the end of the
+ * list.
+ * Print areas are numbered from 1
+ * @param string $method Determines the method used when setting multiple print areas
+ * Default behaviour, or the "O" method, overwrites existing print area
+ * The "I" method, inserts the new print area before any specified index, or at the end of the list
+ * @return PHPExcel\Worksheet_PageSetup
+ * @throws PHPExcel\Exception
+ */
+ public function setPrintArea($value, $index = 0, $method = self::SETPRINTRANGE_OVERWRITE) {
+ if (strpos($value,'!') !== false) {
+ throw new Exception('Cell coordinate must not specify a worksheet.');
+ } elseif (strpos($value,':') === false) {
+ throw new Exception('Cell coordinate must be a range of cells.');
+ } elseif (strpos($value,'$') !== false) {
+ throw new Exception('Cell coordinate must not be absolute.');
+ }
+ $value = strtoupper($value);
- if ($method == self::SETPRINTRANGE_OVERWRITE) {
- if ($index == 0) {
- $this->_printArea = $value;
- } else {
- $printAreas = explode(',',$this->_printArea);
- if($index < 0) {
- $index = count($printAreas) - abs($index) + 1;
- }
- if (($index <= 0) || ($index > count($printAreas))) {
- throw new Exception('Invalid index for setting print range.');
- }
- $printAreas[$index-1] = $value;
- $this->_printArea = implode(',',$printAreas);
- }
- } elseif($method == self::SETPRINTRANGE_INSERT) {
- if ($index == 0) {
- $this->_printArea .= ($this->_printArea == '') ? $value : ','.$value;
- } else {
- $printAreas = explode(',',$this->_printArea);
- if($index < 0) {
- $index = abs($index) - 1;
- }
- if ($index > count($printAreas)) {
- throw new Exception('Invalid index for setting print range.');
- }
- $printAreas = array_merge(array_slice($printAreas,0,$index),array($value),array_slice($printAreas,$index));
- $this->_printArea = implode(',',$printAreas);
- }
- } else {
- throw new Exception('Invalid method for setting print range.');
- }
+ if ($method == self::SETPRINTRANGE_OVERWRITE) {
+ if ($index == 0) {
+ $this->_printArea = $value;
+ } else {
+ $printAreas = explode(',',$this->_printArea);
+ if($index < 0) {
+ $index = count($printAreas) - abs($index) + 1;
+ }
+ if (($index <= 0) || ($index > count($printAreas))) {
+ throw new Exception('Invalid index for setting print range.');
+ }
+ $printAreas[$index-1] = $value;
+ $this->_printArea = implode(',',$printAreas);
+ }
+ } elseif($method == self::SETPRINTRANGE_INSERT) {
+ if ($index == 0) {
+ $this->_printArea .= ($this->_printArea == '') ? $value : ','.$value;
+ } else {
+ $printAreas = explode(',',$this->_printArea);
+ if($index < 0) {
+ $index = abs($index) - 1;
+ }
+ if ($index > count($printAreas)) {
+ throw new Exception('Invalid index for setting print range.');
+ }
+ $printAreas = array_merge(array_slice($printAreas,0,$index),array($value),array_slice($printAreas,$index));
+ $this->_printArea = implode(',',$printAreas);
+ }
+ } else {
+ throw new Exception('Invalid method for setting print range.');
+ }
- return $this;
- }
+ return $this;
+ }
- /**
- * Add a new print area (e.g. 'A1:D10' or 'A1:D10,G5:M20') to the list of print areas
- *
- * @param string $value
- * @param int $index Identifier for a specific print area range allowing several ranges to be set
- * A positive index will insert after that indexed entry in the print areas list, while a
- * negative index will insert before the indexed entry.
- * Specifying an index value of 0, will always append the new print range at the end of the
- * list.
- * Print areas are numbered from 1
- * @return PHPExcel\Worksheet_PageSetup
- * @throws PHPExcel\Exception
- */
- public function addPrintArea($value, $index = -1) {
- return $this->setPrintArea($value, $index, self::SETPRINTRANGE_INSERT);
- }
+ /**
+ * Add a new print area (e.g. 'A1:D10' or 'A1:D10,G5:M20') to the list of print areas
+ *
+ * @param string $value
+ * @param int $index Identifier for a specific print area range allowing several ranges to be set
+ * A positive index will insert after that indexed entry in the print areas list, while a
+ * negative index will insert before the indexed entry.
+ * Specifying an index value of 0, will always append the new print range at the end of the
+ * list.
+ * Print areas are numbered from 1
+ * @return PHPExcel\Worksheet_PageSetup
+ * @throws PHPExcel\Exception
+ */
+ public function addPrintArea($value, $index = -1) {
+ return $this->setPrintArea($value, $index, self::SETPRINTRANGE_INSERT);
+ }
- /**
- * Set print area
- *
- * @param int $column1 Column 1
- * @param int $row1 Row 1
- * @param int $column2 Column 2
- * @param int $row2 Row 2
- * @param int $index Identifier for a specific print area range allowing several ranges to be set
- * When the method is "O"verwrite, then a positive integer index will overwrite that indexed
- * entry in the print areas list; a negative index value will identify which entry to
- * overwrite working bacward through the print area to the list, with the last entry as -1.
- * Specifying an index value of 0, will overwrite all existing print ranges.
- * When the method is "I"nsert, then a positive index will insert after that indexed entry in
- * the print areas list, while a negative index will insert before the indexed entry.
- * Specifying an index value of 0, will always append the new print range at the end of the
- * list.
- * Print areas are numbered from 1
- * @param string $method Determines the method used when setting multiple print areas
- * Default behaviour, or the "O" method, overwrites existing print area
- * The "I" method, inserts the new print area before any specified index, or at the end of the list
- * @return PHPExcel\Worksheet_PageSetup
- * @throws PHPExcel\Exception
- */
+ /**
+ * Set print area
+ *
+ * @param int $column1 Column 1
+ * @param int $row1 Row 1
+ * @param int $column2 Column 2
+ * @param int $row2 Row 2
+ * @param int $index Identifier for a specific print area range allowing several ranges to be set
+ * When the method is "O"verwrite, then a positive integer index will overwrite that indexed
+ * entry in the print areas list; a negative index value will identify which entry to
+ * overwrite working bacward through the print area to the list, with the last entry as -1.
+ * Specifying an index value of 0, will overwrite all existing print ranges.
+ * When the method is "I"nsert, then a positive index will insert after that indexed entry in
+ * the print areas list, while a negative index will insert before the indexed entry.
+ * Specifying an index value of 0, will always append the new print range at the end of the
+ * list.
+ * Print areas are numbered from 1
+ * @param string $method Determines the method used when setting multiple print areas
+ * Default behaviour, or the "O" method, overwrites existing print area
+ * The "I" method, inserts the new print area before any specified index, or at the end of the list
+ * @return PHPExcel\Worksheet_PageSetup
+ * @throws PHPExcel\Exception
+ */
public function setPrintAreaByColumnAndRow($column1, $row1, $column2, $row2, $index = 0, $method = self::SETPRINTRANGE_OVERWRITE)
{
- return $this->setPrintArea(Cell::stringFromColumnIndex($column1) . $row1 . ':' . Cell::stringFromColumnIndex($column2) . $row2, $index, $method);
+ return $this->setPrintArea(Cell::stringFromColumnIndex($column1) . $row1 . ':' . Cell::stringFromColumnIndex($column2) . $row2, $index, $method);
}
- /**
- * Add a new print area to the list of print areas
- *
- * @param int $column1 Start Column for the print area
- * @param int $row1 Start Row for the print area
- * @param int $column2 End Column for the print area
- * @param int $row2 End Row for the print area
- * @param int $index Identifier for a specific print area range allowing several ranges to be set
- * A positive index will insert after that indexed entry in the print areas list, while a
- * negative index will insert before the indexed entry.
- * Specifying an index value of 0, will always append the new print range at the end of the
- * list.
- * Print areas are numbered from 1
- * @return PHPExcel\Worksheet_PageSetup
- * @throws PHPExcel\Exception
- */
+ /**
+ * Add a new print area to the list of print areas
+ *
+ * @param int $column1 Start Column for the print area
+ * @param int $row1 Start Row for the print area
+ * @param int $column2 End Column for the print area
+ * @param int $row2 End Row for the print area
+ * @param int $index Identifier for a specific print area range allowing several ranges to be set
+ * A positive index will insert after that indexed entry in the print areas list, while a
+ * negative index will insert before the indexed entry.
+ * Specifying an index value of 0, will always append the new print range at the end of the
+ * list.
+ * Print areas are numbered from 1
+ * @return PHPExcel\Worksheet_PageSetup
+ * @throws PHPExcel\Exception
+ */
public function addPrintAreaByColumnAndRow($column1, $row1, $column2, $row2, $index = -1)
{
- return $this->setPrintArea(Cell::stringFromColumnIndex($column1) . $row1 . ':' . Cell::stringFromColumnIndex($column2) . $row2, $index, self::SETPRINTRANGE_INSERT);
- }
+ return $this->setPrintArea(Cell::stringFromColumnIndex($column1) . $row1 . ':' . Cell::stringFromColumnIndex($column2) . $row2, $index, self::SETPRINTRANGE_INSERT);
+ }
- /**
- * Get first page number
- *
- * @return int
- */
+ /**
+ * Get first page number
+ *
+ * @return int
+ */
public function getFirstPageNumber() {
- return $this->_firstPageNumber;
+ return $this->_firstPageNumber;
}
/**
@@ -771,8 +771,8 @@ class Worksheet_PageSetup
* @return PHPExcel\Worksheet_HeaderFooter
*/
public function setFirstPageNumber($value = null) {
- $this->_firstPageNumber = $value;
- return $this;
+ $this->_firstPageNumber = $value;
+ return $this;
}
/**
@@ -781,20 +781,20 @@ class Worksheet_PageSetup
* @return PHPExcel\Worksheet_HeaderFooter
*/
public function resetFirstPageNumber() {
- return $this->setFirstPageNumber(null);
+ return $this->setFirstPageNumber(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)) {
- $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;
+ }
+ }
+ }
}
diff --git a/Classes/PHPExcel/Worksheet/Protection.php b/Classes/PHPExcel/Worksheet/Protection.php
index 2ae7ae9..e0c0cf3 100644
--- a/Classes/PHPExcel/Worksheet/Protection.php
+++ b/Classes/PHPExcel/Worksheet/Protection.php
@@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\Worksheet
* @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,124 +37,124 @@ namespace PHPExcel;
*/
class Worksheet_Protection
{
- /**
- * Sheet
- *
- * @var boolean
- */
- protected $_sheet = false;
+ /**
+ * Sheet
+ *
+ * @var boolean
+ */
+ protected $_sheet = false;
- /**
- * Objects
- *
- * @var boolean
- */
- protected $_objects = false;
+ /**
+ * Objects
+ *
+ * @var boolean
+ */
+ protected $_objects = false;
- /**
- * Scenarios
- *
- * @var boolean
- */
- protected $_scenarios = false;
+ /**
+ * Scenarios
+ *
+ * @var boolean
+ */
+ protected $_scenarios = false;
- /**
- * Format cells
- *
- * @var boolean
- */
- protected $_formatCells = false;
+ /**
+ * Format cells
+ *
+ * @var boolean
+ */
+ protected $_formatCells = false;
- /**
- * Format columns
- *
- * @var boolean
- */
- protected $_formatColumns = false;
+ /**
+ * Format columns
+ *
+ * @var boolean
+ */
+ protected $_formatColumns = false;
- /**
- * Format rows
- *
- * @var boolean
- */
- protected $_formatRows = false;
+ /**
+ * Format rows
+ *
+ * @var boolean
+ */
+ protected $_formatRows = false;
- /**
- * Insert columns
- *
- * @var boolean
- */
- protected $_insertColumns = false;
+ /**
+ * Insert columns
+ *
+ * @var boolean
+ */
+ protected $_insertColumns = false;
- /**
- * Insert rows
- *
- * @var boolean
- */
- protected $_insertRows = false;
+ /**
+ * Insert rows
+ *
+ * @var boolean
+ */
+ protected $_insertRows = false;
- /**
- * Insert hyperlinks
- *
- * @var boolean
- */
- protected $_insertHyperlinks = false;
+ /**
+ * Insert hyperlinks
+ *
+ * @var boolean
+ */
+ protected $_insertHyperlinks = false;
- /**
- * Delete columns
- *
- * @var boolean
- */
- protected $_deleteColumns = false;
+ /**
+ * Delete columns
+ *
+ * @var boolean
+ */
+ protected $_deleteColumns = false;
- /**
- * Delete rows
- *
- * @var boolean
- */
- protected $_deleteRows = false;
+ /**
+ * Delete rows
+ *
+ * @var boolean
+ */
+ protected $_deleteRows = false;
- /**
- * Select locked cells
- *
- * @var boolean
- */
- protected $_selectLockedCells = false;
+ /**
+ * Select locked cells
+ *
+ * @var boolean
+ */
+ protected $_selectLockedCells = false;
- /**
- * Sort
- *
- * @var boolean
- */
- protected $_sort = false;
+ /**
+ * Sort
+ *
+ * @var boolean
+ */
+ protected $_sort = false;
- /**
- * AutoFilter
- *
- * @var boolean
- */
- protected $_autoFilter = false;
+ /**
+ * AutoFilter
+ *
+ * @var boolean
+ */
+ protected $_autoFilter = false;
- /**
- * Pivot tables
- *
- * @var boolean
- */
- protected $_pivotTables = false;
+ /**
+ * Pivot tables
+ *
+ * @var boolean
+ */
+ protected $_pivotTables = false;
- /**
- * Select unlocked cells
- *
- * @var boolean
- */
- protected $_selectUnlockedCells = false;
+ /**
+ * Select unlocked cells
+ *
+ * @var boolean
+ */
+ protected $_selectUnlockedCells = false;
- /**
- * Password
- *
- * @var string
- */
- protected $_password = '';
+ /**
+ * Password
+ *
+ * @var string
+ */
+ protected $_password = '';
/**
* Create a new PHPExcel\Worksheet_Protection
@@ -169,22 +169,22 @@ class Worksheet_Protection
* @return boolean
*/
function isProtectionEnabled() {
- return $this->_sheet ||
- $this->_objects ||
- $this->_scenarios ||
- $this->_formatCells ||
- $this->_formatColumns ||
- $this->_formatRows ||
- $this->_insertColumns ||
- $this->_insertRows ||
- $this->_insertHyperlinks ||
- $this->_deleteColumns ||
- $this->_deleteRows ||
- $this->_selectLockedCells ||
- $this->_sort ||
- $this->_autoFilter ||
- $this->_pivotTables ||
- $this->_selectUnlockedCells;
+ return $this->_sheet ||
+ $this->_objects ||
+ $this->_scenarios ||
+ $this->_formatCells ||
+ $this->_formatColumns ||
+ $this->_formatRows ||
+ $this->_insertColumns ||
+ $this->_insertRows ||
+ $this->_insertHyperlinks ||
+ $this->_deleteColumns ||
+ $this->_deleteRows ||
+ $this->_selectLockedCells ||
+ $this->_sort ||
+ $this->_autoFilter ||
+ $this->_pivotTables ||
+ $this->_selectUnlockedCells;
}
/**
@@ -193,7 +193,7 @@ class Worksheet_Protection
* @return boolean
*/
function getSheet() {
- return $this->_sheet;
+ return $this->_sheet;
}
/**
@@ -203,8 +203,8 @@ class Worksheet_Protection
* @return PHPExcel\Worksheet_Protection
*/
function setSheet($pValue = false) {
- $this->_sheet = $pValue;
- return $this;
+ $this->_sheet = $pValue;
+ return $this;
}
/**
@@ -213,7 +213,7 @@ class Worksheet_Protection
* @return boolean
*/
function getObjects() {
- return $this->_objects;
+ return $this->_objects;
}
/**
@@ -223,8 +223,8 @@ class Worksheet_Protection
* @return PHPExcel\Worksheet_Protection
*/
function setObjects($pValue = false) {
- $this->_objects = $pValue;
- return $this;
+ $this->_objects = $pValue;
+ return $this;
}
/**
@@ -233,7 +233,7 @@ class Worksheet_Protection
* @return boolean
*/
function getScenarios() {
- return $this->_scenarios;
+ return $this->_scenarios;
}
/**
@@ -243,8 +243,8 @@ class Worksheet_Protection
* @return PHPExcel\Worksheet_Protection
*/
function setScenarios($pValue = false) {
- $this->_scenarios = $pValue;
- return $this;
+ $this->_scenarios = $pValue;
+ return $this;
}
/**
@@ -253,7 +253,7 @@ class Worksheet_Protection
* @return boolean
*/
function getFormatCells() {
- return $this->_formatCells;
+ return $this->_formatCells;
}
/**
@@ -263,8 +263,8 @@ class Worksheet_Protection
* @return PHPExcel\Worksheet_Protection
*/
function setFormatCells($pValue = false) {
- $this->_formatCells = $pValue;
- return $this;
+ $this->_formatCells = $pValue;
+ return $this;
}
/**
@@ -273,7 +273,7 @@ class Worksheet_Protection
* @return boolean
*/
function getFormatColumns() {
- return $this->_formatColumns;
+ return $this->_formatColumns;
}
/**
@@ -283,8 +283,8 @@ class Worksheet_Protection
* @return PHPExcel\Worksheet_Protection
*/
function setFormatColumns($pValue = false) {
- $this->_formatColumns = $pValue;
- return $this;
+ $this->_formatColumns = $pValue;
+ return $this;
}
/**
@@ -293,7 +293,7 @@ class Worksheet_Protection
* @return boolean
*/
function getFormatRows() {
- return $this->_formatRows;
+ return $this->_formatRows;
}
/**
@@ -303,8 +303,8 @@ class Worksheet_Protection
* @return PHPExcel\Worksheet_Protection
*/
function setFormatRows($pValue = false) {
- $this->_formatRows = $pValue;
- return $this;
+ $this->_formatRows = $pValue;
+ return $this;
}
/**
@@ -313,7 +313,7 @@ class Worksheet_Protection
* @return boolean
*/
function getInsertColumns() {
- return $this->_insertColumns;
+ return $this->_insertColumns;
}
/**
@@ -323,8 +323,8 @@ class Worksheet_Protection
* @return PHPExcel\Worksheet_Protection
*/
function setInsertColumns($pValue = false) {
- $this->_insertColumns = $pValue;
- return $this;
+ $this->_insertColumns = $pValue;
+ return $this;
}
/**
@@ -333,7 +333,7 @@ class Worksheet_Protection
* @return boolean
*/
function getInsertRows() {
- return $this->_insertRows;
+ return $this->_insertRows;
}
/**
@@ -343,8 +343,8 @@ class Worksheet_Protection
* @return PHPExcel\Worksheet_Protection
*/
function setInsertRows($pValue = false) {
- $this->_insertRows = $pValue;
- return $this;
+ $this->_insertRows = $pValue;
+ return $this;
}
/**
@@ -353,7 +353,7 @@ class Worksheet_Protection
* @return boolean
*/
function getInsertHyperlinks() {
- return $this->_insertHyperlinks;
+ return $this->_insertHyperlinks;
}
/**
@@ -363,8 +363,8 @@ class Worksheet_Protection
* @return PHPExcel\Worksheet_Protection
*/
function setInsertHyperlinks($pValue = false) {
- $this->_insertHyperlinks = $pValue;
- return $this;
+ $this->_insertHyperlinks = $pValue;
+ return $this;
}
/**
@@ -373,7 +373,7 @@ class Worksheet_Protection
* @return boolean
*/
function getDeleteColumns() {
- return $this->_deleteColumns;
+ return $this->_deleteColumns;
}
/**
@@ -383,8 +383,8 @@ class Worksheet_Protection
* @return PHPExcel\Worksheet_Protection
*/
function setDeleteColumns($pValue = false) {
- $this->_deleteColumns = $pValue;
- return $this;
+ $this->_deleteColumns = $pValue;
+ return $this;
}
/**
@@ -393,7 +393,7 @@ class Worksheet_Protection
* @return boolean
*/
function getDeleteRows() {
- return $this->_deleteRows;
+ return $this->_deleteRows;
}
/**
@@ -403,8 +403,8 @@ class Worksheet_Protection
* @return PHPExcel\Worksheet_Protection
*/
function setDeleteRows($pValue = false) {
- $this->_deleteRows = $pValue;
- return $this;
+ $this->_deleteRows = $pValue;
+ return $this;
}
/**
@@ -413,7 +413,7 @@ class Worksheet_Protection
* @return boolean
*/
function getSelectLockedCells() {
- return $this->_selectLockedCells;
+ return $this->_selectLockedCells;
}
/**
@@ -423,8 +423,8 @@ class Worksheet_Protection
* @return PHPExcel\Worksheet_Protection
*/
function setSelectLockedCells($pValue = false) {
- $this->_selectLockedCells = $pValue;
- return $this;
+ $this->_selectLockedCells = $pValue;
+ return $this;
}
/**
@@ -433,7 +433,7 @@ class Worksheet_Protection
* @return boolean
*/
function getSort() {
- return $this->_sort;
+ return $this->_sort;
}
/**
@@ -443,8 +443,8 @@ class Worksheet_Protection
* @return PHPExcel\Worksheet_Protection
*/
function setSort($pValue = false) {
- $this->_sort = $pValue;
- return $this;
+ $this->_sort = $pValue;
+ return $this;
}
/**
@@ -453,7 +453,7 @@ class Worksheet_Protection
* @return boolean
*/
function getAutoFilter() {
- return $this->_autoFilter;
+ return $this->_autoFilter;
}
/**
@@ -463,8 +463,8 @@ class Worksheet_Protection
* @return PHPExcel\Worksheet_Protection
*/
function setAutoFilter($pValue = false) {
- $this->_autoFilter = $pValue;
- return $this;
+ $this->_autoFilter = $pValue;
+ return $this;
}
/**
@@ -473,7 +473,7 @@ class Worksheet_Protection
* @return boolean
*/
function getPivotTables() {
- return $this->_pivotTables;
+ return $this->_pivotTables;
}
/**
@@ -483,8 +483,8 @@ class Worksheet_Protection
* @return PHPExcel\Worksheet_Protection
*/
function setPivotTables($pValue = false) {
- $this->_pivotTables = $pValue;
- return $this;
+ $this->_pivotTables = $pValue;
+ return $this;
}
/**
@@ -493,7 +493,7 @@ class Worksheet_Protection
* @return boolean
*/
function getSelectUnlockedCells() {
- return $this->_selectUnlockedCells;
+ return $this->_selectUnlockedCells;
}
/**
@@ -503,8 +503,8 @@ class Worksheet_Protection
* @return PHPExcel\Worksheet_Protection
*/
function setSelectUnlockedCells($pValue = false) {
- $this->_selectUnlockedCells = $pValue;
- return $this;
+ $this->_selectUnlockedCells = $pValue;
+ return $this;
}
/**
@@ -513,35 +513,35 @@ class Worksheet_Protection
* @return string
*/
function getPassword() {
- return $this->_password;
+ return $this->_password;
}
/**
* Set Password
*
- * @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\Worksheet_Protection
*/
function setPassword($pValue = '', $pAlreadyHashed = false) {
- if (!$pAlreadyHashed) {
- $pValue = Shared_PasswordHasher::hashPassword($pValue);
- }
- $this->_password = $pValue;
- return $this;
+ if (!$pAlreadyHashed) {
+ $pValue = Shared_PasswordHasher::hashPassword($pValue);
+ }
+ $this->_password = $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;
+ }
+ }
+ }
}
diff --git a/Classes/PHPExcel/Worksheet/Row.php b/Classes/PHPExcel/Worksheet/Row.php
index 62a81f0..b587d45 100644
--- a/Classes/PHPExcel/Worksheet/Row.php
+++ b/Classes/PHPExcel/Worksheet/Row.php
@@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\Worksheet
* @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##
*/
@@ -39,54 +39,54 @@ namespace PHPExcel;
*/
class Worksheet_Row
{
- /**
- * PHPExcel\Worksheet
- *
- * @var PHPExcel\Worksheet
- */
- protected $_parent;
+ /**
+ * PHPExcel\Worksheet
+ *
+ * @var PHPExcel\Worksheet
+ */
+ protected $_parent;
- /**
- * Row index
- *
- * @var int
- */
- protected $_rowIndex = 0;
+ /**
+ * Row index
+ *
+ * @var int
+ */
+ protected $_rowIndex = 0;
- /**
- * Create a new row
- *
- * @param PHPExcel\Worksheet $parent
- * @param int $rowIndex
- */
- public function __construct(Worksheet $parent = null, $rowIndex = 1) {
- // Set parent and row index
- $this->_parent = $parent;
- $this->_rowIndex = $rowIndex;
- }
+ /**
+ * Create a new row
+ *
+ * @param PHPExcel\Worksheet $parent
+ * @param int $rowIndex
+ */
+ public function __construct(Worksheet $parent = null, $rowIndex = 1) {
+ // Set parent and row index
+ $this->_parent = $parent;
+ $this->_rowIndex = $rowIndex;
+ }
- /**
- * Destructor
- */
- public function __destruct() {
- unset($this->_parent);
- }
+ /**
+ * Destructor
+ */
+ public function __destruct() {
+ unset($this->_parent);
+ }
- /**
- * Get row index
- *
- * @return int
- */
- public function getRowIndex() {
- return $this->_rowIndex;
- }
+ /**
+ * Get row index
+ *
+ * @return int
+ */
+ public function getRowIndex() {
+ return $this->_rowIndex;
+ }
- /**
- * Get cell iterator
- *
- * @return PHPExcel\Worksheet_CellIterator
- */
- public function getCellIterator() {
- return new Worksheet_CellIterator($this->_parent, $this->_rowIndex);
- }
+ /**
+ * Get cell iterator
+ *
+ * @return PHPExcel\Worksheet_CellIterator
+ */
+ public function getCellIterator() {
+ return new Worksheet_CellIterator($this->_parent, $this->_rowIndex);
+ }
}
diff --git a/Classes/PHPExcel/Worksheet/RowDimension.php b/Classes/PHPExcel/Worksheet/RowDimension.php
index bd10364..4210c1f 100644
--- a/Classes/PHPExcel/Worksheet/RowDimension.php
+++ b/Classes/PHPExcel/Worksheet/RowDimension.php
@@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\Worksheet
* @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,56 +37,56 @@ namespace PHPExcel;
*/
class Worksheet_RowDimension
{
- /**
- * Row index
- *
- * @var int
- */
- protected $_rowIndex;
+ /**
+ * Row index
+ *
+ * @var int
+ */
+ protected $_rowIndex;
- /**
- * Row height (in pt)
- *
- * When this is set to a negative value, the row height should be ignored by IWriter
- *
- * @var double
- */
- protected $_rowHeight = -1;
+ /**
+ * Row height (in pt)
+ *
+ * When this is set to a negative value, the row height should be ignored by IWriter
+ *
+ * @var double
+ */
+ protected $_rowHeight = -1;
- /**
- * ZeroHeight for Row?
- *
- * @var bool
- */
- protected $_zeroHeight = false;
+ /**
+ * ZeroHeight for Row?
+ *
+ * @var bool
+ */
+ protected $_zeroHeight = false;
- /**
- * Visible?
- *
- * @var bool
- */
- protected $_visible = true;
+ /**
+ * Visible?
+ *
+ * @var bool
+ */
+ protected $_visible = true;
- /**
- * Outline level
- *
- * @var int
- */
- protected $_outlineLevel = 0;
+ /**
+ * Outline level
+ *
+ * @var int
+ */
+ protected $_outlineLevel = 0;
- /**
- * Collapsed
- *
- * @var bool
- */
- protected $_collapsed = false;
+ /**
+ * Collapsed
+ *
+ * @var bool
+ */
+ protected $_collapsed = false;
- /**
- * Index to cellXf. Null value means row has no explicit cellXf format.
- *
- * @var int|null
- */
- protected $_xfIndex;
+ /**
+ * Index to cellXf. Null value means row has no explicit cellXf format.
+ *
+ * @var int|null
+ */
+ protected $_xfIndex;
/**
* Create a new PHPExcel\Worksheet_RowDimension
@@ -95,11 +95,11 @@ class Worksheet_RowDimension
*/
public function __construct($pIndex = 0)
{
- // Initialise values
- $this->_rowIndex = $pIndex;
+ // Initialise values
+ $this->_rowIndex = $pIndex;
- // set row dimension as unformatted by default
- $this->_xfIndex = null;
+ // set row dimension as unformatted by default
+ $this->_xfIndex = null;
}
/**
@@ -108,7 +108,7 @@ class Worksheet_RowDimension
* @return int
*/
public function getRowIndex() {
- return $this->_rowIndex;
+ return $this->_rowIndex;
}
/**
@@ -118,8 +118,8 @@ class Worksheet_RowDimension
* @return PHPExcel\Worksheet_RowDimension
*/
public function setRowIndex($pValue) {
- $this->_rowIndex = $pValue;
- return $this;
+ $this->_rowIndex = $pValue;
+ return $this;
}
/**
@@ -128,7 +128,7 @@ class Worksheet_RowDimension
* @return double
*/
public function getRowHeight() {
- return $this->_rowHeight;
+ return $this->_rowHeight;
}
/**
@@ -138,29 +138,29 @@ class Worksheet_RowDimension
* @return PHPExcel\Worksheet_RowDimension
*/
public function setRowHeight($pValue = -1) {
- $this->_rowHeight = $pValue;
- return $this;
+ $this->_rowHeight = $pValue;
+ return $this;
}
- /**
- * Get ZeroHeight
- *
- * @return bool
- */
- public function getzeroHeight() {
- return $this->_zeroHeight;
- }
+ /**
+ * Get ZeroHeight
+ *
+ * @return bool
+ */
+ public function getzeroHeight() {
+ return $this->_zeroHeight;
+ }
- /**
- * Set ZeroHeight
- *
- * @param bool $pValue
- * @return PHPExcel\Worksheet_RowDimension
- */
- public function setzeroHeight($pValue = false) {
- $this->_zeroHeight = $pValue;
- return $this;
- }
+ /**
+ * Set ZeroHeight
+ *
+ * @param bool $pValue
+ * @return PHPExcel\Worksheet_RowDimension
+ */
+ public function setzeroHeight($pValue = false) {
+ $this->_zeroHeight = $pValue;
+ return $this;
+ }
/**
* Get Visible
@@ -168,7 +168,7 @@ class Worksheet_RowDimension
* @return bool
*/
public function getVisible() {
- return $this->_visible;
+ return $this->_visible;
}
/**
@@ -178,8 +178,8 @@ class Worksheet_RowDimension
* @return PHPExcel\Worksheet_RowDimension
*/
public function setVisible($pValue = true) {
- $this->_visible = $pValue;
- return $this;
+ $this->_visible = $pValue;
+ return $this;
}
/**
@@ -188,7 +188,7 @@ class Worksheet_RowDimension
* @return int
*/
public function getOutlineLevel() {
- return $this->_outlineLevel;
+ return $this->_outlineLevel;
}
/**
@@ -201,12 +201,12 @@ class Worksheet_RowDimension
* @return PHPExcel\Worksheet_RowDimension
*/
public function setOutlineLevel($pValue) {
- if ($pValue < 0 || $pValue > 7) {
- throw new Exception("Outline level must range between 0 and 7.");
- }
+ if ($pValue < 0 || $pValue > 7) {
+ throw new Exception("Outline level must range between 0 and 7.");
+ }
- $this->_outlineLevel = $pValue;
- return $this;
+ $this->_outlineLevel = $pValue;
+ return $this;
}
/**
@@ -215,7 +215,7 @@ class Worksheet_RowDimension
* @return bool
*/
public function getCollapsed() {
- return $this->_collapsed;
+ return $this->_collapsed;
}
/**
@@ -225,43 +225,43 @@ class Worksheet_RowDimension
* @return PHPExcel\Worksheet_RowDimension
*/
public function setCollapsed($pValue = true) {
- $this->_collapsed = $pValue;
- return $this;
+ $this->_collapsed = $pValue;
+ return $this;
}
- /**
- * Get index to cellXf
- *
- * @return int
- */
- public function getXfIndex()
- {
- return $this->_xfIndex;
- }
+ /**
+ * Get index to cellXf
+ *
+ * @return int
+ */
+ public function getXfIndex()
+ {
+ return $this->_xfIndex;
+ }
- /**
- * Set index to cellXf
- *
- * @param int $pValue
- * @return PHPExcel\Worksheet_RowDimension
- */
- public function setXfIndex($pValue = 0)
- {
- $this->_xfIndex = $pValue;
- return $this;
- }
+ /**
+ * Set index to cellXf
+ *
+ * @param int $pValue
+ * @return PHPExcel\Worksheet_RowDimension
+ */
+ public function setXfIndex($pValue = 0)
+ {
+ $this->_xfIndex = $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;
+ }
+ }
+ }
}
diff --git a/Classes/PHPExcel/Worksheet/RowIterator.php b/Classes/PHPExcel/Worksheet/RowIterator.php
index d8b4982..6f041d0 100644
--- a/Classes/PHPExcel/Worksheet/RowIterator.php
+++ b/Classes/PHPExcel/Worksheet/RowIterator.php
@@ -19,10 +19,10 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category PHPExcel
- * @package PHPExcel\Worksheet
+ * @package PHPExcel\Worksheet
* @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,117 +34,117 @@ namespace PHPExcel;
* Used to iterate rows in a PHPExcel\Worksheet
*
* @category PHPExcel
- * @package PHPExcel\Worksheet
+ * @package PHPExcel\Worksheet
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
*/
class Worksheet_RowIterator implements \Iterator
{
- /**
- * PHPExcel\Worksheet to iterate
- *
- * @var PHPExcel\Worksheet
- */
- protected $_subject;
+ /**
+ * PHPExcel\Worksheet to iterate
+ *
+ * @var PHPExcel\Worksheet
+ */
+ protected $_subject;
- /**
- * Current iterator position
- *
- * @var int
- */
- protected $_position = 1;
+ /**
+ * Current iterator position
+ *
+ * @var int
+ */
+ protected $_position = 1;
- /**
- * Start position
- *
- * @var int
- */
- protected $_startRow = 1;
+ /**
+ * Start position
+ *
+ * @var int
+ */
+ protected $_startRow = 1;
- /**
- * Create a new row iterator
- *
- * @param PHPExcel\Worksheet $subject The worksheet to iterate over
- * @param integer $startRow The row number at which to start iterating
- */
- public function __construct(Worksheet $subject = null, $startRow = 1) {
- // Set subject
- $this->_subject = $subject;
- $this->resetStart($startRow);
- }
+ /**
+ * Create a new row iterator
+ *
+ * @param PHPExcel\Worksheet $subject The worksheet to iterate over
+ * @param integer $startRow The row number at which to start iterating
+ */
+ public function __construct(Worksheet $subject = null, $startRow = 1) {
+ // Set subject
+ $this->_subject = $subject;
+ $this->resetStart($startRow);
+ }
- /**
- * Destructor
- */
- public function __destruct() {
- unset($this->_subject);
- }
+ /**
+ * Destructor
+ */
+ public function __destruct() {
+ unset($this->_subject);
+ }
- /**
- * (Re)Set the start row and the current row pointer
- *
- * @param integer $startRow The row number at which to start iterating
- */
- public function resetStart($startRow = 1) {
- $this->_startRow = $startRow;
- $this->seek($startRow);
- }
+ /**
+ * (Re)Set the start row and the current row pointer
+ *
+ * @param integer $startRow The row number at which to start iterating
+ */
+ public function resetStart($startRow = 1) {
+ $this->_startRow = $startRow;
+ $this->seek($startRow);
+ }
- /**
- * Set the row pointer to the selected row
- *
- * @param integer $row The row number to set the current pointer at
- */
- public function seek($row = 1) {
- $this->_position = $row;
- }
+ /**
+ * Set the row pointer to the selected row
+ *
+ * @param integer $row The row number to set the current pointer at
+ */
+ public function seek($row = 1) {
+ $this->_position = $row;
+ }
- /**
- * Rewind the iterator to the starting row
- */
- public function rewind() {
- $this->_position = $this->_startRow;
- }
+ /**
+ * Rewind the iterator to the starting row
+ */
+ public function rewind() {
+ $this->_position = $this->_startRow;
+ }
- /**
- * Return the current row in this worksheet
- *
- * @return PHPExcel\Worksheet_Row
- */
- public function current() {
- return new Worksheet_Row($this->_subject, $this->_position);
- }
+ /**
+ * Return the current row in this worksheet
+ *
+ * @return PHPExcel\Worksheet_Row
+ */
+ public function current() {
+ return new Worksheet_Row($this->_subject, $this->_position);
+ }
- /**
- * Return the current iterator key
- *
- * @return int
- */
- public function key() {
- return $this->_position;
- }
+ /**
+ * Return the current iterator key
+ *
+ * @return int
+ */
+ public function key() {
+ return $this->_position;
+ }
- /**
- * Set the iterator to its next value
- */
- public function next() {
- ++$this->_position;
- }
+ /**
+ * Set the iterator to its next value
+ */
+ public function next() {
+ ++$this->_position;
+ }
- /**
- * Set the iterator to its previous value
- */
- public function prev() {
- if ($this->_position > 1)
- --$this->_position;
- }
+ /**
+ * Set the iterator to its previous value
+ */
+ public function prev() {
+ if ($this->_position > 1)
+ --$this->_position;
+ }
- /**
- * Indicate if more rows exist in the worksheet
- *
- * @return boolean
- */
- public function valid() {
- return $this->_position <= $this->_subject->getHighestRow();
- }
+ /**
+ * Indicate if more rows exist in the worksheet
+ *
+ * @return boolean
+ */
+ public function valid() {
+ return $this->_position <= $this->_subject->getHighestRow();
+ }
}
diff --git a/Classes/PHPExcel/Worksheet/SheetView.php b/Classes/PHPExcel/Worksheet/SheetView.php
index 34fc9cb..af7d69d 100644
--- a/Classes/PHPExcel/Worksheet/SheetView.php
+++ b/Classes/PHPExcel/Worksheet/SheetView.php
@@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\Worksheet
* @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,43 +38,43 @@ namespace PHPExcel;
class Worksheet_SheetView
{
- /* Sheet View types */
- const SHEETVIEW_NORMAL = 'normal';
- const SHEETVIEW_PAGE_LAYOUT = 'pageLayout';
- const SHEETVIEW_PAGE_BREAK_PREVIEW = 'pageBreakPreview';
+ /* Sheet View types */
+ const SHEETVIEW_NORMAL = 'normal';
+ const SHEETVIEW_PAGE_LAYOUT = 'pageLayout';
+ const SHEETVIEW_PAGE_BREAK_PREVIEW = 'pageBreakPreview';
- protected static $_sheetViewTypes = array(
- self::SHEETVIEW_NORMAL,
- self::SHEETVIEW_PAGE_LAYOUT,
- self::SHEETVIEW_PAGE_BREAK_PREVIEW,
- );
+ protected static $_sheetViewTypes = array(
+ self::SHEETVIEW_NORMAL,
+ self::SHEETVIEW_PAGE_LAYOUT,
+ self::SHEETVIEW_PAGE_BREAK_PREVIEW,
+ );
- /**
- * ZoomScale
- *
- * Valid values range from 10 to 400.
- *
- * @var int
- */
- protected $_zoomScale = 100;
+ /**
+ * ZoomScale
+ *
+ * Valid values range from 10 to 400.
+ *
+ * @var int
+ */
+ protected $_zoomScale = 100;
- /**
- * ZoomScaleNormal
- *
- * Valid values range from 10 to 400.
- *
- * @var int
- */
- protected $_zoomScaleNormal = 100;
+ /**
+ * ZoomScaleNormal
+ *
+ * Valid values range from 10 to 400.
+ *
+ * @var int
+ */
+ protected $_zoomScaleNormal = 100;
- /**
- * View
- *
- * Valid values range from 10 to 400.
- *
- * @var string
- */
- protected $_sheetviewType = self::SHEETVIEW_NORMAL;
+ /**
+ * View
+ *
+ * Valid values range from 10 to 400.
+ *
+ * @var string
+ */
+ protected $_sheetviewType = self::SHEETVIEW_NORMAL;
/**
* Create a new PHPExcel\Worksheet_SheetView
@@ -83,108 +83,108 @@ class Worksheet_SheetView
{
}
- /**
- * Get ZoomScale
- *
- * @return int
- */
- public function getZoomScale() {
- return $this->_zoomScale;
- }
+ /**
+ * Get ZoomScale
+ *
+ * @return int
+ */
+ public function getZoomScale() {
+ return $this->_zoomScale;
+ }
- /**
- * Set ZoomScale
- *
- * Valid values range from 10 to 400.
- *
- * @param int $pValue
- * @throws PHPExcel\Exception
- * @return PHPExcel\Worksheet_SheetView
- */
- public function setZoomScale($pValue = 100) {
- // Microsoft Office Excel 2007 only allows setting a scale between 10 and 400 via the user interface,
- // but it is apparently still able to handle any scale >= 1
- if (($pValue >= 1) || is_null($pValue)) {
- $this->_zoomScale = $pValue;
- } else {
- throw new Exception("Scale must be greater than or equal to 1.");
- }
- return $this;
- }
+ /**
+ * Set ZoomScale
+ *
+ * Valid values range from 10 to 400.
+ *
+ * @param int $pValue
+ * @throws PHPExcel\Exception
+ * @return PHPExcel\Worksheet_SheetView
+ */
+ public function setZoomScale($pValue = 100) {
+ // Microsoft Office Excel 2007 only allows setting a scale between 10 and 400 via the user interface,
+ // but it is apparently still able to handle any scale >= 1
+ if (($pValue >= 1) || is_null($pValue)) {
+ $this->_zoomScale = $pValue;
+ } else {
+ throw new Exception("Scale must be greater than or equal to 1.");
+ }
+ return $this;
+ }
- /**
- * Get ZoomScaleNormal
- *
- * @return int
- */
- public function getZoomScaleNormal() {
- return $this->_zoomScaleNormal;
- }
+ /**
+ * Get ZoomScaleNormal
+ *
+ * @return int
+ */
+ public function getZoomScaleNormal() {
+ return $this->_zoomScaleNormal;
+ }
- /**
- * Set ZoomScale
- *
- * Valid values range from 10 to 400.
- *
- * @param int $pValue
- * @throws PHPExcel\Exception
- * @return PHPExcel\Worksheet_SheetView
- */
- public function setZoomScaleNormal($pValue = 100) {
- if (($pValue >= 1) || is_null($pValue)) {
- $this->_zoomScaleNormal = $pValue;
- } else {
- throw new Exception("Scale must be greater than or equal to 1.");
- }
- return $this;
- }
+ /**
+ * Set ZoomScale
+ *
+ * Valid values range from 10 to 400.
+ *
+ * @param int $pValue
+ * @throws PHPExcel\Exception
+ * @return PHPExcel\Worksheet_SheetView
+ */
+ public function setZoomScaleNormal($pValue = 100) {
+ if (($pValue >= 1) || is_null($pValue)) {
+ $this->_zoomScaleNormal = $pValue;
+ } else {
+ throw new Exception("Scale must be greater than or equal to 1.");
+ }
+ return $this;
+ }
- /**
- * Get View
- *
- * @return string
- */
- public function getView() {
- return $this->_sheetviewType;
- }
+ /**
+ * Get View
+ *
+ * @return string
+ */
+ public function getView() {
+ return $this->_sheetviewType;
+ }
- /**
- * Set View
- *
- * Valid values are
- * 'normal' self::SHEETVIEW_NORMAL
- * 'pageLayout' self::SHEETVIEW_PAGE_LAYOUT
- * 'pageBreakPreview' self::SHEETVIEW_PAGE_BREAK_PREVIEW
- *
- * @param string $pValue
- * @throws PHPExcel\Exception
- * @return PHPExcel\Worksheet_SheetView
- */
- public function setView($pValue = NULL) {
- // MS Excel 2007 allows setting the view to 'normal', 'pageLayout' or 'pageBreakPreview'
- // via the user interface
- if ($pValue === NULL)
- $pValue = self::SHEETVIEW_NORMAL;
- if (in_array($pValue, self::$_sheetViewTypes)) {
- $this->_sheetviewType = $pValue;
- } else {
- throw new Exception("Invalid sheetview layout type.");
- }
+ /**
+ * Set View
+ *
+ * Valid values are
+ * 'normal' self::SHEETVIEW_NORMAL
+ * 'pageLayout' self::SHEETVIEW_PAGE_LAYOUT
+ * 'pageBreakPreview' self::SHEETVIEW_PAGE_BREAK_PREVIEW
+ *
+ * @param string $pValue
+ * @throws PHPExcel\Exception
+ * @return PHPExcel\Worksheet_SheetView
+ */
+ public function setView($pValue = null) {
+ // MS Excel 2007 allows setting the view to 'normal', 'pageLayout' or 'pageBreakPreview'
+ // via the user interface
+ if ($pValue === null)
+ $pValue = self::SHEETVIEW_NORMAL;
+ if (in_array($pValue, self::$_sheetViewTypes)) {
+ $this->_sheetviewType = $pValue;
+ } else {
+ throw new Exception("Invalid sheetview layout type.");
+ }
- return $this;
- }
+ 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;
+ }
+ }
+ }
}
diff --git a/Classes/PHPExcel/Writer/Abstract.php b/Classes/PHPExcel/Writer/Abstract.php
index 7a0f749..f0a39d2 100644
--- a/Classes/PHPExcel/Writer/Abstract.php
+++ b/Classes/PHPExcel/Writer/Abstract.php
@@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\Writer
* @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,124 +37,124 @@ namespace PHPExcel;
*/
abstract class Writer_Abstract implements Writer_IWriter
{
- /**
- * Write charts that are defined in the workbook?
- * Identifies whether the Writer should write definitions for any charts that exist in the PHPExcel object;
- *
- * @var boolean
- */
- protected $_includeCharts = FALSE;
+ /**
+ * Write charts that are defined in the workbook?
+ * Identifies whether the Writer should write definitions for any charts that exist in the PHPExcel object;
+ *
+ * @var boolean
+ */
+ protected $_includeCharts = false;
- /**
- * Pre-calculate formulas
- * Forces PHPExcel to recalculate all formulae in a workbook when saving, so that the pre-calculated values are
- * immediately available to MS Excel or other office spreadsheet viewer when opening the file
- *
- * @var boolean
- */
- protected $_preCalculateFormulas = TRUE;
+ /**
+ * Pre-calculate formulas
+ * Forces PHPExcel to recalculate all formulae in a workbook when saving, so that the pre-calculated values are
+ * immediately available to MS Excel or other office spreadsheet viewer when opening the file
+ *
+ * @var boolean
+ */
+ protected $_preCalculateFormulas = true;
- /**
- * Use disk caching where possible?
- *
- * @var boolean
- */
- protected $_useDiskCaching = FALSE;
+ /**
+ * Use disk caching where possible?
+ *
+ * @var boolean
+ */
+ protected $_useDiskCaching = false;
- /**
- * Disk caching directory
- *
- * @var string
- */
- protected $_diskCachingDirectory = './';
+ /**
+ * Disk caching directory
+ *
+ * @var string
+ */
+ protected $_diskCachingDirectory = './';
- /**
- * Write charts in workbook?
- * If this is true, then the Writer will write definitions for any charts that exist in the PHPExcel object.
- * If false (the default) it will ignore any charts defined in the PHPExcel object.
- *
- * @return boolean
- */
- public function getIncludeCharts() {
- return $this->_includeCharts;
- }
+ /**
+ * Write charts in workbook?
+ * If this is true, then the Writer will write definitions for any charts that exist in the PHPExcel object.
+ * If false (the default) it will ignore any charts defined in the PHPExcel object.
+ *
+ * @return boolean
+ */
+ public function getIncludeCharts() {
+ return $this->_includeCharts;
+ }
- /**
- * Set write charts in workbook
- * Set to true, to advise the Writer to include any charts that exist in the PHPExcel object.
- * Set to false (the default) to ignore charts.
- *
- * @param boolean $pValue
- * @return PHPExcel\Writer_IWriter
- */
- public function setIncludeCharts($pValue = FALSE) {
- $this->_includeCharts = (boolean) $pValue;
- return $this;
- }
+ /**
+ * Set write charts in workbook
+ * Set to true, to advise the Writer to include any charts that exist in the PHPExcel object.
+ * Set to false (the default) to ignore charts.
+ *
+ * @param boolean $pValue
+ * @return PHPExcel\Writer_IWriter
+ */
+ public function setIncludeCharts($pValue = false) {
+ $this->_includeCharts = (boolean) $pValue;
+ return $this;
+ }
/**
* Get Pre-Calculate Formulas flag
- * If this is true (the default), then the writer will recalculate all formulae in a workbook when saving,
- * so that the pre-calculated values are immediately available to MS Excel or other office spreadsheet
- * viewer when opening the file
- * If false, then formulae are not calculated on save. This is faster for saving in PHPExcel, but slower
- * when opening the resulting file in MS Excel, because Excel has to recalculate the formulae itself
+ * If this is true (the default), then the writer will recalculate all formulae in a workbook when saving,
+ * so that the pre-calculated values are immediately available to MS Excel or other office spreadsheet
+ * viewer when opening the file
+ * If false, then formulae are not calculated on save. This is faster for saving in PHPExcel, but slower
+ * when opening the resulting file in MS Excel, because Excel has to recalculate the formulae itself
*
* @return boolean
*/
public function getPreCalculateFormulas() {
- return $this->_preCalculateFormulas;
+ return $this->_preCalculateFormulas;
}
/**
* Set Pre-Calculate Formulas
- * Set to true (the default) to advise the Writer to calculate all formulae on save
- * Set to false to prevent precalculation of formulae on save.
+ * Set to true (the default) to advise the Writer to calculate all formulae on save
+ * Set to false to prevent precalculation of formulae on save.
*
- * @param boolean $pValue Pre-Calculate Formulas?
- * @return PHPExcel\Writer_IWriter
+ * @param boolean $pValue Pre-Calculate Formulas?
+ * @return PHPExcel\Writer_IWriter
*/
- public function setPreCalculateFormulas($pValue = TRUE) {
- $this->_preCalculateFormulas = (boolean) $pValue;
- return $this;
+ public function setPreCalculateFormulas($pValue = true) {
+ $this->_preCalculateFormulas = (boolean) $pValue;
+ return $this;
}
- /**
- * Get use disk caching where possible?
- *
- * @return boolean
- */
- public function getUseDiskCaching() {
- return $this->_useDiskCaching;
- }
+ /**
+ * Get use disk caching where possible?
+ *
+ * @return boolean
+ */
+ public function getUseDiskCaching() {
+ return $this->_useDiskCaching;
+ }
- /**
- * Set use disk caching where possible?
- *
- * @param boolean $pValue
- * @param string $pDirectory Disk caching directory
- * @throws PHPExcel\Writer_Exception when directory does not exist
- * @return PHPExcel\Writer_Excel2007
- */
- public function setUseDiskCaching($pValue = FALSE, $pDirectory = NULL) {
- $this->_useDiskCaching = $pValue;
+ /**
+ * Set use disk caching where possible?
+ *
+ * @param boolean $pValue
+ * @param string $pDirectory Disk caching directory
+ * @throws PHPExcel\Writer_Exception when directory does not exist
+ * @return PHPExcel\Writer_Excel2007
+ */
+ public function setUseDiskCaching($pValue = false, $pDirectory = null) {
+ $this->_useDiskCaching = $pValue;
- if ($pDirectory !== NULL) {
- if (is_dir($pDirectory)) {
- $this->_diskCachingDirectory = $pDirectory;
- } else {
- throw new Writer_Exception("Directory does not exist: $pDirectory");
- }
- }
- return $this;
- }
+ if ($pDirectory !== null) {
+ if (is_dir($pDirectory)) {
+ $this->_diskCachingDirectory = $pDirectory;
+ } else {
+ throw new Writer_Exception("Directory does not exist: $pDirectory");
+ }
+ }
+ return $this;
+ }
- /**
- * Get disk caching directory
- *
- * @return string
- */
- public function getDiskCachingDirectory() {
- return $this->_diskCachingDirectory;
- }
+ /**
+ * Get disk caching directory
+ *
+ * @return string
+ */
+ public function getDiskCachingDirectory() {
+ return $this->_diskCachingDirectory;
+ }
}
diff --git a/Classes/PHPExcel/Writer/CSV.php b/Classes/PHPExcel/Writer/CSV.php
index 6e94771..bf1ae36 100644
--- a/Classes/PHPExcel/Writer/CSV.php
+++ b/Classes/PHPExcel/Writer/CSV.php
@@ -19,10 +19,10 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category PHPExcel
- * @package PHPExcel\Writer_CSV
+ * @package PHPExcel\Writer_CSV
* @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,284 +31,284 @@ namespace PHPExcel;
* PHPExcel\Writer_CSV
*
* @category PHPExcel
- * @package PHPExcel\Writer_CSV
+ * @package PHPExcel\Writer_CSV
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
*/
class Writer_CSV extends Writer_Abstract implements Writer_IWriter {
- /**
- * PHPExcel object
- *
- * @var PHPExcel
- */
- private $_phpExcel;
+ /**
+ * PHPExcel object
+ *
+ * @var PHPExcel
+ */
+ private $_phpExcel;
- /**
- * Delimiter
- *
- * @var string
- */
- private $_delimiter = ',';
+ /**
+ * Delimiter
+ *
+ * @var string
+ */
+ private $_delimiter = ',';
- /**
- * Enclosure
- *
- * @var string
- */
- private $_enclosure = '"';
+ /**
+ * Enclosure
+ *
+ * @var string
+ */
+ private $_enclosure = '"';
- /**
- * Line ending
- *
- * @var string
- */
- private $_lineEnding = PHP_EOL;
+ /**
+ * Line ending
+ *
+ * @var string
+ */
+ private $_lineEnding = PHP_EOL;
- /**
- * Sheet index to write
- *
- * @var int
- */
- private $_sheetIndex = 0;
+ /**
+ * Sheet index to write
+ *
+ * @var int
+ */
+ private $_sheetIndex = 0;
- /**
- * Whether to write a BOM (for UTF8).
- *
- * @var boolean
- */
- private $_useBOM = false;
+ /**
+ * Whether to write a BOM (for UTF8).
+ *
+ * @var boolean
+ */
+ private $_useBOM = false;
- /**
- * Whether to write a fully Excel compatible CSV file.
- *
- * @var boolean
- */
- private $_excelCompatibility = false;
+ /**
+ * Whether to write a fully Excel compatible CSV file.
+ *
+ * @var boolean
+ */
+ private $_excelCompatibility = false;
- /**
- * Create a new PHPExcel\Writer_CSV
- *
- * @param PHPExcel\Workbook $phpExcel PHPExcel object
- */
- public function __construct(Workbook $phpExcel) {
- $this->_phpExcel = $phpExcel;
- }
+ /**
+ * Create a new PHPExcel\Writer_CSV
+ *
+ * @param PHPExcel\Workbook $phpExcel PHPExcel object
+ */
+ public function __construct(Workbook $phpExcel) {
+ $this->_phpExcel = $phpExcel;
+ }
- /**
- * Save PHPExcel to file
- *
- * @param string $pFilename
- * @throws PHPExcel\Writer_Exception
- */
- public function save($pFilename = null) {
- // Fetch sheet
- $sheet = $this->_phpExcel->getSheet($this->_sheetIndex);
+ /**
+ * Save PHPExcel to file
+ *
+ * @param string $pFilename
+ * @throws PHPExcel\Writer_Exception
+ */
+ public function save($pFilename = null) {
+ // Fetch sheet
+ $sheet = $this->_phpExcel->getSheet($this->_sheetIndex);
- $saveDebugLog = Calculation::getInstance($this->_phpExcel)->getDebugLog()->getWriteDebugLog();
- Calculation::getInstance($this->_phpExcel)->getDebugLog()->setWriteDebugLog(FALSE);
- $saveArrayReturnType = Calculation::getArrayReturnType();
- Calculation::setArrayReturnType(Calculation::RETURN_ARRAY_AS_VALUE);
+ $saveDebugLog = Calculation::getInstance($this->_phpExcel)->getDebugLog()->getWriteDebugLog();
+ Calculation::getInstance($this->_phpExcel)->getDebugLog()->setWriteDebugLog(false);
+ $saveArrayReturnType = Calculation::getArrayReturnType();
+ Calculation::setArrayReturnType(Calculation::RETURN_ARRAY_AS_VALUE);
- // Open file
- $fileHandle = fopen($pFilename, 'wb+');
- if ($fileHandle === false) {
- throw new Writer_Exception("Could not open file $pFilename for writing.");
- }
+ // Open file
+ $fileHandle = fopen($pFilename, 'wb+');
+ if ($fileHandle === false) {
+ throw new Writer_Exception("Could not open file $pFilename for writing.");
+ }
- if ($this->_excelCompatibility) {
- // Write the UTF-16LE BOM code
- fwrite($fileHandle, "\xFF\xFE"); // Excel uses UTF-16LE encoding
- $this->setEnclosure(); // Default enclosure is "
- $this->setDelimiter("\t"); // Excel delimiter is a TAB
- } elseif ($this->_useBOM) {
- // Write the UTF-8 BOM code
- fwrite($fileHandle, "\xEF\xBB\xBF");
- }
+ if ($this->_excelCompatibility) {
+ // Write the UTF-16LE BOM code
+ fwrite($fileHandle, "\xFF\xFE"); // Excel uses UTF-16LE encoding
+ $this->setEnclosure(); // Default enclosure is "
+ $this->setDelimiter("\t"); // Excel delimiter is a TAB
+ } elseif ($this->_useBOM) {
+ // Write the UTF-8 BOM code
+ fwrite($fileHandle, "\xEF\xBB\xBF");
+ }
- // Identify the range that we need to extract from the worksheet
- $maxCol = $sheet->getHighestColumn();
- $maxRow = $sheet->getHighestRow();
+ // Identify the range that we need to extract from the worksheet
+ $maxCol = $sheet->getHighestColumn();
+ $maxRow = $sheet->getHighestRow();
- // Write rows to file
- for($row = 1; $row <= $maxRow; ++$row) {
- // Convert the row to an array...
- $cellsArray = $sheet->rangeToArray('A'.$row.':'.$maxCol.$row,'', $this->_preCalculateFormulas);
- // ... and write to the file
- $this->_writeLine($fileHandle, $cellsArray[0]);
- }
+ // Write rows to file
+ for($row = 1; $row <= $maxRow; ++$row) {
+ // Convert the row to an array...
+ $cellsArray = $sheet->rangeToArray('A'.$row.':'.$maxCol.$row,'', $this->_preCalculateFormulas);
+ // ... and write to the file
+ $this->_writeLine($fileHandle, $cellsArray[0]);
+ }
- // Close file
- fclose($fileHandle);
+ // Close file
+ fclose($fileHandle);
- Calculation::setArrayReturnType($saveArrayReturnType);
- Calculation::getInstance($this->_phpExcel)->getDebugLog()->setWriteDebugLog($saveDebugLog);
- }
+ Calculation::setArrayReturnType($saveArrayReturnType);
+ Calculation::getInstance($this->_phpExcel)->getDebugLog()->setWriteDebugLog($saveDebugLog);
+ }
- /**
- * 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\Writer_CSV
- */
- public function setDelimiter($pValue = ',') {
- $this->_delimiter = $pValue;
- return $this;
- }
+ /**
+ * Set delimiter
+ *
+ * @param string $pValue Delimiter, defaults to ,
+ * @return PHPExcel\Writer_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\Writer_CSV
- */
- public function setEnclosure($pValue = '"') {
- if ($pValue == '') {
- $pValue = null;
- }
- $this->_enclosure = $pValue;
- return $this;
- }
+ /**
+ * Set enclosure
+ *
+ * @param string $pValue Enclosure, defaults to "
+ * @return PHPExcel\Writer_CSV
+ */
+ public function setEnclosure($pValue = '"') {
+ if ($pValue == '') {
+ $pValue = null;
+ }
+ $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\Writer_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\Writer_CSV
+ */
+ public function setLineEnding($pValue = PHP_EOL) {
+ $this->_lineEnding = $pValue;
+ return $this;
+ }
- /**
- * Get whether BOM should be used
- *
- * @return boolean
- */
- public function getUseBOM() {
- return $this->_useBOM;
- }
+ /**
+ * Get whether BOM should be used
+ *
+ * @return boolean
+ */
+ public function getUseBOM() {
+ return $this->_useBOM;
+ }
- /**
- * Set whether BOM should be used
- *
- * @param boolean $pValue Use UTF-8 byte-order mark? Defaults to false
- * @return PHPExcel\Writer_CSV
- */
- public function setUseBOM($pValue = false) {
- $this->_useBOM = $pValue;
- return $this;
- }
+ /**
+ * Set whether BOM should be used
+ *
+ * @param boolean $pValue Use UTF-8 byte-order mark? Defaults to false
+ * @return PHPExcel\Writer_CSV
+ */
+ public function setUseBOM($pValue = false) {
+ $this->_useBOM = $pValue;
+ return $this;
+ }
- /**
- * Get whether the file should be saved with full Excel Compatibility
- *
- * @return boolean
- */
- public function getExcelCompatibility() {
- return $this->_excelCompatibility;
- }
+ /**
+ * Get whether the file should be saved with full Excel Compatibility
+ *
+ * @return boolean
+ */
+ public function getExcelCompatibility() {
+ return $this->_excelCompatibility;
+ }
- /**
- * Set whether the file should be saved with full Excel Compatibility
- *
- * @param boolean $pValue Set the file to be written as a fully Excel compatible csv file
- * Note that this overrides other settings such as useBOM, enclosure and delimiter
- * @return PHPExcel\Writer_CSV
- */
- public function setExcelCompatibility($pValue = false) {
- $this->_excelCompatibility = $pValue;
- return $this;
- }
+ /**
+ * Set whether the file should be saved with full Excel Compatibility
+ *
+ * @param boolean $pValue Set the file to be written as a fully Excel compatible csv file
+ * Note that this overrides other settings such as useBOM, enclosure and delimiter
+ * @return PHPExcel\Writer_CSV
+ */
+ public function setExcelCompatibility($pValue = false) {
+ $this->_excelCompatibility = $pValue;
+ return $this;
+ }
- /**
- * Get sheet index
- *
- * @return int
- */
- public function getSheetIndex() {
- return $this->_sheetIndex;
- }
+ /**
+ * Get sheet index
+ *
+ * @return int
+ */
+ public function getSheetIndex() {
+ return $this->_sheetIndex;
+ }
- /**
- * Set sheet index
- *
- * @param int $pValue Sheet index
- * @return PHPExcel\Writer_CSV
- */
- public function setSheetIndex($pValue = 0) {
- $this->_sheetIndex = $pValue;
- return $this;
- }
+ /**
+ * Set sheet index
+ *
+ * @param int $pValue Sheet index
+ * @return PHPExcel\Writer_CSV
+ */
+ public function setSheetIndex($pValue = 0) {
+ $this->_sheetIndex = $pValue;
+ return $this;
+ }
- /**
- * Write line to CSV file
- *
- * @param mixed $pFileHandle PHP filehandle
- * @param array $pValues Array containing values in a row
- * @throws PHPExcel\Writer_Exception
- */
- private function _writeLine($pFileHandle = null, $pValues = null) {
- if (is_array($pValues)) {
- // No leading delimiter
- $writeDelimiter = false;
+ /**
+ * Write line to CSV file
+ *
+ * @param mixed $pFileHandle PHP filehandle
+ * @param array $pValues Array containing values in a row
+ * @throws PHPExcel\Writer_Exception
+ */
+ private function _writeLine($pFileHandle = null, $pValues = null) {
+ if (is_array($pValues)) {
+ // No leading delimiter
+ $writeDelimiter = false;
- // Build the line
- $line = '';
+ // Build the line
+ $line = '';
- foreach ($pValues as $element) {
- // Escape enclosures
- $element = str_replace($this->_enclosure, $this->_enclosure . $this->_enclosure, $element);
+ foreach ($pValues as $element) {
+ // Escape enclosures
+ $element = str_replace($this->_enclosure, $this->_enclosure . $this->_enclosure, $element);
- // Add delimiter
- if ($writeDelimiter) {
- $line .= $this->_delimiter;
- } else {
- $writeDelimiter = true;
- }
+ // Add delimiter
+ if ($writeDelimiter) {
+ $line .= $this->_delimiter;
+ } else {
+ $writeDelimiter = true;
+ }
- // Add enclosed string
- $line .= $this->_enclosure . $element . $this->_enclosure;
- }
+ // Add enclosed string
+ $line .= $this->_enclosure . $element . $this->_enclosure;
+ }
- // Add line ending
- $line .= $this->_lineEnding;
+ // Add line ending
+ $line .= $this->_lineEnding;
- // Write to file
- if ($this->_excelCompatibility) {
- fwrite($pFileHandle, mb_convert_encoding($line,"UTF-16LE","UTF-8"));
- } else {
- fwrite($pFileHandle, $line);
- }
- } else {
- throw new Writer_Exception("Invalid data row passed to CSV writer.");
- }
- }
+ // Write to file
+ if ($this->_excelCompatibility) {
+ fwrite($pFileHandle, mb_convert_encoding($line,"UTF-16LE","UTF-8"));
+ } else {
+ fwrite($pFileHandle, $line);
+ }
+ } else {
+ throw new Writer_Exception("Invalid data row passed to CSV writer.");
+ }
+ }
}
diff --git a/Classes/PHPExcel/Writer/Excel2007.php b/Classes/PHPExcel/Writer/Excel2007.php
index ba5ab1e..8dd902d 100644
--- a/Classes/PHPExcel/Writer/Excel2007.php
+++ b/Classes/PHPExcel/Writer/Excel2007.php
@@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\Writer_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,356 +37,356 @@ namespace PHPExcel;
*/
class Writer_Excel2007 extends Writer_Abstract implements Writer_IWriter
{
- /**
- * Office2003 compatibility
- *
- * @var boolean
- */
- private $_office2003compatibility = false;
+ /**
+ * Office2003 compatibility
+ *
+ * @var boolean
+ */
+ private $_office2003compatibility = false;
- /**
- * Private writer parts
- *
- * @var PHPExcel\Writer_Excel2007_WriterPart[]
- */
- private $_writerParts = array();
+ /**
+ * Private writer parts
+ *
+ * @var PHPExcel\Writer_Excel2007_WriterPart[]
+ */
+ private $_writerParts = array();
- /**
- * Private PHPExcel
- *
- * @var PHPExcel
- */
- private $_spreadSheet;
+ /**
+ * Private PHPExcel
+ *
+ * @var PHPExcel
+ */
+ private $_spreadSheet;
- /**
- * Private string table
- *
- * @var string[]
- */
- private $_stringTable = array();
+ /**
+ * Private string table
+ *
+ * @var string[]
+ */
+ private $_stringTable = array();
- /**
- * Private unique PHPExcel\Style_Conditional HashTable
- *
- * @var PHPExcel\HashTable
- */
- private $_stylesConditionalHashTable;
+ /**
+ * Private unique PHPExcel\Style_Conditional HashTable
+ *
+ * @var PHPExcel\HashTable
+ */
+ private $_stylesConditionalHashTable;
- /**
- * Private unique PHPExcel\Style_Fill HashTable
- *
- * @var PHPExcel\HashTable
- */
- private $_fillHashTable;
+ /**
+ * Private unique PHPExcel\Style_Fill HashTable
+ *
+ * @var PHPExcel\HashTable
+ */
+ private $_fillHashTable;
- /**
- * Private unique PHPExcel\Style_Font HashTable
- *
- * @var PHPExcel\HashTable
- */
- private $_fontHashTable;
+ /**
+ * Private unique PHPExcel\Style_Font HashTable
+ *
+ * @var PHPExcel\HashTable
+ */
+ private $_fontHashTable;
- /**
- * Private unique PHPExcel\Style_Borders HashTable
- *
- * @var PHPExcel\HashTable
- */
- private $_bordersHashTable ;
+ /**
+ * Private unique PHPExcel\Style_Borders HashTable
+ *
+ * @var PHPExcel\HashTable
+ */
+ private $_bordersHashTable ;
- /**
- * Private unique PHPExcel\Style_NumberFormat HashTable
- *
- * @var PHPExcel\HashTable
- */
- private $_numFmtHashTable;
+ /**
+ * Private unique PHPExcel\Style_NumberFormat HashTable
+ *
+ * @var PHPExcel\HashTable
+ */
+ private $_numFmtHashTable;
- /**
- * Private unique PHPExcel\Worksheet_BaseDrawing HashTable
- *
- * @var PHPExcel\HashTable
- */
- private $_drawingHashTable;
+ /**
+ * Private unique PHPExcel\Worksheet_BaseDrawing HashTable
+ *
+ * @var PHPExcel\HashTable
+ */
+ private $_drawingHashTable;
/**
* Create a new PHPExcel\Writer_Excel2007
*
- * @param PHPExcel $pPHPExcel
+ * @param PHPExcel $pPHPExcel
*/
public function __construct(Workbook $pPHPExcel = null)
{
- // Assign PHPExcel
- $this->setPHPExcel($pPHPExcel);
+ // Assign PHPExcel
+ $this->setPHPExcel($pPHPExcel);
- $writerPartsArray = array( 'stringtable' => __NAMESPACE__ . '\Writer_Excel2007_StringTable',
- 'contenttypes' => __NAMESPACE__ . '\Writer_Excel2007_ContentTypes',
- 'docprops' => __NAMESPACE__ . '\Writer_Excel2007_DocProps',
- 'rels' => __NAMESPACE__ . '\Writer_Excel2007_Rels',
- 'theme' => __NAMESPACE__ . '\Writer_Excel2007_Theme',
- 'style' => __NAMESPACE__ . '\Writer_Excel2007_Style',
- 'workbook' => __NAMESPACE__ . '\Writer_Excel2007_Workbook',
- 'worksheet' => __NAMESPACE__ . '\Writer_Excel2007_Worksheet',
- 'drawing' => __NAMESPACE__ . '\Writer_Excel2007_Drawing',
- 'comments' => __NAMESPACE__ . '\Writer_Excel2007_Comments',
- 'chart' => __NAMESPACE__ . '\Writer_Excel2007_Chart',
- );
+ $writerPartsArray = array( 'stringtable' => __NAMESPACE__ . '\Writer_Excel2007_StringTable',
+ 'contenttypes' => __NAMESPACE__ . '\Writer_Excel2007_ContentTypes',
+ 'docprops' => __NAMESPACE__ . '\Writer_Excel2007_DocProps',
+ 'rels' => __NAMESPACE__ . '\Writer_Excel2007_Rels',
+ 'theme' => __NAMESPACE__ . '\Writer_Excel2007_Theme',
+ 'style' => __NAMESPACE__ . '\Writer_Excel2007_Style',
+ 'workbook' => __NAMESPACE__ . '\Writer_Excel2007_Workbook',
+ 'worksheet' => __NAMESPACE__ . '\Writer_Excel2007_Worksheet',
+ 'drawing' => __NAMESPACE__ . '\Writer_Excel2007_Drawing',
+ 'comments' => __NAMESPACE__ . '\Writer_Excel2007_Comments',
+ 'chart' => __NAMESPACE__ . '\Writer_Excel2007_Chart',
+ );
- // Initialise writer parts
- // and Assign their parent IWriters
- foreach ($writerPartsArray as $writer => $class) {
- $this->_writerParts[$writer] = new $class($this);
- }
+ // Initialise writer parts
+ // and Assign their parent IWriters
+ foreach ($writerPartsArray as $writer => $class) {
+ $this->_writerParts[$writer] = new $class($this);
+ }
- $hashTablesArray = array( '_stylesConditionalHashTable', '_fillHashTable', '_fontHashTable',
- '_bordersHashTable', '_numFmtHashTable', '_drawingHashTable'
- );
+ $hashTablesArray = array( '_stylesConditionalHashTable', '_fillHashTable', '_fontHashTable',
+ '_bordersHashTable', '_numFmtHashTable', '_drawingHashTable'
+ );
- // Set HashTable variables
- foreach ($hashTablesArray as $tableName) {
- $this->$tableName = new HashTable();
- }
+ // Set HashTable variables
+ foreach ($hashTablesArray as $tableName) {
+ $this->$tableName = new HashTable();
+ }
}
- /**
- * Get writer part
- *
- * @param string $pPartName Writer part name
- * @return PHPExcel\Writer_Excel2007_WriterPart
- */
- public function getWriterPart($pPartName = '') {
- if ($pPartName != '' && isset($this->_writerParts[strtolower($pPartName)])) {
- return $this->_writerParts[strtolower($pPartName)];
- } else {
- return null;
- }
- }
+ /**
+ * Get writer part
+ *
+ * @param string $pPartName Writer part name
+ * @return PHPExcel\Writer_Excel2007_WriterPart
+ */
+ public function getWriterPart($pPartName = '') {
+ if ($pPartName != '' && isset($this->_writerParts[strtolower($pPartName)])) {
+ return $this->_writerParts[strtolower($pPartName)];
+ } else {
+ return null;
+ }
+ }
- /**
- * Save PHPExcel to file
- *
- * @param string $pFilename
- * @throws PHPExcel\Writer_Exception
- */
- public function save($pFilename = null)
- {
- if ($this->_spreadSheet !== NULL) {
- // garbage collect
- $this->_spreadSheet->garbageCollect();
+ /**
+ * Save PHPExcel to file
+ *
+ * @param string $pFilename
+ * @throws PHPExcel\Writer_Exception
+ */
+ public function save($pFilename = null)
+ {
+ if ($this->_spreadSheet !== null) {
+ // garbage collect
+ $this->_spreadSheet->garbageCollect();
- // If $pFilename is php://output or php://stdout, make it a temporary file...
- $originalFilename = $pFilename;
- if (strtolower($pFilename) == 'php://output' || strtolower($pFilename) == 'php://stdout') {
- $pFilename = @tempnam(Shared_File::sys_get_temp_dir(), 'phpxltmp');
- if ($pFilename == '') {
- $pFilename = $originalFilename;
- }
- }
+ // If $pFilename is php://output or php://stdout, make it a temporary file...
+ $originalFilename = $pFilename;
+ if (strtolower($pFilename) == 'php://output' || strtolower($pFilename) == 'php://stdout') {
+ $pFilename = @tempnam(Shared_File::sys_get_temp_dir(), 'phpxltmp');
+ if ($pFilename == '') {
+ $pFilename = $originalFilename;
+ }
+ }
- $saveDebugLog = Calculation::getInstance($this->_spreadSheet)->getDebugLog()->getWriteDebugLog();
- Calculation::getInstance($this->_spreadSheet)->getDebugLog()->setWriteDebugLog(FALSE);
- $saveDateReturnType = Calculation_Functions::getReturnDateType();
- Calculation_Functions::setReturnDateType(Calculation_Functions::RETURNDATE_EXCEL);
+ $saveDebugLog = Calculation::getInstance($this->_spreadSheet)->getDebugLog()->getWriteDebugLog();
+ Calculation::getInstance($this->_spreadSheet)->getDebugLog()->setWriteDebugLog(false);
+ $saveDateReturnType = Calculation_Functions::getReturnDateType();
+ Calculation_Functions::setReturnDateType(Calculation_Functions::RETURNDATE_EXCEL);
- // Create string lookup table
- $this->_stringTable = array();
- for ($i = 0; $i < $this->_spreadSheet->getSheetCount(); ++$i) {
- $this->_stringTable = $this->getWriterPart('StringTable')->createStringTable($this->_spreadSheet->getSheet($i), $this->_stringTable);
- }
+ // Create string lookup table
+ $this->_stringTable = array();
+ for ($i = 0; $i < $this->_spreadSheet->getSheetCount(); ++$i) {
+ $this->_stringTable = $this->getWriterPart('StringTable')->createStringTable($this->_spreadSheet->getSheet($i), $this->_stringTable);
+ }
- // Create styles dictionaries
- $this->_stylesConditionalHashTable->addFromSource( $this->getWriterPart('Style')->allConditionalStyles($this->_spreadSheet) );
- $this->_fillHashTable->addFromSource( $this->getWriterPart('Style')->allFills($this->_spreadSheet) );
- $this->_fontHashTable->addFromSource( $this->getWriterPart('Style')->allFonts($this->_spreadSheet) );
- $this->_bordersHashTable->addFromSource( $this->getWriterPart('Style')->allBorders($this->_spreadSheet) );
- $this->_numFmtHashTable->addFromSource( $this->getWriterPart('Style')->allNumberFormats($this->_spreadSheet) );
+ // Create styles dictionaries
+ $this->_stylesConditionalHashTable->addFromSource( $this->getWriterPart('Style')->allConditionalStyles($this->_spreadSheet) );
+ $this->_fillHashTable->addFromSource( $this->getWriterPart('Style')->allFills($this->_spreadSheet) );
+ $this->_fontHashTable->addFromSource( $this->getWriterPart('Style')->allFonts($this->_spreadSheet) );
+ $this->_bordersHashTable->addFromSource( $this->getWriterPart('Style')->allBorders($this->_spreadSheet) );
+ $this->_numFmtHashTable->addFromSource( $this->getWriterPart('Style')->allNumberFormats($this->_spreadSheet) );
- // Create drawing dictionary
- $this->_drawingHashTable->addFromSource( $this->getWriterPart('Drawing')->allDrawings($this->_spreadSheet) );
+ // Create drawing dictionary
+ $this->_drawingHashTable->addFromSource( $this->getWriterPart('Drawing')->allDrawings($this->_spreadSheet) );
- // Create new ZIP file and open it for writing
- $zipClass = Settings::getZipClass();
- $objZip = new $zipClass();
+ // Create new ZIP file and open it for writing
+ $zipClass = Settings::getZipClass();
+ $objZip = new $zipClass();
- // Retrieve OVERWRITE and CREATE constants from the instantiated zip class
- // This method of accessing constant values from a dynamic class should work with all appropriate versions of PHP
- $ro = new \ReflectionObject($objZip);
- $zipOverWrite = $ro->getConstant('OVERWRITE');
- $zipCreate = $ro->getConstant('CREATE');
+ // Retrieve OVERWRITE and CREATE constants from the instantiated zip class
+ // This method of accessing constant values from a dynamic class should work with all appropriate versions of PHP
+ $ro = new \ReflectionObject($objZip);
+ $zipOverWrite = $ro->getConstant('OVERWRITE');
+ $zipCreate = $ro->getConstant('CREATE');
- if (file_exists($pFilename)) {
- unlink($pFilename);
- }
- // Try opening the ZIP file
- if ($objZip->open($pFilename, $zipOverWrite) !== true) {
- if ($objZip->open($pFilename, $zipCreate) !== true) {
- throw new Writer_Exception("Could not open " . $pFilename . " for writing.");
- }
- }
+ if (file_exists($pFilename)) {
+ unlink($pFilename);
+ }
+ // Try opening the ZIP file
+ if ($objZip->open($pFilename, $zipOverWrite) !== true) {
+ if ($objZip->open($pFilename, $zipCreate) !== true) {
+ throw new Writer_Exception("Could not open " . $pFilename . " for writing.");
+ }
+ }
- // Add [Content_Types].xml to ZIP file
- $objZip->addFromString('[Content_Types].xml', $this->getWriterPart('ContentTypes')->writeContentTypes($this->_spreadSheet, $this->_includeCharts));
+ // Add [Content_Types].xml to ZIP file
+ $objZip->addFromString('[Content_Types].xml', $this->getWriterPart('ContentTypes')->writeContentTypes($this->_spreadSheet, $this->_includeCharts));
- // Add relationships to ZIP file
- $objZip->addFromString('_rels/.rels', $this->getWriterPart('Rels')->writeRelationships($this->_spreadSheet));
- $objZip->addFromString('xl/_rels/workbook.xml.rels', $this->getWriterPart('Rels')->writeWorkbookRelationships($this->_spreadSheet));
+ // Add relationships to ZIP file
+ $objZip->addFromString('_rels/.rels', $this->getWriterPart('Rels')->writeRelationships($this->_spreadSheet));
+ $objZip->addFromString('xl/_rels/workbook.xml.rels', $this->getWriterPart('Rels')->writeWorkbookRelationships($this->_spreadSheet));
- // Add document properties to ZIP file
- $objZip->addFromString('docProps/app.xml', $this->getWriterPart('DocProps')->writeDocPropsApp($this->_spreadSheet));
- $objZip->addFromString('docProps/core.xml', $this->getWriterPart('DocProps')->writeDocPropsCore($this->_spreadSheet));
- $customPropertiesPart = $this->getWriterPart('DocProps')->writeDocPropsCustom($this->_spreadSheet);
- if ($customPropertiesPart !== NULL) {
- $objZip->addFromString('docProps/custom.xml', $customPropertiesPart);
- }
+ // Add document properties to ZIP file
+ $objZip->addFromString('docProps/app.xml', $this->getWriterPart('DocProps')->writeDocPropsApp($this->_spreadSheet));
+ $objZip->addFromString('docProps/core.xml', $this->getWriterPart('DocProps')->writeDocPropsCore($this->_spreadSheet));
+ $customPropertiesPart = $this->getWriterPart('DocProps')->writeDocPropsCustom($this->_spreadSheet);
+ if ($customPropertiesPart !== null) {
+ $objZip->addFromString('docProps/custom.xml', $customPropertiesPart);
+ }
- // Add theme to ZIP file
- $objZip->addFromString('xl/theme/theme1.xml', $this->getWriterPart('Theme')->writeTheme($this->_spreadSheet));
+ // Add theme to ZIP file
+ $objZip->addFromString('xl/theme/theme1.xml', $this->getWriterPart('Theme')->writeTheme($this->_spreadSheet));
- // Add string table to ZIP file
- $objZip->addFromString('xl/sharedStrings.xml', $this->getWriterPart('StringTable')->writeStringTable($this->_stringTable));
+ // Add string table to ZIP file
+ $objZip->addFromString('xl/sharedStrings.xml', $this->getWriterPart('StringTable')->writeStringTable($this->_stringTable));
- // Add styles to ZIP file
- $objZip->addFromString('xl/styles.xml', $this->getWriterPart('Style')->writeStyles($this->_spreadSheet));
+ // Add styles to ZIP file
+ $objZip->addFromString('xl/styles.xml', $this->getWriterPart('Style')->writeStyles($this->_spreadSheet));
- // Add workbook to ZIP file
- $objZip->addFromString('xl/workbook.xml', $this->getWriterPart('Workbook')->writeWorkbook($this->_spreadSheet, $this->_preCalculateFormulas));
+ // Add workbook to ZIP file
+ $objZip->addFromString('xl/workbook.xml', $this->getWriterPart('Workbook')->writeWorkbook($this->_spreadSheet, $this->_preCalculateFormulas));
- $chartCount = 0;
- // Add worksheets
- for ($i = 0; $i < $this->_spreadSheet->getSheetCount(); ++$i) {
- $objZip->addFromString('xl/worksheets/sheet' . ($i + 1) . '.xml', $this->getWriterPart('Worksheet')->writeWorksheet($this->_spreadSheet->getSheet($i), $this->_stringTable, $this->_includeCharts));
- if ($this->_includeCharts) {
- $charts = $this->_spreadSheet->getSheet($i)->getChartCollection();
- if (count($charts) > 0) {
- foreach($charts as $chart) {
- $objZip->addFromString('xl/charts/chart' . ($chartCount + 1) . '.xml', $this->getWriterPart('Chart')->writeChart($chart));
- $chartCount++;
- }
- }
- }
- }
+ $chartCount = 0;
+ // Add worksheets
+ for ($i = 0; $i < $this->_spreadSheet->getSheetCount(); ++$i) {
+ $objZip->addFromString('xl/worksheets/sheet' . ($i + 1) . '.xml', $this->getWriterPart('Worksheet')->writeWorksheet($this->_spreadSheet->getSheet($i), $this->_stringTable, $this->_includeCharts));
+ if ($this->_includeCharts) {
+ $charts = $this->_spreadSheet->getSheet($i)->getChartCollection();
+ if (count($charts) > 0) {
+ foreach($charts as $chart) {
+ $objZip->addFromString('xl/charts/chart' . ($chartCount + 1) . '.xml', $this->getWriterPart('Chart')->writeChart($chart));
+ $chartCount++;
+ }
+ }
+ }
+ }
- $chartRef1 = $chartRef2 = 0;
- // Add worksheet relationships (drawings, ...)
- for ($i = 0; $i < $this->_spreadSheet->getSheetCount(); ++$i) {
+ $chartRef1 = $chartRef2 = 0;
+ // Add worksheet relationships (drawings, ...)
+ for ($i = 0; $i < $this->_spreadSheet->getSheetCount(); ++$i) {
- // Add relationships
- $objZip->addFromString('xl/worksheets/_rels/sheet' . ($i + 1) . '.xml.rels', $this->getWriterPart('Rels')->writeWorksheetRelationships($this->_spreadSheet->getSheet($i), ($i + 1), $this->_includeCharts));
+ // Add relationships
+ $objZip->addFromString('xl/worksheets/_rels/sheet' . ($i + 1) . '.xml.rels', $this->getWriterPart('Rels')->writeWorksheetRelationships($this->_spreadSheet->getSheet($i), ($i + 1), $this->_includeCharts));
- $drawings = $this->_spreadSheet->getSheet($i)->getDrawingCollection();
- $drawingCount = count($drawings);
- if ($this->_includeCharts) {
- $chartCount = $this->_spreadSheet->getSheet($i)->getChartCount();
- }
+ $drawings = $this->_spreadSheet->getSheet($i)->getDrawingCollection();
+ $drawingCount = count($drawings);
+ if ($this->_includeCharts) {
+ $chartCount = $this->_spreadSheet->getSheet($i)->getChartCount();
+ }
- // Add drawing and image relationship parts
- if (($drawingCount > 0) || ($chartCount > 0)) {
- // Drawing relationships
- $objZip->addFromString('xl/drawings/_rels/drawing' . ($i + 1) . '.xml.rels', $this->getWriterPart('Rels')->writeDrawingRelationships($this->_spreadSheet->getSheet($i),$chartRef1, $this->_includeCharts));
+ // Add drawing and image relationship parts
+ if (($drawingCount > 0) || ($chartCount > 0)) {
+ // Drawing relationships
+ $objZip->addFromString('xl/drawings/_rels/drawing' . ($i + 1) . '.xml.rels', $this->getWriterPart('Rels')->writeDrawingRelationships($this->_spreadSheet->getSheet($i),$chartRef1, $this->_includeCharts));
- // Drawings
- $objZip->addFromString('xl/drawings/drawing' . ($i + 1) . '.xml', $this->getWriterPart('Drawing')->writeDrawings($this->_spreadSheet->getSheet($i),$chartRef2,$this->_includeCharts));
- }
+ // Drawings
+ $objZip->addFromString('xl/drawings/drawing' . ($i + 1) . '.xml', $this->getWriterPart('Drawing')->writeDrawings($this->_spreadSheet->getSheet($i),$chartRef2,$this->_includeCharts));
+ }
- // Add comment relationship parts
- if (count($this->_spreadSheet->getSheet($i)->getComments()) > 0) {
- // VML Comments
- $objZip->addFromString('xl/drawings/vmlDrawing' . ($i + 1) . '.vml', $this->getWriterPart('Comments')->writeVMLComments($this->_spreadSheet->getSheet($i)));
+ // Add comment relationship parts
+ if (count($this->_spreadSheet->getSheet($i)->getComments()) > 0) {
+ // VML Comments
+ $objZip->addFromString('xl/drawings/vmlDrawing' . ($i + 1) . '.vml', $this->getWriterPart('Comments')->writeVMLComments($this->_spreadSheet->getSheet($i)));
- // Comments
- $objZip->addFromString('xl/comments' . ($i + 1) . '.xml', $this->getWriterPart('Comments')->writeComments($this->_spreadSheet->getSheet($i)));
- }
+ // Comments
+ $objZip->addFromString('xl/comments' . ($i + 1) . '.xml', $this->getWriterPart('Comments')->writeComments($this->_spreadSheet->getSheet($i)));
+ }
- // Add header/footer relationship parts
- if (count($this->_spreadSheet->getSheet($i)->getHeaderFooter()->getImages()) > 0) {
- // VML Drawings
- $objZip->addFromString('xl/drawings/vmlDrawingHF' . ($i + 1) . '.vml', $this->getWriterPart('Drawing')->writeVMLHeaderFooterImages($this->_spreadSheet->getSheet($i)));
+ // Add header/footer relationship parts
+ if (count($this->_spreadSheet->getSheet($i)->getHeaderFooter()->getImages()) > 0) {
+ // VML Drawings
+ $objZip->addFromString('xl/drawings/vmlDrawingHF' . ($i + 1) . '.vml', $this->getWriterPart('Drawing')->writeVMLHeaderFooterImages($this->_spreadSheet->getSheet($i)));
- // VML Drawing relationships
- $objZip->addFromString('xl/drawings/_rels/vmlDrawingHF' . ($i + 1) . '.vml.rels', $this->getWriterPart('Rels')->writeHeaderFooterDrawingRelationships($this->_spreadSheet->getSheet($i)));
+ // VML Drawing relationships
+ $objZip->addFromString('xl/drawings/_rels/vmlDrawingHF' . ($i + 1) . '.vml.rels', $this->getWriterPart('Rels')->writeHeaderFooterDrawingRelationships($this->_spreadSheet->getSheet($i)));
- // Media
- foreach ($this->_spreadSheet->getSheet($i)->getHeaderFooter()->getImages() as $image) {
- $objZip->addFromString('xl/media/' . $image->getIndexedFilename(), file_get_contents($image->getPath()));
- }
- }
- }
+ // Media
+ foreach ($this->_spreadSheet->getSheet($i)->getHeaderFooter()->getImages() as $image) {
+ $objZip->addFromString('xl/media/' . $image->getIndexedFilename(), file_get_contents($image->getPath()));
+ }
+ }
+ }
- // Add media
- for ($i = 0; $i < $this->getDrawingHashTable()->count(); ++$i) {
- if ($this->getDrawingHashTable()->getByIndex($i) instanceof Worksheet_Drawing) {
- $imageContents = null;
- $imagePath = $this->getDrawingHashTable()->getByIndex($i)->getPath();
- if (strpos($imagePath, 'zip://') !== false) {
- $imagePath = substr($imagePath, 6);
- $imagePathSplitted = explode('#', $imagePath);
+ // Add media
+ for ($i = 0; $i < $this->getDrawingHashTable()->count(); ++$i) {
+ if ($this->getDrawingHashTable()->getByIndex($i) instanceof Worksheet_Drawing) {
+ $imageContents = null;
+ $imagePath = $this->getDrawingHashTable()->getByIndex($i)->getPath();
+ if (strpos($imagePath, 'zip://') !== false) {
+ $imagePath = substr($imagePath, 6);
+ $imagePathSplitted = explode('#', $imagePath);
- $imageZip = new \ZipArchive();
- $imageZip->open($imagePathSplitted[0]);
- $imageContents = $imageZip->getFromName($imagePathSplitted[1]);
- $imageZip->close();
- unset($imageZip);
- } else {
- $imageContents = file_get_contents($imagePath);
- }
+ $imageZip = new \ZipArchive();
+ $imageZip->open($imagePathSplitted[0]);
+ $imageContents = $imageZip->getFromName($imagePathSplitted[1]);
+ $imageZip->close();
+ unset($imageZip);
+ } else {
+ $imageContents = file_get_contents($imagePath);
+ }
- $objZip->addFromString('xl/media/' . str_replace(' ', '_', $this->getDrawingHashTable()->getByIndex($i)->getIndexedFilename()), $imageContents);
- } else if ($this->getDrawingHashTable()->getByIndex($i) instanceof Worksheet_MemoryDrawing) {
- ob_start();
- call_user_func(
- $this->getDrawingHashTable()->getByIndex($i)->getRenderingFunction(),
- $this->getDrawingHashTable()->getByIndex($i)->getImageResource()
- );
- $imageContents = ob_get_contents();
- ob_end_clean();
+ $objZip->addFromString('xl/media/' . str_replace(' ', '_', $this->getDrawingHashTable()->getByIndex($i)->getIndexedFilename()), $imageContents);
+ } else if ($this->getDrawingHashTable()->getByIndex($i) instanceof Worksheet_MemoryDrawing) {
+ ob_start();
+ call_user_func(
+ $this->getDrawingHashTable()->getByIndex($i)->getRenderingFunction(),
+ $this->getDrawingHashTable()->getByIndex($i)->getImageResource()
+ );
+ $imageContents = ob_get_contents();
+ ob_end_clean();
- $objZip->addFromString('xl/media/' . str_replace(' ', '_', $this->getDrawingHashTable()->getByIndex($i)->getIndexedFilename()), $imageContents);
- }
- }
+ $objZip->addFromString('xl/media/' . str_replace(' ', '_', $this->getDrawingHashTable()->getByIndex($i)->getIndexedFilename()), $imageContents);
+ }
+ }
- Calculation_Functions::setReturnDateType($saveDateReturnType);
- Calculation::getInstance($this->_spreadSheet)->getDebugLog()->setWriteDebugLog($saveDebugLog);
+ Calculation_Functions::setReturnDateType($saveDateReturnType);
+ Calculation::getInstance($this->_spreadSheet)->getDebugLog()->setWriteDebugLog($saveDebugLog);
- // Close file
- if ($objZip->close() === false) {
- throw new Writer_Exception("Could not close zip file $pFilename.");
- }
+ // Close file
+ if ($objZip->close() === false) {
+ throw new Writer_Exception("Could not close zip file $pFilename.");
+ }
- // If a temporary file was used, copy it to the correct file stream
- if ($originalFilename != $pFilename) {
- if (copy($pFilename, $originalFilename) === false) {
- throw new Writer_Exception("Could not copy temporary zip file $pFilename to $originalFilename.");
- }
- @unlink($pFilename);
- }
- } else {
- throw new Writer_Exception("PHPExcel object unassigned.");
- }
- }
+ // If a temporary file was used, copy it to the correct file stream
+ if ($originalFilename != $pFilename) {
+ if (copy($pFilename, $originalFilename) === false) {
+ throw new Writer_Exception("Could not copy temporary zip file $pFilename to $originalFilename.");
+ }
+ @unlink($pFilename);
+ }
+ } else {
+ throw new Writer_Exception("PHPExcel object unassigned.");
+ }
+ }
- /**
- * Get PHPExcel object
- *
- * @return PHPExcel\Workbook
- * @throws PHPExcel\Writer_Exception
- */
- public function getPHPExcel() {
- if ($this->_spreadSheet !== null) {
- return $this->_spreadSheet;
- } else {
- throw new Writer_Exception("No PHPExcel assigned.");
- }
- }
+ /**
+ * Get PHPExcel object
+ *
+ * @return PHPExcel\Workbook
+ * @throws PHPExcel\Writer_Exception
+ */
+ public function getPHPExcel() {
+ if ($this->_spreadSheet !== null) {
+ return $this->_spreadSheet;
+ } else {
+ throw new Writer_Exception("No PHPExcel assigned.");
+ }
+ }
- /**
- * Set PHPExcel object
- *
- * @param PHPExcel\Workbook $pPHPExcel PHPExcel object
- * @throws PHPExcel\Writer_Exception
- * @return PHPExcel\Writer_Excel2007
- */
- public function setPHPExcel(Workbook $pPHPExcel = null) {
- $this->_spreadSheet = $pPHPExcel;
- return $this;
- }
+ /**
+ * Set PHPExcel object
+ *
+ * @param PHPExcel\Workbook $pPHPExcel PHPExcel object
+ * @throws PHPExcel\Writer_Exception
+ * @return PHPExcel\Writer_Excel2007
+ */
+ public function setPHPExcel(Workbook $pPHPExcel = null) {
+ $this->_spreadSheet = $pPHPExcel;
+ return $this;
+ }
/**
* Get string table
@@ -394,7 +394,7 @@ class Writer_Excel2007 extends Writer_Abstract implements Writer_IWriter
* @return string[]
*/
public function getStringTable() {
- return $this->_stringTable;
+ return $this->_stringTable;
}
/**
@@ -403,7 +403,7 @@ class Writer_Excel2007 extends Writer_Abstract implements Writer_IWriter
* @return PHPExcel\HashTable
*/
public function getStylesConditionalHashTable() {
- return $this->_stylesConditionalHashTable;
+ return $this->_stylesConditionalHashTable;
}
/**
@@ -412,7 +412,7 @@ class Writer_Excel2007 extends Writer_Abstract implements Writer_IWriter
* @return PHPExcel\HashTable
*/
public function getFillHashTable() {
- return $this->_fillHashTable;
+ return $this->_fillHashTable;
}
/**
@@ -421,7 +421,7 @@ class Writer_Excel2007 extends Writer_Abstract implements Writer_IWriter
* @return PHPExcel\HashTable
*/
public function getFontHashTable() {
- return $this->_fontHashTable;
+ return $this->_fontHashTable;
}
/**
@@ -430,7 +430,7 @@ class Writer_Excel2007 extends Writer_Abstract implements Writer_IWriter
* @return PHPExcel\HashTable
*/
public function getBordersHashTable() {
- return $this->_bordersHashTable;
+ return $this->_bordersHashTable;
}
/**
@@ -439,7 +439,7 @@ class Writer_Excel2007 extends Writer_Abstract implements Writer_IWriter
* @return PHPExcel\HashTable
*/
public function getNumFmtHashTable() {
- return $this->_numFmtHashTable;
+ return $this->_numFmtHashTable;
}
/**
@@ -448,7 +448,7 @@ class Writer_Excel2007 extends Writer_Abstract implements Writer_IWriter
* @return PHPExcel\HashTable
*/
public function getDrawingHashTable() {
- return $this->_drawingHashTable;
+ return $this->_drawingHashTable;
}
/**
@@ -457,18 +457,17 @@ class Writer_Excel2007 extends Writer_Abstract implements Writer_IWriter
* @return boolean
*/
public function getOffice2003Compatibility() {
- return $this->_office2003compatibility;
+ return $this->_office2003compatibility;
}
/**
* Set Office2003 compatibility
*
- * @param boolean $pValue Office2003 compatibility?
+ * @param boolean $pValue Office2003 compatibility?
* @return PHPExcel\Writer_Excel2007
*/
public function setOffice2003Compatibility($pValue = false) {
- $this->_office2003compatibility = $pValue;
- return $this;
+ $this->_office2003compatibility = $pValue;
+ return $this;
}
-
}
diff --git a/Classes/PHPExcel/Writer/Excel2007/Chart.php b/Classes/PHPExcel/Writer/Excel2007/Chart.php
index 4a29723..b2cd084 100644
--- a/Classes/PHPExcel/Writer/Excel2007/Chart.php
+++ b/Classes/PHPExcel/Writer/Excel2007/Chart.php
@@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\Writer_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,1150 +37,1149 @@ namespace PHPExcel;
*/
class Writer_Excel2007_Chart extends Writer_Excel2007_WriterPart
{
- /**
- * Write charts to XML format
- *
- * @param PHPExcel\Chart $pChart
- * @return string XML Output
- * @throws PHPExcel\Writer_Exception
- */
- public function writeChart(Chart $pChart = null)
- {
- // Create XML writer
- $objWriter = null;
- if ($this->getParentWriter()->getUseDiskCaching()) {
- $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
- } else {
- $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_MEMORY);
- }
- // Ensure that data series values are up-to-date before we save
- $pChart->refresh();
-
- // XML header
- $objWriter->startDocument('1.0','UTF-8','yes');
-
- // c:chartSpace
- $objWriter->startElement('c:chartSpace');
- $objWriter->writeAttribute('xmlns:c', 'http://schemas.openxmlformats.org/drawingml/2006/chart');
- $objWriter->writeAttribute('xmlns:a', 'http://schemas.openxmlformats.org/drawingml/2006/main');
- $objWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships');
-
- $objWriter->startElement('c:date1904');
- $objWriter->writeAttribute('val', 0);
- $objWriter->endElement();
- $objWriter->startElement('c:lang');
- $objWriter->writeAttribute('val', "en-GB");
- $objWriter->endElement();
- $objWriter->startElement('c:roundedCorners');
- $objWriter->writeAttribute('val', 0);
- $objWriter->endElement();
-
- $this->_writeAlternateContent($objWriter);
-
- $objWriter->startElement('c:chart');
-
- $this->_writeTitle($pChart->getTitle(), $objWriter);
-
- $objWriter->startElement('c:autoTitleDeleted');
- $objWriter->writeAttribute('val', 0);
- $objWriter->endElement();
-
- $this->_writePlotArea($pChart->getPlotArea(),
- $pChart->getXAxisLabel(),
- $pChart->getYAxisLabel(),
- $objWriter,
- $pChart->getWorksheet()
- );
-
- $this->_writeLegend($pChart->getLegend(), $objWriter);
-
-
- $objWriter->startElement('c:plotVisOnly');
- $objWriter->writeAttribute('val', 1);
- $objWriter->endElement();
-
- $objWriter->startElement('c:dispBlanksAs');
- $objWriter->writeAttribute('val', "gap");
- $objWriter->endElement();
-
- $objWriter->startElement('c:showDLblsOverMax');
- $objWriter->writeAttribute('val', 0);
- $objWriter->endElement();
-
- $objWriter->endElement();
-
- $this->_writePrintSettings($objWriter);
-
- $objWriter->endElement();
-
- // Return
- return $objWriter->getData();
- }
-
- /**
- * Write Chart Title
- *
- * @param PHPExcel\Chart_Title $title
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @throws PHPExcel\Writer_Exception
- */
- private function _writeTitle(Chart_Title $title = null, $objWriter)
- {
- if (is_null($title)) {
- return;
- }
-
- $objWriter->startElement('c:title');
- $objWriter->startElement('c:tx');
- $objWriter->startElement('c:rich');
-
- $objWriter->startElement('a:bodyPr');
- $objWriter->endElement();
-
- $objWriter->startElement('a:lstStyle');
- $objWriter->endElement();
-
- $objWriter->startElement('a:p');
-
- $caption = $title->getCaption();
- if ((is_array($caption)) && (count($caption) > 0))
- $caption = $caption[0];
- $this->getParentWriter()->getWriterPart('stringtable')->writeRichTextForCharts($objWriter, $caption, 'a');
-
- $objWriter->endElement();
- $objWriter->endElement();
- $objWriter->endElement();
-
- $layout = $title->getLayout();
- $this->_writeLayout($layout, $objWriter);
-
- $objWriter->startElement('c:overlay');
- $objWriter->writeAttribute('val', 0);
- $objWriter->endElement();
-
- $objWriter->endElement();
- }
-
- /**
- * Write Chart Legend
- *
- * @param PHPExcel\Chart_Legend $legend
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @throws PHPExcel\Writer_Exception
- */
- private function _writeLegend(Chart_Legend $legend = null, $objWriter)
- {
- if (is_null($legend)) {
- return;
- }
-
- $objWriter->startElement('c:legend');
-
- $objWriter->startElement('c:legendPos');
- $objWriter->writeAttribute('val', $legend->getPosition());
- $objWriter->endElement();
-
- $layout = $legend->getLayout();
- $this->_writeLayout($layout, $objWriter);
-
- $objWriter->startElement('c:overlay');
- $objWriter->writeAttribute('val', ($legend->getOverlay()) ? '1' : '0');
- $objWriter->endElement();
-
- $objWriter->startElement('c:txPr');
- $objWriter->startElement('a:bodyPr');
- $objWriter->endElement();
-
- $objWriter->startElement('a:lstStyle');
- $objWriter->endElement();
-
- $objWriter->startElement('a:p');
- $objWriter->startElement('a:pPr');
- $objWriter->writeAttribute('rtl', 0);
-
- $objWriter->startElement('a:defRPr');
- $objWriter->endElement();
- $objWriter->endElement();
-
- $objWriter->startElement('a:endParaRPr');
- $objWriter->writeAttribute('lang', "en-US");
- $objWriter->endElement();
-
- $objWriter->endElement();
- $objWriter->endElement();
-
- $objWriter->endElement();
- }
-
- /**
- * Write Chart Plot Area
- *
- * @param PHPExcel\Chart_PlotArea $plotArea
- * @param PHPExcel\Chart_Title $xAxisLabel
- * @param PHPExcel\Chart_Title $yAxisLabel
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @throws PHPExcel\Writer_Exception
- */
- private function _writePlotArea(Chart_PlotArea $plotArea,
- Chart_Title $xAxisLabel = NULL,
- Chart_Title $yAxisLabel = NULL,
- $objWriter,
- Worksheet $pSheet)
- {
- if (is_null($plotArea)) {
- return;
- }
-
- $id1 = $id2 = 0;
- $this->_seriesIndex = 0;
- $objWriter->startElement('c:plotArea');
-
- $layout = $plotArea->getLayout();
-
- $this->_writeLayout($layout, $objWriter);
-
- $chartTypes = self::_getChartType($plotArea);
- $catIsMultiLevelSeries = $valIsMultiLevelSeries = FALSE;
- $plotGroupingType = '';
- foreach($chartTypes as $chartType) {
- $objWriter->startElement('c:'.$chartType);
-
- $groupCount = $plotArea->getPlotGroupCount();
- for($i = 0; $i < $groupCount; ++$i) {
- $plotGroup = $plotArea->getPlotGroupByIndex($i);
- $groupType = $plotGroup->getPlotType();
- if ($groupType == $chartType) {
-
- $plotStyle = $plotGroup->getPlotStyle();
- if ($groupType === Chart_DataSeries::TYPE_RADARCHART) {
- $objWriter->startElement('c:radarStyle');
- $objWriter->writeAttribute('val', $plotStyle );
- $objWriter->endElement();
- } elseif ($groupType === Chart_DataSeries::TYPE_SCATTERCHART) {
- $objWriter->startElement('c:scatterStyle');
- $objWriter->writeAttribute('val', $plotStyle );
- $objWriter->endElement();
- }
-
- $this->_writePlotGroup($plotGroup, $chartType, $objWriter, $catIsMultiLevelSeries, $valIsMultiLevelSeries, $plotGroupingType, $pSheet);
- }
- }
-
- $this->_writeDataLbls($objWriter, $layout);
-
- if ($chartType === Chart_DataSeries::TYPE_LINECHART) {
- // Line only, Line3D can't be smoothed
-
- $objWriter->startElement('c:smooth');
- $objWriter->writeAttribute('val', (integer) $plotGroup->getSmoothLine() );
- $objWriter->endElement();
- } elseif (($chartType === Chart_DataSeries::TYPE_BARCHART) ||
- ($chartType === Chart_DataSeries::TYPE_BARCHART_3D)) {
-
- $objWriter->startElement('c:gapWidth');
- $objWriter->writeAttribute('val', 150 );
- $objWriter->endElement();
-
- if ($plotGroupingType == 'percentStacked' ||
- $plotGroupingType == 'stacked') {
-
- $objWriter->startElement('c:overlap');
- $objWriter->writeAttribute('val', 100 );
- $objWriter->endElement();
- }
- } elseif ($chartType === Chart_DataSeries::TYPE_BUBBLECHART) {
-
- $objWriter->startElement('c:bubbleScale');
- $objWriter->writeAttribute('val', 25 );
- $objWriter->endElement();
-
- $objWriter->startElement('c:showNegBubbles');
- $objWriter->writeAttribute('val', 0 );
- $objWriter->endElement();
- } elseif ($chartType === Chart_DataSeries::TYPE_STOCKCHART) {
-
- $objWriter->startElement('c:hiLowLines');
- $objWriter->endElement();
- }
-
- // Generate 2 unique numbers to use for axId values
-// $id1 = $id2 = rand(10000000,99999999);
-// do {
-// $id2 = rand(10000000,99999999);
-// } while ($id1 == $id2);
- $id1 = '75091328';
- $id2 = '75089408';
-
- if (($chartType !== Chart_DataSeries::TYPE_PIECHART) &&
- ($chartType !== Chart_DataSeries::TYPE_PIECHART_3D) &&
- ($chartType !== Chart_DataSeries::TYPE_DONUTCHART)) {
-
- $objWriter->startElement('c:axId');
- $objWriter->writeAttribute('val', $id1 );
- $objWriter->endElement();
- $objWriter->startElement('c:axId');
- $objWriter->writeAttribute('val', $id2 );
- $objWriter->endElement();
- } else {
- $objWriter->startElement('c:firstSliceAng');
- $objWriter->writeAttribute('val', 0);
- $objWriter->endElement();
-
- if ($chartType === Chart_DataSeries::TYPE_DONUTCHART) {
-
- $objWriter->startElement('c:holeSize');
- $objWriter->writeAttribute('val', 50);
- $objWriter->endElement();
- }
- }
-
- $objWriter->endElement();
- }
-
- if (($chartType !== Chart_DataSeries::TYPE_PIECHART) &&
- ($chartType !== Chart_DataSeries::TYPE_PIECHART_3D) &&
- ($chartType !== Chart_DataSeries::TYPE_DONUTCHART)) {
-
- if ($chartType === Chart_DataSeries::TYPE_BUBBLECHART) {
- $this->_writeValAx($objWriter,$plotArea,$xAxisLabel,$chartType,$id1,$id2,$catIsMultiLevelSeries);
- } else {
- $this->_writeCatAx($objWriter,$plotArea,$xAxisLabel,$chartType,$id1,$id2,$catIsMultiLevelSeries);
- }
-
- $this->_writeValAx($objWriter,$plotArea,$yAxisLabel,$chartType,$id1,$id2,$valIsMultiLevelSeries);
- }
-
- $objWriter->endElement();
- }
-
- /**
- * Write Data Labels
- *
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel\Chart_Layout $chartLayout Chart layout
- * @throws PHPExcel\Writer_Exception
- */
- private function _writeDataLbls($objWriter, $chartLayout)
- {
- $objWriter->startElement('c:dLbls');
-
- $objWriter->startElement('c:showLegendKey');
- $showLegendKey = (empty($chartLayout)) ? 0 : $chartLayout->getShowLegendKey();
- $objWriter->writeAttribute('val', ((empty($showLegendKey)) ? 0 : 1) );
- $objWriter->endElement();
-
-
- $objWriter->startElement('c:showVal');
- $showVal = (empty($chartLayout)) ? 0 : $chartLayout->getShowVal();
- $objWriter->writeAttribute('val', ((empty($showVal)) ? 0 : 1) );
- $objWriter->endElement();
-
- $objWriter->startElement('c:showCatName');
- $showCatName = (empty($chartLayout)) ? 0 : $chartLayout->getShowCatName();
- $objWriter->writeAttribute('val', ((empty($showCatName)) ? 0 : 1) );
- $objWriter->endElement();
-
- $objWriter->startElement('c:showSerName');
- $showSerName = (empty($chartLayout)) ? 0 : $chartLayout->getShowSerName();
- $objWriter->writeAttribute('val', ((empty($showSerName)) ? 0 : 1) );
- $objWriter->endElement();
-
- $objWriter->startElement('c:showPercent');
- $showPercent = (empty($chartLayout)) ? 0 : $chartLayout->getShowPercent();
- $objWriter->writeAttribute('val', ((empty($showPercent)) ? 0 : 1) );
- $objWriter->endElement();
-
- $objWriter->startElement('c:showBubbleSize');
- $showBubbleSize = (empty($chartLayout)) ? 0 : $chartLayout->getShowBubbleSize();
- $objWriter->writeAttribute('val', ((empty($showBubbleSize)) ? 0 : 1) );
- $objWriter->endElement();
-
- $objWriter->startElement('c:showLeaderLines');
- $showLeaderLines = (empty($chartLayout)) ? 1 : $chartLayout->getShowLeaderLines();
- $objWriter->writeAttribute('val', ((empty($showLeaderLines)) ? 0 : 1) );
- $objWriter->endElement();
-
- $objWriter->endElement();
- }
-
- /**
- * Write Category Axis
- *
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel\Chart_PlotArea $plotArea
- * @param PHPExcel\Chart_Title $xAxisLabel
- * @param string $groupType Chart type
- * @param string $id1
- * @param string $id2
- * @param boolean $isMultiLevelSeries
- * @throws PHPExcel\Writer_Exception
- */
- private function _writeCatAx($objWriter, Chart_PlotArea $plotArea, $xAxisLabel, $groupType, $id1, $id2, $isMultiLevelSeries)
- {
- $objWriter->startElement('c:catAx');
-
- if ($id1 > 0) {
- $objWriter->startElement('c:axId');
- $objWriter->writeAttribute('val', $id1);
- $objWriter->endElement();
- }
-
- $objWriter->startElement('c:scaling');
- $objWriter->startElement('c:orientation');
- $objWriter->writeAttribute('val', "minMax");
- $objWriter->endElement();
- $objWriter->endElement();
-
- $objWriter->startElement('c:delete');
- $objWriter->writeAttribute('val', 0);
- $objWriter->endElement();
-
- $objWriter->startElement('c:axPos');
- $objWriter->writeAttribute('val', "b");
- $objWriter->endElement();
-
- if (!is_null($xAxisLabel)) {
- $objWriter->startElement('c:title');
- $objWriter->startElement('c:tx');
- $objWriter->startElement('c:rich');
-
- $objWriter->startElement('a:bodyPr');
- $objWriter->endElement();
-
- $objWriter->startElement('a:lstStyle');
- $objWriter->endElement();
-
- $objWriter->startElement('a:p');
- $objWriter->startElement('a:r');
-
- $caption = $xAxisLabel->getCaption();
- if (is_array($caption))
- $caption = $caption[0];
- $objWriter->startElement('a:t');
-// $objWriter->writeAttribute('xml:space', 'preserve');
- $objWriter->writeRawData(Shared_String::ControlCharacterPHP2OOXML( $caption ));
- $objWriter->endElement();
-
- $objWriter->endElement();
- $objWriter->endElement();
- $objWriter->endElement();
- $objWriter->endElement();
-
- $layout = $xAxisLabel->getLayout();
- $this->_writeLayout($layout, $objWriter);
-
- $objWriter->startElement('c:overlay');
- $objWriter->writeAttribute('val', 0);
- $objWriter->endElement();
-
- $objWriter->endElement();
-
- }
-
- $objWriter->startElement('c:numFmt');
- $objWriter->writeAttribute('formatCode', "General");
- $objWriter->writeAttribute('sourceLinked', 1);
- $objWriter->endElement();
-
- $objWriter->startElement('c:majorTickMark');
- $objWriter->writeAttribute('val', "out");
- $objWriter->endElement();
-
- $objWriter->startElement('c:minorTickMark');
- $objWriter->writeAttribute('val', "none");
- $objWriter->endElement();
-
- $objWriter->startElement('c:tickLblPos');
- $objWriter->writeAttribute('val', "nextTo");
- $objWriter->endElement();
-
- if ($id2 > 0) {
- $objWriter->startElement('c:crossAx');
- $objWriter->writeAttribute('val', $id2);
- $objWriter->endElement();
-
- $objWriter->startElement('c:crosses');
- $objWriter->writeAttribute('val', "autoZero");
- $objWriter->endElement();
- }
-
- $objWriter->startElement('c:auto');
- $objWriter->writeAttribute('val', 1);
- $objWriter->endElement();
-
- $objWriter->startElement('c:lblAlgn');
- $objWriter->writeAttribute('val', "ctr");
- $objWriter->endElement();
-
- $objWriter->startElement('c:lblOffset');
- $objWriter->writeAttribute('val', 100);
- $objWriter->endElement();
-
- if ($isMultiLevelSeries) {
- $objWriter->startElement('c:noMultiLvlLbl');
- $objWriter->writeAttribute('val', 0);
- $objWriter->endElement();
- }
- $objWriter->endElement();
-
- }
-
-
- /**
- * Write Value Axis
- *
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel\Chart_PlotArea $plotArea
- * @param PHPExcel\Chart_Title $yAxisLabel
- * @param string $groupType Chart type
- * @param string $id1
- * @param string $id2
- * @param boolean $isMultiLevelSeries
- * @throws PHPExcel\Writer_Exception
- */
- private function _writeValAx($objWriter, Chart_PlotArea $plotArea, $yAxisLabel, $groupType, $id1, $id2, $isMultiLevelSeries)
- {
- $objWriter->startElement('c:valAx');
-
- if ($id2 > 0) {
- $objWriter->startElement('c:axId');
- $objWriter->writeAttribute('val', $id2);
- $objWriter->endElement();
- }
-
- $objWriter->startElement('c:scaling');
- $objWriter->startElement('c:orientation');
- $objWriter->writeAttribute('val', "minMax");
- $objWriter->endElement();
- $objWriter->endElement();
-
- $objWriter->startElement('c:delete');
- $objWriter->writeAttribute('val', 0);
- $objWriter->endElement();
-
- $objWriter->startElement('c:axPos');
- $objWriter->writeAttribute('val', "l");
- $objWriter->endElement();
-
- $objWriter->startElement('c:majorGridlines');
- $objWriter->endElement();
-
- if (!is_null($yAxisLabel)) {
- $objWriter->startElement('c:title');
- $objWriter->startElement('c:tx');
- $objWriter->startElement('c:rich');
-
- $objWriter->startElement('a:bodyPr');
- $objWriter->endElement();
-
- $objWriter->startElement('a:lstStyle');
- $objWriter->endElement();
-
- $objWriter->startElement('a:p');
- $objWriter->startElement('a:r');
-
- $caption = $yAxisLabel->getCaption();
- if (is_array($caption))
- $caption = $caption[0];
- $objWriter->startElement('a:t');
-// $objWriter->writeAttribute('xml:space', 'preserve');
- $objWriter->writeRawData(Shared_String::ControlCharacterPHP2OOXML( $caption ));
- $objWriter->endElement();
-
- $objWriter->endElement();
- $objWriter->endElement();
- $objWriter->endElement();
- $objWriter->endElement();
-
- if ($groupType !== Chart_DataSeries::TYPE_BUBBLECHART) {
- $layout = $yAxisLabel->getLayout();
- $this->_writeLayout($layout, $objWriter);
- }
-
- $objWriter->startElement('c:overlay');
- $objWriter->writeAttribute('val', 0);
- $objWriter->endElement();
-
- $objWriter->endElement();
- }
-
- $objWriter->startElement('c:numFmt');
- $objWriter->writeAttribute('formatCode', "General");
- $objWriter->writeAttribute('sourceLinked', 1);
- $objWriter->endElement();
-
- $objWriter->startElement('c:majorTickMark');
- $objWriter->writeAttribute('val', "out");
- $objWriter->endElement();
-
- $objWriter->startElement('c:minorTickMark');
- $objWriter->writeAttribute('val', "none");
- $objWriter->endElement();
-
- $objWriter->startElement('c:tickLblPos');
- $objWriter->writeAttribute('val', "nextTo");
- $objWriter->endElement();
-
- if ($id1 > 0) {
- $objWriter->startElement('c:crossAx');
- $objWriter->writeAttribute('val', $id2);
- $objWriter->endElement();
-
- $objWriter->startElement('c:crosses');
- $objWriter->writeAttribute('val', "autoZero");
- $objWriter->endElement();
-
- $objWriter->startElement('c:crossBetween');
- $objWriter->writeAttribute('val', "midCat");
- $objWriter->endElement();
- }
-
- if ($isMultiLevelSeries) {
- if ($groupType !== Chart_DataSeries::TYPE_BUBBLECHART) {
- $objWriter->startElement('c:noMultiLvlLbl');
- $objWriter->writeAttribute('val', 0);
- $objWriter->endElement();
- }
- }
- $objWriter->endElement();
-
- }
-
-
- /**
- * Get the data series type(s) for a chart plot series
- *
- * @param PHPExcel\Chart_PlotArea $plotArea
- * @return string|array
- * @throws PHPExcel\Writer_Exception
- */
- private static function _getChartType($plotArea)
- {
- $groupCount = $plotArea->getPlotGroupCount();
-
- if ($groupCount == 1) {
- $chartType = array($plotArea->getPlotGroupByIndex(0)->getPlotType());
- } else {
- $chartTypes = array();
- for($i = 0; $i < $groupCount; ++$i) {
- $chartTypes[] = $plotArea->getPlotGroupByIndex($i)->getPlotType();
- }
- $chartType = array_unique($chartTypes);
- if (count($chartTypes) == 0) {
- throw new Writer_Exception('Chart is not yet implemented');
- }
- }
-
- return $chartType;
- }
-
- /**
- * Write Plot Group (series of related plots)
- *
- * @param PHPExcel\Chart_DataSeries $plotGroup
- * @param string $groupType Type of plot for dataseries
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @param boolean &$catIsMultiLevelSeries Is category a multi-series category
- * @param boolean &$valIsMultiLevelSeries Is value set a multi-series set
- * @param string &$plotGroupingType Type of grouping for multi-series values
- * @param PHPExcel\Worksheet $pSheet
- * @throws PHPExcel\Writer_Exception
- */
- private function _writePlotGroup( $plotGroup,
- $groupType,
- $objWriter,
- &$catIsMultiLevelSeries,
- &$valIsMultiLevelSeries,
- &$plotGroupingType,
- Worksheet $pSheet
- )
- {
- if (is_null($plotGroup)) {
- return;
- }
-
- if (($groupType == Chart_DataSeries::TYPE_BARCHART) ||
- ($groupType == Chart_DataSeries::TYPE_BARCHART_3D)) {
- $objWriter->startElement('c:barDir');
- $objWriter->writeAttribute('val', $plotGroup->getPlotDirection());
- $objWriter->endElement();
- }
-
- if (!is_null($plotGroup->getPlotGrouping())) {
- $plotGroupingType = $plotGroup->getPlotGrouping();
- $objWriter->startElement('c:grouping');
- $objWriter->writeAttribute('val', $plotGroupingType);
- $objWriter->endElement();
- }
-
- // Get these details before the loop, because we can use the count to check for varyColors
- $plotSeriesOrder = $plotGroup->getPlotOrder();
- $plotSeriesCount = count($plotSeriesOrder);
-
- if (($groupType !== Chart_DataSeries::TYPE_RADARCHART) &&
- ($groupType !== Chart_DataSeries::TYPE_STOCKCHART)) {
-
- if ($groupType !== Chart_DataSeries::TYPE_LINECHART) {
- if (($groupType == Chart_DataSeries::TYPE_PIECHART) ||
- ($groupType == Chart_DataSeries::TYPE_PIECHART_3D) ||
- ($groupType == Chart_DataSeries::TYPE_DONUTCHART) ||
- ($plotSeriesCount > 1)) {
- $objWriter->startElement('c:varyColors');
- $objWriter->writeAttribute('val', 1);
- $objWriter->endElement();
- } else {
- $objWriter->startElement('c:varyColors');
- $objWriter->writeAttribute('val', 0);
- $objWriter->endElement();
- }
- }
- }
-
- foreach($plotSeriesOrder as $plotSeriesIdx => $plotSeriesRef) {
- $objWriter->startElement('c:ser');
-
- $objWriter->startElement('c:idx');
- $objWriter->writeAttribute('val', $this->_seriesIndex + $plotSeriesIdx);
- $objWriter->endElement();
-
- $objWriter->startElement('c:order');
- $objWriter->writeAttribute('val', $this->_seriesIndex + $plotSeriesRef);
- $objWriter->endElement();
-
- if (($groupType == Chart_DataSeries::TYPE_PIECHART) ||
- ($groupType == Chart_DataSeries::TYPE_PIECHART_3D) ||
- ($groupType == Chart_DataSeries::TYPE_DONUTCHART)) {
-
- $objWriter->startElement('c:dPt');
- $objWriter->startElement('c:idx');
- $objWriter->writeAttribute('val', 3);
- $objWriter->endElement();
-
- $objWriter->startElement('c:bubble3D');
- $objWriter->writeAttribute('val', 0);
- $objWriter->endElement();
-
- $objWriter->startElement('c:spPr');
- $objWriter->startElement('a:solidFill');
- $objWriter->startElement('a:srgbClr');
- $objWriter->writeAttribute('val', 'FF9900');
- $objWriter->endElement();
- $objWriter->endElement();
- $objWriter->endElement();
- $objWriter->endElement();
- }
-
- // Labels
- $plotSeriesLabel = $plotGroup->getPlotLabelByIndex($plotSeriesRef);
- if ($plotSeriesLabel && ($plotSeriesLabel->getPointCount() > 0)) {
- $objWriter->startElement('c:tx');
- $objWriter->startElement('c:strRef');
- $this->_writePlotSeriesLabel($plotSeriesLabel, $objWriter);
- $objWriter->endElement();
- $objWriter->endElement();
- }
-
- // Formatting for the points
- if ($groupType == Chart_DataSeries::TYPE_LINECHART) {
- $objWriter->startElement('c:spPr');
- $objWriter->startElement('a:ln');
- $objWriter->writeAttribute('w', 12700);
- $objWriter->endElement();
- $objWriter->endElement();
- }
-
- $plotSeriesValues = $plotGroup->getPlotValuesByIndex($plotSeriesRef);
- if ($plotSeriesValues) {
- $plotSeriesMarker = $plotSeriesValues->getPointMarker();
- if ($plotSeriesMarker) {
- $objWriter->startElement('c:marker');
- $objWriter->startElement('c:symbol');
- $objWriter->writeAttribute('val', $plotSeriesMarker);
- $objWriter->endElement();
-
- if ($plotSeriesMarker !== 'none') {
- $objWriter->startElement('c:size');
- $objWriter->writeAttribute('val', 3);
- $objWriter->endElement();
- }
- $objWriter->endElement();
- }
- }
-
- if (($groupType === Chart_DataSeries::TYPE_BARCHART) ||
- ($groupType === Chart_DataSeries::TYPE_BARCHART_3D) ||
- ($groupType === Chart_DataSeries::TYPE_BUBBLECHART)) {
-
- $objWriter->startElement('c:invertIfNegative');
- $objWriter->writeAttribute('val', 0);
- $objWriter->endElement();
- }
-
- // Category Labels
- $plotSeriesCategory = $plotGroup->getPlotCategoryByIndex($plotSeriesRef);
- if ($plotSeriesCategory && ($plotSeriesCategory->getPointCount() > 0)) {
- $catIsMultiLevelSeries = $catIsMultiLevelSeries || $plotSeriesCategory->isMultiLevelSeries();
-
- if (($groupType == Chart_DataSeries::TYPE_PIECHART) ||
- ($groupType == Chart_DataSeries::TYPE_PIECHART_3D) ||
- ($groupType == Chart_DataSeries::TYPE_DONUTCHART)) {
-
- if (!is_null($plotGroup->getPlotStyle())) {
- $plotStyle = $plotGroup->getPlotStyle();
- if ($plotStyle) {
- $objWriter->startElement('c:explosion');
- $objWriter->writeAttribute('val', 25);
- $objWriter->endElement();
- }
- }
- }
-
- if (($groupType === Chart_DataSeries::TYPE_BUBBLECHART) ||
- ($groupType === Chart_DataSeries::TYPE_SCATTERCHART)) {
- $objWriter->startElement('c:xVal');
- } else {
- $objWriter->startElement('c:cat');
- }
-
- $this->_writePlotSeriesValues($plotSeriesCategory, $objWriter, $groupType, 'str', $pSheet);
- $objWriter->endElement();
- }
-
- // Values
- if ($plotSeriesValues) {
- $valIsMultiLevelSeries = $valIsMultiLevelSeries || $plotSeriesValues->isMultiLevelSeries();
-
- if (($groupType === Chart_DataSeries::TYPE_BUBBLECHART) ||
- ($groupType === Chart_DataSeries::TYPE_SCATTERCHART)) {
- $objWriter->startElement('c:yVal');
- } else {
- $objWriter->startElement('c:val');
- }
-
- $this->_writePlotSeriesValues($plotSeriesValues, $objWriter, $groupType, 'num', $pSheet);
- $objWriter->endElement();
- }
-
- if ($groupType === Chart_DataSeries::TYPE_BUBBLECHART) {
- $this->_writeBubbles($plotSeriesValues, $objWriter, $pSheet);
- }
-
- $objWriter->endElement();
-
- }
-
- $this->_seriesIndex += $plotSeriesIdx + 1;
- }
-
- /**
- * Write Plot Series Label
- *
- * @param PHPExcel\Chart_DataSeriesValues $plotSeriesLabel
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @throws PHPExcel\Writer_Exception
- */
- private function _writePlotSeriesLabel($plotSeriesLabel, $objWriter)
- {
- if (is_null($plotSeriesLabel)) {
- return;
- }
-
- $objWriter->startElement('c:f');
- $objWriter->writeRawData($plotSeriesLabel->getDataSource());
- $objWriter->endElement();
-
- $objWriter->startElement('c:strCache');
- $objWriter->startElement('c:ptCount');
- $objWriter->writeAttribute('val', $plotSeriesLabel->getPointCount() );
- $objWriter->endElement();
-
- foreach($plotSeriesLabel->getDataValues() as $plotLabelKey => $plotLabelValue) {
- $objWriter->startElement('c:pt');
- $objWriter->writeAttribute('idx', $plotLabelKey );
-
- $objWriter->startElement('c:v');
- $objWriter->writeRawData( $plotLabelValue );
- $objWriter->endElement();
- $objWriter->endElement();
- }
- $objWriter->endElement();
-
- }
-
- /**
- * Write Plot Series Values
- *
- * @param PHPExcel\Chart_DataSeriesValues $plotSeriesValues
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @param string $groupType Type of plot for dataseries
- * @param string $dataType Datatype of series values
- * @param PHPExcel\Worksheet $pSheet
- * @throws PHPExcel\Writer_Exception
- */
- private function _writePlotSeriesValues( $plotSeriesValues,
- $objWriter,
- $groupType,
- $dataType='str',
- Worksheet $pSheet
- )
- {
- if (is_null($plotSeriesValues)) {
- return;
- }
-
- if ($plotSeriesValues->isMultiLevelSeries()) {
- $levelCount = $plotSeriesValues->multiLevelCount();
-
- $objWriter->startElement('c:multiLvlStrRef');
-
- $objWriter->startElement('c:f');
- $objWriter->writeRawData( $plotSeriesValues->getDataSource() );
- $objWriter->endElement();
-
- $objWriter->startElement('c:multiLvlStrCache');
-
- $objWriter->startElement('c:ptCount');
- $objWriter->writeAttribute('val', $plotSeriesValues->getPointCount() );
- $objWriter->endElement();
-
- for ($level = 0; $level < $levelCount; ++$level) {
- $objWriter->startElement('c:lvl');
-
- foreach($plotSeriesValues->getDataValues() as $plotSeriesKey => $plotSeriesValue) {
- if (isset($plotSeriesValue[$level])) {
- $objWriter->startElement('c:pt');
- $objWriter->writeAttribute('idx', $plotSeriesKey );
-
- $objWriter->startElement('c:v');
- $objWriter->writeRawData( $plotSeriesValue[$level] );
- $objWriter->endElement();
- $objWriter->endElement();
- }
- }
-
- $objWriter->endElement();
- }
-
- $objWriter->endElement();
-
- $objWriter->endElement();
- } else {
- $objWriter->startElement('c:'.$dataType.'Ref');
-
- $objWriter->startElement('c:f');
- $objWriter->writeRawData( $plotSeriesValues->getDataSource() );
- $objWriter->endElement();
-
- $objWriter->startElement('c:'.$dataType.'Cache');
-
- if (($groupType != Chart_DataSeries::TYPE_PIECHART) &&
- ($groupType != Chart_DataSeries::TYPE_PIECHART_3D) &&
- ($groupType != Chart_DataSeries::TYPE_DONUTCHART)) {
-
- if (($plotSeriesValues->getFormatCode() !== NULL) &&
- ($plotSeriesValues->getFormatCode() !== '')) {
- $objWriter->startElement('c:formatCode');
- $objWriter->writeRawData( $plotSeriesValues->getFormatCode() );
- $objWriter->endElement();
- }
- }
-
- $objWriter->startElement('c:ptCount');
- $objWriter->writeAttribute('val', $plotSeriesValues->getPointCount() );
- $objWriter->endElement();
-
- $dataValues = $plotSeriesValues->getDataValues();
- if (!empty($dataValues)) {
- if (is_array($dataValues)) {
- foreach($dataValues as $plotSeriesKey => $plotSeriesValue) {
- $objWriter->startElement('c:pt');
- $objWriter->writeAttribute('idx', $plotSeriesKey );
-
- $objWriter->startElement('c:v');
- $objWriter->writeRawData( $plotSeriesValue );
- $objWriter->endElement();
- $objWriter->endElement();
- }
- }
- }
-
- $objWriter->endElement();
-
- $objWriter->endElement();
- }
- }
-
- /**
- * Write Bubble Chart Details
- *
- * @param PHPExcel\Chart_DataSeriesValues $plotSeriesValues
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @throws PHPExcel\Writer_Exception
- */
- private function _writeBubbles($plotSeriesValues, $objWriter, Worksheet $pSheet)
- {
- if (is_null($plotSeriesValues)) {
- return;
- }
-
- $objWriter->startElement('c:bubbleSize');
- $objWriter->startElement('c:numLit');
-
- $objWriter->startElement('c:formatCode');
- $objWriter->writeRawData( 'General' );
- $objWriter->endElement();
-
- $objWriter->startElement('c:ptCount');
- $objWriter->writeAttribute('val', $plotSeriesValues->getPointCount() );
- $objWriter->endElement();
-
- $dataValues = $plotSeriesValues->getDataValues();
- if (!empty($dataValues)) {
- if (is_array($dataValues)) {
- foreach($dataValues as $plotSeriesKey => $plotSeriesValue) {
- $objWriter->startElement('c:pt');
- $objWriter->writeAttribute('idx', $plotSeriesKey );
- $objWriter->startElement('c:v');
- $objWriter->writeRawData( 1 );
- $objWriter->endElement();
- $objWriter->endElement();
- }
- }
- }
-
- $objWriter->endElement();
- $objWriter->endElement();
-
- $objWriter->startElement('c:bubble3D');
- $objWriter->writeAttribute('val', 0 );
- $objWriter->endElement();
- }
-
- /**
- * Write Layout
- *
- * @param PHPExcel\Chart_Layout $layout
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @throws PHPExcel\Writer_Exception
- */
- private function _writeLayout(Chart_Layout $layout = NULL, $objWriter)
- {
- $objWriter->startElement('c:layout');
-
- if (!is_null($layout)) {
- $objWriter->startElement('c:manualLayout');
-
- $layoutTarget = $layout->getLayoutTarget();
- if (!is_null($layoutTarget)) {
- $objWriter->startElement('c:layoutTarget');
- $objWriter->writeAttribute('val', $layoutTarget);
- $objWriter->endElement();
- }
-
- $xMode = $layout->getXMode();
- if (!is_null($xMode)) {
- $objWriter->startElement('c:xMode');
- $objWriter->writeAttribute('val', $xMode);
- $objWriter->endElement();
- }
-
- $yMode = $layout->getYMode();
- if (!is_null($yMode)) {
- $objWriter->startElement('c:yMode');
- $objWriter->writeAttribute('val', $yMode);
- $objWriter->endElement();
- }
-
- $x = $layout->getXPosition();
- if (!is_null($x)) {
- $objWriter->startElement('c:x');
- $objWriter->writeAttribute('val', $x);
- $objWriter->endElement();
- }
-
- $y = $layout->getYPosition();
- if (!is_null($y)) {
- $objWriter->startElement('c:y');
- $objWriter->writeAttribute('val', $y);
- $objWriter->endElement();
- }
-
- $w = $layout->getWidth();
- if (!is_null($w)) {
- $objWriter->startElement('c:w');
- $objWriter->writeAttribute('val', $w);
- $objWriter->endElement();
- }
-
- $h = $layout->getHeight();
- if (!is_null($h)) {
- $objWriter->startElement('c:h');
- $objWriter->writeAttribute('val', $h);
- $objWriter->endElement();
- }
-
- $objWriter->endElement();
- }
-
- $objWriter->endElement();
- }
-
- /**
- * Write Alternate Content block
- *
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @throws PHPExcel\Writer_Exception
- */
- private function _writeAlternateContent($objWriter)
- {
- $objWriter->startElement('mc:AlternateContent');
- $objWriter->writeAttribute('xmlns:mc', 'http://schemas.openxmlformats.org/markup-compatibility/2006');
-
- $objWriter->startElement('mc:Choice');
- $objWriter->writeAttribute('xmlns:c14', 'http://schemas.microsoft.com/office/drawing/2007/8/2/chart');
- $objWriter->writeAttribute('Requires', 'c14');
-
- $objWriter->startElement('c14:style');
- $objWriter->writeAttribute('val', '102');
- $objWriter->endElement();
- $objWriter->endElement();
-
- $objWriter->startElement('mc:Fallback');
- $objWriter->startElement('c:style');
- $objWriter->writeAttribute('val', '2');
- $objWriter->endElement();
- $objWriter->endElement();
-
- $objWriter->endElement();
- }
-
- /**
- * Write Printer Settings
- *
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @throws PHPExcel\Writer_Exception
- */
- private function _writePrintSettings($objWriter)
- {
- $objWriter->startElement('c:printSettings');
-
- $objWriter->startElement('c:headerFooter');
- $objWriter->endElement();
-
- $objWriter->startElement('c:pageMargins');
- $objWriter->writeAttribute('footer', 0.3);
- $objWriter->writeAttribute('header', 0.3);
- $objWriter->writeAttribute('r', 0.7);
- $objWriter->writeAttribute('l', 0.7);
- $objWriter->writeAttribute('t', 0.75);
- $objWriter->writeAttribute('b', 0.75);
- $objWriter->endElement();
-
- $objWriter->startElement('c:pageSetup');
- $objWriter->writeAttribute('orientation', "portrait");
- $objWriter->endElement();
-
- $objWriter->endElement();
- }
-
+ /**
+ * Write charts to XML format
+ *
+ * @param PHPExcel\Chart $pChart
+ * @return string XML Output
+ * @throws PHPExcel\Writer_Exception
+ */
+ public function writeChart(Chart $pChart = null)
+ {
+ // Create XML writer
+ $objWriter = null;
+ if ($this->getParentWriter()->getUseDiskCaching()) {
+ $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
+ } else {
+ $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_MEMORY);
+ }
+ // Ensure that data series values are up-to-date before we save
+ $pChart->refresh();
+
+ // XML header
+ $objWriter->startDocument('1.0','UTF-8','yes');
+
+ // c:chartSpace
+ $objWriter->startElement('c:chartSpace');
+ $objWriter->writeAttribute('xmlns:c', 'http://schemas.openxmlformats.org/drawingml/2006/chart');
+ $objWriter->writeAttribute('xmlns:a', 'http://schemas.openxmlformats.org/drawingml/2006/main');
+ $objWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships');
+
+ $objWriter->startElement('c:date1904');
+ $objWriter->writeAttribute('val', 0);
+ $objWriter->endElement();
+ $objWriter->startElement('c:lang');
+ $objWriter->writeAttribute('val', "en-GB");
+ $objWriter->endElement();
+ $objWriter->startElement('c:roundedCorners');
+ $objWriter->writeAttribute('val', 0);
+ $objWriter->endElement();
+
+ $this->_writeAlternateContent($objWriter);
+
+ $objWriter->startElement('c:chart');
+
+ $this->_writeTitle($pChart->getTitle(), $objWriter);
+
+ $objWriter->startElement('c:autoTitleDeleted');
+ $objWriter->writeAttribute('val', 0);
+ $objWriter->endElement();
+
+ $this->_writePlotArea($pChart->getPlotArea(),
+ $pChart->getXAxisLabel(),
+ $pChart->getYAxisLabel(),
+ $objWriter,
+ $pChart->getWorksheet()
+ );
+
+ $this->_writeLegend($pChart->getLegend(), $objWriter);
+
+
+ $objWriter->startElement('c:plotVisOnly');
+ $objWriter->writeAttribute('val', 1);
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:dispBlanksAs');
+ $objWriter->writeAttribute('val', "gap");
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:showDLblsOverMax');
+ $objWriter->writeAttribute('val', 0);
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ $this->_writePrintSettings($objWriter);
+
+ $objWriter->endElement();
+
+ // Return
+ return $objWriter->getData();
+ }
+
+ /**
+ * Write Chart Title
+ *
+ * @param PHPExcel\Chart_Title $title
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @throws PHPExcel\Writer_Exception
+ */
+ private function _writeTitle(Chart_Title $title = null, $objWriter)
+ {
+ if (is_null($title)) {
+ return;
+ }
+
+ $objWriter->startElement('c:title');
+ $objWriter->startElement('c:tx');
+ $objWriter->startElement('c:rich');
+
+ $objWriter->startElement('a:bodyPr');
+ $objWriter->endElement();
+
+ $objWriter->startElement('a:lstStyle');
+ $objWriter->endElement();
+
+ $objWriter->startElement('a:p');
+
+ $caption = $title->getCaption();
+ if ((is_array($caption)) && (count($caption) > 0))
+ $caption = $caption[0];
+ $this->getParentWriter()->getWriterPart('stringtable')->writeRichTextForCharts($objWriter, $caption, 'a');
+
+ $objWriter->endElement();
+ $objWriter->endElement();
+ $objWriter->endElement();
+
+ $layout = $title->getLayout();
+ $this->_writeLayout($layout, $objWriter);
+
+ $objWriter->startElement('c:overlay');
+ $objWriter->writeAttribute('val', 0);
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+ }
+
+ /**
+ * Write Chart Legend
+ *
+ * @param PHPExcel\Chart_Legend $legend
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @throws PHPExcel\Writer_Exception
+ */
+ private function _writeLegend(Chart_Legend $legend = null, $objWriter)
+ {
+ if (is_null($legend)) {
+ return;
+ }
+
+ $objWriter->startElement('c:legend');
+
+ $objWriter->startElement('c:legendPos');
+ $objWriter->writeAttribute('val', $legend->getPosition());
+ $objWriter->endElement();
+
+ $layout = $legend->getLayout();
+ $this->_writeLayout($layout, $objWriter);
+
+ $objWriter->startElement('c:overlay');
+ $objWriter->writeAttribute('val', ($legend->getOverlay()) ? '1' : '0');
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:txPr');
+ $objWriter->startElement('a:bodyPr');
+ $objWriter->endElement();
+
+ $objWriter->startElement('a:lstStyle');
+ $objWriter->endElement();
+
+ $objWriter->startElement('a:p');
+ $objWriter->startElement('a:pPr');
+ $objWriter->writeAttribute('rtl', 0);
+
+ $objWriter->startElement('a:defRPr');
+ $objWriter->endElement();
+ $objWriter->endElement();
+
+ $objWriter->startElement('a:endParaRPr');
+ $objWriter->writeAttribute('lang', "en-US");
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+ }
+
+ /**
+ * Write Chart Plot Area
+ *
+ * @param PHPExcel\Chart_PlotArea $plotArea
+ * @param PHPExcel\Chart_Title $xAxisLabel
+ * @param PHPExcel\Chart_Title $yAxisLabel
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @throws PHPExcel\Writer_Exception
+ */
+ private function _writePlotArea(Chart_PlotArea $plotArea,
+ Chart_Title $xAxisLabel = null,
+ Chart_Title $yAxisLabel = null,
+ $objWriter,
+ Worksheet $pSheet)
+ {
+ if (is_null($plotArea)) {
+ return;
+ }
+
+ $id1 = $id2 = 0;
+ $this->_seriesIndex = 0;
+ $objWriter->startElement('c:plotArea');
+
+ $layout = $plotArea->getLayout();
+
+ $this->_writeLayout($layout, $objWriter);
+
+ $chartTypes = self::_getChartType($plotArea);
+ $catIsMultiLevelSeries = $valIsMultiLevelSeries = false;
+ $plotGroupingType = '';
+ foreach($chartTypes as $chartType) {
+ $objWriter->startElement('c:'.$chartType);
+
+ $groupCount = $plotArea->getPlotGroupCount();
+ for($i = 0; $i < $groupCount; ++$i) {
+ $plotGroup = $plotArea->getPlotGroupByIndex($i);
+ $groupType = $plotGroup->getPlotType();
+ if ($groupType == $chartType) {
+
+ $plotStyle = $plotGroup->getPlotStyle();
+ if ($groupType === Chart_DataSeries::TYPE_RADARCHART) {
+ $objWriter->startElement('c:radarStyle');
+ $objWriter->writeAttribute('val', $plotStyle );
+ $objWriter->endElement();
+ } elseif ($groupType === Chart_DataSeries::TYPE_SCATTERCHART) {
+ $objWriter->startElement('c:scatterStyle');
+ $objWriter->writeAttribute('val', $plotStyle );
+ $objWriter->endElement();
+ }
+
+ $this->_writePlotGroup($plotGroup, $chartType, $objWriter, $catIsMultiLevelSeries, $valIsMultiLevelSeries, $plotGroupingType, $pSheet);
+ }
+ }
+
+ $this->_writeDataLbls($objWriter, $layout);
+
+ if ($chartType === Chart_DataSeries::TYPE_LINECHART) {
+ // Line only, Line3D can't be smoothed
+
+ $objWriter->startElement('c:smooth');
+ $objWriter->writeAttribute('val', (integer) $plotGroup->getSmoothLine() );
+ $objWriter->endElement();
+ } elseif (($chartType === Chart_DataSeries::TYPE_BARCHART) ||
+ ($chartType === Chart_DataSeries::TYPE_BARCHART_3D)) {
+
+ $objWriter->startElement('c:gapWidth');
+ $objWriter->writeAttribute('val', 150 );
+ $objWriter->endElement();
+
+ if ($plotGroupingType == 'percentStacked' ||
+ $plotGroupingType == 'stacked') {
+
+ $objWriter->startElement('c:overlap');
+ $objWriter->writeAttribute('val', 100 );
+ $objWriter->endElement();
+ }
+ } elseif ($chartType === Chart_DataSeries::TYPE_BUBBLECHART) {
+
+ $objWriter->startElement('c:bubbleScale');
+ $objWriter->writeAttribute('val', 25 );
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:showNegBubbles');
+ $objWriter->writeAttribute('val', 0 );
+ $objWriter->endElement();
+ } elseif ($chartType === Chart_DataSeries::TYPE_STOCKCHART) {
+
+ $objWriter->startElement('c:hiLowLines');
+ $objWriter->endElement();
+ }
+
+ // Generate 2 unique numbers to use for axId values
+// $id1 = $id2 = rand(10000000,99999999);
+// do {
+// $id2 = rand(10000000,99999999);
+// } while ($id1 == $id2);
+ $id1 = '75091328';
+ $id2 = '75089408';
+
+ if (($chartType !== Chart_DataSeries::TYPE_PIECHART) &&
+ ($chartType !== Chart_DataSeries::TYPE_PIECHART_3D) &&
+ ($chartType !== Chart_DataSeries::TYPE_DONUTCHART)) {
+
+ $objWriter->startElement('c:axId');
+ $objWriter->writeAttribute('val', $id1 );
+ $objWriter->endElement();
+ $objWriter->startElement('c:axId');
+ $objWriter->writeAttribute('val', $id2 );
+ $objWriter->endElement();
+ } else {
+ $objWriter->startElement('c:firstSliceAng');
+ $objWriter->writeAttribute('val', 0);
+ $objWriter->endElement();
+
+ if ($chartType === Chart_DataSeries::TYPE_DONUTCHART) {
+
+ $objWriter->startElement('c:holeSize');
+ $objWriter->writeAttribute('val', 50);
+ $objWriter->endElement();
+ }
+ }
+
+ $objWriter->endElement();
+ }
+
+ if (($chartType !== Chart_DataSeries::TYPE_PIECHART) &&
+ ($chartType !== Chart_DataSeries::TYPE_PIECHART_3D) &&
+ ($chartType !== Chart_DataSeries::TYPE_DONUTCHART)) {
+
+ if ($chartType === Chart_DataSeries::TYPE_BUBBLECHART) {
+ $this->_writeValAx($objWriter,$plotArea,$xAxisLabel,$chartType,$id1,$id2,$catIsMultiLevelSeries);
+ } else {
+ $this->_writeCatAx($objWriter,$plotArea,$xAxisLabel,$chartType,$id1,$id2,$catIsMultiLevelSeries);
+ }
+
+ $this->_writeValAx($objWriter,$plotArea,$yAxisLabel,$chartType,$id1,$id2,$valIsMultiLevelSeries);
+ }
+
+ $objWriter->endElement();
+ }
+
+ /**
+ * Write Data Labels
+ *
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel\Chart_Layout $chartLayout Chart layout
+ * @throws PHPExcel\Writer_Exception
+ */
+ private function _writeDataLbls($objWriter, $chartLayout)
+ {
+ $objWriter->startElement('c:dLbls');
+
+ $objWriter->startElement('c:showLegendKey');
+ $showLegendKey = (empty($chartLayout)) ? 0 : $chartLayout->getShowLegendKey();
+ $objWriter->writeAttribute('val', ((empty($showLegendKey)) ? 0 : 1) );
+ $objWriter->endElement();
+
+
+ $objWriter->startElement('c:showVal');
+ $showVal = (empty($chartLayout)) ? 0 : $chartLayout->getShowVal();
+ $objWriter->writeAttribute('val', ((empty($showVal)) ? 0 : 1) );
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:showCatName');
+ $showCatName = (empty($chartLayout)) ? 0 : $chartLayout->getShowCatName();
+ $objWriter->writeAttribute('val', ((empty($showCatName)) ? 0 : 1) );
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:showSerName');
+ $showSerName = (empty($chartLayout)) ? 0 : $chartLayout->getShowSerName();
+ $objWriter->writeAttribute('val', ((empty($showSerName)) ? 0 : 1) );
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:showPercent');
+ $showPercent = (empty($chartLayout)) ? 0 : $chartLayout->getShowPercent();
+ $objWriter->writeAttribute('val', ((empty($showPercent)) ? 0 : 1) );
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:showBubbleSize');
+ $showBubbleSize = (empty($chartLayout)) ? 0 : $chartLayout->getShowBubbleSize();
+ $objWriter->writeAttribute('val', ((empty($showBubbleSize)) ? 0 : 1) );
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:showLeaderLines');
+ $showLeaderLines = (empty($chartLayout)) ? 1 : $chartLayout->getShowLeaderLines();
+ $objWriter->writeAttribute('val', ((empty($showLeaderLines)) ? 0 : 1) );
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+ }
+
+ /**
+ * Write Category Axis
+ *
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel\Chart_PlotArea $plotArea
+ * @param PHPExcel\Chart_Title $xAxisLabel
+ * @param string $groupType Chart type
+ * @param string $id1
+ * @param string $id2
+ * @param boolean $isMultiLevelSeries
+ * @throws PHPExcel\Writer_Exception
+ */
+ private function _writeCatAx($objWriter, Chart_PlotArea $plotArea, $xAxisLabel, $groupType, $id1, $id2, $isMultiLevelSeries)
+ {
+ $objWriter->startElement('c:catAx');
+
+ if ($id1 > 0) {
+ $objWriter->startElement('c:axId');
+ $objWriter->writeAttribute('val', $id1);
+ $objWriter->endElement();
+ }
+
+ $objWriter->startElement('c:scaling');
+ $objWriter->startElement('c:orientation');
+ $objWriter->writeAttribute('val', "minMax");
+ $objWriter->endElement();
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:delete');
+ $objWriter->writeAttribute('val', 0);
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:axPos');
+ $objWriter->writeAttribute('val', "b");
+ $objWriter->endElement();
+
+ if (!is_null($xAxisLabel)) {
+ $objWriter->startElement('c:title');
+ $objWriter->startElement('c:tx');
+ $objWriter->startElement('c:rich');
+
+ $objWriter->startElement('a:bodyPr');
+ $objWriter->endElement();
+
+ $objWriter->startElement('a:lstStyle');
+ $objWriter->endElement();
+
+ $objWriter->startElement('a:p');
+ $objWriter->startElement('a:r');
+
+ $caption = $xAxisLabel->getCaption();
+ if (is_array($caption))
+ $caption = $caption[0];
+ $objWriter->startElement('a:t');
+// $objWriter->writeAttribute('xml:space', 'preserve');
+ $objWriter->writeRawData(Shared_String::ControlCharacterPHP2OOXML( $caption ));
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+ $objWriter->endElement();
+ $objWriter->endElement();
+ $objWriter->endElement();
+
+ $layout = $xAxisLabel->getLayout();
+ $this->_writeLayout($layout, $objWriter);
+
+ $objWriter->startElement('c:overlay');
+ $objWriter->writeAttribute('val', 0);
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ }
+
+ $objWriter->startElement('c:numFmt');
+ $objWriter->writeAttribute('formatCode', "General");
+ $objWriter->writeAttribute('sourceLinked', 1);
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:majorTickMark');
+ $objWriter->writeAttribute('val', "out");
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:minorTickMark');
+ $objWriter->writeAttribute('val', "none");
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:tickLblPos');
+ $objWriter->writeAttribute('val', "nextTo");
+ $objWriter->endElement();
+
+ if ($id2 > 0) {
+ $objWriter->startElement('c:crossAx');
+ $objWriter->writeAttribute('val', $id2);
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:crosses');
+ $objWriter->writeAttribute('val', "autoZero");
+ $objWriter->endElement();
+ }
+
+ $objWriter->startElement('c:auto');
+ $objWriter->writeAttribute('val', 1);
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:lblAlgn');
+ $objWriter->writeAttribute('val', "ctr");
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:lblOffset');
+ $objWriter->writeAttribute('val', 100);
+ $objWriter->endElement();
+
+ if ($isMultiLevelSeries) {
+ $objWriter->startElement('c:noMultiLvlLbl');
+ $objWriter->writeAttribute('val', 0);
+ $objWriter->endElement();
+ }
+ $objWriter->endElement();
+
+ }
+
+
+ /**
+ * Write Value Axis
+ *
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel\Chart_PlotArea $plotArea
+ * @param PHPExcel\Chart_Title $yAxisLabel
+ * @param string $groupType Chart type
+ * @param string $id1
+ * @param string $id2
+ * @param boolean $isMultiLevelSeries
+ * @throws PHPExcel\Writer_Exception
+ */
+ private function _writeValAx($objWriter, Chart_PlotArea $plotArea, $yAxisLabel, $groupType, $id1, $id2, $isMultiLevelSeries)
+ {
+ $objWriter->startElement('c:valAx');
+
+ if ($id2 > 0) {
+ $objWriter->startElement('c:axId');
+ $objWriter->writeAttribute('val', $id2);
+ $objWriter->endElement();
+ }
+
+ $objWriter->startElement('c:scaling');
+ $objWriter->startElement('c:orientation');
+ $objWriter->writeAttribute('val', "minMax");
+ $objWriter->endElement();
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:delete');
+ $objWriter->writeAttribute('val', 0);
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:axPos');
+ $objWriter->writeAttribute('val', "l");
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:majorGridlines');
+ $objWriter->endElement();
+
+ if (!is_null($yAxisLabel)) {
+ $objWriter->startElement('c:title');
+ $objWriter->startElement('c:tx');
+ $objWriter->startElement('c:rich');
+
+ $objWriter->startElement('a:bodyPr');
+ $objWriter->endElement();
+
+ $objWriter->startElement('a:lstStyle');
+ $objWriter->endElement();
+
+ $objWriter->startElement('a:p');
+ $objWriter->startElement('a:r');
+
+ $caption = $yAxisLabel->getCaption();
+ if (is_array($caption))
+ $caption = $caption[0];
+ $objWriter->startElement('a:t');
+// $objWriter->writeAttribute('xml:space', 'preserve');
+ $objWriter->writeRawData(Shared_String::ControlCharacterPHP2OOXML( $caption ));
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+ $objWriter->endElement();
+ $objWriter->endElement();
+ $objWriter->endElement();
+
+ if ($groupType !== Chart_DataSeries::TYPE_BUBBLECHART) {
+ $layout = $yAxisLabel->getLayout();
+ $this->_writeLayout($layout, $objWriter);
+ }
+
+ $objWriter->startElement('c:overlay');
+ $objWriter->writeAttribute('val', 0);
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+ }
+
+ $objWriter->startElement('c:numFmt');
+ $objWriter->writeAttribute('formatCode', "General");
+ $objWriter->writeAttribute('sourceLinked', 1);
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:majorTickMark');
+ $objWriter->writeAttribute('val', "out");
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:minorTickMark');
+ $objWriter->writeAttribute('val', "none");
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:tickLblPos');
+ $objWriter->writeAttribute('val', "nextTo");
+ $objWriter->endElement();
+
+ if ($id1 > 0) {
+ $objWriter->startElement('c:crossAx');
+ $objWriter->writeAttribute('val', $id2);
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:crosses');
+ $objWriter->writeAttribute('val', "autoZero");
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:crossBetween');
+ $objWriter->writeAttribute('val', "midCat");
+ $objWriter->endElement();
+ }
+
+ if ($isMultiLevelSeries) {
+ if ($groupType !== Chart_DataSeries::TYPE_BUBBLECHART) {
+ $objWriter->startElement('c:noMultiLvlLbl');
+ $objWriter->writeAttribute('val', 0);
+ $objWriter->endElement();
+ }
+ }
+ $objWriter->endElement();
+
+ }
+
+
+ /**
+ * Get the data series type(s) for a chart plot series
+ *
+ * @param PHPExcel\Chart_PlotArea $plotArea
+ * @return string|array
+ * @throws PHPExcel\Writer_Exception
+ */
+ private static function _getChartType($plotArea)
+ {
+ $groupCount = $plotArea->getPlotGroupCount();
+
+ if ($groupCount == 1) {
+ $chartType = array($plotArea->getPlotGroupByIndex(0)->getPlotType());
+ } else {
+ $chartTypes = array();
+ for($i = 0; $i < $groupCount; ++$i) {
+ $chartTypes[] = $plotArea->getPlotGroupByIndex($i)->getPlotType();
+ }
+ $chartType = array_unique($chartTypes);
+ if (count($chartTypes) == 0) {
+ throw new Writer_Exception('Chart is not yet implemented');
+ }
+ }
+
+ return $chartType;
+ }
+
+ /**
+ * Write Plot Group (series of related plots)
+ *
+ * @param PHPExcel\Chart_DataSeries $plotGroup
+ * @param string $groupType Type of plot for dataseries
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @param boolean &$catIsMultiLevelSeries Is category a multi-series category
+ * @param boolean &$valIsMultiLevelSeries Is value set a multi-series set
+ * @param string &$plotGroupingType Type of grouping for multi-series values
+ * @param PHPExcel\Worksheet $pSheet
+ * @throws PHPExcel\Writer_Exception
+ */
+ private function _writePlotGroup( $plotGroup,
+ $groupType,
+ $objWriter,
+ &$catIsMultiLevelSeries,
+ &$valIsMultiLevelSeries,
+ &$plotGroupingType,
+ Worksheet $pSheet
+ )
+ {
+ if (is_null($plotGroup)) {
+ return;
+ }
+
+ if (($groupType == Chart_DataSeries::TYPE_BARCHART) ||
+ ($groupType == Chart_DataSeries::TYPE_BARCHART_3D)) {
+ $objWriter->startElement('c:barDir');
+ $objWriter->writeAttribute('val', $plotGroup->getPlotDirection());
+ $objWriter->endElement();
+ }
+
+ if (!is_null($plotGroup->getPlotGrouping())) {
+ $plotGroupingType = $plotGroup->getPlotGrouping();
+ $objWriter->startElement('c:grouping');
+ $objWriter->writeAttribute('val', $plotGroupingType);
+ $objWriter->endElement();
+ }
+
+ // Get these details before the loop, because we can use the count to check for varyColors
+ $plotSeriesOrder = $plotGroup->getPlotOrder();
+ $plotSeriesCount = count($plotSeriesOrder);
+
+ if (($groupType !== Chart_DataSeries::TYPE_RADARCHART) &&
+ ($groupType !== Chart_DataSeries::TYPE_STOCKCHART)) {
+
+ if ($groupType !== Chart_DataSeries::TYPE_LINECHART) {
+ if (($groupType == Chart_DataSeries::TYPE_PIECHART) ||
+ ($groupType == Chart_DataSeries::TYPE_PIECHART_3D) ||
+ ($groupType == Chart_DataSeries::TYPE_DONUTCHART) ||
+ ($plotSeriesCount > 1)) {
+ $objWriter->startElement('c:varyColors');
+ $objWriter->writeAttribute('val', 1);
+ $objWriter->endElement();
+ } else {
+ $objWriter->startElement('c:varyColors');
+ $objWriter->writeAttribute('val', 0);
+ $objWriter->endElement();
+ }
+ }
+ }
+
+ foreach($plotSeriesOrder as $plotSeriesIdx => $plotSeriesRef) {
+ $objWriter->startElement('c:ser');
+
+ $objWriter->startElement('c:idx');
+ $objWriter->writeAttribute('val', $this->_seriesIndex + $plotSeriesIdx);
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:order');
+ $objWriter->writeAttribute('val', $this->_seriesIndex + $plotSeriesRef);
+ $objWriter->endElement();
+
+ if (($groupType == Chart_DataSeries::TYPE_PIECHART) ||
+ ($groupType == Chart_DataSeries::TYPE_PIECHART_3D) ||
+ ($groupType == Chart_DataSeries::TYPE_DONUTCHART)) {
+
+ $objWriter->startElement('c:dPt');
+ $objWriter->startElement('c:idx');
+ $objWriter->writeAttribute('val', 3);
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:bubble3D');
+ $objWriter->writeAttribute('val', 0);
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:spPr');
+ $objWriter->startElement('a:solidFill');
+ $objWriter->startElement('a:srgbClr');
+ $objWriter->writeAttribute('val', 'FF9900');
+ $objWriter->endElement();
+ $objWriter->endElement();
+ $objWriter->endElement();
+ $objWriter->endElement();
+ }
+
+ // Labels
+ $plotSeriesLabel = $plotGroup->getPlotLabelByIndex($plotSeriesRef);
+ if ($plotSeriesLabel && ($plotSeriesLabel->getPointCount() > 0)) {
+ $objWriter->startElement('c:tx');
+ $objWriter->startElement('c:strRef');
+ $this->_writePlotSeriesLabel($plotSeriesLabel, $objWriter);
+ $objWriter->endElement();
+ $objWriter->endElement();
+ }
+
+ // Formatting for the points
+ if ($groupType == Chart_DataSeries::TYPE_LINECHART) {
+ $objWriter->startElement('c:spPr');
+ $objWriter->startElement('a:ln');
+ $objWriter->writeAttribute('w', 12700);
+ $objWriter->endElement();
+ $objWriter->endElement();
+ }
+
+ $plotSeriesValues = $plotGroup->getPlotValuesByIndex($plotSeriesRef);
+ if ($plotSeriesValues) {
+ $plotSeriesMarker = $plotSeriesValues->getPointMarker();
+ if ($plotSeriesMarker) {
+ $objWriter->startElement('c:marker');
+ $objWriter->startElement('c:symbol');
+ $objWriter->writeAttribute('val', $plotSeriesMarker);
+ $objWriter->endElement();
+
+ if ($plotSeriesMarker !== 'none') {
+ $objWriter->startElement('c:size');
+ $objWriter->writeAttribute('val', 3);
+ $objWriter->endElement();
+ }
+ $objWriter->endElement();
+ }
+ }
+
+ if (($groupType === Chart_DataSeries::TYPE_BARCHART) ||
+ ($groupType === Chart_DataSeries::TYPE_BARCHART_3D) ||
+ ($groupType === Chart_DataSeries::TYPE_BUBBLECHART)) {
+
+ $objWriter->startElement('c:invertIfNegative');
+ $objWriter->writeAttribute('val', 0);
+ $objWriter->endElement();
+ }
+
+ // Category Labels
+ $plotSeriesCategory = $plotGroup->getPlotCategoryByIndex($plotSeriesRef);
+ if ($plotSeriesCategory && ($plotSeriesCategory->getPointCount() > 0)) {
+ $catIsMultiLevelSeries = $catIsMultiLevelSeries || $plotSeriesCategory->isMultiLevelSeries();
+
+ if (($groupType == Chart_DataSeries::TYPE_PIECHART) ||
+ ($groupType == Chart_DataSeries::TYPE_PIECHART_3D) ||
+ ($groupType == Chart_DataSeries::TYPE_DONUTCHART)) {
+
+ if (!is_null($plotGroup->getPlotStyle())) {
+ $plotStyle = $plotGroup->getPlotStyle();
+ if ($plotStyle) {
+ $objWriter->startElement('c:explosion');
+ $objWriter->writeAttribute('val', 25);
+ $objWriter->endElement();
+ }
+ }
+ }
+
+ if (($groupType === Chart_DataSeries::TYPE_BUBBLECHART) ||
+ ($groupType === Chart_DataSeries::TYPE_SCATTERCHART)) {
+ $objWriter->startElement('c:xVal');
+ } else {
+ $objWriter->startElement('c:cat');
+ }
+
+ $this->_writePlotSeriesValues($plotSeriesCategory, $objWriter, $groupType, 'str', $pSheet);
+ $objWriter->endElement();
+ }
+
+ // Values
+ if ($plotSeriesValues) {
+ $valIsMultiLevelSeries = $valIsMultiLevelSeries || $plotSeriesValues->isMultiLevelSeries();
+
+ if (($groupType === Chart_DataSeries::TYPE_BUBBLECHART) ||
+ ($groupType === Chart_DataSeries::TYPE_SCATTERCHART)) {
+ $objWriter->startElement('c:yVal');
+ } else {
+ $objWriter->startElement('c:val');
+ }
+
+ $this->_writePlotSeriesValues($plotSeriesValues, $objWriter, $groupType, 'num', $pSheet);
+ $objWriter->endElement();
+ }
+
+ if ($groupType === Chart_DataSeries::TYPE_BUBBLECHART) {
+ $this->_writeBubbles($plotSeriesValues, $objWriter, $pSheet);
+ }
+
+ $objWriter->endElement();
+
+ }
+
+ $this->_seriesIndex += $plotSeriesIdx + 1;
+ }
+
+ /**
+ * Write Plot Series Label
+ *
+ * @param PHPExcel\Chart_DataSeriesValues $plotSeriesLabel
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @throws PHPExcel\Writer_Exception
+ */
+ private function _writePlotSeriesLabel($plotSeriesLabel, $objWriter)
+ {
+ if (is_null($plotSeriesLabel)) {
+ return;
+ }
+
+ $objWriter->startElement('c:f');
+ $objWriter->writeRawData($plotSeriesLabel->getDataSource());
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:strCache');
+ $objWriter->startElement('c:ptCount');
+ $objWriter->writeAttribute('val', $plotSeriesLabel->getPointCount() );
+ $objWriter->endElement();
+
+ foreach($plotSeriesLabel->getDataValues() as $plotLabelKey => $plotLabelValue) {
+ $objWriter->startElement('c:pt');
+ $objWriter->writeAttribute('idx', $plotLabelKey );
+
+ $objWriter->startElement('c:v');
+ $objWriter->writeRawData( $plotLabelValue );
+ $objWriter->endElement();
+ $objWriter->endElement();
+ }
+ $objWriter->endElement();
+
+ }
+
+ /**
+ * Write Plot Series Values
+ *
+ * @param PHPExcel\Chart_DataSeriesValues $plotSeriesValues
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @param string $groupType Type of plot for dataseries
+ * @param string $dataType Datatype of series values
+ * @param PHPExcel\Worksheet $pSheet
+ * @throws PHPExcel\Writer_Exception
+ */
+ private function _writePlotSeriesValues( $plotSeriesValues,
+ $objWriter,
+ $groupType,
+ $dataType='str',
+ Worksheet $pSheet
+ )
+ {
+ if (is_null($plotSeriesValues)) {
+ return;
+ }
+
+ if ($plotSeriesValues->isMultiLevelSeries()) {
+ $levelCount = $plotSeriesValues->multiLevelCount();
+
+ $objWriter->startElement('c:multiLvlStrRef');
+
+ $objWriter->startElement('c:f');
+ $objWriter->writeRawData( $plotSeriesValues->getDataSource() );
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:multiLvlStrCache');
+
+ $objWriter->startElement('c:ptCount');
+ $objWriter->writeAttribute('val', $plotSeriesValues->getPointCount() );
+ $objWriter->endElement();
+
+ for ($level = 0; $level < $levelCount; ++$level) {
+ $objWriter->startElement('c:lvl');
+
+ foreach($plotSeriesValues->getDataValues() as $plotSeriesKey => $plotSeriesValue) {
+ if (isset($plotSeriesValue[$level])) {
+ $objWriter->startElement('c:pt');
+ $objWriter->writeAttribute('idx', $plotSeriesKey );
+
+ $objWriter->startElement('c:v');
+ $objWriter->writeRawData( $plotSeriesValue[$level] );
+ $objWriter->endElement();
+ $objWriter->endElement();
+ }
+ }
+
+ $objWriter->endElement();
+ }
+
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+ } else {
+ $objWriter->startElement('c:'.$dataType.'Ref');
+
+ $objWriter->startElement('c:f');
+ $objWriter->writeRawData( $plotSeriesValues->getDataSource() );
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:'.$dataType.'Cache');
+
+ if (($groupType != Chart_DataSeries::TYPE_PIECHART) &&
+ ($groupType != Chart_DataSeries::TYPE_PIECHART_3D) &&
+ ($groupType != Chart_DataSeries::TYPE_DONUTCHART)) {
+
+ if (($plotSeriesValues->getFormatCode() !== null) &&
+ ($plotSeriesValues->getFormatCode() !== '')) {
+ $objWriter->startElement('c:formatCode');
+ $objWriter->writeRawData( $plotSeriesValues->getFormatCode() );
+ $objWriter->endElement();
+ }
+ }
+
+ $objWriter->startElement('c:ptCount');
+ $objWriter->writeAttribute('val', $plotSeriesValues->getPointCount() );
+ $objWriter->endElement();
+
+ $dataValues = $plotSeriesValues->getDataValues();
+ if (!empty($dataValues)) {
+ if (is_array($dataValues)) {
+ foreach($dataValues as $plotSeriesKey => $plotSeriesValue) {
+ $objWriter->startElement('c:pt');
+ $objWriter->writeAttribute('idx', $plotSeriesKey );
+
+ $objWriter->startElement('c:v');
+ $objWriter->writeRawData( $plotSeriesValue );
+ $objWriter->endElement();
+ $objWriter->endElement();
+ }
+ }
+ }
+
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+ }
+ }
+
+ /**
+ * Write Bubble Chart Details
+ *
+ * @param PHPExcel\Chart_DataSeriesValues $plotSeriesValues
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @throws PHPExcel\Writer_Exception
+ */
+ private function _writeBubbles($plotSeriesValues, $objWriter, Worksheet $pSheet)
+ {
+ if (is_null($plotSeriesValues)) {
+ return;
+ }
+
+ $objWriter->startElement('c:bubbleSize');
+ $objWriter->startElement('c:numLit');
+
+ $objWriter->startElement('c:formatCode');
+ $objWriter->writeRawData( 'General' );
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:ptCount');
+ $objWriter->writeAttribute('val', $plotSeriesValues->getPointCount() );
+ $objWriter->endElement();
+
+ $dataValues = $plotSeriesValues->getDataValues();
+ if (!empty($dataValues)) {
+ if (is_array($dataValues)) {
+ foreach($dataValues as $plotSeriesKey => $plotSeriesValue) {
+ $objWriter->startElement('c:pt');
+ $objWriter->writeAttribute('idx', $plotSeriesKey );
+ $objWriter->startElement('c:v');
+ $objWriter->writeRawData( 1 );
+ $objWriter->endElement();
+ $objWriter->endElement();
+ }
+ }
+ }
+
+ $objWriter->endElement();
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:bubble3D');
+ $objWriter->writeAttribute('val', 0 );
+ $objWriter->endElement();
+ }
+
+ /**
+ * Write Layout
+ *
+ * @param PHPExcel\Chart_Layout $layout
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @throws PHPExcel\Writer_Exception
+ */
+ private function _writeLayout(Chart_Layout $layout = null, $objWriter)
+ {
+ $objWriter->startElement('c:layout');
+
+ if (!is_null($layout)) {
+ $objWriter->startElement('c:manualLayout');
+
+ $layoutTarget = $layout->getLayoutTarget();
+ if (!is_null($layoutTarget)) {
+ $objWriter->startElement('c:layoutTarget');
+ $objWriter->writeAttribute('val', $layoutTarget);
+ $objWriter->endElement();
+ }
+
+ $xMode = $layout->getXMode();
+ if (!is_null($xMode)) {
+ $objWriter->startElement('c:xMode');
+ $objWriter->writeAttribute('val', $xMode);
+ $objWriter->endElement();
+ }
+
+ $yMode = $layout->getYMode();
+ if (!is_null($yMode)) {
+ $objWriter->startElement('c:yMode');
+ $objWriter->writeAttribute('val', $yMode);
+ $objWriter->endElement();
+ }
+
+ $x = $layout->getXPosition();
+ if (!is_null($x)) {
+ $objWriter->startElement('c:x');
+ $objWriter->writeAttribute('val', $x);
+ $objWriter->endElement();
+ }
+
+ $y = $layout->getYPosition();
+ if (!is_null($y)) {
+ $objWriter->startElement('c:y');
+ $objWriter->writeAttribute('val', $y);
+ $objWriter->endElement();
+ }
+
+ $w = $layout->getWidth();
+ if (!is_null($w)) {
+ $objWriter->startElement('c:w');
+ $objWriter->writeAttribute('val', $w);
+ $objWriter->endElement();
+ }
+
+ $h = $layout->getHeight();
+ if (!is_null($h)) {
+ $objWriter->startElement('c:h');
+ $objWriter->writeAttribute('val', $h);
+ $objWriter->endElement();
+ }
+
+ $objWriter->endElement();
+ }
+
+ $objWriter->endElement();
+ }
+
+ /**
+ * Write Alternate Content block
+ *
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @throws PHPExcel\Writer_Exception
+ */
+ private function _writeAlternateContent($objWriter)
+ {
+ $objWriter->startElement('mc:AlternateContent');
+ $objWriter->writeAttribute('xmlns:mc', 'http://schemas.openxmlformats.org/markup-compatibility/2006');
+
+ $objWriter->startElement('mc:Choice');
+ $objWriter->writeAttribute('xmlns:c14', 'http://schemas.microsoft.com/office/drawing/2007/8/2/chart');
+ $objWriter->writeAttribute('Requires', 'c14');
+
+ $objWriter->startElement('c14:style');
+ $objWriter->writeAttribute('val', '102');
+ $objWriter->endElement();
+ $objWriter->endElement();
+
+ $objWriter->startElement('mc:Fallback');
+ $objWriter->startElement('c:style');
+ $objWriter->writeAttribute('val', '2');
+ $objWriter->endElement();
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+ }
+
+ /**
+ * Write Printer Settings
+ *
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @throws PHPExcel\Writer_Exception
+ */
+ private function _writePrintSettings($objWriter)
+ {
+ $objWriter->startElement('c:printSettings');
+
+ $objWriter->startElement('c:headerFooter');
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:pageMargins');
+ $objWriter->writeAttribute('footer', 0.3);
+ $objWriter->writeAttribute('header', 0.3);
+ $objWriter->writeAttribute('r', 0.7);
+ $objWriter->writeAttribute('l', 0.7);
+ $objWriter->writeAttribute('t', 0.75);
+ $objWriter->writeAttribute('b', 0.75);
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:pageSetup');
+ $objWriter->writeAttribute('orientation', "portrait");
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+ }
}
diff --git a/Classes/PHPExcel/Writer/Excel2007/Comments.php b/Classes/PHPExcel/Writer/Excel2007/Comments.php
index 0764313..5bfaf63 100644
--- a/Classes/PHPExcel/Writer/Excel2007/Comments.php
+++ b/Classes/PHPExcel/Writer/Excel2007/Comments.php
@@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\Writer_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,234 +37,234 @@ namespace PHPExcel;
*/
class Writer_Excel2007_Comments extends Writer_Excel2007_WriterPart
{
- /**
- * Write comments to XML format
- *
- * @param PHPExcel\Worksheet $pWorksheet
- * @return string XML Output
- * @throws PHPExcel\Writer_Exception
- */
- public function writeComments(Worksheet $pWorksheet = null)
- {
- // Create XML writer
- $objWriter = null;
- if ($this->getParentWriter()->getUseDiskCaching()) {
- $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
- } else {
- $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_MEMORY);
- }
+ /**
+ * Write comments to XML format
+ *
+ * @param PHPExcel\Worksheet $pWorksheet
+ * @return string XML Output
+ * @throws PHPExcel\Writer_Exception
+ */
+ public function writeComments(Worksheet $pWorksheet = null)
+ {
+ // Create XML writer
+ $objWriter = null;
+ if ($this->getParentWriter()->getUseDiskCaching()) {
+ $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
+ } else {
+ $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_MEMORY);
+ }
- // XML header
- $objWriter->startDocument('1.0','UTF-8','yes');
+ // XML header
+ $objWriter->startDocument('1.0','UTF-8','yes');
- // Comments cache
- $comments = $pWorksheet->getComments();
+ // Comments cache
+ $comments = $pWorksheet->getComments();
- // Authors cache
- $authors = array();
- $authorId = 0;
- foreach ($comments as $comment) {
- if (!isset($authors[$comment->getAuthor()])) {
- $authors[$comment->getAuthor()] = $authorId++;
- }
- }
+ // Authors cache
+ $authors = array();
+ $authorId = 0;
+ foreach ($comments as $comment) {
+ if (!isset($authors[$comment->getAuthor()])) {
+ $authors[$comment->getAuthor()] = $authorId++;
+ }
+ }
- // comments
- $objWriter->startElement('comments');
- $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main');
+ // comments
+ $objWriter->startElement('comments');
+ $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main');
- // Loop through authors
- $objWriter->startElement('authors');
- foreach ($authors as $author => $index) {
- $objWriter->writeElement('author', $author);
- }
- $objWriter->endElement();
+ // Loop through authors
+ $objWriter->startElement('authors');
+ foreach ($authors as $author => $index) {
+ $objWriter->writeElement('author', $author);
+ }
+ $objWriter->endElement();
- // Loop through comments
- $objWriter->startElement('commentList');
- foreach ($comments as $key => $value) {
- $this->_writeComment($objWriter, $key, $value, $authors);
- }
- $objWriter->endElement();
+ // Loop through comments
+ $objWriter->startElement('commentList');
+ foreach ($comments as $key => $value) {
+ $this->_writeComment($objWriter, $key, $value, $authors);
+ }
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // Return
- return $objWriter->getData();
- }
+ // Return
+ return $objWriter->getData();
+ }
- /**
- * Write comment to XML format
- *
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @param string $pCellReference Cell reference
- * @param PHPExcel\Comment $pComment Comment
- * @param array $pAuthors Array of authors
- * @throws PHPExcel\Writer_Exception
- */
- public function _writeComment(Shared_XMLWriter $objWriter = null, $pCellReference = 'A1', Comment $pComment = null, $pAuthors = null)
- {
- // comment
- $objWriter->startElement('comment');
- $objWriter->writeAttribute('ref', $pCellReference);
- $objWriter->writeAttribute('authorId', $pAuthors[$pComment->getAuthor()]);
+ /**
+ * Write comment to XML format
+ *
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @param string $pCellReference Cell reference
+ * @param PHPExcel\Comment $pComment Comment
+ * @param array $pAuthors Array of authors
+ * @throws PHPExcel\Writer_Exception
+ */
+ public function _writeComment(Shared_XMLWriter $objWriter = null, $pCellReference = 'A1', Comment $pComment = null, $pAuthors = null)
+ {
+ // comment
+ $objWriter->startElement('comment');
+ $objWriter->writeAttribute('ref', $pCellReference);
+ $objWriter->writeAttribute('authorId', $pAuthors[$pComment->getAuthor()]);
- // text
- $objWriter->startElement('text');
- $this->getParentWriter()->getWriterPart('stringtable')->writeRichText($objWriter, $pComment->getText());
- $objWriter->endElement();
+ // text
+ $objWriter->startElement('text');
+ $this->getParentWriter()->getWriterPart('stringtable')->writeRichText($objWriter, $pComment->getText());
+ $objWriter->endElement();
- $objWriter->endElement();
- }
+ $objWriter->endElement();
+ }
- /**
- * Write VML comments to XML format
- *
- * @param PHPExcel\Worksheet $pWorksheet
- * @return string XML Output
- * @throws PHPExcel\Writer_Exception
- */
- public function writeVMLComments(Worksheet $pWorksheet = null)
- {
- // Create XML writer
- $objWriter = null;
- if ($this->getParentWriter()->getUseDiskCaching()) {
- $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
- } else {
- $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_MEMORY);
- }
+ /**
+ * Write VML comments to XML format
+ *
+ * @param PHPExcel\Worksheet $pWorksheet
+ * @return string XML Output
+ * @throws PHPExcel\Writer_Exception
+ */
+ public function writeVMLComments(Worksheet $pWorksheet = null)
+ {
+ // Create XML writer
+ $objWriter = null;
+ if ($this->getParentWriter()->getUseDiskCaching()) {
+ $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
+ } else {
+ $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_MEMORY);
+ }
- // XML header
- $objWriter->startDocument('1.0','UTF-8','yes');
+ // XML header
+ $objWriter->startDocument('1.0','UTF-8','yes');
- // Comments cache
- $comments = $pWorksheet->getComments();
+ // Comments cache
+ $comments = $pWorksheet->getComments();
- // xml
- $objWriter->startElement('xml');
- $objWriter->writeAttribute('xmlns:v', 'urn:schemas-microsoft-com:vml');
- $objWriter->writeAttribute('xmlns:o', 'urn:schemas-microsoft-com:office:office');
- $objWriter->writeAttribute('xmlns:x', 'urn:schemas-microsoft-com:office:excel');
+ // xml
+ $objWriter->startElement('xml');
+ $objWriter->writeAttribute('xmlns:v', 'urn:schemas-microsoft-com:vml');
+ $objWriter->writeAttribute('xmlns:o', 'urn:schemas-microsoft-com:office:office');
+ $objWriter->writeAttribute('xmlns:x', 'urn:schemas-microsoft-com:office:excel');
- // o:shapelayout
- $objWriter->startElement('o:shapelayout');
- $objWriter->writeAttribute('v:ext', 'edit');
+ // o:shapelayout
+ $objWriter->startElement('o:shapelayout');
+ $objWriter->writeAttribute('v:ext', 'edit');
- // o:idmap
- $objWriter->startElement('o:idmap');
- $objWriter->writeAttribute('v:ext', 'edit');
- $objWriter->writeAttribute('data', '1');
- $objWriter->endElement();
+ // o:idmap
+ $objWriter->startElement('o:idmap');
+ $objWriter->writeAttribute('v:ext', 'edit');
+ $objWriter->writeAttribute('data', '1');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // v:shapetype
- $objWriter->startElement('v:shapetype');
- $objWriter->writeAttribute('id', '_x0000_t202');
- $objWriter->writeAttribute('coordsize', '21600,21600');
- $objWriter->writeAttribute('o:spt', '202');
- $objWriter->writeAttribute('path', 'm,l,21600r21600,l21600,xe');
+ // v:shapetype
+ $objWriter->startElement('v:shapetype');
+ $objWriter->writeAttribute('id', '_x0000_t202');
+ $objWriter->writeAttribute('coordsize', '21600,21600');
+ $objWriter->writeAttribute('o:spt', '202');
+ $objWriter->writeAttribute('path', 'm,l,21600r21600,l21600,xe');
- // v:stroke
- $objWriter->startElement('v:stroke');
- $objWriter->writeAttribute('joinstyle', 'miter');
- $objWriter->endElement();
+ // v:stroke
+ $objWriter->startElement('v:stroke');
+ $objWriter->writeAttribute('joinstyle', 'miter');
+ $objWriter->endElement();
- // v:path
- $objWriter->startElement('v:path');
- $objWriter->writeAttribute('gradientshapeok', 't');
- $objWriter->writeAttribute('o:connecttype', 'rect');
- $objWriter->endElement();
+ // v:path
+ $objWriter->startElement('v:path');
+ $objWriter->writeAttribute('gradientshapeok', 't');
+ $objWriter->writeAttribute('o:connecttype', 'rect');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // Loop through comments
- foreach ($comments as $key => $value) {
- $this->_writeVMLComment($objWriter, $key, $value);
- }
+ // Loop through comments
+ foreach ($comments as $key => $value) {
+ $this->_writeVMLComment($objWriter, $key, $value);
+ }
- $objWriter->endElement();
+ $objWriter->endElement();
- // Return
- return $objWriter->getData();
- }
+ // Return
+ return $objWriter->getData();
+ }
- /**
- * Write VML comment to XML format
- *
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @param string $pCellReference Cell reference
- * @param PHPExcel\Comment $pComment Comment
- * @throws PHPExcel\Writer_Exception
- */
- public function _writeVMLComment(Shared_XMLWriter $objWriter = null, $pCellReference = 'A1', Comment $pComment = null)
- {
- // Metadata
- list($column, $row) = Cell::coordinateFromString($pCellReference);
- $column = Cell::columnIndexFromString($column);
- $id = 1024 + $column + $row;
- $id = substr($id, 0, 4);
+ /**
+ * Write VML comment to XML format
+ *
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @param string $pCellReference Cell reference
+ * @param PHPExcel\Comment $pComment Comment
+ * @throws PHPExcel\Writer_Exception
+ */
+ public function _writeVMLComment(Shared_XMLWriter $objWriter = null, $pCellReference = 'A1', Comment $pComment = null)
+ {
+ // Metadata
+ list($column, $row) = Cell::coordinateFromString($pCellReference);
+ $column = Cell::columnIndexFromString($column);
+ $id = 1024 + $column + $row;
+ $id = substr($id, 0, 4);
- // v:shape
- $objWriter->startElement('v:shape');
- $objWriter->writeAttribute('id', '_x0000_s' . $id);
- $objWriter->writeAttribute('type', '#_x0000_t202');
- $objWriter->writeAttribute('style', 'position:absolute;margin-left:' . $pComment->getMarginLeft() . ';margin-top:' . $pComment->getMarginTop() . ';width:' . $pComment->getWidth() . ';height:' . $pComment->getHeight() . ';z-index:1;visibility:' . ($pComment->getVisible() ? 'visible' : 'hidden'));
- $objWriter->writeAttribute('fillcolor', '#' . $pComment->getFillColor()->getRGB());
- $objWriter->writeAttribute('o:insetmode', 'auto');
+ // v:shape
+ $objWriter->startElement('v:shape');
+ $objWriter->writeAttribute('id', '_x0000_s' . $id);
+ $objWriter->writeAttribute('type', '#_x0000_t202');
+ $objWriter->writeAttribute('style', 'position:absolute;margin-left:' . $pComment->getMarginLeft() . ';margin-top:' . $pComment->getMarginTop() . ';width:' . $pComment->getWidth() . ';height:' . $pComment->getHeight() . ';z-index:1;visibility:' . ($pComment->getVisible() ? 'visible' : 'hidden'));
+ $objWriter->writeAttribute('fillcolor', '#' . $pComment->getFillColor()->getRGB());
+ $objWriter->writeAttribute('o:insetmode', 'auto');
- // v:fill
- $objWriter->startElement('v:fill');
- $objWriter->writeAttribute('color2', '#' . $pComment->getFillColor()->getRGB());
- $objWriter->endElement();
+ // v:fill
+ $objWriter->startElement('v:fill');
+ $objWriter->writeAttribute('color2', '#' . $pComment->getFillColor()->getRGB());
+ $objWriter->endElement();
- // v:shadow
- $objWriter->startElement('v:shadow');
- $objWriter->writeAttribute('on', 't');
- $objWriter->writeAttribute('color', 'black');
- $objWriter->writeAttribute('obscured', 't');
- $objWriter->endElement();
+ // v:shadow
+ $objWriter->startElement('v:shadow');
+ $objWriter->writeAttribute('on', 't');
+ $objWriter->writeAttribute('color', 'black');
+ $objWriter->writeAttribute('obscured', 't');
+ $objWriter->endElement();
- // v:path
- $objWriter->startElement('v:path');
- $objWriter->writeAttribute('o:connecttype', 'none');
- $objWriter->endElement();
+ // v:path
+ $objWriter->startElement('v:path');
+ $objWriter->writeAttribute('o:connecttype', 'none');
+ $objWriter->endElement();
- // v:textbox
- $objWriter->startElement('v:textbox');
- $objWriter->writeAttribute('style', 'mso-direction-alt:auto');
+ // v:textbox
+ $objWriter->startElement('v:textbox');
+ $objWriter->writeAttribute('style', 'mso-direction-alt:auto');
- // div
- $objWriter->startElement('div');
- $objWriter->writeAttribute('style', 'text-align:left');
- $objWriter->endElement();
+ // div
+ $objWriter->startElement('div');
+ $objWriter->writeAttribute('style', 'text-align:left');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // x:ClientData
- $objWriter->startElement('x:ClientData');
- $objWriter->writeAttribute('ObjectType', 'Note');
+ // x:ClientData
+ $objWriter->startElement('x:ClientData');
+ $objWriter->writeAttribute('ObjectType', 'Note');
- // x:MoveWithCells
- $objWriter->writeElement('x:MoveWithCells', '');
+ // x:MoveWithCells
+ $objWriter->writeElement('x:MoveWithCells', '');
- // x:SizeWithCells
- $objWriter->writeElement('x:SizeWithCells', '');
+ // x:SizeWithCells
+ $objWriter->writeElement('x:SizeWithCells', '');
- // x:Anchor
- //$objWriter->writeElement('x:Anchor', $column . ', 15, ' . ($row - 2) . ', 10, ' . ($column + 4) . ', 15, ' . ($row + 5) . ', 18');
+ // x:Anchor
+ //$objWriter->writeElement('x:Anchor', $column . ', 15, ' . ($row - 2) . ', 10, ' . ($column + 4) . ', 15, ' . ($row + 5) . ', 18');
- // x:AutoFill
- $objWriter->writeElement('x:AutoFill', 'False');
+ // x:AutoFill
+ $objWriter->writeElement('x:AutoFill', 'False');
- // x:Row
- $objWriter->writeElement('x:Row', ($row - 1));
+ // x:Row
+ $objWriter->writeElement('x:Row', ($row - 1));
- // x:Column
- $objWriter->writeElement('x:Column', ($column - 1));
+ // x:Column
+ $objWriter->writeElement('x:Column', ($column - 1));
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
- }
+ $objWriter->endElement();
+ }
}
diff --git a/Classes/PHPExcel/Writer/Excel2007/ContentTypes.php b/Classes/PHPExcel/Writer/Excel2007/ContentTypes.php
index 3c4364f..0f12de8 100644
--- a/Classes/PHPExcel/Writer/Excel2007/ContentTypes.php
+++ b/Classes/PHPExcel/Writer/Excel2007/ContentTypes.php
@@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\Writer_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,227 +37,227 @@ namespace PHPExcel;
*/
class Writer_Excel2007_ContentTypes extends Writer_Excel2007_WriterPart
{
- /**
- * Write content types to XML format
- *
- * @param PHPExcel $pPHPExcel
- * @param boolean $includeCharts Flag indicating if we should include drawing details for charts
- * @return string XML Output
- * @throws PHPExcel\Writer_Exception
- */
- public function writeContentTypes(Workbook $pPHPExcel = null, $includeCharts = FALSE)
- {
- // Create XML writer
- $objWriter = null;
- if ($this->getParentWriter()->getUseDiskCaching()) {
- $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
- } else {
- $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_MEMORY);
- }
+ /**
+ * Write content types to XML format
+ *
+ * @param PHPExcel $pPHPExcel
+ * @param boolean $includeCharts Flag indicating if we should include drawing details for charts
+ * @return string XML Output
+ * @throws PHPExcel\Writer_Exception
+ */
+ public function writeContentTypes(Workbook $pPHPExcel = null, $includeCharts = false)
+ {
+ // Create XML writer
+ $objWriter = null;
+ if ($this->getParentWriter()->getUseDiskCaching()) {
+ $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
+ } else {
+ $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_MEMORY);
+ }
- // XML header
- $objWriter->startDocument('1.0','UTF-8','yes');
+ // XML header
+ $objWriter->startDocument('1.0','UTF-8','yes');
- // Types
- $objWriter->startElement('Types');
- $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/content-types');
+ // Types
+ $objWriter->startElement('Types');
+ $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/content-types');
- // Theme
- $this->_writeOverrideContentType(
- $objWriter, '/xl/theme/theme1.xml', 'application/vnd.openxmlformats-officedocument.theme+xml'
- );
+ // Theme
+ $this->_writeOverrideContentType(
+ $objWriter, '/xl/theme/theme1.xml', 'application/vnd.openxmlformats-officedocument.theme+xml'
+ );
- // Styles
- $this->_writeOverrideContentType(
- $objWriter, '/xl/styles.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml'
- );
+ // Styles
+ $this->_writeOverrideContentType(
+ $objWriter, '/xl/styles.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml'
+ );
- // Rels
- $this->_writeDefaultContentType(
- $objWriter, 'rels', 'application/vnd.openxmlformats-package.relationships+xml'
- );
+ // Rels
+ $this->_writeDefaultContentType(
+ $objWriter, 'rels', 'application/vnd.openxmlformats-package.relationships+xml'
+ );
- // XML
- $this->_writeDefaultContentType(
- $objWriter, 'xml', 'application/xml'
- );
+ // XML
+ $this->_writeDefaultContentType(
+ $objWriter, 'xml', 'application/xml'
+ );
- // VML
- $this->_writeDefaultContentType(
- $objWriter, 'vml', 'application/vnd.openxmlformats-officedocument.vmlDrawing'
- );
+ // VML
+ $this->_writeDefaultContentType(
+ $objWriter, 'vml', 'application/vnd.openxmlformats-officedocument.vmlDrawing'
+ );
- // Workbook
- $this->_writeOverrideContentType(
- $objWriter, '/xl/workbook.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml'
- );
+ // Workbook
+ $this->_writeOverrideContentType(
+ $objWriter, '/xl/workbook.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml'
+ );
- // DocProps
- $this->_writeOverrideContentType(
- $objWriter, '/docProps/app.xml', 'application/vnd.openxmlformats-officedocument.extended-properties+xml'
- );
+ // DocProps
+ $this->_writeOverrideContentType(
+ $objWriter, '/docProps/app.xml', 'application/vnd.openxmlformats-officedocument.extended-properties+xml'
+ );
- $this->_writeOverrideContentType(
- $objWriter, '/docProps/core.xml', 'application/vnd.openxmlformats-package.core-properties+xml'
- );
+ $this->_writeOverrideContentType(
+ $objWriter, '/docProps/core.xml', 'application/vnd.openxmlformats-package.core-properties+xml'
+ );
- $customPropertyList = $pPHPExcel->getProperties()->getCustomProperties();
- if (!empty($customPropertyList)) {
- $this->_writeOverrideContentType(
- $objWriter, '/docProps/custom.xml', 'application/vnd.openxmlformats-officedocument.custom-properties+xml'
- );
- }
+ $customPropertyList = $pPHPExcel->getProperties()->getCustomProperties();
+ if (!empty($customPropertyList)) {
+ $this->_writeOverrideContentType(
+ $objWriter, '/docProps/custom.xml', 'application/vnd.openxmlformats-officedocument.custom-properties+xml'
+ );
+ }
- // Worksheets
- $sheetCount = $pPHPExcel->getSheetCount();
- for ($i = 0; $i < $sheetCount; ++$i) {
- $this->_writeOverrideContentType(
- $objWriter, '/xl/worksheets/sheet' . ($i + 1) . '.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml'
- );
- }
+ // Worksheets
+ $sheetCount = $pPHPExcel->getSheetCount();
+ for ($i = 0; $i < $sheetCount; ++$i) {
+ $this->_writeOverrideContentType(
+ $objWriter, '/xl/worksheets/sheet' . ($i + 1) . '.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml'
+ );
+ }
- // Shared strings
- $this->_writeOverrideContentType(
- $objWriter, '/xl/sharedStrings.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml'
- );
+ // Shared strings
+ $this->_writeOverrideContentType(
+ $objWriter, '/xl/sharedStrings.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml'
+ );
- // Add worksheet relationship content types
- $chart = 1;
- for ($i = 0; $i < $sheetCount; ++$i) {
- $drawings = $pPHPExcel->getSheet($i)->getDrawingCollection();
- $drawingCount = count($drawings);
- $chartCount = ($includeCharts) ? $pPHPExcel->getSheet($i)->getChartCount() : 0;
+ // Add worksheet relationship content types
+ $chart = 1;
+ for ($i = 0; $i < $sheetCount; ++$i) {
+ $drawings = $pPHPExcel->getSheet($i)->getDrawingCollection();
+ $drawingCount = count($drawings);
+ $chartCount = ($includeCharts) ? $pPHPExcel->getSheet($i)->getChartCount() : 0;
- // We need a drawing relationship for the worksheet if we have either drawings or charts
- if (($drawingCount > 0) || ($chartCount > 0)) {
- $this->_writeOverrideContentType(
- $objWriter, '/xl/drawings/drawing' . ($i + 1) . '.xml', 'application/vnd.openxmlformats-officedocument.drawing+xml'
- );
- }
+ // We need a drawing relationship for the worksheet if we have either drawings or charts
+ if (($drawingCount > 0) || ($chartCount > 0)) {
+ $this->_writeOverrideContentType(
+ $objWriter, '/xl/drawings/drawing' . ($i + 1) . '.xml', 'application/vnd.openxmlformats-officedocument.drawing+xml'
+ );
+ }
- // If we have charts, then we need a chart relationship for every individual chart
- if ($chartCount > 0) {
- for ($c = 0; $c < $chartCount; ++$c) {
- $this->_writeOverrideContentType(
- $objWriter, '/xl/charts/chart' . $chart++ . '.xml', 'application/vnd.openxmlformats-officedocument.drawingml.chart+xml'
- );
- }
- }
- }
+ // If we have charts, then we need a chart relationship for every individual chart
+ if ($chartCount > 0) {
+ for ($c = 0; $c < $chartCount; ++$c) {
+ $this->_writeOverrideContentType(
+ $objWriter, '/xl/charts/chart' . $chart++ . '.xml', 'application/vnd.openxmlformats-officedocument.drawingml.chart+xml'
+ );
+ }
+ }
+ }
- // Comments
- for ($i = 0; $i < $sheetCount; ++$i) {
- if (count($pPHPExcel->getSheet($i)->getComments()) > 0) {
- $this->_writeOverrideContentType(
- $objWriter, '/xl/comments' . ($i + 1) . '.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml'
- );
- }
- }
+ // Comments
+ for ($i = 0; $i < $sheetCount; ++$i) {
+ if (count($pPHPExcel->getSheet($i)->getComments()) > 0) {
+ $this->_writeOverrideContentType(
+ $objWriter, '/xl/comments' . ($i + 1) . '.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml'
+ );
+ }
+ }
- // Add media content-types
- $aMediaContentTypes = array();
- $mediaCount = $this->getParentWriter()->getDrawingHashTable()->count();
- for ($i = 0; $i < $mediaCount; ++$i) {
- $extension = '';
- $mimeType = '';
+ // Add media content-types
+ $aMediaContentTypes = array();
+ $mediaCount = $this->getParentWriter()->getDrawingHashTable()->count();
+ for ($i = 0; $i < $mediaCount; ++$i) {
+ $extension = '';
+ $mimeType = '';
- if ($this->getParentWriter()->getDrawingHashTable()->getByIndex($i) instanceof Worksheet_Drawing) {
- $extension = strtolower($this->getParentWriter()->getDrawingHashTable()->getByIndex($i)->getExtension());
- $mimeType = $this->_getImageMimeType( $this->getParentWriter()->getDrawingHashTable()->getByIndex($i)->getPath() );
- } else if ($this->getParentWriter()->getDrawingHashTable()->getByIndex($i) instanceof Worksheet_MemoryDrawing) {
- $extension = strtolower($this->getParentWriter()->getDrawingHashTable()->getByIndex($i)->getMimeType());
- $extension = explode('/', $extension);
- $extension = $extension[1];
+ if ($this->getParentWriter()->getDrawingHashTable()->getByIndex($i) instanceof Worksheet_Drawing) {
+ $extension = strtolower($this->getParentWriter()->getDrawingHashTable()->getByIndex($i)->getExtension());
+ $mimeType = $this->_getImageMimeType( $this->getParentWriter()->getDrawingHashTable()->getByIndex($i)->getPath() );
+ } else if ($this->getParentWriter()->getDrawingHashTable()->getByIndex($i) instanceof Worksheet_MemoryDrawing) {
+ $extension = strtolower($this->getParentWriter()->getDrawingHashTable()->getByIndex($i)->getMimeType());
+ $extension = explode('/', $extension);
+ $extension = $extension[1];
- $mimeType = $this->getParentWriter()->getDrawingHashTable()->getByIndex($i)->getMimeType();
- }
+ $mimeType = $this->getParentWriter()->getDrawingHashTable()->getByIndex($i)->getMimeType();
+ }
- if (!isset( $aMediaContentTypes[$extension]) ) {
- $aMediaContentTypes[$extension] = $mimeType;
+ if (!isset( $aMediaContentTypes[$extension]) ) {
+ $aMediaContentTypes[$extension] = $mimeType;
- $this->_writeDefaultContentType(
- $objWriter, $extension, $mimeType
- );
- }
- }
+ $this->_writeDefaultContentType(
+ $objWriter, $extension, $mimeType
+ );
+ }
+ }
- $sheetCount = $pPHPExcel->getSheetCount();
- for ($i = 0; $i < $sheetCount; ++$i) {
- if (count($pPHPExcel->getSheet()->getHeaderFooter()->getImages()) > 0) {
- foreach ($pPHPExcel->getSheet()->getHeaderFooter()->getImages() as $image) {
- if (!isset( $aMediaContentTypes[strtolower($image->getExtension())]) ) {
- $aMediaContentTypes[strtolower($image->getExtension())] = $this->_getImageMimeType( $image->getPath() );
+ $sheetCount = $pPHPExcel->getSheetCount();
+ for ($i = 0; $i < $sheetCount; ++$i) {
+ if (count($pPHPExcel->getSheet()->getHeaderFooter()->getImages()) > 0) {
+ foreach ($pPHPExcel->getSheet()->getHeaderFooter()->getImages() as $image) {
+ if (!isset( $aMediaContentTypes[strtolower($image->getExtension())]) ) {
+ $aMediaContentTypes[strtolower($image->getExtension())] = $this->_getImageMimeType( $image->getPath() );
- $this->_writeDefaultContentType(
- $objWriter, strtolower($image->getExtension()), $aMediaContentTypes[strtolower($image->getExtension())]
- );
- }
- }
- }
- }
+ $this->_writeDefaultContentType(
+ $objWriter, strtolower($image->getExtension()), $aMediaContentTypes[strtolower($image->getExtension())]
+ );
+ }
+ }
+ }
+ }
- $objWriter->endElement();
+ $objWriter->endElement();
- // Return
- return $objWriter->getData();
- }
+ // Return
+ return $objWriter->getData();
+ }
- /**
- * Get image mime type
- *
- * @param string $pFile Filename
- * @return string Mime Type
- * @throws PHPExcel\Writer_Exception
- */
- private function _getImageMimeType($pFile = '')
- {
- if (Shared_File::file_exists($pFile)) {
- $image = getimagesize($pFile);
- return image_type_to_mime_type($image[2]);
- } else {
- throw new Writer_Exception("File $pFile does not exist");
- }
- }
+ /**
+ * Get image mime type
+ *
+ * @param string $pFile Filename
+ * @return string Mime Type
+ * @throws PHPExcel\Writer_Exception
+ */
+ private function _getImageMimeType($pFile = '')
+ {
+ if (Shared_File::file_exists($pFile)) {
+ $image = getimagesize($pFile);
+ return image_type_to_mime_type($image[2]);
+ } else {
+ throw new Writer_Exception("File $pFile does not exist");
+ }
+ }
- /**
- * Write Default content type
- *
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @param string $pPartname Part name
- * @param string $pContentType Content type
- * @throws PHPExcel\Writer_Exception
- */
- private function _writeDefaultContentType(Shared_XMLWriter $objWriter = null, $pPartname = '', $pContentType = '')
- {
- if ($pPartname != '' && $pContentType != '') {
- // Write content type
- $objWriter->startElement('Default');
- $objWriter->writeAttribute('Extension', $pPartname);
- $objWriter->writeAttribute('ContentType', $pContentType);
- $objWriter->endElement();
- } else {
- throw new Writer_Exception("Invalid parameters passed.");
- }
- }
+ /**
+ * Write Default content type
+ *
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @param string $pPartname Part name
+ * @param string $pContentType Content type
+ * @throws PHPExcel\Writer_Exception
+ */
+ private function _writeDefaultContentType(Shared_XMLWriter $objWriter = null, $pPartname = '', $pContentType = '')
+ {
+ if ($pPartname != '' && $pContentType != '') {
+ // Write content type
+ $objWriter->startElement('Default');
+ $objWriter->writeAttribute('Extension', $pPartname);
+ $objWriter->writeAttribute('ContentType', $pContentType);
+ $objWriter->endElement();
+ } else {
+ throw new Writer_Exception("Invalid parameters passed.");
+ }
+ }
- /**
- * Write Override content type
- *
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @param string $pPartname Part name
- * @param string $pContentType Content type
- * @throws PHPExcel\Writer_Exception
- */
- private function _writeOverrideContentType(Shared_XMLWriter $objWriter = null, $pPartname = '', $pContentType = '')
- {
- if ($pPartname != '' && $pContentType != '') {
- // Write content type
- $objWriter->startElement('Override');
- $objWriter->writeAttribute('PartName', $pPartname);
- $objWriter->writeAttribute('ContentType', $pContentType);
- $objWriter->endElement();
- } else {
- throw new Writer_Exception("Invalid parameters passed.");
- }
- }
+ /**
+ * Write Override content type
+ *
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @param string $pPartname Part name
+ * @param string $pContentType Content type
+ * @throws PHPExcel\Writer_Exception
+ */
+ private function _writeOverrideContentType(Shared_XMLWriter $objWriter = null, $pPartname = '', $pContentType = '')
+ {
+ if ($pPartname != '' && $pContentType != '') {
+ // Write content type
+ $objWriter->startElement('Override');
+ $objWriter->writeAttribute('PartName', $pPartname);
+ $objWriter->writeAttribute('ContentType', $pContentType);
+ $objWriter->endElement();
+ } else {
+ throw new Writer_Exception("Invalid parameters passed.");
+ }
+ }
}
diff --git a/Classes/PHPExcel/Writer/Excel2007/DocProps.php b/Classes/PHPExcel/Writer/Excel2007/DocProps.php
index 508df74..37f90c3 100644
--- a/Classes/PHPExcel/Writer/Excel2007/DocProps.php
+++ b/Classes/PHPExcel/Writer/Excel2007/DocProps.php
@@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\Writer_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##
*/
@@ -38,237 +38,237 @@ namespace PHPExcel;
class Writer_Excel2007_DocProps extends Writer_Excel2007_WriterPart
{
/**
- * Write docProps/app.xml to XML format
- *
- * @param PHPExcel $pPHPExcel
- * @return string XML Output
- * @throws PHPExcel\Writer_Exception
- */
- public function writeDocPropsApp(Workbook $pPHPExcel = null)
- {
- // Create XML writer
- $objWriter = null;
- if ($this->getParentWriter()->getUseDiskCaching()) {
- $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
- } else {
- $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_MEMORY);
- }
+ * Write docProps/app.xml to XML format
+ *
+ * @param PHPExcel $pPHPExcel
+ * @return string XML Output
+ * @throws PHPExcel\Writer_Exception
+ */
+ public function writeDocPropsApp(Workbook $pPHPExcel = null)
+ {
+ // Create XML writer
+ $objWriter = null;
+ if ($this->getParentWriter()->getUseDiskCaching()) {
+ $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
+ } else {
+ $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_MEMORY);
+ }
- // XML header
- $objWriter->startDocument('1.0','UTF-8','yes');
+ // XML header
+ $objWriter->startDocument('1.0','UTF-8','yes');
- // Properties
- $objWriter->startElement('Properties');
- $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/officeDocument/2006/extended-properties');
- $objWriter->writeAttribute('xmlns:vt', 'http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes');
+ // Properties
+ $objWriter->startElement('Properties');
+ $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/officeDocument/2006/extended-properties');
+ $objWriter->writeAttribute('xmlns:vt', 'http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes');
- // Application
- $objWriter->writeElement('Application', 'Microsoft Excel');
+ // Application
+ $objWriter->writeElement('Application', 'Microsoft Excel');
- // DocSecurity
- $objWriter->writeElement('DocSecurity', '0');
+ // DocSecurity
+ $objWriter->writeElement('DocSecurity', '0');
- // ScaleCrop
- $objWriter->writeElement('ScaleCrop', 'false');
+ // ScaleCrop
+ $objWriter->writeElement('ScaleCrop', 'false');
- // HeadingPairs
- $objWriter->startElement('HeadingPairs');
+ // HeadingPairs
+ $objWriter->startElement('HeadingPairs');
- // Vector
- $objWriter->startElement('vt:vector');
- $objWriter->writeAttribute('size', '2');
- $objWriter->writeAttribute('baseType', 'variant');
+ // Vector
+ $objWriter->startElement('vt:vector');
+ $objWriter->writeAttribute('size', '2');
+ $objWriter->writeAttribute('baseType', 'variant');
- // Variant
- $objWriter->startElement('vt:variant');
- $objWriter->writeElement('vt:lpstr', 'Worksheets');
- $objWriter->endElement();
+ // Variant
+ $objWriter->startElement('vt:variant');
+ $objWriter->writeElement('vt:lpstr', 'Worksheets');
+ $objWriter->endElement();
- // Variant
- $objWriter->startElement('vt:variant');
- $objWriter->writeElement('vt:i4', $pPHPExcel->getSheetCount());
- $objWriter->endElement();
+ // Variant
+ $objWriter->startElement('vt:variant');
+ $objWriter->writeElement('vt:i4', $pPHPExcel->getSheetCount());
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // TitlesOfParts
- $objWriter->startElement('TitlesOfParts');
+ // TitlesOfParts
+ $objWriter->startElement('TitlesOfParts');
- // Vector
- $objWriter->startElement('vt:vector');
- $objWriter->writeAttribute('size', $pPHPExcel->getSheetCount());
- $objWriter->writeAttribute('baseType', 'lpstr');
+ // Vector
+ $objWriter->startElement('vt:vector');
+ $objWriter->writeAttribute('size', $pPHPExcel->getSheetCount());
+ $objWriter->writeAttribute('baseType', 'lpstr');
- $sheetCount = $pPHPExcel->getSheetCount();
- for ($i = 0; $i < $sheetCount; ++$i) {
- $objWriter->writeElement('vt:lpstr', $pPHPExcel->getSheet($i)->getTitle());
- }
+ $sheetCount = $pPHPExcel->getSheetCount();
+ for ($i = 0; $i < $sheetCount; ++$i) {
+ $objWriter->writeElement('vt:lpstr', $pPHPExcel->getSheet($i)->getTitle());
+ }
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // Company
- $objWriter->writeElement('Company', $pPHPExcel->getProperties()->getCompany());
+ // Company
+ $objWriter->writeElement('Company', $pPHPExcel->getProperties()->getCompany());
- // Company
- $objWriter->writeElement('Manager', $pPHPExcel->getProperties()->getManager());
+ // Company
+ $objWriter->writeElement('Manager', $pPHPExcel->getProperties()->getManager());
- // LinksUpToDate
- $objWriter->writeElement('LinksUpToDate', 'false');
+ // LinksUpToDate
+ $objWriter->writeElement('LinksUpToDate', 'false');
- // SharedDoc
- $objWriter->writeElement('SharedDoc', 'false');
+ // SharedDoc
+ $objWriter->writeElement('SharedDoc', 'false');
- // HyperlinksChanged
- $objWriter->writeElement('HyperlinksChanged', 'false');
+ // HyperlinksChanged
+ $objWriter->writeElement('HyperlinksChanged', 'false');
- // AppVersion
- $objWriter->writeElement('AppVersion', '12.0000');
+ // AppVersion
+ $objWriter->writeElement('AppVersion', '12.0000');
- $objWriter->endElement();
+ $objWriter->endElement();
- // Return
- return $objWriter->getData();
- }
+ // Return
+ return $objWriter->getData();
+ }
- /**
- * Write docProps/core.xml to XML format
- *
- * @param PHPExcel $pPHPExcel
- * @return string XML Output
- * @throws PHPExcel\Writer_Exception
- */
- public function writeDocPropsCore(Workbook $pPHPExcel = null)
- {
- // Create XML writer
- $objWriter = null;
- if ($this->getParentWriter()->getUseDiskCaching()) {
- $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
- } else {
- $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_MEMORY);
- }
+ /**
+ * Write docProps/core.xml to XML format
+ *
+ * @param PHPExcel $pPHPExcel
+ * @return string XML Output
+ * @throws PHPExcel\Writer_Exception
+ */
+ public function writeDocPropsCore(Workbook $pPHPExcel = null)
+ {
+ // Create XML writer
+ $objWriter = null;
+ if ($this->getParentWriter()->getUseDiskCaching()) {
+ $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
+ } else {
+ $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_MEMORY);
+ }
- // XML header
- $objWriter->startDocument('1.0','UTF-8','yes');
+ // XML header
+ $objWriter->startDocument('1.0','UTF-8','yes');
- // cp:coreProperties
- $objWriter->startElement('cp:coreProperties');
- $objWriter->writeAttribute('xmlns:cp', 'http://schemas.openxmlformats.org/package/2006/metadata/core-properties');
- $objWriter->writeAttribute('xmlns:dc', 'http://purl.org/dc/elements/1.1/');
- $objWriter->writeAttribute('xmlns:dcterms', 'http://purl.org/dc/terms/');
- $objWriter->writeAttribute('xmlns:dcmitype', 'http://purl.org/dc/dcmitype/');
- $objWriter->writeAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
+ // cp:coreProperties
+ $objWriter->startElement('cp:coreProperties');
+ $objWriter->writeAttribute('xmlns:cp', 'http://schemas.openxmlformats.org/package/2006/metadata/core-properties');
+ $objWriter->writeAttribute('xmlns:dc', 'http://purl.org/dc/elements/1.1/');
+ $objWriter->writeAttribute('xmlns:dcterms', 'http://purl.org/dc/terms/');
+ $objWriter->writeAttribute('xmlns:dcmitype', 'http://purl.org/dc/dcmitype/');
+ $objWriter->writeAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
- // dc:creator
- $objWriter->writeElement('dc:creator', $pPHPExcel->getProperties()->getCreator());
+ // dc:creator
+ $objWriter->writeElement('dc:creator', $pPHPExcel->getProperties()->getCreator());
- // cp:lastModifiedBy
- $objWriter->writeElement('cp:lastModifiedBy', $pPHPExcel->getProperties()->getLastModifiedBy());
+ // cp:lastModifiedBy
+ $objWriter->writeElement('cp:lastModifiedBy', $pPHPExcel->getProperties()->getLastModifiedBy());
- // dcterms:created
- $objWriter->startElement('dcterms:created');
- $objWriter->writeAttribute('xsi:type', 'dcterms:W3CDTF');
- $objWriter->writeRawData(date(DATE_W3C, $pPHPExcel->getProperties()->getCreated()));
- $objWriter->endElement();
+ // dcterms:created
+ $objWriter->startElement('dcterms:created');
+ $objWriter->writeAttribute('xsi:type', 'dcterms:W3CDTF');
+ $objWriter->writeRawData(date(DATE_W3C, $pPHPExcel->getProperties()->getCreated()));
+ $objWriter->endElement();
- // dcterms:modified
- $objWriter->startElement('dcterms:modified');
- $objWriter->writeAttribute('xsi:type', 'dcterms:W3CDTF');
- $objWriter->writeRawData(date(DATE_W3C, $pPHPExcel->getProperties()->getModified()));
- $objWriter->endElement();
+ // dcterms:modified
+ $objWriter->startElement('dcterms:modified');
+ $objWriter->writeAttribute('xsi:type', 'dcterms:W3CDTF');
+ $objWriter->writeRawData(date(DATE_W3C, $pPHPExcel->getProperties()->getModified()));
+ $objWriter->endElement();
- // dc:title
- $objWriter->writeElement('dc:title', $pPHPExcel->getProperties()->getTitle());
+ // dc:title
+ $objWriter->writeElement('dc:title', $pPHPExcel->getProperties()->getTitle());
- // dc:description
- $objWriter->writeElement('dc:description', $pPHPExcel->getProperties()->getDescription());
+ // dc:description
+ $objWriter->writeElement('dc:description', $pPHPExcel->getProperties()->getDescription());
- // dc:subject
- $objWriter->writeElement('dc:subject', $pPHPExcel->getProperties()->getSubject());
+ // dc:subject
+ $objWriter->writeElement('dc:subject', $pPHPExcel->getProperties()->getSubject());
- // cp:keywords
- $objWriter->writeElement('cp:keywords', $pPHPExcel->getProperties()->getKeywords());
+ // cp:keywords
+ $objWriter->writeElement('cp:keywords', $pPHPExcel->getProperties()->getKeywords());
- // cp:category
- $objWriter->writeElement('cp:category', $pPHPExcel->getProperties()->getCategory());
+ // cp:category
+ $objWriter->writeElement('cp:category', $pPHPExcel->getProperties()->getCategory());
- $objWriter->endElement();
+ $objWriter->endElement();
- // Return
- return $objWriter->getData();
- }
+ // Return
+ return $objWriter->getData();
+ }
- /**
- * Write docProps/custom.xml to XML format
- *
- * @param PHPExcel $pPHPExcel
- * @return string XML Output
- * @throws PHPExcel\Writer_Exception
- */
- public function writeDocPropsCustom(Workbook $pPHPExcel = null)
- {
- $customPropertyList = $pPHPExcel->getProperties()->getCustomProperties();
- if (empty($customPropertyList)) {
- return;
- }
+ /**
+ * Write docProps/custom.xml to XML format
+ *
+ * @param PHPExcel $pPHPExcel
+ * @return string XML Output
+ * @throws PHPExcel\Writer_Exception
+ */
+ public function writeDocPropsCustom(Workbook $pPHPExcel = null)
+ {
+ $customPropertyList = $pPHPExcel->getProperties()->getCustomProperties();
+ if (empty($customPropertyList)) {
+ return;
+ }
- // Create XML writer
- $objWriter = null;
- if ($this->getParentWriter()->getUseDiskCaching()) {
- $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
- } else {
- $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_MEMORY);
- }
+ // Create XML writer
+ $objWriter = null;
+ if ($this->getParentWriter()->getUseDiskCaching()) {
+ $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
+ } else {
+ $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_MEMORY);
+ }
- // XML header
- $objWriter->startDocument('1.0','UTF-8','yes');
+ // XML header
+ $objWriter->startDocument('1.0','UTF-8','yes');
- // cp:coreProperties
- $objWriter->startElement('Properties');
- $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/officeDocument/2006/custom-properties');
- $objWriter->writeAttribute('xmlns:vt', 'http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes');
+ // cp:coreProperties
+ $objWriter->startElement('Properties');
+ $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/officeDocument/2006/custom-properties');
+ $objWriter->writeAttribute('xmlns:vt', 'http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes');
- foreach($customPropertyList as $key => $customProperty) {
- $propertyValue = $pPHPExcel->getProperties()->getCustomPropertyValue($customProperty);
- $propertyType = $pPHPExcel->getProperties()->getCustomPropertyType($customProperty);
+ foreach($customPropertyList as $key => $customProperty) {
+ $propertyValue = $pPHPExcel->getProperties()->getCustomPropertyValue($customProperty);
+ $propertyType = $pPHPExcel->getProperties()->getCustomPropertyType($customProperty);
- $objWriter->startElement('property');
- $objWriter->writeAttribute('fmtid', '{D5CDD505-2E9C-101B-9397-08002B2CF9AE}');
- $objWriter->writeAttribute('pid', $key+2);
- $objWriter->writeAttribute('name', $customProperty);
+ $objWriter->startElement('property');
+ $objWriter->writeAttribute('fmtid', '{D5CDD505-2E9C-101B-9397-08002B2CF9AE}');
+ $objWriter->writeAttribute('pid', $key+2);
+ $objWriter->writeAttribute('name', $customProperty);
- switch($propertyType) {
- case 'i' :
- $objWriter->writeElement('vt:i4', $propertyValue);
- break;
- case 'f' :
- $objWriter->writeElement('vt:r8', $propertyValue);
- break;
- case 'b' :
- $objWriter->writeElement('vt:bool', ($propertyValue) ? 'true' : 'false');
- break;
- case 'd' :
- $objWriter->startElement('vt:filetime');
- $objWriter->writeRawData(date(DATE_W3C, $propertyValue));
- $objWriter->endElement();
- break;
- default :
- $objWriter->writeElement('vt:lpwstr', $propertyValue);
- break;
- }
+ switch($propertyType) {
+ case 'i' :
+ $objWriter->writeElement('vt:i4', $propertyValue);
+ break;
+ case 'f' :
+ $objWriter->writeElement('vt:r8', $propertyValue);
+ break;
+ case 'b' :
+ $objWriter->writeElement('vt:bool', ($propertyValue) ? 'true' : 'false');
+ break;
+ case 'd' :
+ $objWriter->startElement('vt:filetime');
+ $objWriter->writeRawData(date(DATE_W3C, $propertyValue));
+ $objWriter->endElement();
+ break;
+ default :
+ $objWriter->writeElement('vt:lpwstr', $propertyValue);
+ break;
+ }
- $objWriter->endElement();
- }
+ $objWriter->endElement();
+ }
- $objWriter->endElement();
+ $objWriter->endElement();
- // Return
- return $objWriter->getData();
- }
+ // Return
+ return $objWriter->getData();
+ }
}
diff --git a/Classes/PHPExcel/Writer/Excel2007/Drawing.php b/Classes/PHPExcel/Writer/Excel2007/Drawing.php
index 93fd15d..5ee8f6c 100644
--- a/Classes/PHPExcel/Writer/Excel2007/Drawing.php
+++ b/Classes/PHPExcel/Writer/Excel2007/Drawing.php
@@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\Writer_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,564 +37,564 @@ namespace PHPExcel;
*/
class Writer_Excel2007_Drawing extends Writer_Excel2007_WriterPart
{
- /**
- * Write drawings to XML format
- *
- * @param PHPExcel\Worksheet $pWorksheet
- * @param int &$chartRef Chart ID
- * @param boolean $includeCharts Flag indicating if we should include drawing details for charts
- * @return string XML Output
- * @throws PHPExcel\Writer_Exception
- */
- public function writeDrawings(Worksheet $pWorksheet = null, &$chartRef, $includeCharts = FALSE)
- {
- // Create XML writer
- $objWriter = null;
- if ($this->getParentWriter()->getUseDiskCaching()) {
- $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
- } else {
- $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_MEMORY);
- }
+ /**
+ * Write drawings to XML format
+ *
+ * @param PHPExcel\Worksheet $pWorksheet
+ * @param int &$chartRef Chart ID
+ * @param boolean $includeCharts Flag indicating if we should include drawing details for charts
+ * @return string XML Output
+ * @throws PHPExcel\Writer_Exception
+ */
+ public function writeDrawings(Worksheet $pWorksheet = null, &$chartRef, $includeCharts = false)
+ {
+ // Create XML writer
+ $objWriter = null;
+ if ($this->getParentWriter()->getUseDiskCaching()) {
+ $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
+ } else {
+ $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_MEMORY);
+ }
- // XML header
- $objWriter->startDocument('1.0','UTF-8','yes');
+ // XML header
+ $objWriter->startDocument('1.0','UTF-8','yes');
- // xdr:wsDr
- $objWriter->startElement('xdr:wsDr');
- $objWriter->writeAttribute('xmlns:xdr', 'http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing');
- $objWriter->writeAttribute('xmlns:a', 'http://schemas.openxmlformats.org/drawingml/2006/main');
+ // xdr:wsDr
+ $objWriter->startElement('xdr:wsDr');
+ $objWriter->writeAttribute('xmlns:xdr', 'http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing');
+ $objWriter->writeAttribute('xmlns:a', 'http://schemas.openxmlformats.org/drawingml/2006/main');
- // Loop through images and write drawings
- $i = 1;
- $iterator = $pWorksheet->getDrawingCollection()->getIterator();
- while ($iterator->valid()) {
- $this->_writeDrawing($objWriter, $iterator->current(), $i);
+ // Loop through images and write drawings
+ $i = 1;
+ $iterator = $pWorksheet->getDrawingCollection()->getIterator();
+ while ($iterator->valid()) {
+ $this->_writeDrawing($objWriter, $iterator->current(), $i);
- $iterator->next();
- ++$i;
- }
+ $iterator->next();
+ ++$i;
+ }
- if ($includeCharts) {
- $chartCount = $pWorksheet->getChartCount();
- // Loop through charts and write the chart position
- if ($chartCount > 0) {
- for ($c = 0; $c < $chartCount; ++$c) {
- $this->_writeChart($objWriter, $pWorksheet->getChartByIndex($c), $c+$i);
- }
- }
- }
+ if ($includeCharts) {
+ $chartCount = $pWorksheet->getChartCount();
+ // Loop through charts and write the chart position
+ if ($chartCount > 0) {
+ for ($c = 0; $c < $chartCount; ++$c) {
+ $this->_writeChart($objWriter, $pWorksheet->getChartByIndex($c), $c+$i);
+ }
+ }
+ }
- $objWriter->endElement();
+ $objWriter->endElement();
- // Return
- return $objWriter->getData();
- }
+ // Return
+ return $objWriter->getData();
+ }
- /**
- * Write drawings to XML format
- *
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel\Chart $pChart
- * @param int $pRelationId
- * @throws PHPExcel\Writer_Exception
- */
- public function _writeChart(Shared_XMLWriter $objWriter = null, Chart $pChart = null, $pRelationId = -1)
- {
- $tl = $pChart->getTopLeftPosition();
- $tl['colRow'] = Cell::coordinateFromString($tl['cell']);
- $br = $pChart->getBottomRightPosition();
- $br['colRow'] = Cell::coordinateFromString($br['cell']);
+ /**
+ * Write drawings to XML format
+ *
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel\Chart $pChart
+ * @param int $pRelationId
+ * @throws PHPExcel\Writer_Exception
+ */
+ public function _writeChart(Shared_XMLWriter $objWriter = null, Chart $pChart = null, $pRelationId = -1)
+ {
+ $tl = $pChart->getTopLeftPosition();
+ $tl['colRow'] = Cell::coordinateFromString($tl['cell']);
+ $br = $pChart->getBottomRightPosition();
+ $br['colRow'] = Cell::coordinateFromString($br['cell']);
- $objWriter->startElement('xdr:twoCellAnchor');
+ $objWriter->startElement('xdr:twoCellAnchor');
- $objWriter->startElement('xdr:from');
- $objWriter->writeElement('xdr:col', Cell::columnIndexFromString($tl['colRow'][0]) - 1);
- $objWriter->writeElement('xdr:colOff', Shared_Drawing::pixelsToEMU($tl['xOffset']));
- $objWriter->writeElement('xdr:row', $tl['colRow'][1] - 1);
- $objWriter->writeElement('xdr:rowOff', Shared_Drawing::pixelsToEMU($tl['yOffset']));
- $objWriter->endElement();
- $objWriter->startElement('xdr:to');
- $objWriter->writeElement('xdr:col', Cell::columnIndexFromString($br['colRow'][0]) - 1);
- $objWriter->writeElement('xdr:colOff', Shared_Drawing::pixelsToEMU($br['xOffset']));
- $objWriter->writeElement('xdr:row', $br['colRow'][1] - 1);
- $objWriter->writeElement('xdr:rowOff', Shared_Drawing::pixelsToEMU($br['yOffset']));
- $objWriter->endElement();
+ $objWriter->startElement('xdr:from');
+ $objWriter->writeElement('xdr:col', Cell::columnIndexFromString($tl['colRow'][0]) - 1);
+ $objWriter->writeElement('xdr:colOff', Shared_Drawing::pixelsToEMU($tl['xOffset']));
+ $objWriter->writeElement('xdr:row', $tl['colRow'][1] - 1);
+ $objWriter->writeElement('xdr:rowOff', Shared_Drawing::pixelsToEMU($tl['yOffset']));
+ $objWriter->endElement();
+ $objWriter->startElement('xdr:to');
+ $objWriter->writeElement('xdr:col', Cell::columnIndexFromString($br['colRow'][0]) - 1);
+ $objWriter->writeElement('xdr:colOff', Shared_Drawing::pixelsToEMU($br['xOffset']));
+ $objWriter->writeElement('xdr:row', $br['colRow'][1] - 1);
+ $objWriter->writeElement('xdr:rowOff', Shared_Drawing::pixelsToEMU($br['yOffset']));
+ $objWriter->endElement();
- $objWriter->startElement('xdr:graphicFrame');
- $objWriter->writeAttribute('macro', '');
- $objWriter->startElement('xdr:nvGraphicFramePr');
- $objWriter->startElement('xdr:cNvPr');
- $objWriter->writeAttribute('name', 'Chart '.$pRelationId);
- $objWriter->writeAttribute('id', 1025 * $pRelationId);
- $objWriter->endElement();
- $objWriter->startElement('xdr:cNvGraphicFramePr');
- $objWriter->startElement('a:graphicFrameLocks');
- $objWriter->endElement();
- $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->startElement('xdr:graphicFrame');
+ $objWriter->writeAttribute('macro', '');
+ $objWriter->startElement('xdr:nvGraphicFramePr');
+ $objWriter->startElement('xdr:cNvPr');
+ $objWriter->writeAttribute('name', 'Chart '.$pRelationId);
+ $objWriter->writeAttribute('id', 1025 * $pRelationId);
+ $objWriter->endElement();
+ $objWriter->startElement('xdr:cNvGraphicFramePr');
+ $objWriter->startElement('a:graphicFrameLocks');
+ $objWriter->endElement();
+ $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->startElement('xdr:xfrm');
- $objWriter->startElement('a:off');
- $objWriter->writeAttribute('x', '0');
- $objWriter->writeAttribute('y', '0');
- $objWriter->endElement();
- $objWriter->startElement('a:ext');
- $objWriter->writeAttribute('cx', '0');
- $objWriter->writeAttribute('cy', '0');
- $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->startElement('xdr:xfrm');
+ $objWriter->startElement('a:off');
+ $objWriter->writeAttribute('x', '0');
+ $objWriter->writeAttribute('y', '0');
+ $objWriter->endElement();
+ $objWriter->startElement('a:ext');
+ $objWriter->writeAttribute('cx', '0');
+ $objWriter->writeAttribute('cy', '0');
+ $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->startElement('a:graphic');
- $objWriter->startElement('a:graphicData');
- $objWriter->writeAttribute('uri', 'http://schemas.openxmlformats.org/drawingml/2006/chart');
- $objWriter->startElement('c:chart');
- $objWriter->writeAttribute('xmlns:c', 'http://schemas.openxmlformats.org/drawingml/2006/chart');
- $objWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships');
- $objWriter->writeAttribute('r:id', 'rId'.$pRelationId);
- $objWriter->endElement();
- $objWriter->endElement();
- $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->startElement('a:graphic');
+ $objWriter->startElement('a:graphicData');
+ $objWriter->writeAttribute('uri', 'http://schemas.openxmlformats.org/drawingml/2006/chart');
+ $objWriter->startElement('c:chart');
+ $objWriter->writeAttribute('xmlns:c', 'http://schemas.openxmlformats.org/drawingml/2006/chart');
+ $objWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships');
+ $objWriter->writeAttribute('r:id', 'rId'.$pRelationId);
+ $objWriter->endElement();
+ $objWriter->endElement();
+ $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->startElement('xdr:clientData');
- $objWriter->endElement();
+ $objWriter->startElement('xdr:clientData');
+ $objWriter->endElement();
- $objWriter->endElement();
- }
+ $objWriter->endElement();
+ }
- /**
- * Write drawings to XML format
- *
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel\Worksheet_BaseDrawing $pDrawing
- * @param int $pRelationId
- * @throws PHPExcel\Writer_Exception
- */
- public function _writeDrawing(Shared_XMLWriter $objWriter = null, Worksheet_BaseDrawing $pDrawing = null, $pRelationId = -1)
- {
- if ($pRelationId >= 0) {
- // xdr:oneCellAnchor
- $objWriter->startElement('xdr:oneCellAnchor');
- // Image location
- $aCoordinates = Cell::coordinateFromString($pDrawing->getCoordinates());
- $aCoordinates[0] = Cell::columnIndexFromString($aCoordinates[0]);
+ /**
+ * Write drawings to XML format
+ *
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel\Worksheet_BaseDrawing $pDrawing
+ * @param int $pRelationId
+ * @throws PHPExcel\Writer_Exception
+ */
+ public function _writeDrawing(Shared_XMLWriter $objWriter = null, Worksheet_BaseDrawing $pDrawing = null, $pRelationId = -1)
+ {
+ if ($pRelationId >= 0) {
+ // xdr:oneCellAnchor
+ $objWriter->startElement('xdr:oneCellAnchor');
+ // Image location
+ $aCoordinates = Cell::coordinateFromString($pDrawing->getCoordinates());
+ $aCoordinates[0] = Cell::columnIndexFromString($aCoordinates[0]);
- // xdr:from
- $objWriter->startElement('xdr:from');
- $objWriter->writeElement('xdr:col', $aCoordinates[0] - 1);
- $objWriter->writeElement('xdr:colOff', Shared_Drawing::pixelsToEMU($pDrawing->getOffsetX()));
- $objWriter->writeElement('xdr:row', $aCoordinates[1] - 1);
- $objWriter->writeElement('xdr:rowOff', Shared_Drawing::pixelsToEMU($pDrawing->getOffsetY()));
- $objWriter->endElement();
+ // xdr:from
+ $objWriter->startElement('xdr:from');
+ $objWriter->writeElement('xdr:col', $aCoordinates[0] - 1);
+ $objWriter->writeElement('xdr:colOff', Shared_Drawing::pixelsToEMU($pDrawing->getOffsetX()));
+ $objWriter->writeElement('xdr:row', $aCoordinates[1] - 1);
+ $objWriter->writeElement('xdr:rowOff', Shared_Drawing::pixelsToEMU($pDrawing->getOffsetY()));
+ $objWriter->endElement();
- // xdr:ext
- $objWriter->startElement('xdr:ext');
- $objWriter->writeAttribute('cx', Shared_Drawing::pixelsToEMU($pDrawing->getWidth()));
- $objWriter->writeAttribute('cy', Shared_Drawing::pixelsToEMU($pDrawing->getHeight()));
- $objWriter->endElement();
+ // xdr:ext
+ $objWriter->startElement('xdr:ext');
+ $objWriter->writeAttribute('cx', Shared_Drawing::pixelsToEMU($pDrawing->getWidth()));
+ $objWriter->writeAttribute('cy', Shared_Drawing::pixelsToEMU($pDrawing->getHeight()));
+ $objWriter->endElement();
- // xdr:pic
- $objWriter->startElement('xdr:pic');
+ // xdr:pic
+ $objWriter->startElement('xdr:pic');
- // xdr:nvPicPr
- $objWriter->startElement('xdr:nvPicPr');
+ // xdr:nvPicPr
+ $objWriter->startElement('xdr:nvPicPr');
- // xdr:cNvPr
- $objWriter->startElement('xdr:cNvPr');
- $objWriter->writeAttribute('id', $pRelationId);
- $objWriter->writeAttribute('name', $pDrawing->getName());
- $objWriter->writeAttribute('descr', $pDrawing->getDescription());
- $objWriter->endElement();
+ // xdr:cNvPr
+ $objWriter->startElement('xdr:cNvPr');
+ $objWriter->writeAttribute('id', $pRelationId);
+ $objWriter->writeAttribute('name', $pDrawing->getName());
+ $objWriter->writeAttribute('descr', $pDrawing->getDescription());
+ $objWriter->endElement();
- // xdr:cNvPicPr
- $objWriter->startElement('xdr:cNvPicPr');
+ // xdr:cNvPicPr
+ $objWriter->startElement('xdr:cNvPicPr');
- // a:picLocks
- $objWriter->startElement('a:picLocks');
- $objWriter->writeAttribute('noChangeAspect', '1');
- $objWriter->endElement();
+ // a:picLocks
+ $objWriter->startElement('a:picLocks');
+ $objWriter->writeAttribute('noChangeAspect', '1');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // xdr:blipFill
- $objWriter->startElement('xdr:blipFill');
+ // xdr:blipFill
+ $objWriter->startElement('xdr:blipFill');
- // a:blip
- $objWriter->startElement('a:blip');
- $objWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships');
- $objWriter->writeAttribute('r:embed', 'rId' . $pRelationId);
- $objWriter->endElement();
+ // a:blip
+ $objWriter->startElement('a:blip');
+ $objWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships');
+ $objWriter->writeAttribute('r:embed', 'rId' . $pRelationId);
+ $objWriter->endElement();
- // a:stretch
- $objWriter->startElement('a:stretch');
- $objWriter->writeElement('a:fillRect', null);
- $objWriter->endElement();
+ // a:stretch
+ $objWriter->startElement('a:stretch');
+ $objWriter->writeElement('a:fillRect', null);
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // xdr:spPr
- $objWriter->startElement('xdr:spPr');
+ // xdr:spPr
+ $objWriter->startElement('xdr:spPr');
- // a:xfrm
- $objWriter->startElement('a:xfrm');
- $objWriter->writeAttribute('rot', Shared_Drawing::degreesToAngle($pDrawing->getRotation()));
- $objWriter->endElement();
+ // a:xfrm
+ $objWriter->startElement('a:xfrm');
+ $objWriter->writeAttribute('rot', Shared_Drawing::degreesToAngle($pDrawing->getRotation()));
+ $objWriter->endElement();
- // a:prstGeom
- $objWriter->startElement('a:prstGeom');
- $objWriter->writeAttribute('prst', 'rect');
+ // a:prstGeom
+ $objWriter->startElement('a:prstGeom');
+ $objWriter->writeAttribute('prst', 'rect');
- // a:avLst
- $objWriter->writeElement('a:avLst', null);
+ // a:avLst
+ $objWriter->writeElement('a:avLst', null);
- $objWriter->endElement();
+ $objWriter->endElement();
-// // a:solidFill
-// $objWriter->startElement('a:solidFill');
+// // a:solidFill
+// $objWriter->startElement('a:solidFill');
-// // a:srgbClr
-// $objWriter->startElement('a:srgbClr');
-// $objWriter->writeAttribute('val', 'FFFFFF');
+// // a:srgbClr
+// $objWriter->startElement('a:srgbClr');
+// $objWriter->writeAttribute('val', 'FFFFFF');
///* SHADE
-// // a:shade
-// $objWriter->startElement('a:shade');
-// $objWriter->writeAttribute('val', '85000');
-// $objWriter->endElement();
+// // a:shade
+// $objWriter->startElement('a:shade');
+// $objWriter->writeAttribute('val', '85000');
+// $objWriter->endElement();
//*/
-// $objWriter->endElement();
+// $objWriter->endElement();
-// $objWriter->endElement();
+// $objWriter->endElement();
/*
- // a:ln
- $objWriter->startElement('a:ln');
- $objWriter->writeAttribute('w', '88900');
- $objWriter->writeAttribute('cap', 'sq');
+ // a:ln
+ $objWriter->startElement('a:ln');
+ $objWriter->writeAttribute('w', '88900');
+ $objWriter->writeAttribute('cap', 'sq');
- // a:solidFill
- $objWriter->startElement('a:solidFill');
+ // a:solidFill
+ $objWriter->startElement('a:solidFill');
- // a:srgbClr
- $objWriter->startElement('a:srgbClr');
- $objWriter->writeAttribute('val', 'FFFFFF');
- $objWriter->endElement();
+ // a:srgbClr
+ $objWriter->startElement('a:srgbClr');
+ $objWriter->writeAttribute('val', 'FFFFFF');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // a:miter
- $objWriter->startElement('a:miter');
- $objWriter->writeAttribute('lim', '800000');
- $objWriter->endElement();
+ // a:miter
+ $objWriter->startElement('a:miter');
+ $objWriter->writeAttribute('lim', '800000');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
*/
- if ($pDrawing->getShadow()->getVisible()) {
- // a:effectLst
- $objWriter->startElement('a:effectLst');
+ if ($pDrawing->getShadow()->getVisible()) {
+ // a:effectLst
+ $objWriter->startElement('a:effectLst');
- // a:outerShdw
- $objWriter->startElement('a:outerShdw');
- $objWriter->writeAttribute('blurRad', Shared_Drawing::pixelsToEMU($pDrawing->getShadow()->getBlurRadius()));
- $objWriter->writeAttribute('dist', Shared_Drawing::pixelsToEMU($pDrawing->getShadow()->getDistance()));
- $objWriter->writeAttribute('dir', Shared_Drawing::degreesToAngle($pDrawing->getShadow()->getDirection()));
- $objWriter->writeAttribute('algn', $pDrawing->getShadow()->getAlignment());
- $objWriter->writeAttribute('rotWithShape', '0');
+ // a:outerShdw
+ $objWriter->startElement('a:outerShdw');
+ $objWriter->writeAttribute('blurRad', Shared_Drawing::pixelsToEMU($pDrawing->getShadow()->getBlurRadius()));
+ $objWriter->writeAttribute('dist', Shared_Drawing::pixelsToEMU($pDrawing->getShadow()->getDistance()));
+ $objWriter->writeAttribute('dir', Shared_Drawing::degreesToAngle($pDrawing->getShadow()->getDirection()));
+ $objWriter->writeAttribute('algn', $pDrawing->getShadow()->getAlignment());
+ $objWriter->writeAttribute('rotWithShape', '0');
- // a:srgbClr
- $objWriter->startElement('a:srgbClr');
- $objWriter->writeAttribute('val', $pDrawing->getShadow()->getColor()->getRGB());
+ // a:srgbClr
+ $objWriter->startElement('a:srgbClr');
+ $objWriter->writeAttribute('val', $pDrawing->getShadow()->getColor()->getRGB());
- // a:alpha
- $objWriter->startElement('a:alpha');
- $objWriter->writeAttribute('val', $pDrawing->getShadow()->getAlpha() * 1000);
- $objWriter->endElement();
+ // a:alpha
+ $objWriter->startElement('a:alpha');
+ $objWriter->writeAttribute('val', $pDrawing->getShadow()->getAlpha() * 1000);
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
- }
+ $objWriter->endElement();
+ }
/*
- // a:scene3d
- $objWriter->startElement('a:scene3d');
+ // a:scene3d
+ $objWriter->startElement('a:scene3d');
- // a:camera
- $objWriter->startElement('a:camera');
- $objWriter->writeAttribute('prst', 'orthographicFront');
- $objWriter->endElement();
+ // a:camera
+ $objWriter->startElement('a:camera');
+ $objWriter->writeAttribute('prst', 'orthographicFront');
+ $objWriter->endElement();
- // a:lightRig
- $objWriter->startElement('a:lightRig');
- $objWriter->writeAttribute('rig', 'twoPt');
- $objWriter->writeAttribute('dir', 't');
+ // a:lightRig
+ $objWriter->startElement('a:lightRig');
+ $objWriter->writeAttribute('rig', 'twoPt');
+ $objWriter->writeAttribute('dir', 't');
- // a:rot
- $objWriter->startElement('a:rot');
- $objWriter->writeAttribute('lat', '0');
- $objWriter->writeAttribute('lon', '0');
- $objWriter->writeAttribute('rev', '0');
- $objWriter->endElement();
+ // a:rot
+ $objWriter->startElement('a:rot');
+ $objWriter->writeAttribute('lat', '0');
+ $objWriter->writeAttribute('lon', '0');
+ $objWriter->writeAttribute('rev', '0');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
*/
/*
- // a:sp3d
- $objWriter->startElement('a:sp3d');
+ // a:sp3d
+ $objWriter->startElement('a:sp3d');
- // a:bevelT
- $objWriter->startElement('a:bevelT');
- $objWriter->writeAttribute('w', '25400');
- $objWriter->writeAttribute('h', '19050');
- $objWriter->endElement();
+ // a:bevelT
+ $objWriter->startElement('a:bevelT');
+ $objWriter->writeAttribute('w', '25400');
+ $objWriter->writeAttribute('h', '19050');
+ $objWriter->endElement();
- // a:contourClr
- $objWriter->startElement('a:contourClr');
+ // a:contourClr
+ $objWriter->startElement('a:contourClr');
- // a:srgbClr
- $objWriter->startElement('a:srgbClr');
- $objWriter->writeAttribute('val', 'FFFFFF');
- $objWriter->endElement();
+ // a:srgbClr
+ $objWriter->startElement('a:srgbClr');
+ $objWriter->writeAttribute('val', 'FFFFFF');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
*/
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // xdr:clientData
- $objWriter->writeElement('xdr:clientData', null);
+ // xdr:clientData
+ $objWriter->writeElement('xdr:clientData', null);
- $objWriter->endElement();
- } else {
- throw new Writer_Exception("Invalid parameters passed.");
- }
- }
+ $objWriter->endElement();
+ } else {
+ throw new Writer_Exception("Invalid parameters passed.");
+ }
+ }
- /**
- * Write VML header/footer images to XML format
- *
- * @param PHPExcel\Worksheet $pWorksheet
- * @return string XML Output
- * @throws PHPExcel\Writer_Exception
- */
- public function writeVMLHeaderFooterImages(Worksheet $pWorksheet = null)
- {
- // Create XML writer
- $objWriter = null;
- if ($this->getParentWriter()->getUseDiskCaching()) {
- $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
- } else {
- $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_MEMORY);
- }
+ /**
+ * Write VML header/footer images to XML format
+ *
+ * @param PHPExcel\Worksheet $pWorksheet
+ * @return string XML Output
+ * @throws PHPExcel\Writer_Exception
+ */
+ public function writeVMLHeaderFooterImages(Worksheet $pWorksheet = null)
+ {
+ // Create XML writer
+ $objWriter = null;
+ if ($this->getParentWriter()->getUseDiskCaching()) {
+ $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
+ } else {
+ $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_MEMORY);
+ }
- // XML header
- $objWriter->startDocument('1.0','UTF-8','yes');
+ // XML header
+ $objWriter->startDocument('1.0','UTF-8','yes');
- // Header/footer images
- $images = $pWorksheet->getHeaderFooter()->getImages();
+ // Header/footer images
+ $images = $pWorksheet->getHeaderFooter()->getImages();
- // xml
- $objWriter->startElement('xml');
- $objWriter->writeAttribute('xmlns:v', 'urn:schemas-microsoft-com:vml');
- $objWriter->writeAttribute('xmlns:o', 'urn:schemas-microsoft-com:office:office');
- $objWriter->writeAttribute('xmlns:x', 'urn:schemas-microsoft-com:office:excel');
+ // xml
+ $objWriter->startElement('xml');
+ $objWriter->writeAttribute('xmlns:v', 'urn:schemas-microsoft-com:vml');
+ $objWriter->writeAttribute('xmlns:o', 'urn:schemas-microsoft-com:office:office');
+ $objWriter->writeAttribute('xmlns:x', 'urn:schemas-microsoft-com:office:excel');
- // o:shapelayout
- $objWriter->startElement('o:shapelayout');
- $objWriter->writeAttribute('v:ext', 'edit');
+ // o:shapelayout
+ $objWriter->startElement('o:shapelayout');
+ $objWriter->writeAttribute('v:ext', 'edit');
- // o:idmap
- $objWriter->startElement('o:idmap');
- $objWriter->writeAttribute('v:ext', 'edit');
- $objWriter->writeAttribute('data', '1');
- $objWriter->endElement();
+ // o:idmap
+ $objWriter->startElement('o:idmap');
+ $objWriter->writeAttribute('v:ext', 'edit');
+ $objWriter->writeAttribute('data', '1');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // v:shapetype
- $objWriter->startElement('v:shapetype');
- $objWriter->writeAttribute('id', '_x0000_t75');
- $objWriter->writeAttribute('coordsize', '21600,21600');
- $objWriter->writeAttribute('o:spt', '75');
- $objWriter->writeAttribute('o:preferrelative', 't');
- $objWriter->writeAttribute('path', 'm@4@5l@4@11@9@11@9@5xe');
- $objWriter->writeAttribute('filled', 'f');
- $objWriter->writeAttribute('stroked', 'f');
+ // v:shapetype
+ $objWriter->startElement('v:shapetype');
+ $objWriter->writeAttribute('id', '_x0000_t75');
+ $objWriter->writeAttribute('coordsize', '21600,21600');
+ $objWriter->writeAttribute('o:spt', '75');
+ $objWriter->writeAttribute('o:preferrelative', 't');
+ $objWriter->writeAttribute('path', 'm@4@5l@4@11@9@11@9@5xe');
+ $objWriter->writeAttribute('filled', 'f');
+ $objWriter->writeAttribute('stroked', 'f');
- // v:stroke
- $objWriter->startElement('v:stroke');
- $objWriter->writeAttribute('joinstyle', 'miter');
- $objWriter->endElement();
+ // v:stroke
+ $objWriter->startElement('v:stroke');
+ $objWriter->writeAttribute('joinstyle', 'miter');
+ $objWriter->endElement();
- // v:formulas
- $objWriter->startElement('v:formulas');
+ // v:formulas
+ $objWriter->startElement('v:formulas');
- // v:f
- $objWriter->startElement('v:f');
- $objWriter->writeAttribute('eqn', 'if lineDrawn pixelLineWidth 0');
- $objWriter->endElement();
+ // v:f
+ $objWriter->startElement('v:f');
+ $objWriter->writeAttribute('eqn', 'if lineDrawn pixelLineWidth 0');
+ $objWriter->endElement();
- // v:f
- $objWriter->startElement('v:f');
- $objWriter->writeAttribute('eqn', 'sum @0 1 0');
- $objWriter->endElement();
+ // v:f
+ $objWriter->startElement('v:f');
+ $objWriter->writeAttribute('eqn', 'sum @0 1 0');
+ $objWriter->endElement();
- // v:f
- $objWriter->startElement('v:f');
- $objWriter->writeAttribute('eqn', 'sum 0 0 @1');
- $objWriter->endElement();
+ // v:f
+ $objWriter->startElement('v:f');
+ $objWriter->writeAttribute('eqn', 'sum 0 0 @1');
+ $objWriter->endElement();
- // v:f
- $objWriter->startElement('v:f');
- $objWriter->writeAttribute('eqn', 'prod @2 1 2');
- $objWriter->endElement();
+ // v:f
+ $objWriter->startElement('v:f');
+ $objWriter->writeAttribute('eqn', 'prod @2 1 2');
+ $objWriter->endElement();
- // v:f
- $objWriter->startElement('v:f');
- $objWriter->writeAttribute('eqn', 'prod @3 21600 pixelWidth');
- $objWriter->endElement();
+ // v:f
+ $objWriter->startElement('v:f');
+ $objWriter->writeAttribute('eqn', 'prod @3 21600 pixelWidth');
+ $objWriter->endElement();
- // v:f
- $objWriter->startElement('v:f');
- $objWriter->writeAttribute('eqn', 'prod @3 21600 pixelHeight');
- $objWriter->endElement();
+ // v:f
+ $objWriter->startElement('v:f');
+ $objWriter->writeAttribute('eqn', 'prod @3 21600 pixelHeight');
+ $objWriter->endElement();
- // v:f
- $objWriter->startElement('v:f');
- $objWriter->writeAttribute('eqn', 'sum @0 0 1');
- $objWriter->endElement();
+ // v:f
+ $objWriter->startElement('v:f');
+ $objWriter->writeAttribute('eqn', 'sum @0 0 1');
+ $objWriter->endElement();
- // v:f
- $objWriter->startElement('v:f');
- $objWriter->writeAttribute('eqn', 'prod @6 1 2');
- $objWriter->endElement();
+ // v:f
+ $objWriter->startElement('v:f');
+ $objWriter->writeAttribute('eqn', 'prod @6 1 2');
+ $objWriter->endElement();
- // v:f
- $objWriter->startElement('v:f');
- $objWriter->writeAttribute('eqn', 'prod @7 21600 pixelWidth');
- $objWriter->endElement();
+ // v:f
+ $objWriter->startElement('v:f');
+ $objWriter->writeAttribute('eqn', 'prod @7 21600 pixelWidth');
+ $objWriter->endElement();
- // v:f
- $objWriter->startElement('v:f');
- $objWriter->writeAttribute('eqn', 'sum @8 21600 0');
- $objWriter->endElement();
+ // v:f
+ $objWriter->startElement('v:f');
+ $objWriter->writeAttribute('eqn', 'sum @8 21600 0');
+ $objWriter->endElement();
- // v:f
- $objWriter->startElement('v:f');
- $objWriter->writeAttribute('eqn', 'prod @7 21600 pixelHeight');
- $objWriter->endElement();
+ // v:f
+ $objWriter->startElement('v:f');
+ $objWriter->writeAttribute('eqn', 'prod @7 21600 pixelHeight');
+ $objWriter->endElement();
- // v:f
- $objWriter->startElement('v:f');
- $objWriter->writeAttribute('eqn', 'sum @10 21600 0');
- $objWriter->endElement();
+ // v:f
+ $objWriter->startElement('v:f');
+ $objWriter->writeAttribute('eqn', 'sum @10 21600 0');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // v:path
- $objWriter->startElement('v:path');
- $objWriter->writeAttribute('o:extrusionok', 'f');
- $objWriter->writeAttribute('gradientshapeok', 't');
- $objWriter->writeAttribute('o:connecttype', 'rect');
- $objWriter->endElement();
+ // v:path
+ $objWriter->startElement('v:path');
+ $objWriter->writeAttribute('o:extrusionok', 'f');
+ $objWriter->writeAttribute('gradientshapeok', 't');
+ $objWriter->writeAttribute('o:connecttype', 'rect');
+ $objWriter->endElement();
- // o:lock
- $objWriter->startElement('o:lock');
- $objWriter->writeAttribute('v:ext', 'edit');
- $objWriter->writeAttribute('aspectratio', 't');
- $objWriter->endElement();
+ // o:lock
+ $objWriter->startElement('o:lock');
+ $objWriter->writeAttribute('v:ext', 'edit');
+ $objWriter->writeAttribute('aspectratio', 't');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // Loop through images
- foreach ($images as $key => $value) {
- $this->_writeVMLHeaderFooterImage($objWriter, $key, $value);
- }
+ // Loop through images
+ foreach ($images as $key => $value) {
+ $this->_writeVMLHeaderFooterImage($objWriter, $key, $value);
+ }
- $objWriter->endElement();
+ $objWriter->endElement();
- // Return
- return $objWriter->getData();
- }
+ // Return
+ return $objWriter->getData();
+ }
- /**
- * Write VML comment to XML format
- *
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @param string $pReference Reference
- * @param PHPExcel\Worksheet_HeaderFooterDrawing $pImage Image
- * @throws PHPExcel\Writer_Exception
- */
- public function _writeVMLHeaderFooterImage(Shared_XMLWriter $objWriter = null, $pReference = '', Worksheet_HeaderFooterDrawing $pImage = null)
- {
- // Calculate object id
- preg_match('{(\d+)}', md5($pReference), $m);
- $id = 1500 + (substr($m[1], 0, 2) * 1);
+ /**
+ * Write VML comment to XML format
+ *
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @param string $pReference Reference
+ * @param PHPExcel\Worksheet_HeaderFooterDrawing $pImage Image
+ * @throws PHPExcel\Writer_Exception
+ */
+ public function _writeVMLHeaderFooterImage(Shared_XMLWriter $objWriter = null, $pReference = '', Worksheet_HeaderFooterDrawing $pImage = null)
+ {
+ // Calculate object id
+ preg_match('{(\d+)}', md5($pReference), $m);
+ $id = 1500 + (substr($m[1], 0, 2) * 1);
- // Calculate offset
- $width = $pImage->getWidth();
- $height = $pImage->getHeight();
- $marginLeft = $pImage->getOffsetX();
- $marginTop = $pImage->getOffsetY();
+ // Calculate offset
+ $width = $pImage->getWidth();
+ $height = $pImage->getHeight();
+ $marginLeft = $pImage->getOffsetX();
+ $marginTop = $pImage->getOffsetY();
- // v:shape
- $objWriter->startElement('v:shape');
- $objWriter->writeAttribute('id', $pReference);
- $objWriter->writeAttribute('o:spid', '_x0000_s' . $id);
- $objWriter->writeAttribute('type', '#_x0000_t75');
- $objWriter->writeAttribute('style', "position:absolute;margin-left:{$marginLeft}px;margin-top:{$marginTop}px;width:{$width}px;height:{$height}px;z-index:1");
+ // v:shape
+ $objWriter->startElement('v:shape');
+ $objWriter->writeAttribute('id', $pReference);
+ $objWriter->writeAttribute('o:spid', '_x0000_s' . $id);
+ $objWriter->writeAttribute('type', '#_x0000_t75');
+ $objWriter->writeAttribute('style', "position:absolute;margin-left:{$marginLeft}px;margin-top:{$marginTop}px;width:{$width}px;height:{$height}px;z-index:1");
- // v:imagedata
- $objWriter->startElement('v:imagedata');
- $objWriter->writeAttribute('o:relid', 'rId' . $pReference);
- $objWriter->writeAttribute('o:title', $pImage->getName());
- $objWriter->endElement();
+ // v:imagedata
+ $objWriter->startElement('v:imagedata');
+ $objWriter->writeAttribute('o:relid', 'rId' . $pReference);
+ $objWriter->writeAttribute('o:title', $pImage->getName());
+ $objWriter->endElement();
- // o:lock
- $objWriter->startElement('o:lock');
- $objWriter->writeAttribute('v:ext', 'edit');
- $objWriter->writeAttribute('rotation', 't');
- $objWriter->endElement();
+ // o:lock
+ $objWriter->startElement('o:lock');
+ $objWriter->writeAttribute('v:ext', 'edit');
+ $objWriter->writeAttribute('rotation', 't');
+ $objWriter->endElement();
- $objWriter->endElement();
- }
+ $objWriter->endElement();
+ }
- /**
- * Get an array of all drawings
- *
- * @param PHPExcel\Workbook $pPHPExcel
- * @return PHPExcel\Worksheet_Drawing[] All drawings in PHPExcel
- * @throws PHPExcel\Writer_Exception
- */
- public function allDrawings(Workbook $pPHPExcel = null)
- {
- // Get an array of all drawings
- $aDrawings = array();
+ /**
+ * Get an array of all drawings
+ *
+ * @param PHPExcel\Workbook $pPHPExcel
+ * @return PHPExcel\Worksheet_Drawing[] All drawings in PHPExcel
+ * @throws PHPExcel\Writer_Exception
+ */
+ public function allDrawings(Workbook $pPHPExcel = null)
+ {
+ // Get an array of all drawings
+ $aDrawings = array();
- // Loop through PHPExcel
- $sheetCount = $pPHPExcel->getSheetCount();
- for ($i = 0; $i < $sheetCount; ++$i) {
- // Loop through images and add to array
- $iterator = $pPHPExcel->getSheet($i)->getDrawingCollection()->getIterator();
- while ($iterator->valid()) {
- $aDrawings[] = $iterator->current();
+ // Loop through PHPExcel
+ $sheetCount = $pPHPExcel->getSheetCount();
+ for ($i = 0; $i < $sheetCount; ++$i) {
+ // Loop through images and add to array
+ $iterator = $pPHPExcel->getSheet($i)->getDrawingCollection()->getIterator();
+ while ($iterator->valid()) {
+ $aDrawings[] = $iterator->current();
- $iterator->next();
- }
- }
+ $iterator->next();
+ }
+ }
- return $aDrawings;
- }
+ return $aDrawings;
+ }
}
diff --git a/Classes/PHPExcel/Writer/Excel2007/Rels.php b/Classes/PHPExcel/Writer/Excel2007/Rels.php
index 3378459..8a0aef6 100644
--- a/Classes/PHPExcel/Writer/Excel2007/Rels.php
+++ b/Classes/PHPExcel/Writer/Excel2007/Rels.php
@@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\Writer_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,383 +37,383 @@ namespace PHPExcel;
*/
class Writer_Excel2007_Rels extends Writer_Excel2007_WriterPart
{
- /**
- * Write relationships to XML format
- *
- * @param PHPExcel $pPHPExcel
- * @return string XML Output
- * @throws PHPExcel\Writer_Exception
- */
- public function writeRelationships(Workbook $pPHPExcel = null)
- {
- // Create XML writer
- $objWriter = null;
- if ($this->getParentWriter()->getUseDiskCaching()) {
- $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
- } else {
- $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_MEMORY);
- }
+ /**
+ * Write relationships to XML format
+ *
+ * @param PHPExcel $pPHPExcel
+ * @return string XML Output
+ * @throws PHPExcel\Writer_Exception
+ */
+ public function writeRelationships(Workbook $pPHPExcel = null)
+ {
+ // Create XML writer
+ $objWriter = null;
+ if ($this->getParentWriter()->getUseDiskCaching()) {
+ $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
+ } else {
+ $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_MEMORY);
+ }
- // XML header
- $objWriter->startDocument('1.0','UTF-8','yes');
+ // XML header
+ $objWriter->startDocument('1.0','UTF-8','yes');
- // Relationships
- $objWriter->startElement('Relationships');
- $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/relationships');
+ // Relationships
+ $objWriter->startElement('Relationships');
+ $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/relationships');
- $customPropertyList = $pPHPExcel->getProperties()->getCustomProperties();
- if (!empty($customPropertyList)) {
- // Relationship docProps/app.xml
- $this->_writeRelationship(
- $objWriter,
- 4,
- 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties',
- 'docProps/custom.xml'
- );
+ $customPropertyList = $pPHPExcel->getProperties()->getCustomProperties();
+ if (!empty($customPropertyList)) {
+ // Relationship docProps/app.xml
+ $this->_writeRelationship(
+ $objWriter,
+ 4,
+ 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties',
+ 'docProps/custom.xml'
+ );
- }
+ }
- // Relationship docProps/app.xml
- $this->_writeRelationship(
- $objWriter,
- 3,
- 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties',
- 'docProps/app.xml'
- );
+ // Relationship docProps/app.xml
+ $this->_writeRelationship(
+ $objWriter,
+ 3,
+ 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties',
+ 'docProps/app.xml'
+ );
- // Relationship docProps/core.xml
- $this->_writeRelationship(
- $objWriter,
- 2,
- 'http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties',
- 'docProps/core.xml'
- );
+ // Relationship docProps/core.xml
+ $this->_writeRelationship(
+ $objWriter,
+ 2,
+ 'http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties',
+ 'docProps/core.xml'
+ );
- // Relationship xl/workbook.xml
- $this->_writeRelationship(
- $objWriter,
- 1,
- 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument',
- 'xl/workbook.xml'
- );
+ // Relationship xl/workbook.xml
+ $this->_writeRelationship(
+ $objWriter,
+ 1,
+ 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument',
+ 'xl/workbook.xml'
+ );
- $objWriter->endElement();
+ $objWriter->endElement();
- // Return
- return $objWriter->getData();
- }
+ // Return
+ return $objWriter->getData();
+ }
- /**
- * Write workbook relationships to XML format
- *
- * @param PHPExcel $pPHPExcel
- * @return string XML Output
- * @throws PHPExcel\Writer_Exception
- */
- public function writeWorkbookRelationships(Workbook $pPHPExcel = null)
- {
- // Create XML writer
- $objWriter = null;
- if ($this->getParentWriter()->getUseDiskCaching()) {
- $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
- } else {
- $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_MEMORY);
- }
+ /**
+ * Write workbook relationships to XML format
+ *
+ * @param PHPExcel $pPHPExcel
+ * @return string XML Output
+ * @throws PHPExcel\Writer_Exception
+ */
+ public function writeWorkbookRelationships(Workbook $pPHPExcel = null)
+ {
+ // Create XML writer
+ $objWriter = null;
+ if ($this->getParentWriter()->getUseDiskCaching()) {
+ $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
+ } else {
+ $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_MEMORY);
+ }
- // XML header
- $objWriter->startDocument('1.0','UTF-8','yes');
+ // XML header
+ $objWriter->startDocument('1.0','UTF-8','yes');
- // Relationships
- $objWriter->startElement('Relationships');
- $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/relationships');
+ // Relationships
+ $objWriter->startElement('Relationships');
+ $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/relationships');
- // Relationship styles.xml
- $this->_writeRelationship(
- $objWriter,
- 1,
- 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles',
- 'styles.xml'
- );
+ // Relationship styles.xml
+ $this->_writeRelationship(
+ $objWriter,
+ 1,
+ 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles',
+ 'styles.xml'
+ );
- // Relationship theme/theme1.xml
- $this->_writeRelationship(
- $objWriter,
- 2,
- 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme',
- 'theme/theme1.xml'
- );
+ // Relationship theme/theme1.xml
+ $this->_writeRelationship(
+ $objWriter,
+ 2,
+ 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme',
+ 'theme/theme1.xml'
+ );
- // Relationship sharedStrings.xml
- $this->_writeRelationship(
- $objWriter,
- 3,
- 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings',
- 'sharedStrings.xml'
- );
+ // Relationship sharedStrings.xml
+ $this->_writeRelationship(
+ $objWriter,
+ 3,
+ 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings',
+ 'sharedStrings.xml'
+ );
- // Relationships with sheets
- $sheetCount = $pPHPExcel->getSheetCount();
- for ($i = 0; $i < $sheetCount; ++$i) {
- $this->_writeRelationship(
- $objWriter,
- ($i + 1 + 3),
- 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet',
- 'worksheets/sheet' . ($i + 1) . '.xml'
- );
- }
+ // Relationships with sheets
+ $sheetCount = $pPHPExcel->getSheetCount();
+ for ($i = 0; $i < $sheetCount; ++$i) {
+ $this->_writeRelationship(
+ $objWriter,
+ ($i + 1 + 3),
+ 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet',
+ 'worksheets/sheet' . ($i + 1) . '.xml'
+ );
+ }
- $objWriter->endElement();
+ $objWriter->endElement();
- // Return
- return $objWriter->getData();
- }
+ // Return
+ return $objWriter->getData();
+ }
- /**
- * Write worksheet relationships to XML format
- *
- * Numbering is as follows:
- * rId1 - Drawings
- * rId_hyperlink_x - Hyperlinks
- *
- * @param PHPExcel\Worksheet $pWorksheet
- * @param int $pWorksheetId
- * @param boolean $includeCharts Flag indicating if we should write charts
- * @return string XML Output
- * @throws PHPExcel\Writer_Exception
- */
- public function writeWorksheetRelationships(Worksheet $pWorksheet = null, $pWorksheetId = 1, $includeCharts = FALSE)
- {
- // Create XML writer
- $objWriter = null;
- if ($this->getParentWriter()->getUseDiskCaching()) {
- $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
- } else {
- $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_MEMORY);
- }
+ /**
+ * Write worksheet relationships to XML format
+ *
+ * Numbering is as follows:
+ * rId1 - Drawings
+ * rId_hyperlink_x - Hyperlinks
+ *
+ * @param PHPExcel\Worksheet $pWorksheet
+ * @param int $pWorksheetId
+ * @param boolean $includeCharts Flag indicating if we should write charts
+ * @return string XML Output
+ * @throws PHPExcel\Writer_Exception
+ */
+ public function writeWorksheetRelationships(Worksheet $pWorksheet = null, $pWorksheetId = 1, $includeCharts = false)
+ {
+ // Create XML writer
+ $objWriter = null;
+ if ($this->getParentWriter()->getUseDiskCaching()) {
+ $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
+ } else {
+ $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_MEMORY);
+ }
- // XML header
- $objWriter->startDocument('1.0','UTF-8','yes');
+ // XML header
+ $objWriter->startDocument('1.0','UTF-8','yes');
- // Relationships
- $objWriter->startElement('Relationships');
- $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/relationships');
+ // Relationships
+ $objWriter->startElement('Relationships');
+ $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/relationships');
- // Write drawing relationships?
- $d = 0;
- if ($includeCharts) {
- $charts = $pWorksheet->getChartCollection();
- } else {
- $charts = array();
- }
- if (($pWorksheet->getDrawingCollection()->count() > 0) ||
- (count($charts) > 0)) {
- $this->_writeRelationship(
- $objWriter,
- ++$d,
- 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing',
- '../drawings/drawing' . $pWorksheetId . '.xml'
- );
- }
+ // Write drawing relationships?
+ $d = 0;
+ if ($includeCharts) {
+ $charts = $pWorksheet->getChartCollection();
+ } else {
+ $charts = array();
+ }
+ if (($pWorksheet->getDrawingCollection()->count() > 0) ||
+ (count($charts) > 0)) {
+ $this->_writeRelationship(
+ $objWriter,
+ ++$d,
+ 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing',
+ '../drawings/drawing' . $pWorksheetId . '.xml'
+ );
+ }
- // Write chart relationships?
-// $chartCount = 0;
-// $charts = $pWorksheet->getChartCollection();
-// echo 'Chart Rels: ' , count($charts) , '
* $objDrawing->setResizeProportional(true);
* $objDrawing->setWidthAndHeight(160,120);
- *
- *
+ *
';
-// if (count($charts) > 0) {
-// foreach($charts as $chart) {
-// $this->_writeRelationship(
-// $objWriter,
-// ++$d,
-// 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart',
-// '../charts/chart' . ++$chartCount . '.xml'
-// );
-// }
-// }
+ // Write chart relationships?
+// $chartCount = 0;
+// $charts = $pWorksheet->getChartCollection();
+// echo 'Chart Rels: ' , count($charts) , '
';
+// if (count($charts) > 0) {
+// foreach($charts as $chart) {
+// $this->_writeRelationship(
+// $objWriter,
+// ++$d,
+// 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart',
+// '../charts/chart' . ++$chartCount . '.xml'
+// );
+// }
+// }
//
- // Write hyperlink relationships?
- $i = 1;
- foreach ($pWorksheet->getHyperlinkCollection() as $hyperlink) {
- if (!$hyperlink->isInternal()) {
- $this->_writeRelationship(
- $objWriter,
- '_hyperlink_' . $i,
- 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink',
- $hyperlink->getUrl(),
- 'External'
- );
+ // Write hyperlink relationships?
+ $i = 1;
+ foreach ($pWorksheet->getHyperlinkCollection() as $hyperlink) {
+ if (!$hyperlink->isInternal()) {
+ $this->_writeRelationship(
+ $objWriter,
+ '_hyperlink_' . $i,
+ 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink',
+ $hyperlink->getUrl(),
+ 'External'
+ );
- ++$i;
- }
- }
+ ++$i;
+ }
+ }
- // Write comments relationship?
- $i = 1;
- if (count($pWorksheet->getComments()) > 0) {
- $this->_writeRelationship(
- $objWriter,
- '_comments_vml' . $i,
- 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing',
- '../drawings/vmlDrawing' . $pWorksheetId . '.vml'
- );
+ // Write comments relationship?
+ $i = 1;
+ if (count($pWorksheet->getComments()) > 0) {
+ $this->_writeRelationship(
+ $objWriter,
+ '_comments_vml' . $i,
+ 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing',
+ '../drawings/vmlDrawing' . $pWorksheetId . '.vml'
+ );
- $this->_writeRelationship(
- $objWriter,
- '_comments' . $i,
- 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments',
- '../comments' . $pWorksheetId . '.xml'
- );
- }
+ $this->_writeRelationship(
+ $objWriter,
+ '_comments' . $i,
+ 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments',
+ '../comments' . $pWorksheetId . '.xml'
+ );
+ }
- // Write header/footer relationship?
- $i = 1;
- if (count($pWorksheet->getHeaderFooter()->getImages()) > 0) {
- $this->_writeRelationship(
- $objWriter,
- '_headerfooter_vml' . $i,
- 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing',
- '../drawings/vmlDrawingHF' . $pWorksheetId . '.vml'
- );
- }
+ // Write header/footer relationship?
+ $i = 1;
+ if (count($pWorksheet->getHeaderFooter()->getImages()) > 0) {
+ $this->_writeRelationship(
+ $objWriter,
+ '_headerfooter_vml' . $i,
+ 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing',
+ '../drawings/vmlDrawingHF' . $pWorksheetId . '.vml'
+ );
+ }
- $objWriter->endElement();
+ $objWriter->endElement();
- // Return
- return $objWriter->getData();
- }
+ // Return
+ return $objWriter->getData();
+ }
- /**
- * Write drawing relationships to XML format
- *
- * @param PHPExcel\Worksheet $pWorksheet
- * @param int &$chartRef Chart ID
- * @param boolean $includeCharts Flag indicating if we should write charts
- * @return string XML Output
- * @throws PHPExcel\Writer_Exception
- */
- public function writeDrawingRelationships(Worksheet $pWorksheet = null, &$chartRef, $includeCharts = FALSE)
- {
- // Create XML writer
- $objWriter = null;
- if ($this->getParentWriter()->getUseDiskCaching()) {
- $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
- } else {
- $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_MEMORY);
- }
+ /**
+ * Write drawing relationships to XML format
+ *
+ * @param PHPExcel\Worksheet $pWorksheet
+ * @param int &$chartRef Chart ID
+ * @param boolean $includeCharts Flag indicating if we should write charts
+ * @return string XML Output
+ * @throws PHPExcel\Writer_Exception
+ */
+ public function writeDrawingRelationships(Worksheet $pWorksheet = null, &$chartRef, $includeCharts = false)
+ {
+ // Create XML writer
+ $objWriter = null;
+ if ($this->getParentWriter()->getUseDiskCaching()) {
+ $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
+ } else {
+ $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_MEMORY);
+ }
- // XML header
- $objWriter->startDocument('1.0','UTF-8','yes');
+ // XML header
+ $objWriter->startDocument('1.0','UTF-8','yes');
- // Relationships
- $objWriter->startElement('Relationships');
- $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/relationships');
+ // Relationships
+ $objWriter->startElement('Relationships');
+ $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/relationships');
- // Loop through images and write relationships
- $i = 1;
- $iterator = $pWorksheet->getDrawingCollection()->getIterator();
- while ($iterator->valid()) {
- if ($iterator->current() instanceof Worksheet_Drawing
- || $iterator->current() instanceof Worksheet_MemoryDrawing) {
- // Write relationship for image drawing
- $this->_writeRelationship(
- $objWriter,
- $i,
- 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image',
- '../media/' . str_replace(' ', '', $iterator->current()->getIndexedFilename())
- );
- }
+ // Loop through images and write relationships
+ $i = 1;
+ $iterator = $pWorksheet->getDrawingCollection()->getIterator();
+ while ($iterator->valid()) {
+ if ($iterator->current() instanceof Worksheet_Drawing
+ || $iterator->current() instanceof Worksheet_MemoryDrawing) {
+ // Write relationship for image drawing
+ $this->_writeRelationship(
+ $objWriter,
+ $i,
+ 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image',
+ '../media/' . str_replace(' ', '', $iterator->current()->getIndexedFilename())
+ );
+ }
- $iterator->next();
- ++$i;
- }
+ $iterator->next();
+ ++$i;
+ }
- if ($includeCharts) {
- // Loop through charts and write relationships
- $chartCount = $pWorksheet->getChartCount();
- if ($chartCount > 0) {
- for ($c = 0; $c < $chartCount; ++$c) {
- $this->_writeRelationship(
- $objWriter,
- $i++,
- 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart',
- '../charts/chart' . ++$chartRef . '.xml'
- );
- }
- }
- }
+ if ($includeCharts) {
+ // Loop through charts and write relationships
+ $chartCount = $pWorksheet->getChartCount();
+ if ($chartCount > 0) {
+ for ($c = 0; $c < $chartCount; ++$c) {
+ $this->_writeRelationship(
+ $objWriter,
+ $i++,
+ 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart',
+ '../charts/chart' . ++$chartRef . '.xml'
+ );
+ }
+ }
+ }
- $objWriter->endElement();
+ $objWriter->endElement();
- // Return
- return $objWriter->getData();
- }
+ // Return
+ return $objWriter->getData();
+ }
- /**
- * Write header/footer drawing relationships to XML format
- *
- * @param PHPExcel\Worksheet $pWorksheet
- * @return string XML Output
- * @throws PHPExcel\Writer_Exception
- */
- public function writeHeaderFooterDrawingRelationships(Worksheet $pWorksheet = null)
- {
- // Create XML writer
- $objWriter = null;
- if ($this->getParentWriter()->getUseDiskCaching()) {
- $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
- } else {
- $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_MEMORY);
- }
+ /**
+ * Write header/footer drawing relationships to XML format
+ *
+ * @param PHPExcel\Worksheet $pWorksheet
+ * @return string XML Output
+ * @throws PHPExcel\Writer_Exception
+ */
+ public function writeHeaderFooterDrawingRelationships(Worksheet $pWorksheet = null)
+ {
+ // Create XML writer
+ $objWriter = null;
+ if ($this->getParentWriter()->getUseDiskCaching()) {
+ $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
+ } else {
+ $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_MEMORY);
+ }
- // XML header
- $objWriter->startDocument('1.0','UTF-8','yes');
+ // XML header
+ $objWriter->startDocument('1.0','UTF-8','yes');
- // Relationships
- $objWriter->startElement('Relationships');
- $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/relationships');
+ // Relationships
+ $objWriter->startElement('Relationships');
+ $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/relationships');
- // Loop through images and write relationships
- foreach ($pWorksheet->getHeaderFooter()->getImages() as $key => $value) {
- // Write relationship for image drawing
- $this->_writeRelationship(
- $objWriter,
- $key,
- 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image',
- '../media/' . $value->getIndexedFilename()
- );
- }
+ // Loop through images and write relationships
+ foreach ($pWorksheet->getHeaderFooter()->getImages() as $key => $value) {
+ // Write relationship for image drawing
+ $this->_writeRelationship(
+ $objWriter,
+ $key,
+ 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image',
+ '../media/' . $value->getIndexedFilename()
+ );
+ }
- $objWriter->endElement();
+ $objWriter->endElement();
- // Return
- return $objWriter->getData();
- }
+ // Return
+ return $objWriter->getData();
+ }
- /**
- * Write Override content type
- *
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @param int $pId Relationship ID. rId will be prepended!
- * @param string $pType Relationship type
- * @param string $pTarget Relationship target
- * @param string $pTargetMode Relationship target mode
- * @throws PHPExcel\Writer_Exception
- */
- private function _writeRelationship(Shared_XMLWriter $objWriter = null, $pId = 1, $pType = '', $pTarget = '', $pTargetMode = '')
- {
- if ($pType != '' && $pTarget != '') {
- // Write relationship
- $objWriter->startElement('Relationship');
- $objWriter->writeAttribute('Id', 'rId' . $pId);
- $objWriter->writeAttribute('Type', $pType);
- $objWriter->writeAttribute('Target', $pTarget);
+ /**
+ * Write Override content type
+ *
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @param int $pId Relationship ID. rId will be prepended!
+ * @param string $pType Relationship type
+ * @param string $pTarget Relationship target
+ * @param string $pTargetMode Relationship target mode
+ * @throws PHPExcel\Writer_Exception
+ */
+ private function _writeRelationship(Shared_XMLWriter $objWriter = null, $pId = 1, $pType = '', $pTarget = '', $pTargetMode = '')
+ {
+ if ($pType != '' && $pTarget != '') {
+ // Write relationship
+ $objWriter->startElement('Relationship');
+ $objWriter->writeAttribute('Id', 'rId' . $pId);
+ $objWriter->writeAttribute('Type', $pType);
+ $objWriter->writeAttribute('Target', $pTarget);
- if ($pTargetMode != '') {
- $objWriter->writeAttribute('TargetMode', $pTargetMode);
- }
+ if ($pTargetMode != '') {
+ $objWriter->writeAttribute('TargetMode', $pTargetMode);
+ }
- $objWriter->endElement();
- } else {
- throw new Writer_Exception("Invalid parameters passed.");
- }
- }
+ $objWriter->endElement();
+ } else {
+ throw new Writer_Exception("Invalid parameters passed.");
+ }
+ }
}
diff --git a/Classes/PHPExcel/Writer/Excel2007/StringTable.php b/Classes/PHPExcel/Writer/Excel2007/StringTable.php
index ca41ab6..fc37304 100644
--- a/Classes/PHPExcel/Writer/Excel2007/StringTable.php
+++ b/Classes/PHPExcel/Writer/Excel2007/StringTable.php
@@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\Writer_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,285 +37,285 @@ namespace PHPExcel;
*/
class Writer_Excel2007_StringTable extends Writer_Excel2007_WriterPart
{
- /**
- * Create worksheet stringtable
- *
- * @param PHPExcel\Worksheet $pSheet Worksheet
- * @param string[] $pExistingTable Existing table to eventually merge with
- * @return string[] String table for worksheet
- * @throws PHPExcel\Writer_Exception
- */
- public function createStringTable($pSheet = null, $pExistingTable = null)
- {
- if ($pSheet !== NULL) {
- // Create string lookup table
- $aStringTable = array();
- $cellCollection = null;
- $aFlippedStringTable = null; // For faster lookup
+ /**
+ * Create worksheet stringtable
+ *
+ * @param PHPExcel\Worksheet $pSheet Worksheet
+ * @param string[] $pExistingTable Existing table to eventually merge with
+ * @return string[] String table for worksheet
+ * @throws PHPExcel\Writer_Exception
+ */
+ public function createStringTable($pSheet = null, $pExistingTable = null)
+ {
+ if ($pSheet !== null) {
+ // Create string lookup table
+ $aStringTable = array();
+ $cellCollection = null;
+ $aFlippedStringTable = null; // For faster lookup
- // Is an existing table given?
- if (($pExistingTable !== NULL) && is_array($pExistingTable)) {
- $aStringTable = $pExistingTable;
- }
+ // Is an existing table given?
+ if (($pExistingTable !== null) && is_array($pExistingTable)) {
+ $aStringTable = $pExistingTable;
+ }
- // Fill index array
- $aFlippedStringTable = $this->flipStringTable($aStringTable);
+ // Fill index array
+ $aFlippedStringTable = $this->flipStringTable($aStringTable);
- // Loop through cells
- foreach ($pSheet->getCellCollection() as $cellID) {
- $cell = $pSheet->getCell($cellID);
- $cellValue = $cell->getValue();
- if (!is_object($cellValue) &&
- ($cellValue !== NULL) &&
- $cellValue !== '' &&
- !isset($aFlippedStringTable[$cellValue]) &&
- ($cell->getDataType() == Cell_DataType::TYPE_STRING || $cell->getDataType() == Cell_DataType::TYPE_STRING2 || $cell->getDataType() == Cell_DataType::TYPE_NULL)) {
- $aStringTable[] = $cellValue;
- $aFlippedStringTable[$cellValue] = true;
- } elseif ($cellValue instanceof RichText &&
- ($cellValue !== NULL) &&
- !isset($aFlippedStringTable[$cellValue->getHashCode()])) {
- $aStringTable[] = $cellValue;
- $aFlippedStringTable[$cellValue->getHashCode()] = true;
- }
- }
+ // Loop through cells
+ foreach ($pSheet->getCellCollection() as $cellID) {
+ $cell = $pSheet->getCell($cellID);
+ $cellValue = $cell->getValue();
+ if (!is_object($cellValue) &&
+ ($cellValue !== null) &&
+ $cellValue !== '' &&
+ !isset($aFlippedStringTable[$cellValue]) &&
+ ($cell->getDataType() == Cell_DataType::TYPE_STRING || $cell->getDataType() == Cell_DataType::TYPE_STRING2 || $cell->getDataType() == Cell_DataType::TYPE_NULL)) {
+ $aStringTable[] = $cellValue;
+ $aFlippedStringTable[$cellValue] = true;
+ } elseif ($cellValue instanceof RichText &&
+ ($cellValue !== null) &&
+ !isset($aFlippedStringTable[$cellValue->getHashCode()])) {
+ $aStringTable[] = $cellValue;
+ $aFlippedStringTable[$cellValue->getHashCode()] = true;
+ }
+ }
- // Return
- return $aStringTable;
- } else {
- throw new Writer_Exception("Invalid PHPExcel\Worksheet object passed.");
- }
- }
+ // Return
+ return $aStringTable;
+ } else {
+ throw new Writer_Exception("Invalid PHPExcel\Worksheet object passed.");
+ }
+ }
- /**
- * Write string table to XML format
- *
- * @param string[] $pStringTable
- * @return string XML Output
- * @throws PHPExcel\Writer_Exception
- */
- public function writeStringTable($pStringTable = null)
- {
- if ($pStringTable !== NULL) {
- // Create XML writer
- $objWriter = null;
- if ($this->getParentWriter()->getUseDiskCaching()) {
- $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
- } else {
- $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_MEMORY);
- }
+ /**
+ * Write string table to XML format
+ *
+ * @param string[] $pStringTable
+ * @return string XML Output
+ * @throws PHPExcel\Writer_Exception
+ */
+ public function writeStringTable($pStringTable = null)
+ {
+ if ($pStringTable !== null) {
+ // Create XML writer
+ $objWriter = null;
+ if ($this->getParentWriter()->getUseDiskCaching()) {
+ $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
+ } else {
+ $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_MEMORY);
+ }
- // XML header
- $objWriter->startDocument('1.0','UTF-8','yes');
+ // XML header
+ $objWriter->startDocument('1.0','UTF-8','yes');
- // String table
- $objWriter->startElement('sst');
- $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main');
- $objWriter->writeAttribute('uniqueCount', count($pStringTable));
+ // String table
+ $objWriter->startElement('sst');
+ $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main');
+ $objWriter->writeAttribute('uniqueCount', count($pStringTable));
- // Loop through string table
- foreach ($pStringTable as $textElement) {
- $objWriter->startElement('si');
+ // Loop through string table
+ foreach ($pStringTable as $textElement) {
+ $objWriter->startElement('si');
- if (! $textElement instanceof RichText) {
- $textToWrite = Shared_String::ControlCharacterPHP2OOXML( $textElement );
- $objWriter->startElement('t');
- if ($textToWrite !== trim($textToWrite)) {
- $objWriter->writeAttribute('xml:space', 'preserve');
- }
- $objWriter->writeRawData($textToWrite);
- $objWriter->endElement();
- } else if ($textElement instanceof RichText) {
- $this->writeRichText($objWriter, $textElement);
- }
+ if (! $textElement instanceof RichText) {
+ $textToWrite = Shared_String::ControlCharacterPHP2OOXML( $textElement );
+ $objWriter->startElement('t');
+ if ($textToWrite !== trim($textToWrite)) {
+ $objWriter->writeAttribute('xml:space', 'preserve');
+ }
+ $objWriter->writeRawData($textToWrite);
+ $objWriter->endElement();
+ } else if ($textElement instanceof RichText) {
+ $this->writeRichText($objWriter, $textElement);
+ }
$objWriter->endElement();
- }
+ }
- $objWriter->endElement();
+ $objWriter->endElement();
- // Return
- return $objWriter->getData();
- } else {
- throw new Writer_Exception("Invalid string table array passed.");
- }
- }
+ // Return
+ return $objWriter->getData();
+ } else {
+ throw new Writer_Exception("Invalid string table array passed.");
+ }
+ }
- /**
- * Write Rich Text
- *
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel\RichText $pRichText Rich text
- * @param string $prefix Optional Namespace prefix
- * @throws PHPExcel\Writer_Exception
- */
- public function writeRichText(Shared_XMLWriter $objWriter = null, RichText $pRichText = null, $prefix=NULL)
- {
- if ($prefix !== NULL)
- $prefix .= ':';
- // Loop through rich text elements
- $elements = $pRichText->getRichTextElements();
- foreach ($elements as $element) {
- // r
- $objWriter->startElement($prefix.'r');
+ /**
+ * Write Rich Text
+ *
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel\RichText $pRichText Rich text
+ * @param string $prefix Optional Namespace prefix
+ * @throws PHPExcel\Writer_Exception
+ */
+ public function writeRichText(Shared_XMLWriter $objWriter = null, RichText $pRichText = null, $prefix=null)
+ {
+ if ($prefix !== null)
+ $prefix .= ':';
+ // Loop through rich text elements
+ $elements = $pRichText->getRichTextElements();
+ foreach ($elements as $element) {
+ // r
+ $objWriter->startElement($prefix.'r');
- // rPr
- if ($element instanceof RichText_Run) {
- // rPr
- $objWriter->startElement($prefix.'rPr');
+ // rPr
+ if ($element instanceof RichText_Run) {
+ // rPr
+ $objWriter->startElement($prefix.'rPr');
- // rFont
- $objWriter->startElement($prefix.'rFont');
- $objWriter->writeAttribute('val', $element->getFont()->getName());
- $objWriter->endElement();
+ // rFont
+ $objWriter->startElement($prefix.'rFont');
+ $objWriter->writeAttribute('val', $element->getFont()->getName());
+ $objWriter->endElement();
- // Bold
- $objWriter->startElement($prefix.'b');
- $objWriter->writeAttribute('val', ($element->getFont()->getBold() ? 'true' : 'false'));
- $objWriter->endElement();
+ // Bold
+ $objWriter->startElement($prefix.'b');
+ $objWriter->writeAttribute('val', ($element->getFont()->getBold() ? 'true' : 'false'));
+ $objWriter->endElement();
- // Italic
- $objWriter->startElement($prefix.'i');
- $objWriter->writeAttribute('val', ($element->getFont()->getItalic() ? 'true' : 'false'));
- $objWriter->endElement();
+ // Italic
+ $objWriter->startElement($prefix.'i');
+ $objWriter->writeAttribute('val', ($element->getFont()->getItalic() ? 'true' : 'false'));
+ $objWriter->endElement();
- // Superscript / subscript
- if ($element->getFont()->getSuperScript() || $element->getFont()->getSubScript()) {
- $objWriter->startElement($prefix.'vertAlign');
- if ($element->getFont()->getSuperScript()) {
- $objWriter->writeAttribute('val', 'superscript');
- } else if ($element->getFont()->getSubScript()) {
- $objWriter->writeAttribute('val', 'subscript');
- }
- $objWriter->endElement();
- }
+ // Superscript / subscript
+ if ($element->getFont()->getSuperScript() || $element->getFont()->getSubScript()) {
+ $objWriter->startElement($prefix.'vertAlign');
+ if ($element->getFont()->getSuperScript()) {
+ $objWriter->writeAttribute('val', 'superscript');
+ } else if ($element->getFont()->getSubScript()) {
+ $objWriter->writeAttribute('val', 'subscript');
+ }
+ $objWriter->endElement();
+ }
- // Strikethrough
- $objWriter->startElement($prefix.'strike');
- $objWriter->writeAttribute('val', ($element->getFont()->getStrikethrough() ? 'true' : 'false'));
- $objWriter->endElement();
+ // Strikethrough
+ $objWriter->startElement($prefix.'strike');
+ $objWriter->writeAttribute('val', ($element->getFont()->getStrikethrough() ? 'true' : 'false'));
+ $objWriter->endElement();
- // Color
- $objWriter->startElement($prefix.'color');
- $objWriter->writeAttribute('rgb', $element->getFont()->getColor()->getARGB());
- $objWriter->endElement();
+ // Color
+ $objWriter->startElement($prefix.'color');
+ $objWriter->writeAttribute('rgb', $element->getFont()->getColor()->getARGB());
+ $objWriter->endElement();
- // Size
- $objWriter->startElement($prefix.'sz');
- $objWriter->writeAttribute('val', $element->getFont()->getSize());
- $objWriter->endElement();
+ // Size
+ $objWriter->startElement($prefix.'sz');
+ $objWriter->writeAttribute('val', $element->getFont()->getSize());
+ $objWriter->endElement();
- // Underline
- $objWriter->startElement($prefix.'u');
- $objWriter->writeAttribute('val', $element->getFont()->getUnderline());
- $objWriter->endElement();
+ // Underline
+ $objWriter->startElement($prefix.'u');
+ $objWriter->writeAttribute('val', $element->getFont()->getUnderline());
+ $objWriter->endElement();
- $objWriter->endElement();
- }
+ $objWriter->endElement();
+ }
- // t
- $objWriter->startElement($prefix.'t');
- $objWriter->writeAttribute('xml:space', 'preserve');
- $objWriter->writeRawData(Shared_String::ControlCharacterPHP2OOXML( $element->getText() ));
- $objWriter->endElement();
+ // t
+ $objWriter->startElement($prefix.'t');
+ $objWriter->writeAttribute('xml:space', 'preserve');
+ $objWriter->writeRawData(Shared_String::ControlCharacterPHP2OOXML( $element->getText() ));
+ $objWriter->endElement();
- $objWriter->endElement();
- }
- }
+ $objWriter->endElement();
+ }
+ }
- /**
- * Write Rich Text
- *
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @param string|PHPExcel\RichText $pRichText text string or Rich text
- * @param string $prefix Optional Namespace prefix
- * @throws PHPExcel\Writer_Exception
- */
- public function writeRichTextForCharts(Shared_XMLWriter $objWriter = null, $pRichText = null, $prefix=NULL)
- {
- if (!$pRichText instanceof RichText) {
- $textRun = $pRichText;
- $pRichText = new RichText();
- $pRichText->createTextRun($textRun);
- }
+ /**
+ * Write Rich Text
+ *
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @param string|PHPExcel\RichText $pRichText text string or Rich text
+ * @param string $prefix Optional Namespace prefix
+ * @throws PHPExcel\Writer_Exception
+ */
+ public function writeRichTextForCharts(Shared_XMLWriter $objWriter = null, $pRichText = null, $prefix=null)
+ {
+ if (!$pRichText instanceof RichText) {
+ $textRun = $pRichText;
+ $pRichText = new RichText();
+ $pRichText->createTextRun($textRun);
+ }
- if ($prefix !== NULL)
- $prefix .= ':';
- // Loop through rich text elements
- $elements = $pRichText->getRichTextElements();
- foreach ($elements as $element) {
- // r
- $objWriter->startElement($prefix.'r');
+ if ($prefix !== null)
+ $prefix .= ':';
+ // Loop through rich text elements
+ $elements = $pRichText->getRichTextElements();
+ foreach ($elements as $element) {
+ // r
+ $objWriter->startElement($prefix.'r');
- // rPr
- $objWriter->startElement($prefix.'rPr');
+ // rPr
+ $objWriter->startElement($prefix.'rPr');
- // Bold
- $objWriter->writeAttribute('b', ($element->getFont()->getBold() ? 1 : 0));
- // Italic
- $objWriter->writeAttribute('i', ($element->getFont()->getItalic() ? 1 : 0));
- // Underline
- $underlineType = $element->getFont()->getUnderline();
- switch($underlineType) {
- case 'single' :
- $underlineType = 'sng';
- break;
- case 'double' :
- $underlineType = 'dbl';
- break;
- }
- $objWriter->writeAttribute('u', $underlineType);
- // Strikethrough
- $objWriter->writeAttribute('strike', ($element->getFont()->getStrikethrough() ? 'sngStrike' : 'noStrike'));
+ // Bold
+ $objWriter->writeAttribute('b', ($element->getFont()->getBold() ? 1 : 0));
+ // Italic
+ $objWriter->writeAttribute('i', ($element->getFont()->getItalic() ? 1 : 0));
+ // Underline
+ $underlineType = $element->getFont()->getUnderline();
+ switch($underlineType) {
+ case 'single' :
+ $underlineType = 'sng';
+ break;
+ case 'double' :
+ $underlineType = 'dbl';
+ break;
+ }
+ $objWriter->writeAttribute('u', $underlineType);
+ // Strikethrough
+ $objWriter->writeAttribute('strike', ($element->getFont()->getStrikethrough() ? 'sngStrike' : 'noStrike'));
- // rFont
- $objWriter->startElement($prefix.'latin');
- $objWriter->writeAttribute('typeface', $element->getFont()->getName());
- $objWriter->endElement();
+ // rFont
+ $objWriter->startElement($prefix.'latin');
+ $objWriter->writeAttribute('typeface', $element->getFont()->getName());
+ $objWriter->endElement();
- // Superscript / subscript
-// if ($element->getFont()->getSuperScript() || $element->getFont()->getSubScript()) {
-// $objWriter->startElement($prefix.'vertAlign');
-// if ($element->getFont()->getSuperScript()) {
-// $objWriter->writeAttribute('val', 'superscript');
-// } else if ($element->getFont()->getSubScript()) {
-// $objWriter->writeAttribute('val', 'subscript');
-// }
-// $objWriter->endElement();
-// }
+ // Superscript / subscript
+// if ($element->getFont()->getSuperScript() || $element->getFont()->getSubScript()) {
+// $objWriter->startElement($prefix.'vertAlign');
+// if ($element->getFont()->getSuperScript()) {
+// $objWriter->writeAttribute('val', 'superscript');
+// } else if ($element->getFont()->getSubScript()) {
+// $objWriter->writeAttribute('val', 'subscript');
+// }
+// $objWriter->endElement();
+// }
//
- $objWriter->endElement();
+ $objWriter->endElement();
- // t
- $objWriter->startElement($prefix.'t');
-// $objWriter->writeAttribute('xml:space', 'preserve'); // Excel2010 accepts, Excel2007 complains
- $objWriter->writeRawData(Shared_String::ControlCharacterPHP2OOXML( $element->getText() ));
- $objWriter->endElement();
+ // t
+ $objWriter->startElement($prefix.'t');
+// $objWriter->writeAttribute('xml:space', 'preserve'); // Excel2010 accepts, Excel2007 complains
+ $objWriter->writeRawData(Shared_String::ControlCharacterPHP2OOXML( $element->getText() ));
+ $objWriter->endElement();
- $objWriter->endElement();
- }
- }
+ $objWriter->endElement();
+ }
+ }
- /**
- * Flip string table (for index searching)
- *
- * @param array $stringTable Stringtable
- * @return array
- */
- public function flipStringTable($stringTable = array()) {
- // Return value
- $returnValue = array();
+ /**
+ * Flip string table (for index searching)
+ *
+ * @param array $stringTable Stringtable
+ * @return array
+ */
+ public function flipStringTable($stringTable = array()) {
+ // Return value
+ $returnValue = array();
- // Loop through stringtable and add flipped items to $returnValue
- foreach ($stringTable as $key => $value) {
- if (! $value instanceof RichText) {
- $returnValue[$value] = $key;
- } else if ($value instanceof RichText) {
- $returnValue[$value->getHashCode()] = $key;
- }
- }
+ // Loop through stringtable and add flipped items to $returnValue
+ foreach ($stringTable as $key => $value) {
+ if (! $value instanceof RichText) {
+ $returnValue[$value] = $key;
+ } else if ($value instanceof RichText) {
+ $returnValue[$value->getHashCode()] = $key;
+ }
+ }
- // Return
- return $returnValue;
- }
+ // Return
+ return $returnValue;
+ }
}
diff --git a/Classes/PHPExcel/Writer/Excel2007/Style.php b/Classes/PHPExcel/Writer/Excel2007/Style.php
index edac85b..f79e81a 100644
--- a/Classes/PHPExcel/Writer/Excel2007/Style.php
+++ b/Classes/PHPExcel/Writer/Excel2007/Style.php
@@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\Writer_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,667 +37,667 @@ namespace PHPExcel;
*/
class Writer_Excel2007_Style extends Writer_Excel2007_WriterPart
{
- /**
- * Write styles to XML format
- *
- * @param PHPExcel\Workbook $pPHPExcel
- * @return string XML Output
- * @throws PHPExcel\Writer_Exception
- */
- public function writeStyles(Workbook $pPHPExcel = null)
- {
- // Create XML writer
- $objWriter = null;
- if ($this->getParentWriter()->getUseDiskCaching()) {
- $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
- } else {
- $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_MEMORY);
- }
-
- // XML header
- $objWriter->startDocument('1.0','UTF-8','yes');
-
- // styleSheet
- $objWriter->startElement('styleSheet');
- $objWriter->writeAttribute('xml:space', 'preserve');
- $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main');
-
- // numFmts
- $objWriter->startElement('numFmts');
- $objWriter->writeAttribute('count', $this->getParentWriter()->getNumFmtHashTable()->count());
-
- // numFmt
- for ($i = 0; $i < $this->getParentWriter()->getNumFmtHashTable()->count(); ++$i) {
- $this->_writeNumFmt($objWriter, $this->getParentWriter()->getNumFmtHashTable()->getByIndex($i), $i);
- }
-
- $objWriter->endElement();
-
- // fonts
- $objWriter->startElement('fonts');
- $objWriter->writeAttribute('count', $this->getParentWriter()->getFontHashTable()->count());
-
- // font
- for ($i = 0; $i < $this->getParentWriter()->getFontHashTable()->count(); ++$i) {
- $this->_writeFont($objWriter, $this->getParentWriter()->getFontHashTable()->getByIndex($i));
- }
-
- $objWriter->endElement();
-
- // fills
- $objWriter->startElement('fills');
- $objWriter->writeAttribute('count', $this->getParentWriter()->getFillHashTable()->count());
-
- // fill
- for ($i = 0; $i < $this->getParentWriter()->getFillHashTable()->count(); ++$i) {
- $this->_writeFill($objWriter, $this->getParentWriter()->getFillHashTable()->getByIndex($i));
- }
-
- $objWriter->endElement();
-
- // borders
- $objWriter->startElement('borders');
- $objWriter->writeAttribute('count', $this->getParentWriter()->getBordersHashTable()->count());
-
- // border
- for ($i = 0; $i < $this->getParentWriter()->getBordersHashTable()->count(); ++$i) {
- $this->_writeBorder($objWriter, $this->getParentWriter()->getBordersHashTable()->getByIndex($i));
- }
-
- $objWriter->endElement();
-
- // cellStyleXfs
- $objWriter->startElement('cellStyleXfs');
- $objWriter->writeAttribute('count', 1);
-
- // xf
- $objWriter->startElement('xf');
- $objWriter->writeAttribute('numFmtId', 0);
- $objWriter->writeAttribute('fontId', 0);
- $objWriter->writeAttribute('fillId', 0);
- $objWriter->writeAttribute('borderId', 0);
- $objWriter->endElement();
-
- $objWriter->endElement();
-
- // cellXfs
- $objWriter->startElement('cellXfs');
- $objWriter->writeAttribute('count', count($pPHPExcel->getCellXfCollection()));
-
- // xf
- foreach ($pPHPExcel->getCellXfCollection() as $cellXf) {
- $this->_writeCellStyleXf($objWriter, $cellXf, $pPHPExcel);
- }
-
- $objWriter->endElement();
-
- // cellStyles
- $objWriter->startElement('cellStyles');
- $objWriter->writeAttribute('count', 1);
-
- // cellStyle
- $objWriter->startElement('cellStyle');
- $objWriter->writeAttribute('name', 'Normal');
- $objWriter->writeAttribute('xfId', 0);
- $objWriter->writeAttribute('builtinId', 0);
- $objWriter->endElement();
-
- $objWriter->endElement();
-
- // dxfs
- $objWriter->startElement('dxfs');
- $objWriter->writeAttribute('count', $this->getParentWriter()->getStylesConditionalHashTable()->count());
-
- // dxf
- for ($i = 0; $i < $this->getParentWriter()->getStylesConditionalHashTable()->count(); ++$i) {
- $this->_writeCellStyleDxf($objWriter, $this->getParentWriter()->getStylesConditionalHashTable()->getByIndex($i)->getStyle());
- }
-
- $objWriter->endElement();
-
- // tableStyles
- $objWriter->startElement('tableStyles');
- $objWriter->writeAttribute('defaultTableStyle', 'TableStyleMedium9');
- $objWriter->writeAttribute('defaultPivotStyle', 'PivotTableStyle1');
- $objWriter->endElement();
-
- $objWriter->endElement();
-
- // Return
- return $objWriter->getData();
- }
-
- /**
- * Write Fill
- *
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel\Style_Fill $pFill Fill style
- * @throws PHPExcel\Writer_Exception
- */
- private function _writeFill(Shared_XMLWriter $objWriter = null, Style_Fill $pFill = null)
- {
- // Check if this is a pattern type or gradient type
- if ($pFill->getFillType() === Style_Fill::FILL_GRADIENT_LINEAR ||
- $pFill->getFillType() === Style_Fill::FILL_GRADIENT_PATH) {
- // Gradient fill
- $this->_writeGradientFill($objWriter, $pFill);
- } elseif($pFill->getFillType() !== NULL) {
- // Pattern fill
- $this->_writePatternFill($objWriter, $pFill);
- }
- }
-
- /**
- * Write Gradient Fill
- *
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel\Style_Fill $pFill Fill style
- * @throws PHPExcel\Writer_Exception
- */
- private function _writeGradientFill(Shared_XMLWriter $objWriter = null, Style_Fill $pFill = null)
- {
- // fill
- $objWriter->startElement('fill');
-
- // gradientFill
- $objWriter->startElement('gradientFill');
- $objWriter->writeAttribute('type', $pFill->getFillType());
- $objWriter->writeAttribute('degree', $pFill->getRotation());
-
- // stop
- $objWriter->startElement('stop');
- $objWriter->writeAttribute('position', '0');
-
- // color
- $objWriter->startElement('color');
- $objWriter->writeAttribute('rgb', $pFill->getStartColor()->getARGB());
- $objWriter->endElement();
-
- $objWriter->endElement();
-
- // stop
- $objWriter->startElement('stop');
- $objWriter->writeAttribute('position', '1');
-
- // color
- $objWriter->startElement('color');
- $objWriter->writeAttribute('rgb', $pFill->getEndColor()->getARGB());
- $objWriter->endElement();
-
- $objWriter->endElement();
-
- $objWriter->endElement();
-
- $objWriter->endElement();
- }
-
- /**
- * Write Pattern Fill
- *
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel\Style_Fill $pFill Fill style
- * @throws PHPExcel\Writer_Exception
- */
- private function _writePatternFill(Shared_XMLWriter $objWriter = null, Style_Fill $pFill = null)
- {
- // fill
- $objWriter->startElement('fill');
-
- // patternFill
- $objWriter->startElement('patternFill');
- $objWriter->writeAttribute('patternType', $pFill->getFillType());
-
- if ($pFill->getFillType() !== Style_Fill::FILL_NONE) {
- // fgColor
- if ($pFill->getStartColor()->getARGB()) {
- $objWriter->startElement('fgColor');
- $objWriter->writeAttribute('rgb', $pFill->getStartColor()->getARGB());
- $objWriter->endElement();
- }
- }
- if ($pFill->getFillType() !== Style_Fill::FILL_NONE) {
- // bgColor
- if ($pFill->getEndColor()->getARGB()) {
- $objWriter->startElement('bgColor');
- $objWriter->writeAttribute('rgb', $pFill->getEndColor()->getARGB());
- $objWriter->endElement();
- }
- }
-
- $objWriter->endElement();
-
- $objWriter->endElement();
- }
-
- /**
- * Write Font
- *
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel\Style_Font $pFont Font style
- * @throws PHPExcel\Writer_Exception
- */
- private function _writeFont(Shared_XMLWriter $objWriter = null, Style_Font $pFont = null)
- {
- // font
- $objWriter->startElement('font');
- // Weird! The order of these elements actually makes a difference when opening Excel2007
- // files in Excel2003 with the compatibility pack. It's not documented behaviour,
- // and makes for a real WTF!
-
- // Bold. We explicitly write this element also when false (like MS Office Excel 2007 does
- // for conditional formatting). Otherwise it will apparently not be picked up in conditional
- // formatting style dialog
- if ($pFont->getBold() !== NULL) {
- $objWriter->startElement('b');
- $objWriter->writeAttribute('val', $pFont->getBold() ? '1' : '0');
- $objWriter->endElement();
- }
-
- // Italic
- if ($pFont->getItalic() !== NULL) {
- $objWriter->startElement('i');
- $objWriter->writeAttribute('val', $pFont->getItalic() ? '1' : '0');
- $objWriter->endElement();
- }
-
- // Strikethrough
- if ($pFont->getStrikethrough() !== NULL) {
- $objWriter->startElement('strike');
- $objWriter->writeAttribute('val', $pFont->getStrikethrough() ? '1' : '0');
- $objWriter->endElement();
- }
-
- // Underline
- if ($pFont->getUnderline() !== NULL) {
- $objWriter->startElement('u');
- $objWriter->writeAttribute('val', $pFont->getUnderline());
- $objWriter->endElement();
- }
-
- // Superscript / subscript
- if ($pFont->getSuperScript() === TRUE || $pFont->getSubScript() === TRUE) {
- $objWriter->startElement('vertAlign');
- if ($pFont->getSuperScript() === TRUE) {
- $objWriter->writeAttribute('val', 'superscript');
- } else if ($pFont->getSubScript() === TRUE) {
- $objWriter->writeAttribute('val', 'subscript');
- }
- $objWriter->endElement();
- }
-
- // Size
- if ($pFont->getSize() !== NULL) {
- $objWriter->startElement('sz');
- $objWriter->writeAttribute('val', $pFont->getSize());
- $objWriter->endElement();
- }
-
- // Foreground color
- if ($pFont->getColor()->getARGB() !== NULL) {
- $objWriter->startElement('color');
- $objWriter->writeAttribute('rgb', $pFont->getColor()->getARGB());
- $objWriter->endElement();
- }
-
- // Name
- if ($pFont->getName() !== NULL) {
- $objWriter->startElement('name');
- $objWriter->writeAttribute('val', $pFont->getName());
- $objWriter->endElement();
- }
-
- $objWriter->endElement();
- }
-
- /**
- * Write Border
- *
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel\Style_Borders $pBorders Borders style
- * @throws PHPExcel\Writer_Exception
- */
- private function _writeBorder(Shared_XMLWriter $objWriter = null, Style_Borders $pBorders = null)
- {
- // Write border
- $objWriter->startElement('border');
- // Diagonal?
- switch ($pBorders->getDiagonalDirection()) {
- case Style_Borders::DIAGONAL_UP:
- $objWriter->writeAttribute('diagonalUp', 'true');
- $objWriter->writeAttribute('diagonalDown', 'false');
- break;
- case Style_Borders::DIAGONAL_DOWN:
- $objWriter->writeAttribute('diagonalUp', 'false');
- $objWriter->writeAttribute('diagonalDown', 'true');
- break;
- case Style_Borders::DIAGONAL_BOTH:
- $objWriter->writeAttribute('diagonalUp', 'true');
- $objWriter->writeAttribute('diagonalDown', 'true');
- break;
- }
-
- // BorderPr
- $this->_writeBorderPr($objWriter, 'left', $pBorders->getLeft());
- $this->_writeBorderPr($objWriter, 'right', $pBorders->getRight());
- $this->_writeBorderPr($objWriter, 'top', $pBorders->getTop());
- $this->_writeBorderPr($objWriter, 'bottom', $pBorders->getBottom());
- $this->_writeBorderPr($objWriter, 'diagonal', $pBorders->getDiagonal());
- $objWriter->endElement();
- }
-
- /**
- * Write Cell Style Xf
- *
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel\Style $pStyle Style
- * @param PHPExcel\Workbook $pPHPExcel Workbook
- * @throws PHPExcel\Writer_Exception
- */
- private function _writeCellStyleXf(Shared_XMLWriter $objWriter = null, Style $pStyle = null, Workbook $pPHPExcel = null)
- {
- // xf
- $objWriter->startElement('xf');
- $objWriter->writeAttribute('xfId', 0);
- $objWriter->writeAttribute('fontId', (int)$this->getParentWriter()->getFontHashTable()->getIndexForHashCode($pStyle->getFont()->getHashCode()));
-
- if ($pStyle->getNumberFormat()->getBuiltInFormatCode() === false) {
- $objWriter->writeAttribute('numFmtId', (int)($this->getParentWriter()->getNumFmtHashTable()->getIndexForHashCode($pStyle->getNumberFormat()->getHashCode()) + 164) );
- } else {
- $objWriter->writeAttribute('numFmtId', (int)$pStyle->getNumberFormat()->getBuiltInFormatCode());
- }
-
- $objWriter->writeAttribute('fillId', (int)$this->getParentWriter()->getFillHashTable()->getIndexForHashCode($pStyle->getFill()->getHashCode()));
- $objWriter->writeAttribute('borderId', (int)$this->getParentWriter()->getBordersHashTable()->getIndexForHashCode($pStyle->getBorders()->getHashCode()));
-
- // Apply styles?
- $objWriter->writeAttribute('applyFont', ($pPHPExcel->getDefaultStyle()->getFont()->getHashCode() != $pStyle->getFont()->getHashCode()) ? '1' : '0');
- $objWriter->writeAttribute('applyNumberFormat', ($pPHPExcel->getDefaultStyle()->getNumberFormat()->getHashCode() != $pStyle->getNumberFormat()->getHashCode()) ? '1' : '0');
- $objWriter->writeAttribute('applyFill', ($pPHPExcel->getDefaultStyle()->getFill()->getHashCode() != $pStyle->getFill()->getHashCode()) ? '1' : '0');
- $objWriter->writeAttribute('applyBorder', ($pPHPExcel->getDefaultStyle()->getBorders()->getHashCode() != $pStyle->getBorders()->getHashCode()) ? '1' : '0');
- $objWriter->writeAttribute('applyAlignment', ($pPHPExcel->getDefaultStyle()->getAlignment()->getHashCode() != $pStyle->getAlignment()->getHashCode()) ? '1' : '0');
- if ($pStyle->getProtection()->getLocked() != Style_Protection::PROTECTION_INHERIT || $pStyle->getProtection()->getHidden() != Style_Protection::PROTECTION_INHERIT) {
- $objWriter->writeAttribute('applyProtection', 'true');
- }
-
- // alignment
- $objWriter->startElement('alignment');
- $objWriter->writeAttribute('horizontal', $pStyle->getAlignment()->getHorizontal());
- $objWriter->writeAttribute('vertical', $pStyle->getAlignment()->getVertical());
-
- $textRotation = 0;
- if ($pStyle->getAlignment()->getTextRotation() >= 0) {
- $textRotation = $pStyle->getAlignment()->getTextRotation();
- } else if ($pStyle->getAlignment()->getTextRotation() < 0) {
- $textRotation = 90 - $pStyle->getAlignment()->getTextRotation();
- }
- $objWriter->writeAttribute('textRotation', $textRotation);
-
- $objWriter->writeAttribute('wrapText', ($pStyle->getAlignment()->getWrapText() ? 'true' : 'false'));
- $objWriter->writeAttribute('shrinkToFit', ($pStyle->getAlignment()->getShrinkToFit() ? 'true' : 'false'));
-
- if ($pStyle->getAlignment()->getIndent() > 0) {
- $objWriter->writeAttribute('indent', $pStyle->getAlignment()->getIndent());
- }
- $objWriter->endElement();
-
- // protection
- if ($pStyle->getProtection()->getLocked() != Style_Protection::PROTECTION_INHERIT || $pStyle->getProtection()->getHidden() != Style_Protection::PROTECTION_INHERIT) {
- $objWriter->startElement('protection');
- if ($pStyle->getProtection()->getLocked() != Style_Protection::PROTECTION_INHERIT) {
- $objWriter->writeAttribute('locked', ($pStyle->getProtection()->getLocked() == Style_Protection::PROTECTION_PROTECTED ? 'true' : 'false'));
- }
- if ($pStyle->getProtection()->getHidden() != Style_Protection::PROTECTION_INHERIT) {
- $objWriter->writeAttribute('hidden', ($pStyle->getProtection()->getHidden() == Style_Protection::PROTECTION_PROTECTED ? 'true' : 'false'));
- }
- $objWriter->endElement();
- }
-
- $objWriter->endElement();
- }
-
- /**
- * Write Cell Style Dxf
- *
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel\Style $pStyle Style
- * @throws PHPExcel\Writer_Exception
- */
- private function _writeCellStyleDxf(Shared_XMLWriter $objWriter = null, Style $pStyle = null)
- {
- // dxf
- $objWriter->startElement('dxf');
-
- // font
- $this->_writeFont($objWriter, $pStyle->getFont());
-
- // numFmt
- $this->_writeNumFmt($objWriter, $pStyle->getNumberFormat());
-
- // fill
- $this->_writeFill($objWriter, $pStyle->getFill());
-
- // alignment
- $objWriter->startElement('alignment');
- if ($pStyle->getAlignment()->getHorizontal() !== NULL) {
- $objWriter->writeAttribute('horizontal', $pStyle->getAlignment()->getHorizontal());
- }
- if ($pStyle->getAlignment()->getVertical() !== NULL) {
- $objWriter->writeAttribute('vertical', $pStyle->getAlignment()->getVertical());
- }
-
- if ($pStyle->getAlignment()->getTextRotation() !== NULL) {
- $textRotation = 0;
- if ($pStyle->getAlignment()->getTextRotation() >= 0) {
- $textRotation = $pStyle->getAlignment()->getTextRotation();
- } else if ($pStyle->getAlignment()->getTextRotation() < 0) {
- $textRotation = 90 - $pStyle->getAlignment()->getTextRotation();
- }
- $objWriter->writeAttribute('textRotation', $textRotation);
- }
- $objWriter->endElement();
-
- // border
- $this->_writeBorder($objWriter, $pStyle->getBorders());
-
- // protection
- if (($pStyle->getProtection()->getLocked() !== NULL) ||
- ($pStyle->getProtection()->getHidden() !== NULL)) {
- if ($pStyle->getProtection()->getLocked() !== Style_Protection::PROTECTION_INHERIT ||
- $pStyle->getProtection()->getHidden() !== Style_Protection::PROTECTION_INHERIT) {
- $objWriter->startElement('protection');
- if (($pStyle->getProtection()->getLocked() !== NULL) &&
- ($pStyle->getProtection()->getLocked() !== Style_Protection::PROTECTION_INHERIT)) {
- $objWriter->writeAttribute('locked', ($pStyle->getProtection()->getLocked() == Style_Protection::PROTECTION_PROTECTED ? 'true' : 'false'));
- }
- if (($pStyle->getProtection()->getHidden() !== NULL) &&
- ($pStyle->getProtection()->getHidden() !== Style_Protection::PROTECTION_INHERIT)) {
- $objWriter->writeAttribute('hidden', ($pStyle->getProtection()->getHidden() == Style_Protection::PROTECTION_PROTECTED ? 'true' : 'false'));
- }
- $objWriter->endElement();
- }
- }
-
- $objWriter->endElement();
- }
-
- /**
- * Write BorderPr
- *
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @param string $pName Element name
- * @param PHPExcel\Style_Border $pBorder Border style
- * @throws PHPExcel\Writer_Exception
- */
- private function _writeBorderPr(Shared_XMLWriter $objWriter = null, $pName = 'left', Style_Border $pBorder = null)
- {
- // Write BorderPr
- if ($pBorder->getBorderStyle() != Style_Border::BORDER_NONE) {
- $objWriter->startElement($pName);
- $objWriter->writeAttribute('style', $pBorder->getBorderStyle());
-
- // color
- $objWriter->startElement('color');
- $objWriter->writeAttribute('rgb', $pBorder->getColor()->getARGB());
- $objWriter->endElement();
-
- $objWriter->endElement();
- }
- }
-
- /**
- * Write NumberFormat
- *
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel\Style_NumberFormat $pNumberFormat Number Format
- * @param int $pId Number Format identifier
- * @throws PHPExcel\Writer_Exception
- */
- private function _writeNumFmt(Shared_XMLWriter $objWriter = null, Style_NumberFormat $pNumberFormat = null, $pId = 0)
- {
- // Translate formatcode
- $formatCode = $pNumberFormat->getFormatCode();
-
- // numFmt
- if ($formatCode !== NULL) {
- $objWriter->startElement('numFmt');
- $objWriter->writeAttribute('numFmtId', ($pId + 164));
- $objWriter->writeAttribute('formatCode', $formatCode);
- $objWriter->endElement();
- }
- }
-
- /**
- * Get an array of all styles
- *
- * @param PHPExcel $pPHPExcel
- * @return PHPExcel\Style[] All styles in PHPExcel
- * @throws PHPExcel\Writer_Exception
- */
- public function allStyles(Workbook $pPHPExcel = null)
- {
- $aStyles = $pPHPExcel->getCellXfCollection();
-
- return $aStyles;
- }
-
- /**
- * Get an array of all conditional styles
- *
- * @param PHPExcel $pPHPExcel
- * @return PHPExcel\Style_Conditional[] All conditional styles in PHPExcel
- * @throws PHPExcel\Writer_Exception
- */
- public function allConditionalStyles(Workbook $pPHPExcel = null)
- {
- // Get an array of all styles
- $aStyles = array();
-
- $sheetCount = $pPHPExcel->getSheetCount();
- for ($i = 0; $i < $sheetCount; ++$i) {
- foreach ($pPHPExcel->getSheet($i)->getConditionalStylesCollection() as $conditionalStyles) {
- foreach ($conditionalStyles as $conditionalStyle) {
- $aStyles[] = $conditionalStyle;
- }
- }
- }
-
- return $aStyles;
- }
-
- /**
- * Get an array of all fills
- *
- * @param PHPExcel $pPHPExcel
- * @return PHPExcel\Style_Fill[] All fills in PHPExcel
- * @throws PHPExcel\Writer_Exception
- */
- public function allFills(Workbook $pPHPExcel = null)
- {
- // Get an array of unique fills
- $aFills = array();
-
- // Two first fills are predefined
- $fill0 = new Style_Fill();
- $fill0->setFillType(Style_Fill::FILL_NONE);
- $aFills[] = $fill0;
-
- $fill1 = new Style_Fill();
- $fill1->setFillType(Style_Fill::FILL_PATTERN_GRAY125);
- $aFills[] = $fill1;
- // The remaining fills
- $aStyles = $this->allStyles($pPHPExcel);
- foreach ($aStyles as $style) {
- if (!array_key_exists($style->getFill()->getHashCode(), $aFills)) {
- $aFills[ $style->getFill()->getHashCode() ] = $style->getFill();
- }
- }
-
- return $aFills;
- }
-
- /**
- * Get an array of all fonts
- *
- * @param PHPExcel $pPHPExcel
- * @return PHPExcel\Style_Font[] All fonts in PHPExcel
- * @throws PHPExcel\Writer_Exception
- */
- public function allFonts(Workbook $pPHPExcel = null)
- {
- // Get an array of unique fonts
- $aFonts = array();
- $aStyles = $this->allStyles($pPHPExcel);
-
- foreach ($aStyles as $style) {
- if (!array_key_exists($style->getFont()->getHashCode(), $aFonts)) {
- $aFonts[ $style->getFont()->getHashCode() ] = $style->getFont();
- }
- }
-
- return $aFonts;
- }
-
- /**
- * Get an array of all borders
- *
- * @param PHPExcel $pPHPExcel
- * @return PHPExcel\Style_Borders[] All borders in PHPExcel
- * @throws PHPExcel\Writer_Exception
- */
- public function allBorders(Workbook $pPHPExcel = null)
- {
- // Get an array of unique borders
- $aBorders = array();
- $aStyles = $this->allStyles($pPHPExcel);
-
- foreach ($aStyles as $style) {
- if (!array_key_exists($style->getBorders()->getHashCode(), $aBorders)) {
- $aBorders[ $style->getBorders()->getHashCode() ] = $style->getBorders();
- }
- }
-
- return $aBorders;
- }
-
- /**
- * Get an array of all number formats
- *
- * @param PHPExcel $pPHPExcel
- * @return PHPExcel\Style_NumberFormat[] All number formats in PHPExcel
- * @throws PHPExcel\Writer_Exception
- */
- public function allNumberFormats(Workbook $pPHPExcel = null)
- {
- // Get an array of unique number formats
- $aNumFmts = array();
- $aStyles = $this->allStyles($pPHPExcel);
-
- foreach ($aStyles as $style) {
- if ($style->getNumberFormat()->getBuiltInFormatCode() === false && !array_key_exists($style->getNumberFormat()->getHashCode(), $aNumFmts)) {
- $aNumFmts[ $style->getNumberFormat()->getHashCode() ] = $style->getNumberFormat();
- }
- }
-
- return $aNumFmts;
- }
+ /**
+ * Write styles to XML format
+ *
+ * @param PHPExcel\Workbook $pPHPExcel
+ * @return string XML Output
+ * @throws PHPExcel\Writer_Exception
+ */
+ public function writeStyles(Workbook $pPHPExcel = null)
+ {
+ // Create XML writer
+ $objWriter = null;
+ if ($this->getParentWriter()->getUseDiskCaching()) {
+ $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
+ } else {
+ $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_MEMORY);
+ }
+
+ // XML header
+ $objWriter->startDocument('1.0','UTF-8','yes');
+
+ // styleSheet
+ $objWriter->startElement('styleSheet');
+ $objWriter->writeAttribute('xml:space', 'preserve');
+ $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main');
+
+ // numFmts
+ $objWriter->startElement('numFmts');
+ $objWriter->writeAttribute('count', $this->getParentWriter()->getNumFmtHashTable()->count());
+
+ // numFmt
+ for ($i = 0; $i < $this->getParentWriter()->getNumFmtHashTable()->count(); ++$i) {
+ $this->_writeNumFmt($objWriter, $this->getParentWriter()->getNumFmtHashTable()->getByIndex($i), $i);
+ }
+
+ $objWriter->endElement();
+
+ // fonts
+ $objWriter->startElement('fonts');
+ $objWriter->writeAttribute('count', $this->getParentWriter()->getFontHashTable()->count());
+
+ // font
+ for ($i = 0; $i < $this->getParentWriter()->getFontHashTable()->count(); ++$i) {
+ $this->_writeFont($objWriter, $this->getParentWriter()->getFontHashTable()->getByIndex($i));
+ }
+
+ $objWriter->endElement();
+
+ // fills
+ $objWriter->startElement('fills');
+ $objWriter->writeAttribute('count', $this->getParentWriter()->getFillHashTable()->count());
+
+ // fill
+ for ($i = 0; $i < $this->getParentWriter()->getFillHashTable()->count(); ++$i) {
+ $this->_writeFill($objWriter, $this->getParentWriter()->getFillHashTable()->getByIndex($i));
+ }
+
+ $objWriter->endElement();
+
+ // borders
+ $objWriter->startElement('borders');
+ $objWriter->writeAttribute('count', $this->getParentWriter()->getBordersHashTable()->count());
+
+ // border
+ for ($i = 0; $i < $this->getParentWriter()->getBordersHashTable()->count(); ++$i) {
+ $this->_writeBorder($objWriter, $this->getParentWriter()->getBordersHashTable()->getByIndex($i));
+ }
+
+ $objWriter->endElement();
+
+ // cellStyleXfs
+ $objWriter->startElement('cellStyleXfs');
+ $objWriter->writeAttribute('count', 1);
+
+ // xf
+ $objWriter->startElement('xf');
+ $objWriter->writeAttribute('numFmtId', 0);
+ $objWriter->writeAttribute('fontId', 0);
+ $objWriter->writeAttribute('fillId', 0);
+ $objWriter->writeAttribute('borderId', 0);
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ // cellXfs
+ $objWriter->startElement('cellXfs');
+ $objWriter->writeAttribute('count', count($pPHPExcel->getCellXfCollection()));
+
+ // xf
+ foreach ($pPHPExcel->getCellXfCollection() as $cellXf) {
+ $this->_writeCellStyleXf($objWriter, $cellXf, $pPHPExcel);
+ }
+
+ $objWriter->endElement();
+
+ // cellStyles
+ $objWriter->startElement('cellStyles');
+ $objWriter->writeAttribute('count', 1);
+
+ // cellStyle
+ $objWriter->startElement('cellStyle');
+ $objWriter->writeAttribute('name', 'Normal');
+ $objWriter->writeAttribute('xfId', 0);
+ $objWriter->writeAttribute('builtinId', 0);
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ // dxfs
+ $objWriter->startElement('dxfs');
+ $objWriter->writeAttribute('count', $this->getParentWriter()->getStylesConditionalHashTable()->count());
+
+ // dxf
+ for ($i = 0; $i < $this->getParentWriter()->getStylesConditionalHashTable()->count(); ++$i) {
+ $this->_writeCellStyleDxf($objWriter, $this->getParentWriter()->getStylesConditionalHashTable()->getByIndex($i)->getStyle());
+ }
+
+ $objWriter->endElement();
+
+ // tableStyles
+ $objWriter->startElement('tableStyles');
+ $objWriter->writeAttribute('defaultTableStyle', 'TableStyleMedium9');
+ $objWriter->writeAttribute('defaultPivotStyle', 'PivotTableStyle1');
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ // Return
+ return $objWriter->getData();
+ }
+
+ /**
+ * Write Fill
+ *
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel\Style_Fill $pFill Fill style
+ * @throws PHPExcel\Writer_Exception
+ */
+ private function _writeFill(Shared_XMLWriter $objWriter = null, Style_Fill $pFill = null)
+ {
+ // Check if this is a pattern type or gradient type
+ if ($pFill->getFillType() === Style_Fill::FILL_GRADIENT_LINEAR ||
+ $pFill->getFillType() === Style_Fill::FILL_GRADIENT_PATH) {
+ // Gradient fill
+ $this->_writeGradientFill($objWriter, $pFill);
+ } elseif($pFill->getFillType() !== null) {
+ // Pattern fill
+ $this->_writePatternFill($objWriter, $pFill);
+ }
+ }
+
+ /**
+ * Write Gradient Fill
+ *
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel\Style_Fill $pFill Fill style
+ * @throws PHPExcel\Writer_Exception
+ */
+ private function _writeGradientFill(Shared_XMLWriter $objWriter = null, Style_Fill $pFill = null)
+ {
+ // fill
+ $objWriter->startElement('fill');
+
+ // gradientFill
+ $objWriter->startElement('gradientFill');
+ $objWriter->writeAttribute('type', $pFill->getFillType());
+ $objWriter->writeAttribute('degree', $pFill->getRotation());
+
+ // stop
+ $objWriter->startElement('stop');
+ $objWriter->writeAttribute('position', '0');
+
+ // color
+ $objWriter->startElement('color');
+ $objWriter->writeAttribute('rgb', $pFill->getStartColor()->getARGB());
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ // stop
+ $objWriter->startElement('stop');
+ $objWriter->writeAttribute('position', '1');
+
+ // color
+ $objWriter->startElement('color');
+ $objWriter->writeAttribute('rgb', $pFill->getEndColor()->getARGB());
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+ }
+
+ /**
+ * Write Pattern Fill
+ *
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel\Style_Fill $pFill Fill style
+ * @throws PHPExcel\Writer_Exception
+ */
+ private function _writePatternFill(Shared_XMLWriter $objWriter = null, Style_Fill $pFill = null)
+ {
+ // fill
+ $objWriter->startElement('fill');
+
+ // patternFill
+ $objWriter->startElement('patternFill');
+ $objWriter->writeAttribute('patternType', $pFill->getFillType());
+
+ if ($pFill->getFillType() !== Style_Fill::FILL_NONE) {
+ // fgColor
+ if ($pFill->getStartColor()->getARGB()) {
+ $objWriter->startElement('fgColor');
+ $objWriter->writeAttribute('rgb', $pFill->getStartColor()->getARGB());
+ $objWriter->endElement();
+ }
+ }
+ if ($pFill->getFillType() !== Style_Fill::FILL_NONE) {
+ // bgColor
+ if ($pFill->getEndColor()->getARGB()) {
+ $objWriter->startElement('bgColor');
+ $objWriter->writeAttribute('rgb', $pFill->getEndColor()->getARGB());
+ $objWriter->endElement();
+ }
+ }
+
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+ }
+
+ /**
+ * Write Font
+ *
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel\Style_Font $pFont Font style
+ * @throws PHPExcel\Writer_Exception
+ */
+ private function _writeFont(Shared_XMLWriter $objWriter = null, Style_Font $pFont = null)
+ {
+ // font
+ $objWriter->startElement('font');
+ // Weird! The order of these elements actually makes a difference when opening Excel2007
+ // files in Excel2003 with the compatibility pack. It's not documented behaviour,
+ // and makes for a real WTF!
+
+ // Bold. We explicitly write this element also when false (like MS Office Excel 2007 does
+ // for conditional formatting). Otherwise it will apparently not be picked up in conditional
+ // formatting style dialog
+ if ($pFont->getBold() !== null) {
+ $objWriter->startElement('b');
+ $objWriter->writeAttribute('val', $pFont->getBold() ? '1' : '0');
+ $objWriter->endElement();
+ }
+
+ // Italic
+ if ($pFont->getItalic() !== null) {
+ $objWriter->startElement('i');
+ $objWriter->writeAttribute('val', $pFont->getItalic() ? '1' : '0');
+ $objWriter->endElement();
+ }
+
+ // Strikethrough
+ if ($pFont->getStrikethrough() !== null) {
+ $objWriter->startElement('strike');
+ $objWriter->writeAttribute('val', $pFont->getStrikethrough() ? '1' : '0');
+ $objWriter->endElement();
+ }
+
+ // Underline
+ if ($pFont->getUnderline() !== null) {
+ $objWriter->startElement('u');
+ $objWriter->writeAttribute('val', $pFont->getUnderline());
+ $objWriter->endElement();
+ }
+
+ // Superscript / subscript
+ if ($pFont->getSuperScript() === TRUE || $pFont->getSubScript() === TRUE) {
+ $objWriter->startElement('vertAlign');
+ if ($pFont->getSuperScript() === TRUE) {
+ $objWriter->writeAttribute('val', 'superscript');
+ } else if ($pFont->getSubScript() === TRUE) {
+ $objWriter->writeAttribute('val', 'subscript');
+ }
+ $objWriter->endElement();
+ }
+
+ // Size
+ if ($pFont->getSize() !== null) {
+ $objWriter->startElement('sz');
+ $objWriter->writeAttribute('val', $pFont->getSize());
+ $objWriter->endElement();
+ }
+
+ // Foreground color
+ if ($pFont->getColor()->getARGB() !== null) {
+ $objWriter->startElement('color');
+ $objWriter->writeAttribute('rgb', $pFont->getColor()->getARGB());
+ $objWriter->endElement();
+ }
+
+ // Name
+ if ($pFont->getName() !== null) {
+ $objWriter->startElement('name');
+ $objWriter->writeAttribute('val', $pFont->getName());
+ $objWriter->endElement();
+ }
+
+ $objWriter->endElement();
+ }
+
+ /**
+ * Write Border
+ *
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel\Style_Borders $pBorders Borders style
+ * @throws PHPExcel\Writer_Exception
+ */
+ private function _writeBorder(Shared_XMLWriter $objWriter = null, Style_Borders $pBorders = null)
+ {
+ // Write border
+ $objWriter->startElement('border');
+ // Diagonal?
+ switch ($pBorders->getDiagonalDirection()) {
+ case Style_Borders::DIAGONAL_UP:
+ $objWriter->writeAttribute('diagonalUp', 'true');
+ $objWriter->writeAttribute('diagonalDown', 'false');
+ break;
+ case Style_Borders::DIAGONAL_DOWN:
+ $objWriter->writeAttribute('diagonalUp', 'false');
+ $objWriter->writeAttribute('diagonalDown', 'true');
+ break;
+ case Style_Borders::DIAGONAL_BOTH:
+ $objWriter->writeAttribute('diagonalUp', 'true');
+ $objWriter->writeAttribute('diagonalDown', 'true');
+ break;
+ }
+
+ // BorderPr
+ $this->_writeBorderPr($objWriter, 'left', $pBorders->getLeft());
+ $this->_writeBorderPr($objWriter, 'right', $pBorders->getRight());
+ $this->_writeBorderPr($objWriter, 'top', $pBorders->getTop());
+ $this->_writeBorderPr($objWriter, 'bottom', $pBorders->getBottom());
+ $this->_writeBorderPr($objWriter, 'diagonal', $pBorders->getDiagonal());
+ $objWriter->endElement();
+ }
+
+ /**
+ * Write Cell Style Xf
+ *
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel\Style $pStyle Style
+ * @param PHPExcel\Workbook $pPHPExcel Workbook
+ * @throws PHPExcel\Writer_Exception
+ */
+ private function _writeCellStyleXf(Shared_XMLWriter $objWriter = null, Style $pStyle = null, Workbook $pPHPExcel = null)
+ {
+ // xf
+ $objWriter->startElement('xf');
+ $objWriter->writeAttribute('xfId', 0);
+ $objWriter->writeAttribute('fontId', (int)$this->getParentWriter()->getFontHashTable()->getIndexForHashCode($pStyle->getFont()->getHashCode()));
+
+ if ($pStyle->getNumberFormat()->getBuiltInFormatCode() === false) {
+ $objWriter->writeAttribute('numFmtId', (int)($this->getParentWriter()->getNumFmtHashTable()->getIndexForHashCode($pStyle->getNumberFormat()->getHashCode()) + 164) );
+ } else {
+ $objWriter->writeAttribute('numFmtId', (int)$pStyle->getNumberFormat()->getBuiltInFormatCode());
+ }
+
+ $objWriter->writeAttribute('fillId', (int)$this->getParentWriter()->getFillHashTable()->getIndexForHashCode($pStyle->getFill()->getHashCode()));
+ $objWriter->writeAttribute('borderId', (int)$this->getParentWriter()->getBordersHashTable()->getIndexForHashCode($pStyle->getBorders()->getHashCode()));
+
+ // Apply styles?
+ $objWriter->writeAttribute('applyFont', ($pPHPExcel->getDefaultStyle()->getFont()->getHashCode() != $pStyle->getFont()->getHashCode()) ? '1' : '0');
+ $objWriter->writeAttribute('applyNumberFormat', ($pPHPExcel->getDefaultStyle()->getNumberFormat()->getHashCode() != $pStyle->getNumberFormat()->getHashCode()) ? '1' : '0');
+ $objWriter->writeAttribute('applyFill', ($pPHPExcel->getDefaultStyle()->getFill()->getHashCode() != $pStyle->getFill()->getHashCode()) ? '1' : '0');
+ $objWriter->writeAttribute('applyBorder', ($pPHPExcel->getDefaultStyle()->getBorders()->getHashCode() != $pStyle->getBorders()->getHashCode()) ? '1' : '0');
+ $objWriter->writeAttribute('applyAlignment', ($pPHPExcel->getDefaultStyle()->getAlignment()->getHashCode() != $pStyle->getAlignment()->getHashCode()) ? '1' : '0');
+ if ($pStyle->getProtection()->getLocked() != Style_Protection::PROTECTION_INHERIT || $pStyle->getProtection()->getHidden() != Style_Protection::PROTECTION_INHERIT) {
+ $objWriter->writeAttribute('applyProtection', 'true');
+ }
+
+ // alignment
+ $objWriter->startElement('alignment');
+ $objWriter->writeAttribute('horizontal', $pStyle->getAlignment()->getHorizontal());
+ $objWriter->writeAttribute('vertical', $pStyle->getAlignment()->getVertical());
+
+ $textRotation = 0;
+ if ($pStyle->getAlignment()->getTextRotation() >= 0) {
+ $textRotation = $pStyle->getAlignment()->getTextRotation();
+ } else if ($pStyle->getAlignment()->getTextRotation() < 0) {
+ $textRotation = 90 - $pStyle->getAlignment()->getTextRotation();
+ }
+ $objWriter->writeAttribute('textRotation', $textRotation);
+
+ $objWriter->writeAttribute('wrapText', ($pStyle->getAlignment()->getWrapText() ? 'true' : 'false'));
+ $objWriter->writeAttribute('shrinkToFit', ($pStyle->getAlignment()->getShrinkToFit() ? 'true' : 'false'));
+
+ if ($pStyle->getAlignment()->getIndent() > 0) {
+ $objWriter->writeAttribute('indent', $pStyle->getAlignment()->getIndent());
+ }
+ $objWriter->endElement();
+
+ // protection
+ if ($pStyle->getProtection()->getLocked() != Style_Protection::PROTECTION_INHERIT || $pStyle->getProtection()->getHidden() != Style_Protection::PROTECTION_INHERIT) {
+ $objWriter->startElement('protection');
+ if ($pStyle->getProtection()->getLocked() != Style_Protection::PROTECTION_INHERIT) {
+ $objWriter->writeAttribute('locked', ($pStyle->getProtection()->getLocked() == Style_Protection::PROTECTION_PROTECTED ? 'true' : 'false'));
+ }
+ if ($pStyle->getProtection()->getHidden() != Style_Protection::PROTECTION_INHERIT) {
+ $objWriter->writeAttribute('hidden', ($pStyle->getProtection()->getHidden() == Style_Protection::PROTECTION_PROTECTED ? 'true' : 'false'));
+ }
+ $objWriter->endElement();
+ }
+
+ $objWriter->endElement();
+ }
+
+ /**
+ * Write Cell Style Dxf
+ *
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel\Style $pStyle Style
+ * @throws PHPExcel\Writer_Exception
+ */
+ private function _writeCellStyleDxf(Shared_XMLWriter $objWriter = null, Style $pStyle = null)
+ {
+ // dxf
+ $objWriter->startElement('dxf');
+
+ // font
+ $this->_writeFont($objWriter, $pStyle->getFont());
+
+ // numFmt
+ $this->_writeNumFmt($objWriter, $pStyle->getNumberFormat());
+
+ // fill
+ $this->_writeFill($objWriter, $pStyle->getFill());
+
+ // alignment
+ $objWriter->startElement('alignment');
+ if ($pStyle->getAlignment()->getHorizontal() !== null) {
+ $objWriter->writeAttribute('horizontal', $pStyle->getAlignment()->getHorizontal());
+ }
+ if ($pStyle->getAlignment()->getVertical() !== null) {
+ $objWriter->writeAttribute('vertical', $pStyle->getAlignment()->getVertical());
+ }
+
+ if ($pStyle->getAlignment()->getTextRotation() !== null) {
+ $textRotation = 0;
+ if ($pStyle->getAlignment()->getTextRotation() >= 0) {
+ $textRotation = $pStyle->getAlignment()->getTextRotation();
+ } else if ($pStyle->getAlignment()->getTextRotation() < 0) {
+ $textRotation = 90 - $pStyle->getAlignment()->getTextRotation();
+ }
+ $objWriter->writeAttribute('textRotation', $textRotation);
+ }
+ $objWriter->endElement();
+
+ // border
+ $this->_writeBorder($objWriter, $pStyle->getBorders());
+
+ // protection
+ if (($pStyle->getProtection()->getLocked() !== null) ||
+ ($pStyle->getProtection()->getHidden() !== null)) {
+ if ($pStyle->getProtection()->getLocked() !== Style_Protection::PROTECTION_INHERIT ||
+ $pStyle->getProtection()->getHidden() !== Style_Protection::PROTECTION_INHERIT) {
+ $objWriter->startElement('protection');
+ if (($pStyle->getProtection()->getLocked() !== null) &&
+ ($pStyle->getProtection()->getLocked() !== Style_Protection::PROTECTION_INHERIT)) {
+ $objWriter->writeAttribute('locked', ($pStyle->getProtection()->getLocked() == Style_Protection::PROTECTION_PROTECTED ? 'true' : 'false'));
+ }
+ if (($pStyle->getProtection()->getHidden() !== null) &&
+ ($pStyle->getProtection()->getHidden() !== Style_Protection::PROTECTION_INHERIT)) {
+ $objWriter->writeAttribute('hidden', ($pStyle->getProtection()->getHidden() == Style_Protection::PROTECTION_PROTECTED ? 'true' : 'false'));
+ }
+ $objWriter->endElement();
+ }
+ }
+
+ $objWriter->endElement();
+ }
+
+ /**
+ * Write BorderPr
+ *
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @param string $pName Element name
+ * @param PHPExcel\Style_Border $pBorder Border style
+ * @throws PHPExcel\Writer_Exception
+ */
+ private function _writeBorderPr(Shared_XMLWriter $objWriter = null, $pName = 'left', Style_Border $pBorder = null)
+ {
+ // Write BorderPr
+ if ($pBorder->getBorderStyle() != Style_Border::BORDER_NONE) {
+ $objWriter->startElement($pName);
+ $objWriter->writeAttribute('style', $pBorder->getBorderStyle());
+
+ // color
+ $objWriter->startElement('color');
+ $objWriter->writeAttribute('rgb', $pBorder->getColor()->getARGB());
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+ }
+ }
+
+ /**
+ * Write NumberFormat
+ *
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel\Style_NumberFormat $pNumberFormat Number Format
+ * @param int $pId Number Format identifier
+ * @throws PHPExcel\Writer_Exception
+ */
+ private function _writeNumFmt(Shared_XMLWriter $objWriter = null, Style_NumberFormat $pNumberFormat = null, $pId = 0)
+ {
+ // Translate formatcode
+ $formatCode = $pNumberFormat->getFormatCode();
+
+ // numFmt
+ if ($formatCode !== null) {
+ $objWriter->startElement('numFmt');
+ $objWriter->writeAttribute('numFmtId', ($pId + 164));
+ $objWriter->writeAttribute('formatCode', $formatCode);
+ $objWriter->endElement();
+ }
+ }
+
+ /**
+ * Get an array of all styles
+ *
+ * @param PHPExcel $pPHPExcel
+ * @return PHPExcel\Style[] All styles in PHPExcel
+ * @throws PHPExcel\Writer_Exception
+ */
+ public function allStyles(Workbook $pPHPExcel = null)
+ {
+ $aStyles = $pPHPExcel->getCellXfCollection();
+
+ return $aStyles;
+ }
+
+ /**
+ * Get an array of all conditional styles
+ *
+ * @param PHPExcel $pPHPExcel
+ * @return PHPExcel\Style_Conditional[] All conditional styles in PHPExcel
+ * @throws PHPExcel\Writer_Exception
+ */
+ public function allConditionalStyles(Workbook $pPHPExcel = null)
+ {
+ // Get an array of all styles
+ $aStyles = array();
+
+ $sheetCount = $pPHPExcel->getSheetCount();
+ for ($i = 0; $i < $sheetCount; ++$i) {
+ foreach ($pPHPExcel->getSheet($i)->getConditionalStylesCollection() as $conditionalStyles) {
+ foreach ($conditionalStyles as $conditionalStyle) {
+ $aStyles[] = $conditionalStyle;
+ }
+ }
+ }
+
+ return $aStyles;
+ }
+
+ /**
+ * Get an array of all fills
+ *
+ * @param PHPExcel $pPHPExcel
+ * @return PHPExcel\Style_Fill[] All fills in PHPExcel
+ * @throws PHPExcel\Writer_Exception
+ */
+ public function allFills(Workbook $pPHPExcel = null)
+ {
+ // Get an array of unique fills
+ $aFills = array();
+
+ // Two first fills are predefined
+ $fill0 = new Style_Fill();
+ $fill0->setFillType(Style_Fill::FILL_NONE);
+ $aFills[] = $fill0;
+
+ $fill1 = new Style_Fill();
+ $fill1->setFillType(Style_Fill::FILL_PATTERN_GRAY125);
+ $aFills[] = $fill1;
+ // The remaining fills
+ $aStyles = $this->allStyles($pPHPExcel);
+ foreach ($aStyles as $style) {
+ if (!array_key_exists($style->getFill()->getHashCode(), $aFills)) {
+ $aFills[ $style->getFill()->getHashCode() ] = $style->getFill();
+ }
+ }
+
+ return $aFills;
+ }
+
+ /**
+ * Get an array of all fonts
+ *
+ * @param PHPExcel $pPHPExcel
+ * @return PHPExcel\Style_Font[] All fonts in PHPExcel
+ * @throws PHPExcel\Writer_Exception
+ */
+ public function allFonts(Workbook $pPHPExcel = null)
+ {
+ // Get an array of unique fonts
+ $aFonts = array();
+ $aStyles = $this->allStyles($pPHPExcel);
+
+ foreach ($aStyles as $style) {
+ if (!array_key_exists($style->getFont()->getHashCode(), $aFonts)) {
+ $aFonts[ $style->getFont()->getHashCode() ] = $style->getFont();
+ }
+ }
+
+ return $aFonts;
+ }
+
+ /**
+ * Get an array of all borders
+ *
+ * @param PHPExcel $pPHPExcel
+ * @return PHPExcel\Style_Borders[] All borders in PHPExcel
+ * @throws PHPExcel\Writer_Exception
+ */
+ public function allBorders(Workbook $pPHPExcel = null)
+ {
+ // Get an array of unique borders
+ $aBorders = array();
+ $aStyles = $this->allStyles($pPHPExcel);
+
+ foreach ($aStyles as $style) {
+ if (!array_key_exists($style->getBorders()->getHashCode(), $aBorders)) {
+ $aBorders[ $style->getBorders()->getHashCode() ] = $style->getBorders();
+ }
+ }
+
+ return $aBorders;
+ }
+
+ /**
+ * Get an array of all number formats
+ *
+ * @param PHPExcel $pPHPExcel
+ * @return PHPExcel\Style_NumberFormat[] All number formats in PHPExcel
+ * @throws PHPExcel\Writer_Exception
+ */
+ public function allNumberFormats(Workbook $pPHPExcel = null)
+ {
+ // Get an array of unique number formats
+ $aNumFmts = array();
+ $aStyles = $this->allStyles($pPHPExcel);
+
+ foreach ($aStyles as $style) {
+ if ($style->getNumberFormat()->getBuiltInFormatCode() === false && !array_key_exists($style->getNumberFormat()->getHashCode(), $aNumFmts)) {
+ $aNumFmts[ $style->getNumberFormat()->getHashCode() ] = $style->getNumberFormat();
+ }
+ }
+
+ return $aNumFmts;
+ }
}
diff --git a/Classes/PHPExcel/Writer/Excel2007/Theme.php b/Classes/PHPExcel/Writer/Excel2007/Theme.php
index aae177a..720752e 100644
--- a/Classes/PHPExcel/Writer/Excel2007/Theme.php
+++ b/Classes/PHPExcel/Writer/Excel2007/Theme.php
@@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\Writer_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,837 +37,837 @@ namespace PHPExcel;
*/
class Writer_Excel2007_Theme extends Writer_Excel2007_WriterPart
{
- /**
- * Map of Major fonts to write
- * @static array of string
- *
- */
- private static $_majorFonts = array(
- 'Jpan' => 'MS Pゴシック',
- 'Hang' => '맑은 고딕',
- 'Hans' => '宋体',
- 'Hant' => '新細明體',
- 'Arab' => 'Times New Roman',
- 'Hebr' => 'Times New Roman',
- 'Thai' => 'Tahoma',
- 'Ethi' => 'Nyala',
- 'Beng' => 'Vrinda',
- 'Gujr' => 'Shruti',
- 'Khmr' => 'MoolBoran',
- 'Knda' => 'Tunga',
- 'Guru' => 'Raavi',
- 'Cans' => 'Euphemia',
- 'Cher' => 'Plantagenet Cherokee',
- 'Yiii' => 'Microsoft Yi Baiti',
- 'Tibt' => 'Microsoft Himalaya',
- 'Thaa' => 'MV Boli',
- 'Deva' => 'Mangal',
- 'Telu' => 'Gautami',
- 'Taml' => 'Latha',
- 'Syrc' => 'Estrangelo Edessa',
- 'Orya' => 'Kalinga',
- 'Mlym' => 'Kartika',
- 'Laoo' => 'DokChampa',
- 'Sinh' => 'Iskoola Pota',
- 'Mong' => 'Mongolian Baiti',
- 'Viet' => 'Times New Roman',
- 'Uigh' => 'Microsoft Uighur',
- 'Geor' => 'Sylfaen',
- );
-
- /**
- * Map of Minor fonts to write
- * @static array of string
- *
- */
- private static $_minorFonts = array(
- 'Jpan' => 'MS Pゴシック',
- 'Hang' => '맑은 고딕',
- 'Hans' => '宋体',
- 'Hant' => '新細明體',
- 'Arab' => 'Arial',
- 'Hebr' => 'Arial',
- 'Thai' => 'Tahoma',
- 'Ethi' => 'Nyala',
- 'Beng' => 'Vrinda',
- 'Gujr' => 'Shruti',
- 'Khmr' => 'DaunPenh',
- 'Knda' => 'Tunga',
- 'Guru' => 'Raavi',
- 'Cans' => 'Euphemia',
- 'Cher' => 'Plantagenet Cherokee',
- 'Yiii' => 'Microsoft Yi Baiti',
- 'Tibt' => 'Microsoft Himalaya',
- 'Thaa' => 'MV Boli',
- 'Deva' => 'Mangal',
- 'Telu' => 'Gautami',
- 'Taml' => 'Latha',
- 'Syrc' => 'Estrangelo Edessa',
- 'Orya' => 'Kalinga',
- 'Mlym' => 'Kartika',
- 'Laoo' => 'DokChampa',
- 'Sinh' => 'Iskoola Pota',
- 'Mong' => 'Mongolian Baiti',
- 'Viet' => 'Arial',
- 'Uigh' => 'Microsoft Uighur',
- 'Geor' => 'Sylfaen',
- );
-
- /**
- * Map of core colours
- * @static array of string
- *
- */
- private static $_colourScheme = array(
- 'dk2' => '1F497D',
- 'lt2' => 'EEECE1',
- 'accent1' => '4F81BD',
- 'accent2' => 'C0504D',
- 'accent3' => '9BBB59',
- 'accent4' => '8064A2',
- 'accent5' => '4BACC6',
- 'accent6' => 'F79646',
- 'hlink' => '0000FF',
- 'folHlink' => '800080',
- );
-
- /**
- * Write theme to XML format
- *
- * @param PHPExcel\Workbook $pPHPExcel
- * @return string XML Output
- * @throws PHPExcel\Writer_Exception
- */
- public function writeTheme(Workbook $pPHPExcel = null)
- {
- // Create XML writer
- $objWriter = null;
- if ($this->getParentWriter()->getUseDiskCaching()) {
- $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
- } else {
- $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_MEMORY);
- }
-
- // XML header
- $objWriter->startDocument('1.0','UTF-8','yes');
-
- // a:theme
- $objWriter->startElement('a:theme');
- $objWriter->writeAttribute('xmlns:a', 'http://schemas.openxmlformats.org/drawingml/2006/main');
- $objWriter->writeAttribute('name', 'Office Theme');
-
- // a:themeElements
- $objWriter->startElement('a:themeElements');
-
- // a:clrScheme
- $objWriter->startElement('a:clrScheme');
- $objWriter->writeAttribute('name', 'Office');
-
- // a:dk1
- $objWriter->startElement('a:dk1');
-
- // a:sysClr
- $objWriter->startElement('a:sysClr');
- $objWriter->writeAttribute('val', 'windowText');
- $objWriter->writeAttribute('lastClr', '000000');
- $objWriter->endElement();
-
- $objWriter->endElement();
-
- // a:lt1
- $objWriter->startElement('a:lt1');
-
- // a:sysClr
- $objWriter->startElement('a:sysClr');
- $objWriter->writeAttribute('val', 'window');
- $objWriter->writeAttribute('lastClr', 'FFFFFF');
- $objWriter->endElement();
-
- $objWriter->endElement();
-
- // a:dk2
- $this->_writeColourScheme($objWriter);
-
- $objWriter->endElement();
-
- // a:fontScheme
- $objWriter->startElement('a:fontScheme');
- $objWriter->writeAttribute('name', 'Office');
-
- // a:majorFont
- $objWriter->startElement('a:majorFont');
- $this->_writeFonts($objWriter, 'Cambria', self::$_majorFonts);
- $objWriter->endElement();
-
- // a:minorFont
- $objWriter->startElement('a:minorFont');
- $this->_writeFonts($objWriter, 'Calibri', self::$_minorFonts);
- $objWriter->endElement();
-
- $objWriter->endElement();
-
- // a:fmtScheme
- $objWriter->startElement('a:fmtScheme');
- $objWriter->writeAttribute('name', 'Office');
-
- // a:fillStyleLst
- $objWriter->startElement('a:fillStyleLst');
-
- // a:solidFill
- $objWriter->startElement('a:solidFill');
-
- // a:schemeClr
- $objWriter->startElement('a:schemeClr');
- $objWriter->writeAttribute('val', 'phClr');
- $objWriter->endElement();
-
- $objWriter->endElement();
-
- // a:gradFill
- $objWriter->startElement('a:gradFill');
- $objWriter->writeAttribute('rotWithShape', '1');
+ /**
+ * Map of Major fonts to write
+ * @static array of string
+ *
+ */
+ private static $_majorFonts = array(
+ 'Jpan' => 'MS Pゴシック',
+ 'Hang' => '맑은 고딕',
+ 'Hans' => '宋体',
+ 'Hant' => '新細明體',
+ 'Arab' => 'Times New Roman',
+ 'Hebr' => 'Times New Roman',
+ 'Thai' => 'Tahoma',
+ 'Ethi' => 'Nyala',
+ 'Beng' => 'Vrinda',
+ 'Gujr' => 'Shruti',
+ 'Khmr' => 'MoolBoran',
+ 'Knda' => 'Tunga',
+ 'Guru' => 'Raavi',
+ 'Cans' => 'Euphemia',
+ 'Cher' => 'Plantagenet Cherokee',
+ 'Yiii' => 'Microsoft Yi Baiti',
+ 'Tibt' => 'Microsoft Himalaya',
+ 'Thaa' => 'MV Boli',
+ 'Deva' => 'Mangal',
+ 'Telu' => 'Gautami',
+ 'Taml' => 'Latha',
+ 'Syrc' => 'Estrangelo Edessa',
+ 'Orya' => 'Kalinga',
+ 'Mlym' => 'Kartika',
+ 'Laoo' => 'DokChampa',
+ 'Sinh' => 'Iskoola Pota',
+ 'Mong' => 'Mongolian Baiti',
+ 'Viet' => 'Times New Roman',
+ 'Uigh' => 'Microsoft Uighur',
+ 'Geor' => 'Sylfaen',
+ );
+
+ /**
+ * Map of Minor fonts to write
+ * @static array of string
+ *
+ */
+ private static $_minorFonts = array(
+ 'Jpan' => 'MS Pゴシック',
+ 'Hang' => '맑은 고딕',
+ 'Hans' => '宋体',
+ 'Hant' => '新細明體',
+ 'Arab' => 'Arial',
+ 'Hebr' => 'Arial',
+ 'Thai' => 'Tahoma',
+ 'Ethi' => 'Nyala',
+ 'Beng' => 'Vrinda',
+ 'Gujr' => 'Shruti',
+ 'Khmr' => 'DaunPenh',
+ 'Knda' => 'Tunga',
+ 'Guru' => 'Raavi',
+ 'Cans' => 'Euphemia',
+ 'Cher' => 'Plantagenet Cherokee',
+ 'Yiii' => 'Microsoft Yi Baiti',
+ 'Tibt' => 'Microsoft Himalaya',
+ 'Thaa' => 'MV Boli',
+ 'Deva' => 'Mangal',
+ 'Telu' => 'Gautami',
+ 'Taml' => 'Latha',
+ 'Syrc' => 'Estrangelo Edessa',
+ 'Orya' => 'Kalinga',
+ 'Mlym' => 'Kartika',
+ 'Laoo' => 'DokChampa',
+ 'Sinh' => 'Iskoola Pota',
+ 'Mong' => 'Mongolian Baiti',
+ 'Viet' => 'Arial',
+ 'Uigh' => 'Microsoft Uighur',
+ 'Geor' => 'Sylfaen',
+ );
+
+ /**
+ * Map of core colours
+ * @static array of string
+ *
+ */
+ private static $_colourScheme = array(
+ 'dk2' => '1F497D',
+ 'lt2' => 'EEECE1',
+ 'accent1' => '4F81BD',
+ 'accent2' => 'C0504D',
+ 'accent3' => '9BBB59',
+ 'accent4' => '8064A2',
+ 'accent5' => '4BACC6',
+ 'accent6' => 'F79646',
+ 'hlink' => '0000FF',
+ 'folHlink' => '800080',
+ );
+
+ /**
+ * Write theme to XML format
+ *
+ * @param PHPExcel\Workbook $pPHPExcel
+ * @return string XML Output
+ * @throws PHPExcel\Writer_Exception
+ */
+ public function writeTheme(Workbook $pPHPExcel = null)
+ {
+ // Create XML writer
+ $objWriter = null;
+ if ($this->getParentWriter()->getUseDiskCaching()) {
+ $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
+ } else {
+ $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_MEMORY);
+ }
+
+ // XML header
+ $objWriter->startDocument('1.0','UTF-8','yes');
+
+ // a:theme
+ $objWriter->startElement('a:theme');
+ $objWriter->writeAttribute('xmlns:a', 'http://schemas.openxmlformats.org/drawingml/2006/main');
+ $objWriter->writeAttribute('name', 'Office Theme');
+
+ // a:themeElements
+ $objWriter->startElement('a:themeElements');
+
+ // a:clrScheme
+ $objWriter->startElement('a:clrScheme');
+ $objWriter->writeAttribute('name', 'Office');
+
+ // a:dk1
+ $objWriter->startElement('a:dk1');
+
+ // a:sysClr
+ $objWriter->startElement('a:sysClr');
+ $objWriter->writeAttribute('val', 'windowText');
+ $objWriter->writeAttribute('lastClr', '000000');
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ // a:lt1
+ $objWriter->startElement('a:lt1');
+
+ // a:sysClr
+ $objWriter->startElement('a:sysClr');
+ $objWriter->writeAttribute('val', 'window');
+ $objWriter->writeAttribute('lastClr', 'FFFFFF');
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ // a:dk2
+ $this->_writeColourScheme($objWriter);
+
+ $objWriter->endElement();
+
+ // a:fontScheme
+ $objWriter->startElement('a:fontScheme');
+ $objWriter->writeAttribute('name', 'Office');
+
+ // a:majorFont
+ $objWriter->startElement('a:majorFont');
+ $this->_writeFonts($objWriter, 'Cambria', self::$_majorFonts);
+ $objWriter->endElement();
+
+ // a:minorFont
+ $objWriter->startElement('a:minorFont');
+ $this->_writeFonts($objWriter, 'Calibri', self::$_minorFonts);
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ // a:fmtScheme
+ $objWriter->startElement('a:fmtScheme');
+ $objWriter->writeAttribute('name', 'Office');
+
+ // a:fillStyleLst
+ $objWriter->startElement('a:fillStyleLst');
+
+ // a:solidFill
+ $objWriter->startElement('a:solidFill');
+
+ // a:schemeClr
+ $objWriter->startElement('a:schemeClr');
+ $objWriter->writeAttribute('val', 'phClr');
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ // a:gradFill
+ $objWriter->startElement('a:gradFill');
+ $objWriter->writeAttribute('rotWithShape', '1');
- // a:gsLst
- $objWriter->startElement('a:gsLst');
+ // a:gsLst
+ $objWriter->startElement('a:gsLst');
- // a:gs
- $objWriter->startElement('a:gs');
- $objWriter->writeAttribute('pos', '0');
+ // a:gs
+ $objWriter->startElement('a:gs');
+ $objWriter->writeAttribute('pos', '0');
- // a:schemeClr
- $objWriter->startElement('a:schemeClr');
- $objWriter->writeAttribute('val', 'phClr');
+ // a:schemeClr
+ $objWriter->startElement('a:schemeClr');
+ $objWriter->writeAttribute('val', 'phClr');
- // a:tint
- $objWriter->startElement('a:tint');
- $objWriter->writeAttribute('val', '50000');
- $objWriter->endElement();
+ // a:tint
+ $objWriter->startElement('a:tint');
+ $objWriter->writeAttribute('val', '50000');
+ $objWriter->endElement();
- // a:satMod
- $objWriter->startElement('a:satMod');
- $objWriter->writeAttribute('val', '300000');
- $objWriter->endElement();
+ // a:satMod
+ $objWriter->startElement('a:satMod');
+ $objWriter->writeAttribute('val', '300000');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // a:gs
- $objWriter->startElement('a:gs');
- $objWriter->writeAttribute('pos', '35000');
+ // a:gs
+ $objWriter->startElement('a:gs');
+ $objWriter->writeAttribute('pos', '35000');
- // a:schemeClr
- $objWriter->startElement('a:schemeClr');
- $objWriter->writeAttribute('val', 'phClr');
+ // a:schemeClr
+ $objWriter->startElement('a:schemeClr');
+ $objWriter->writeAttribute('val', 'phClr');
- // a:tint
- $objWriter->startElement('a:tint');
- $objWriter->writeAttribute('val', '37000');
- $objWriter->endElement();
+ // a:tint
+ $objWriter->startElement('a:tint');
+ $objWriter->writeAttribute('val', '37000');
+ $objWriter->endElement();
- // a:satMod
- $objWriter->startElement('a:satMod');
- $objWriter->writeAttribute('val', '300000');
- $objWriter->endElement();
+ // a:satMod
+ $objWriter->startElement('a:satMod');
+ $objWriter->writeAttribute('val', '300000');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // a:gs
- $objWriter->startElement('a:gs');
- $objWriter->writeAttribute('pos', '100000');
+ // a:gs
+ $objWriter->startElement('a:gs');
+ $objWriter->writeAttribute('pos', '100000');
- // a:schemeClr
- $objWriter->startElement('a:schemeClr');
- $objWriter->writeAttribute('val', 'phClr');
+ // a:schemeClr
+ $objWriter->startElement('a:schemeClr');
+ $objWriter->writeAttribute('val', 'phClr');
- // a:tint
- $objWriter->startElement('a:tint');
- $objWriter->writeAttribute('val', '15000');
- $objWriter->endElement();
+ // a:tint
+ $objWriter->startElement('a:tint');
+ $objWriter->writeAttribute('val', '15000');
+ $objWriter->endElement();
- // a:satMod
- $objWriter->startElement('a:satMod');
- $objWriter->writeAttribute('val', '350000');
- $objWriter->endElement();
+ // a:satMod
+ $objWriter->startElement('a:satMod');
+ $objWriter->writeAttribute('val', '350000');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // a:lin
- $objWriter->startElement('a:lin');
- $objWriter->writeAttribute('ang', '16200000');
- $objWriter->writeAttribute('scaled', '1');
- $objWriter->endElement();
+ // a:lin
+ $objWriter->startElement('a:lin');
+ $objWriter->writeAttribute('ang', '16200000');
+ $objWriter->writeAttribute('scaled', '1');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // a:gradFill
- $objWriter->startElement('a:gradFill');
- $objWriter->writeAttribute('rotWithShape', '1');
+ // a:gradFill
+ $objWriter->startElement('a:gradFill');
+ $objWriter->writeAttribute('rotWithShape', '1');
- // a:gsLst
- $objWriter->startElement('a:gsLst');
+ // a:gsLst
+ $objWriter->startElement('a:gsLst');
- // a:gs
- $objWriter->startElement('a:gs');
- $objWriter->writeAttribute('pos', '0');
+ // a:gs
+ $objWriter->startElement('a:gs');
+ $objWriter->writeAttribute('pos', '0');
- // a:schemeClr
- $objWriter->startElement('a:schemeClr');
- $objWriter->writeAttribute('val', 'phClr');
+ // a:schemeClr
+ $objWriter->startElement('a:schemeClr');
+ $objWriter->writeAttribute('val', 'phClr');
- // a:shade
- $objWriter->startElement('a:shade');
- $objWriter->writeAttribute('val', '51000');
- $objWriter->endElement();
+ // a:shade
+ $objWriter->startElement('a:shade');
+ $objWriter->writeAttribute('val', '51000');
+ $objWriter->endElement();
- // a:satMod
- $objWriter->startElement('a:satMod');
- $objWriter->writeAttribute('val', '130000');
- $objWriter->endElement();
+ // a:satMod
+ $objWriter->startElement('a:satMod');
+ $objWriter->writeAttribute('val', '130000');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // a:gs
- $objWriter->startElement('a:gs');
- $objWriter->writeAttribute('pos', '80000');
+ // a:gs
+ $objWriter->startElement('a:gs');
+ $objWriter->writeAttribute('pos', '80000');
- // a:schemeClr
- $objWriter->startElement('a:schemeClr');
- $objWriter->writeAttribute('val', 'phClr');
+ // a:schemeClr
+ $objWriter->startElement('a:schemeClr');
+ $objWriter->writeAttribute('val', 'phClr');
- // a:shade
- $objWriter->startElement('a:shade');
- $objWriter->writeAttribute('val', '93000');
- $objWriter->endElement();
+ // a:shade
+ $objWriter->startElement('a:shade');
+ $objWriter->writeAttribute('val', '93000');
+ $objWriter->endElement();
- // a:satMod
- $objWriter->startElement('a:satMod');
- $objWriter->writeAttribute('val', '130000');
- $objWriter->endElement();
+ // a:satMod
+ $objWriter->startElement('a:satMod');
+ $objWriter->writeAttribute('val', '130000');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // a:gs
- $objWriter->startElement('a:gs');
- $objWriter->writeAttribute('pos', '100000');
+ // a:gs
+ $objWriter->startElement('a:gs');
+ $objWriter->writeAttribute('pos', '100000');
- // a:schemeClr
- $objWriter->startElement('a:schemeClr');
- $objWriter->writeAttribute('val', 'phClr');
+ // a:schemeClr
+ $objWriter->startElement('a:schemeClr');
+ $objWriter->writeAttribute('val', 'phClr');
- // a:shade
- $objWriter->startElement('a:shade');
- $objWriter->writeAttribute('val', '94000');
- $objWriter->endElement();
+ // a:shade
+ $objWriter->startElement('a:shade');
+ $objWriter->writeAttribute('val', '94000');
+ $objWriter->endElement();
- // a:satMod
- $objWriter->startElement('a:satMod');
- $objWriter->writeAttribute('val', '135000');
- $objWriter->endElement();
+ // a:satMod
+ $objWriter->startElement('a:satMod');
+ $objWriter->writeAttribute('val', '135000');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // a:lin
- $objWriter->startElement('a:lin');
- $objWriter->writeAttribute('ang', '16200000');
- $objWriter->writeAttribute('scaled', '0');
- $objWriter->endElement();
+ // a:lin
+ $objWriter->startElement('a:lin');
+ $objWriter->writeAttribute('ang', '16200000');
+ $objWriter->writeAttribute('scaled', '0');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // a:lnStyleLst
- $objWriter->startElement('a:lnStyleLst');
+ // a:lnStyleLst
+ $objWriter->startElement('a:lnStyleLst');
- // a:ln
- $objWriter->startElement('a:ln');
- $objWriter->writeAttribute('w', '9525');
- $objWriter->writeAttribute('cap', 'flat');
- $objWriter->writeAttribute('cmpd', 'sng');
- $objWriter->writeAttribute('algn', 'ctr');
+ // a:ln
+ $objWriter->startElement('a:ln');
+ $objWriter->writeAttribute('w', '9525');
+ $objWriter->writeAttribute('cap', 'flat');
+ $objWriter->writeAttribute('cmpd', 'sng');
+ $objWriter->writeAttribute('algn', 'ctr');
- // a:solidFill
- $objWriter->startElement('a:solidFill');
+ // a:solidFill
+ $objWriter->startElement('a:solidFill');
- // a:schemeClr
- $objWriter->startElement('a:schemeClr');
- $objWriter->writeAttribute('val', 'phClr');
+ // a:schemeClr
+ $objWriter->startElement('a:schemeClr');
+ $objWriter->writeAttribute('val', 'phClr');
- // a:shade
- $objWriter->startElement('a:shade');
- $objWriter->writeAttribute('val', '95000');
- $objWriter->endElement();
+ // a:shade
+ $objWriter->startElement('a:shade');
+ $objWriter->writeAttribute('val', '95000');
+ $objWriter->endElement();
- // a:satMod
- $objWriter->startElement('a:satMod');
- $objWriter->writeAttribute('val', '105000');
- $objWriter->endElement();
+ // a:satMod
+ $objWriter->startElement('a:satMod');
+ $objWriter->writeAttribute('val', '105000');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // a:prstDash
- $objWriter->startElement('a:prstDash');
- $objWriter->writeAttribute('val', 'solid');
- $objWriter->endElement();
+ // a:prstDash
+ $objWriter->startElement('a:prstDash');
+ $objWriter->writeAttribute('val', 'solid');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // a:ln
- $objWriter->startElement('a:ln');
- $objWriter->writeAttribute('w', '25400');
- $objWriter->writeAttribute('cap', 'flat');
- $objWriter->writeAttribute('cmpd', 'sng');
- $objWriter->writeAttribute('algn', 'ctr');
+ // a:ln
+ $objWriter->startElement('a:ln');
+ $objWriter->writeAttribute('w', '25400');
+ $objWriter->writeAttribute('cap', 'flat');
+ $objWriter->writeAttribute('cmpd', 'sng');
+ $objWriter->writeAttribute('algn', 'ctr');
- // a:solidFill
- $objWriter->startElement('a:solidFill');
+ // a:solidFill
+ $objWriter->startElement('a:solidFill');
- // a:schemeClr
- $objWriter->startElement('a:schemeClr');
- $objWriter->writeAttribute('val', 'phClr');
- $objWriter->endElement();
+ // a:schemeClr
+ $objWriter->startElement('a:schemeClr');
+ $objWriter->writeAttribute('val', 'phClr');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // a:prstDash
- $objWriter->startElement('a:prstDash');
- $objWriter->writeAttribute('val', 'solid');
- $objWriter->endElement();
+ // a:prstDash
+ $objWriter->startElement('a:prstDash');
+ $objWriter->writeAttribute('val', 'solid');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // a:ln
- $objWriter->startElement('a:ln');
- $objWriter->writeAttribute('w', '38100');
- $objWriter->writeAttribute('cap', 'flat');
- $objWriter->writeAttribute('cmpd', 'sng');
- $objWriter->writeAttribute('algn', 'ctr');
+ // a:ln
+ $objWriter->startElement('a:ln');
+ $objWriter->writeAttribute('w', '38100');
+ $objWriter->writeAttribute('cap', 'flat');
+ $objWriter->writeAttribute('cmpd', 'sng');
+ $objWriter->writeAttribute('algn', 'ctr');
- // a:solidFill
- $objWriter->startElement('a:solidFill');
+ // a:solidFill
+ $objWriter->startElement('a:solidFill');
- // a:schemeClr
- $objWriter->startElement('a:schemeClr');
- $objWriter->writeAttribute('val', 'phClr');
- $objWriter->endElement();
+ // a:schemeClr
+ $objWriter->startElement('a:schemeClr');
+ $objWriter->writeAttribute('val', 'phClr');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // a:prstDash
- $objWriter->startElement('a:prstDash');
- $objWriter->writeAttribute('val', 'solid');
- $objWriter->endElement();
+ // a:prstDash
+ $objWriter->startElement('a:prstDash');
+ $objWriter->writeAttribute('val', 'solid');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // a:effectStyleLst
- $objWriter->startElement('a:effectStyleLst');
+ // a:effectStyleLst
+ $objWriter->startElement('a:effectStyleLst');
- // a:effectStyle
- $objWriter->startElement('a:effectStyle');
+ // a:effectStyle
+ $objWriter->startElement('a:effectStyle');
- // a:effectLst
- $objWriter->startElement('a:effectLst');
+ // a:effectLst
+ $objWriter->startElement('a:effectLst');
- // a:outerShdw
- $objWriter->startElement('a:outerShdw');
- $objWriter->writeAttribute('blurRad', '40000');
- $objWriter->writeAttribute('dist', '20000');
- $objWriter->writeAttribute('dir', '5400000');
- $objWriter->writeAttribute('rotWithShape', '0');
+ // a:outerShdw
+ $objWriter->startElement('a:outerShdw');
+ $objWriter->writeAttribute('blurRad', '40000');
+ $objWriter->writeAttribute('dist', '20000');
+ $objWriter->writeAttribute('dir', '5400000');
+ $objWriter->writeAttribute('rotWithShape', '0');
- // a:srgbClr
- $objWriter->startElement('a:srgbClr');
- $objWriter->writeAttribute('val', '000000');
+ // a:srgbClr
+ $objWriter->startElement('a:srgbClr');
+ $objWriter->writeAttribute('val', '000000');
- // a:alpha
- $objWriter->startElement('a:alpha');
- $objWriter->writeAttribute('val', '38000');
- $objWriter->endElement();
+ // a:alpha
+ $objWriter->startElement('a:alpha');
+ $objWriter->writeAttribute('val', '38000');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // a:effectStyle
- $objWriter->startElement('a:effectStyle');
+ // a:effectStyle
+ $objWriter->startElement('a:effectStyle');
- // a:effectLst
- $objWriter->startElement('a:effectLst');
+ // a:effectLst
+ $objWriter->startElement('a:effectLst');
- // a:outerShdw
- $objWriter->startElement('a:outerShdw');
- $objWriter->writeAttribute('blurRad', '40000');
- $objWriter->writeAttribute('dist', '23000');
- $objWriter->writeAttribute('dir', '5400000');
- $objWriter->writeAttribute('rotWithShape', '0');
+ // a:outerShdw
+ $objWriter->startElement('a:outerShdw');
+ $objWriter->writeAttribute('blurRad', '40000');
+ $objWriter->writeAttribute('dist', '23000');
+ $objWriter->writeAttribute('dir', '5400000');
+ $objWriter->writeAttribute('rotWithShape', '0');
- // a:srgbClr
- $objWriter->startElement('a:srgbClr');
- $objWriter->writeAttribute('val', '000000');
+ // a:srgbClr
+ $objWriter->startElement('a:srgbClr');
+ $objWriter->writeAttribute('val', '000000');
- // a:alpha
- $objWriter->startElement('a:alpha');
- $objWriter->writeAttribute('val', '35000');
- $objWriter->endElement();
+ // a:alpha
+ $objWriter->startElement('a:alpha');
+ $objWriter->writeAttribute('val', '35000');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // a:effectStyle
- $objWriter->startElement('a:effectStyle');
+ // a:effectStyle
+ $objWriter->startElement('a:effectStyle');
- // a:effectLst
- $objWriter->startElement('a:effectLst');
+ // a:effectLst
+ $objWriter->startElement('a:effectLst');
- // a:outerShdw
- $objWriter->startElement('a:outerShdw');
- $objWriter->writeAttribute('blurRad', '40000');
- $objWriter->writeAttribute('dist', '23000');
- $objWriter->writeAttribute('dir', '5400000');
- $objWriter->writeAttribute('rotWithShape', '0');
+ // a:outerShdw
+ $objWriter->startElement('a:outerShdw');
+ $objWriter->writeAttribute('blurRad', '40000');
+ $objWriter->writeAttribute('dist', '23000');
+ $objWriter->writeAttribute('dir', '5400000');
+ $objWriter->writeAttribute('rotWithShape', '0');
- // a:srgbClr
- $objWriter->startElement('a:srgbClr');
- $objWriter->writeAttribute('val', '000000');
+ // a:srgbClr
+ $objWriter->startElement('a:srgbClr');
+ $objWriter->writeAttribute('val', '000000');
- // a:alpha
- $objWriter->startElement('a:alpha');
- $objWriter->writeAttribute('val', '35000');
- $objWriter->endElement();
+ // a:alpha
+ $objWriter->startElement('a:alpha');
+ $objWriter->writeAttribute('val', '35000');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // a:scene3d
- $objWriter->startElement('a:scene3d');
+ // a:scene3d
+ $objWriter->startElement('a:scene3d');
- // a:camera
- $objWriter->startElement('a:camera');
- $objWriter->writeAttribute('prst', 'orthographicFront');
+ // a:camera
+ $objWriter->startElement('a:camera');
+ $objWriter->writeAttribute('prst', 'orthographicFront');
- // a:rot
- $objWriter->startElement('a:rot');
- $objWriter->writeAttribute('lat', '0');
- $objWriter->writeAttribute('lon', '0');
- $objWriter->writeAttribute('rev', '0');
- $objWriter->endElement();
+ // a:rot
+ $objWriter->startElement('a:rot');
+ $objWriter->writeAttribute('lat', '0');
+ $objWriter->writeAttribute('lon', '0');
+ $objWriter->writeAttribute('rev', '0');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // a:lightRig
- $objWriter->startElement('a:lightRig');
- $objWriter->writeAttribute('rig', 'threePt');
- $objWriter->writeAttribute('dir', 't');
+ // a:lightRig
+ $objWriter->startElement('a:lightRig');
+ $objWriter->writeAttribute('rig', 'threePt');
+ $objWriter->writeAttribute('dir', 't');
- // a:rot
- $objWriter->startElement('a:rot');
- $objWriter->writeAttribute('lat', '0');
- $objWriter->writeAttribute('lon', '0');
- $objWriter->writeAttribute('rev', '1200000');
- $objWriter->endElement();
+ // a:rot
+ $objWriter->startElement('a:rot');
+ $objWriter->writeAttribute('lat', '0');
+ $objWriter->writeAttribute('lon', '0');
+ $objWriter->writeAttribute('rev', '1200000');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // a:sp3d
- $objWriter->startElement('a:sp3d');
+ // a:sp3d
+ $objWriter->startElement('a:sp3d');
- // a:bevelT
- $objWriter->startElement('a:bevelT');
- $objWriter->writeAttribute('w', '63500');
- $objWriter->writeAttribute('h', '25400');
- $objWriter->endElement();
+ // a:bevelT
+ $objWriter->startElement('a:bevelT');
+ $objWriter->writeAttribute('w', '63500');
+ $objWriter->writeAttribute('h', '25400');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // a:bgFillStyleLst
- $objWriter->startElement('a:bgFillStyleLst');
+ // a:bgFillStyleLst
+ $objWriter->startElement('a:bgFillStyleLst');
- // a:solidFill
- $objWriter->startElement('a:solidFill');
+ // a:solidFill
+ $objWriter->startElement('a:solidFill');
- // a:schemeClr
- $objWriter->startElement('a:schemeClr');
- $objWriter->writeAttribute('val', 'phClr');
- $objWriter->endElement();
+ // a:schemeClr
+ $objWriter->startElement('a:schemeClr');
+ $objWriter->writeAttribute('val', 'phClr');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // a:gradFill
- $objWriter->startElement('a:gradFill');
- $objWriter->writeAttribute('rotWithShape', '1');
+ // a:gradFill
+ $objWriter->startElement('a:gradFill');
+ $objWriter->writeAttribute('rotWithShape', '1');
- // a:gsLst
- $objWriter->startElement('a:gsLst');
+ // a:gsLst
+ $objWriter->startElement('a:gsLst');
- // a:gs
- $objWriter->startElement('a:gs');
- $objWriter->writeAttribute('pos', '0');
+ // a:gs
+ $objWriter->startElement('a:gs');
+ $objWriter->writeAttribute('pos', '0');
- // a:schemeClr
- $objWriter->startElement('a:schemeClr');
- $objWriter->writeAttribute('val', 'phClr');
+ // a:schemeClr
+ $objWriter->startElement('a:schemeClr');
+ $objWriter->writeAttribute('val', 'phClr');
- // a:tint
- $objWriter->startElement('a:tint');
- $objWriter->writeAttribute('val', '40000');
- $objWriter->endElement();
+ // a:tint
+ $objWriter->startElement('a:tint');
+ $objWriter->writeAttribute('val', '40000');
+ $objWriter->endElement();
- // a:satMod
- $objWriter->startElement('a:satMod');
- $objWriter->writeAttribute('val', '350000');
- $objWriter->endElement();
+ // a:satMod
+ $objWriter->startElement('a:satMod');
+ $objWriter->writeAttribute('val', '350000');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // a:gs
- $objWriter->startElement('a:gs');
- $objWriter->writeAttribute('pos', '40000');
+ // a:gs
+ $objWriter->startElement('a:gs');
+ $objWriter->writeAttribute('pos', '40000');
- // a:schemeClr
- $objWriter->startElement('a:schemeClr');
- $objWriter->writeAttribute('val', 'phClr');
+ // a:schemeClr
+ $objWriter->startElement('a:schemeClr');
+ $objWriter->writeAttribute('val', 'phClr');
- // a:tint
- $objWriter->startElement('a:tint');
- $objWriter->writeAttribute('val', '45000');
- $objWriter->endElement();
+ // a:tint
+ $objWriter->startElement('a:tint');
+ $objWriter->writeAttribute('val', '45000');
+ $objWriter->endElement();
- // a:shade
- $objWriter->startElement('a:shade');
- $objWriter->writeAttribute('val', '99000');
- $objWriter->endElement();
+ // a:shade
+ $objWriter->startElement('a:shade');
+ $objWriter->writeAttribute('val', '99000');
+ $objWriter->endElement();
- // a:satMod
- $objWriter->startElement('a:satMod');
- $objWriter->writeAttribute('val', '350000');
- $objWriter->endElement();
+ // a:satMod
+ $objWriter->startElement('a:satMod');
+ $objWriter->writeAttribute('val', '350000');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // a:gs
- $objWriter->startElement('a:gs');
- $objWriter->writeAttribute('pos', '100000');
+ // a:gs
+ $objWriter->startElement('a:gs');
+ $objWriter->writeAttribute('pos', '100000');
- // a:schemeClr
- $objWriter->startElement('a:schemeClr');
- $objWriter->writeAttribute('val', 'phClr');
+ // a:schemeClr
+ $objWriter->startElement('a:schemeClr');
+ $objWriter->writeAttribute('val', 'phClr');
- // a:shade
- $objWriter->startElement('a:shade');
- $objWriter->writeAttribute('val', '20000');
- $objWriter->endElement();
+ // a:shade
+ $objWriter->startElement('a:shade');
+ $objWriter->writeAttribute('val', '20000');
+ $objWriter->endElement();
- // a:satMod
- $objWriter->startElement('a:satMod');
- $objWriter->writeAttribute('val', '255000');
- $objWriter->endElement();
+ // a:satMod
+ $objWriter->startElement('a:satMod');
+ $objWriter->writeAttribute('val', '255000');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // a:path
- $objWriter->startElement('a:path');
- $objWriter->writeAttribute('path', 'circle');
+ // a:path
+ $objWriter->startElement('a:path');
+ $objWriter->writeAttribute('path', 'circle');
- // a:fillToRect
- $objWriter->startElement('a:fillToRect');
- $objWriter->writeAttribute('l', '50000');
- $objWriter->writeAttribute('t', '-80000');
- $objWriter->writeAttribute('r', '50000');
- $objWriter->writeAttribute('b', '180000');
- $objWriter->endElement();
+ // a:fillToRect
+ $objWriter->startElement('a:fillToRect');
+ $objWriter->writeAttribute('l', '50000');
+ $objWriter->writeAttribute('t', '-80000');
+ $objWriter->writeAttribute('r', '50000');
+ $objWriter->writeAttribute('b', '180000');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // a:gradFill
- $objWriter->startElement('a:gradFill');
- $objWriter->writeAttribute('rotWithShape', '1');
+ // a:gradFill
+ $objWriter->startElement('a:gradFill');
+ $objWriter->writeAttribute('rotWithShape', '1');
- // a:gsLst
- $objWriter->startElement('a:gsLst');
+ // a:gsLst
+ $objWriter->startElement('a:gsLst');
- // a:gs
- $objWriter->startElement('a:gs');
- $objWriter->writeAttribute('pos', '0');
+ // a:gs
+ $objWriter->startElement('a:gs');
+ $objWriter->writeAttribute('pos', '0');
- // a:schemeClr
- $objWriter->startElement('a:schemeClr');
- $objWriter->writeAttribute('val', 'phClr');
+ // a:schemeClr
+ $objWriter->startElement('a:schemeClr');
+ $objWriter->writeAttribute('val', 'phClr');
- // a:tint
- $objWriter->startElement('a:tint');
- $objWriter->writeAttribute('val', '80000');
- $objWriter->endElement();
+ // a:tint
+ $objWriter->startElement('a:tint');
+ $objWriter->writeAttribute('val', '80000');
+ $objWriter->endElement();
- // a:satMod
- $objWriter->startElement('a:satMod');
- $objWriter->writeAttribute('val', '300000');
- $objWriter->endElement();
+ // a:satMod
+ $objWriter->startElement('a:satMod');
+ $objWriter->writeAttribute('val', '300000');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // a:gs
- $objWriter->startElement('a:gs');
- $objWriter->writeAttribute('pos', '100000');
+ // a:gs
+ $objWriter->startElement('a:gs');
+ $objWriter->writeAttribute('pos', '100000');
- // a:schemeClr
- $objWriter->startElement('a:schemeClr');
- $objWriter->writeAttribute('val', 'phClr');
+ // a:schemeClr
+ $objWriter->startElement('a:schemeClr');
+ $objWriter->writeAttribute('val', 'phClr');
- // a:shade
- $objWriter->startElement('a:shade');
- $objWriter->writeAttribute('val', '30000');
- $objWriter->endElement();
-
- // a:satMod
- $objWriter->startElement('a:satMod');
- $objWriter->writeAttribute('val', '200000');
- $objWriter->endElement();
-
- $objWriter->endElement();
+ // a:shade
+ $objWriter->startElement('a:shade');
+ $objWriter->writeAttribute('val', '30000');
+ $objWriter->endElement();
+
+ // a:satMod
+ $objWriter->startElement('a:satMod');
+ $objWriter->writeAttribute('val', '200000');
+ $objWriter->endElement();
+
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // a:path
- $objWriter->startElement('a:path');
- $objWriter->writeAttribute('path', 'circle');
+ // a:path
+ $objWriter->startElement('a:path');
+ $objWriter->writeAttribute('path', 'circle');
- // a:fillToRect
- $objWriter->startElement('a:fillToRect');
- $objWriter->writeAttribute('l', '50000');
- $objWriter->writeAttribute('t', '50000');
- $objWriter->writeAttribute('r', '50000');
- $objWriter->writeAttribute('b', '50000');
- $objWriter->endElement();
-
- $objWriter->endElement();
-
- $objWriter->endElement();
-
- $objWriter->endElement();
-
- $objWriter->endElement();
+ // a:fillToRect
+ $objWriter->startElement('a:fillToRect');
+ $objWriter->writeAttribute('l', '50000');
+ $objWriter->writeAttribute('t', '50000');
+ $objWriter->writeAttribute('r', '50000');
+ $objWriter->writeAttribute('b', '50000');
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ $objWriter->endElement();
- $objWriter->endElement();
-
- // a:objectDefaults
- $objWriter->writeElement('a:objectDefaults', null);
+ $objWriter->endElement();
+
+ // a:objectDefaults
+ $objWriter->writeElement('a:objectDefaults', null);
- // a:extraClrSchemeLst
- $objWriter->writeElement('a:extraClrSchemeLst', null);
-
- $objWriter->endElement();
-
- // Return
- return $objWriter->getData();
- }
-
- /**
- * Write fonts to XML format
- *
- * @param PHPExcel\Shared_XMLWriter $objWriter
- * @param string $latinFont
- * @param array of string $fontSet
- * @return string XML Output
- * @throws PHPExcel\Writer_Exception
- */
- private function _writeFonts(Shared_XMLWriter $objWriter, $latinFont, $fontSet)
- {
- // a:latin
- $objWriter->startElement('a:latin');
- $objWriter->writeAttribute('typeface', $latinFont);
- $objWriter->endElement();
-
- // a:ea
- $objWriter->startElement('a:ea');
- $objWriter->writeAttribute('typeface', '');
- $objWriter->endElement();
-
- // a:cs
- $objWriter->startElement('a:cs');
- $objWriter->writeAttribute('typeface', '');
- $objWriter->endElement();
-
- foreach($fontSet as $fontScript => $typeface) {
- $objWriter->startElement('a:font');
- $objWriter->writeAttribute('script', $fontScript);
- $objWriter->writeAttribute('typeface', $typeface);
- $objWriter->endElement();
- }
-
- }
-
- /**
- * Write colour scheme to XML format
- *
- * @param PHPExcel\Shared_XMLWriter $objWriter
- * @return string XML Output
- * @throws PHPExcel\Writer_Exception
- */
- private function _writeColourScheme(Shared_XMLWriter $objWriter)
- {
- foreach(self::$_colourScheme as $colourName => $colourValue) {
- $objWriter->startElement('a:'.$colourName);
-
- $objWriter->startElement('a:srgbClr');
- $objWriter->writeAttribute('val', $colourValue);
- $objWriter->endElement();
-
- $objWriter->endElement();
- }
-
- }
+ // a:extraClrSchemeLst
+ $objWriter->writeElement('a:extraClrSchemeLst', null);
+
+ $objWriter->endElement();
+
+ // Return
+ return $objWriter->getData();
+ }
+
+ /**
+ * Write fonts to XML format
+ *
+ * @param PHPExcel\Shared_XMLWriter $objWriter
+ * @param string $latinFont
+ * @param array of string $fontSet
+ * @return string XML Output
+ * @throws PHPExcel\Writer_Exception
+ */
+ private function _writeFonts(Shared_XMLWriter $objWriter, $latinFont, $fontSet)
+ {
+ // a:latin
+ $objWriter->startElement('a:latin');
+ $objWriter->writeAttribute('typeface', $latinFont);
+ $objWriter->endElement();
+
+ // a:ea
+ $objWriter->startElement('a:ea');
+ $objWriter->writeAttribute('typeface', '');
+ $objWriter->endElement();
+
+ // a:cs
+ $objWriter->startElement('a:cs');
+ $objWriter->writeAttribute('typeface', '');
+ $objWriter->endElement();
+
+ foreach($fontSet as $fontScript => $typeface) {
+ $objWriter->startElement('a:font');
+ $objWriter->writeAttribute('script', $fontScript);
+ $objWriter->writeAttribute('typeface', $typeface);
+ $objWriter->endElement();
+ }
+
+ }
+
+ /**
+ * Write colour scheme to XML format
+ *
+ * @param PHPExcel\Shared_XMLWriter $objWriter
+ * @return string XML Output
+ * @throws PHPExcel\Writer_Exception
+ */
+ private function _writeColourScheme(Shared_XMLWriter $objWriter)
+ {
+ foreach(self::$_colourScheme as $colourName => $colourValue) {
+ $objWriter->startElement('a:'.$colourName);
+
+ $objWriter->startElement('a:srgbClr');
+ $objWriter->writeAttribute('val', $colourValue);
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+ }
+
+ }
}
diff --git a/Classes/PHPExcel/Writer/Excel2007/Workbook.php b/Classes/PHPExcel/Writer/Excel2007/Workbook.php
index 9614fe7..738da50 100644
--- a/Classes/PHPExcel/Writer/Excel2007/Workbook.php
+++ b/Classes/PHPExcel/Writer/Excel2007/Workbook.php
@@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\Writer_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,418 +37,418 @@ namespace PHPExcel;
*/
class Writer_Excel2007_Workbook extends Writer_Excel2007_WriterPart
{
- /**
- * Write workbook to XML format
- *
- * @param PHPExcel\Workbook $pPHPExcel
- * @param boolean $recalcRequired Indicate whether formulas should be recalculated before writing
- * @return string XML Output
- * @throws PHPExcel\Writer_Exception
- */
- public function writeWorkbook(Workbook $pPHPExcel = null, $recalcRequired = FALSE)
- {
- // Create XML writer
- $objWriter = null;
- if ($this->getParentWriter()->getUseDiskCaching()) {
- $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
- } else {
- $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_MEMORY);
- }
+ /**
+ * Write workbook to XML format
+ *
+ * @param PHPExcel\Workbook $pPHPExcel
+ * @param boolean $recalcRequired Indicate whether formulas should be recalculated before writing
+ * @return string XML Output
+ * @throws PHPExcel\Writer_Exception
+ */
+ public function writeWorkbook(Workbook $pPHPExcel = null, $recalcRequired = false)
+ {
+ // Create XML writer
+ $objWriter = null;
+ if ($this->getParentWriter()->getUseDiskCaching()) {
+ $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
+ } else {
+ $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_MEMORY);
+ }
- // XML header
- $objWriter->startDocument('1.0','UTF-8','yes');
+ // XML header
+ $objWriter->startDocument('1.0','UTF-8','yes');
- // workbook
- $objWriter->startElement('workbook');
- $objWriter->writeAttribute('xml:space', 'preserve');
- $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main');
- $objWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships');
+ // workbook
+ $objWriter->startElement('workbook');
+ $objWriter->writeAttribute('xml:space', 'preserve');
+ $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main');
+ $objWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships');
- // fileVersion
- $this->_writeFileVersion($objWriter);
+ // fileVersion
+ $this->_writeFileVersion($objWriter);
- // workbookPr
- $this->_writeWorkbookPr($objWriter);
+ // workbookPr
+ $this->_writeWorkbookPr($objWriter);
- // workbookProtection
- $this->_writeWorkbookProtection($objWriter, $pPHPExcel);
+ // workbookProtection
+ $this->_writeWorkbookProtection($objWriter, $pPHPExcel);
- // bookViews
- if ($this->getParentWriter()->getOffice2003Compatibility() === false) {
- $this->_writeBookViews($objWriter, $pPHPExcel);
- }
+ // bookViews
+ if ($this->getParentWriter()->getOffice2003Compatibility() === false) {
+ $this->_writeBookViews($objWriter, $pPHPExcel);
+ }
- // sheets
- $this->_writeSheets($objWriter, $pPHPExcel);
+ // sheets
+ $this->_writeSheets($objWriter, $pPHPExcel);
- // definedNames
- $this->_writeDefinedNames($objWriter, $pPHPExcel);
+ // definedNames
+ $this->_writeDefinedNames($objWriter, $pPHPExcel);
- // calcPr
- $this->_writeCalcPr($objWriter,$recalcRequired);
+ // calcPr
+ $this->_writeCalcPr($objWriter,$recalcRequired);
- $objWriter->endElement();
+ $objWriter->endElement();
- // Return
- return $objWriter->getData();
- }
+ // Return
+ return $objWriter->getData();
+ }
- /**
- * Write file version
- *
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @throws PHPExcel\Writer_Exception
- */
- private function _writeFileVersion(Shared_XMLWriter $objWriter = null)
- {
- $objWriter->startElement('fileVersion');
- $objWriter->writeAttribute('appName', 'xl');
- $objWriter->writeAttribute('lastEdited', '4');
- $objWriter->writeAttribute('lowestEdited', '4');
- $objWriter->writeAttribute('rupBuild', '4505');
- $objWriter->endElement();
- }
+ /**
+ * Write file version
+ *
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @throws PHPExcel\Writer_Exception
+ */
+ private function _writeFileVersion(Shared_XMLWriter $objWriter = null)
+ {
+ $objWriter->startElement('fileVersion');
+ $objWriter->writeAttribute('appName', 'xl');
+ $objWriter->writeAttribute('lastEdited', '4');
+ $objWriter->writeAttribute('lowestEdited', '4');
+ $objWriter->writeAttribute('rupBuild', '4505');
+ $objWriter->endElement();
+ }
- /**
- * Write WorkbookPr
- *
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @throws PHPExcel\Writer_Exception
- */
- private function _writeWorkbookPr(Shared_XMLWriter $objWriter = null)
- {
- $objWriter->startElement('workbookPr');
+ /**
+ * Write WorkbookPr
+ *
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @throws PHPExcel\Writer_Exception
+ */
+ private function _writeWorkbookPr(Shared_XMLWriter $objWriter = null)
+ {
+ $objWriter->startElement('workbookPr');
- if (Shared_Date::getExcelCalendar() == Shared_Date::CALENDAR_MAC_1904) {
- $objWriter->writeAttribute('date1904', '1');
- }
+ if (Shared_Date::getExcelCalendar() == Shared_Date::CALENDAR_MAC_1904) {
+ $objWriter->writeAttribute('date1904', '1');
+ }
- $objWriter->writeAttribute('codeName', 'ThisWorkbook');
+ $objWriter->writeAttribute('codeName', 'ThisWorkbook');
- $objWriter->endElement();
- }
+ $objWriter->endElement();
+ }
- /**
- * Write BookViews
- *
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel\Workbook $pPHPExcel
- * @throws PHPExcel\Writer_Exception
- */
- private function _writeBookViews(Shared_XMLWriter $objWriter = null, Workbook $pPHPExcel = null)
- {
- // bookViews
- $objWriter->startElement('bookViews');
+ /**
+ * Write BookViews
+ *
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel\Workbook $pPHPExcel
+ * @throws PHPExcel\Writer_Exception
+ */
+ private function _writeBookViews(Shared_XMLWriter $objWriter = null, Workbook $pPHPExcel = null)
+ {
+ // bookViews
+ $objWriter->startElement('bookViews');
- // workbookView
- $objWriter->startElement('workbookView');
+ // workbookView
+ $objWriter->startElement('workbookView');
- $objWriter->writeAttribute('activeTab', $pPHPExcel->getActiveSheetIndex());
- $objWriter->writeAttribute('autoFilterDateGrouping', '1');
- $objWriter->writeAttribute('firstSheet', '0');
- $objWriter->writeAttribute('minimized', '0');
- $objWriter->writeAttribute('showHorizontalScroll', '1');
- $objWriter->writeAttribute('showSheetTabs', '1');
- $objWriter->writeAttribute('showVerticalScroll', '1');
- $objWriter->writeAttribute('tabRatio', '600');
- $objWriter->writeAttribute('visibility', 'visible');
+ $objWriter->writeAttribute('activeTab', $pPHPExcel->getActiveSheetIndex());
+ $objWriter->writeAttribute('autoFilterDateGrouping', '1');
+ $objWriter->writeAttribute('firstSheet', '0');
+ $objWriter->writeAttribute('minimized', '0');
+ $objWriter->writeAttribute('showHorizontalScroll', '1');
+ $objWriter->writeAttribute('showSheetTabs', '1');
+ $objWriter->writeAttribute('showVerticalScroll', '1');
+ $objWriter->writeAttribute('tabRatio', '600');
+ $objWriter->writeAttribute('visibility', 'visible');
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
- }
+ $objWriter->endElement();
+ }
- /**
- * Write WorkbookProtection
- *
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel\Workbook $pPHPExcel
- * @throws PHPExcel\Writer_Exception
- */
- private function _writeWorkbookProtection(Shared_XMLWriter $objWriter = null, Workbook $pPHPExcel = null)
- {
- if ($pPHPExcel->getSecurity()->isSecurityEnabled()) {
- $objWriter->startElement('workbookProtection');
- $objWriter->writeAttribute('lockRevision', ($pPHPExcel->getSecurity()->getLockRevision() ? 'true' : 'false'));
- $objWriter->writeAttribute('lockStructure', ($pPHPExcel->getSecurity()->getLockStructure() ? 'true' : 'false'));
- $objWriter->writeAttribute('lockWindows', ($pPHPExcel->getSecurity()->getLockWindows() ? 'true' : 'false'));
+ /**
+ * Write WorkbookProtection
+ *
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel\Workbook $pPHPExcel
+ * @throws PHPExcel\Writer_Exception
+ */
+ private function _writeWorkbookProtection(Shared_XMLWriter $objWriter = null, Workbook $pPHPExcel = null)
+ {
+ if ($pPHPExcel->getSecurity()->isSecurityEnabled()) {
+ $objWriter->startElement('workbookProtection');
+ $objWriter->writeAttribute('lockRevision', ($pPHPExcel->getSecurity()->getLockRevision() ? 'true' : 'false'));
+ $objWriter->writeAttribute('lockStructure', ($pPHPExcel->getSecurity()->getLockStructure() ? 'true' : 'false'));
+ $objWriter->writeAttribute('lockWindows', ($pPHPExcel->getSecurity()->getLockWindows() ? 'true' : 'false'));
- if ($pPHPExcel->getSecurity()->getRevisionsPassword() != '') {
- $objWriter->writeAttribute('revisionsPassword', $pPHPExcel->getSecurity()->getRevisionsPassword());
- }
+ if ($pPHPExcel->getSecurity()->getRevisionsPassword() != '') {
+ $objWriter->writeAttribute('revisionsPassword', $pPHPExcel->getSecurity()->getRevisionsPassword());
+ }
- if ($pPHPExcel->getSecurity()->getWorkbookPassword() != '') {
- $objWriter->writeAttribute('workbookPassword', $pPHPExcel->getSecurity()->getWorkbookPassword());
- }
+ if ($pPHPExcel->getSecurity()->getWorkbookPassword() != '') {
+ $objWriter->writeAttribute('workbookPassword', $pPHPExcel->getSecurity()->getWorkbookPassword());
+ }
- $objWriter->endElement();
- }
- }
+ $objWriter->endElement();
+ }
+ }
- /**
- * Write calcPr
- *
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @param boolean $recalcRequired Indicate whether formulas should be recalculated before writing
- * @throws PHPExcel\Writer_Exception
- */
- private function _writeCalcPr(Shared_XMLWriter $objWriter = null, $recalcRequired = TRUE)
- {
- $objWriter->startElement('calcPr');
+ /**
+ * Write calcPr
+ *
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @param boolean $recalcRequired Indicate whether formulas should be recalculated before writing
+ * @throws PHPExcel\Writer_Exception
+ */
+ private function _writeCalcPr(Shared_XMLWriter $objWriter = null, $recalcRequired = TRUE)
+ {
+ $objWriter->startElement('calcPr');
- $objWriter->writeAttribute('calcId', '124519');
- $objWriter->writeAttribute('calcMode', 'auto');
- // fullCalcOnLoad isn't needed if we've recalculating for the save
- $objWriter->writeAttribute('fullCalcOnLoad', ($recalcRequired) ? '0' : '1');
+ $objWriter->writeAttribute('calcId', '124519');
+ $objWriter->writeAttribute('calcMode', 'auto');
+ // fullCalcOnLoad isn't needed if we've recalculating for the save
+ $objWriter->writeAttribute('fullCalcOnLoad', ($recalcRequired) ? '0' : '1');
- $objWriter->endElement();
- }
+ $objWriter->endElement();
+ }
- /**
- * Write sheets
- *
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel\Workbook $pPHPExcel
- * @throws PHPExcel\Writer_Exception
- */
- private function _writeSheets(Shared_XMLWriter $objWriter = null, Workbook $pPHPExcel = null)
- {
- // Write sheets
- $objWriter->startElement('sheets');
- $sheetCount = $pPHPExcel->getSheetCount();
- for ($i = 0; $i < $sheetCount; ++$i) {
- // sheet
- $this->_writeSheet(
- $objWriter,
- $pPHPExcel->getSheet($i)->getTitle(),
- ($i + 1),
- ($i + 1 + 3),
- $pPHPExcel->getSheet($i)->getSheetState()
- );
- }
+ /**
+ * Write sheets
+ *
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel\Workbook $pPHPExcel
+ * @throws PHPExcel\Writer_Exception
+ */
+ private function _writeSheets(Shared_XMLWriter $objWriter = null, Workbook $pPHPExcel = null)
+ {
+ // Write sheets
+ $objWriter->startElement('sheets');
+ $sheetCount = $pPHPExcel->getSheetCount();
+ for ($i = 0; $i < $sheetCount; ++$i) {
+ // sheet
+ $this->_writeSheet(
+ $objWriter,
+ $pPHPExcel->getSheet($i)->getTitle(),
+ ($i + 1),
+ ($i + 1 + 3),
+ $pPHPExcel->getSheet($i)->getSheetState()
+ );
+ }
- $objWriter->endElement();
- }
+ $objWriter->endElement();
+ }
- /**
- * Write sheet
- *
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @param string $pSheetname Sheet name
- * @param int $pSheetId Sheet id
- * @param int $pRelId Relationship ID
- * @param string $sheetState Sheet state (visible, hidden, veryHidden)
- * @throws PHPExcel\Writer_Exception
- */
- private function _writeSheet(Shared_XMLWriter $objWriter = null, $pSheetname = '', $pSheetId = 1, $pRelId = 1, $sheetState = 'visible')
- {
- if ($pSheetname != '') {
- // Write sheet
- $objWriter->startElement('sheet');
- $objWriter->writeAttribute('name', $pSheetname);
- $objWriter->writeAttribute('sheetId', $pSheetId);
- if ($sheetState != 'visible' && $sheetState != '') {
- $objWriter->writeAttribute('state', $sheetState);
- }
- $objWriter->writeAttribute('r:id', 'rId' . $pRelId);
- $objWriter->endElement();
- } else {
- throw new Writer_Exception("Invalid parameters passed.");
- }
- }
+ /**
+ * Write sheet
+ *
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @param string $pSheetname Sheet name
+ * @param int $pSheetId Sheet id
+ * @param int $pRelId Relationship ID
+ * @param string $sheetState Sheet state (visible, hidden, veryHidden)
+ * @throws PHPExcel\Writer_Exception
+ */
+ private function _writeSheet(Shared_XMLWriter $objWriter = null, $pSheetname = '', $pSheetId = 1, $pRelId = 1, $sheetState = 'visible')
+ {
+ if ($pSheetname != '') {
+ // Write sheet
+ $objWriter->startElement('sheet');
+ $objWriter->writeAttribute('name', $pSheetname);
+ $objWriter->writeAttribute('sheetId', $pSheetId);
+ if ($sheetState != 'visible' && $sheetState != '') {
+ $objWriter->writeAttribute('state', $sheetState);
+ }
+ $objWriter->writeAttribute('r:id', 'rId' . $pRelId);
+ $objWriter->endElement();
+ } else {
+ throw new Writer_Exception("Invalid parameters passed.");
+ }
+ }
- /**
- * Write Defined Names
- *
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel\Workbook $pPHPExcel
- * @throws PHPExcel\Writer_Exception
- */
- private function _writeDefinedNames(Shared_XMLWriter $objWriter = null, Workbook $pPHPExcel = null)
- {
- // Write defined names
- $objWriter->startElement('definedNames');
+ /**
+ * Write Defined Names
+ *
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel\Workbook $pPHPExcel
+ * @throws PHPExcel\Writer_Exception
+ */
+ private function _writeDefinedNames(Shared_XMLWriter $objWriter = null, Workbook $pPHPExcel = null)
+ {
+ // Write defined names
+ $objWriter->startElement('definedNames');
- // Named ranges
- if (count($pPHPExcel->getNamedRanges()) > 0) {
- // Named ranges
- $this->_writeNamedRanges($objWriter, $pPHPExcel);
- }
+ // Named ranges
+ if (count($pPHPExcel->getNamedRanges()) > 0) {
+ // Named ranges
+ $this->_writeNamedRanges($objWriter, $pPHPExcel);
+ }
- // Other defined names
- $sheetCount = $pPHPExcel->getSheetCount();
- for ($i = 0; $i < $sheetCount; ++$i) {
- // definedName for autoFilter
- $this->_writeDefinedNameForAutofilter($objWriter, $pPHPExcel->getSheet($i), $i);
+ // Other defined names
+ $sheetCount = $pPHPExcel->getSheetCount();
+ for ($i = 0; $i < $sheetCount; ++$i) {
+ // definedName for autoFilter
+ $this->_writeDefinedNameForAutofilter($objWriter, $pPHPExcel->getSheet($i), $i);
- // definedName for Print_Titles
- $this->_writeDefinedNameForPrintTitles($objWriter, $pPHPExcel->getSheet($i), $i);
+ // definedName for Print_Titles
+ $this->_writeDefinedNameForPrintTitles($objWriter, $pPHPExcel->getSheet($i), $i);
- // definedName for Print_Area
- $this->_writeDefinedNameForPrintArea($objWriter, $pPHPExcel->getSheet($i), $i);
- }
+ // definedName for Print_Area
+ $this->_writeDefinedNameForPrintArea($objWriter, $pPHPExcel->getSheet($i), $i);
+ }
- $objWriter->endElement();
- }
+ $objWriter->endElement();
+ }
- /**
- * Write named ranges
- *
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel $pPHPExcel
- * @throws PHPExcel\Writer_Exception
- */
- private function _writeNamedRanges(Shared_XMLWriter $objWriter = null, Workbook $pPHPExcel)
- {
- // Loop named ranges
- $namedRanges = $pPHPExcel->getNamedRanges();
- foreach ($namedRanges as $namedRange) {
- $this->_writeDefinedNameForNamedRange($objWriter, $namedRange);
- }
- }
+ /**
+ * Write named ranges
+ *
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel $pPHPExcel
+ * @throws PHPExcel\Writer_Exception
+ */
+ private function _writeNamedRanges(Shared_XMLWriter $objWriter = null, Workbook $pPHPExcel)
+ {
+ // Loop named ranges
+ $namedRanges = $pPHPExcel->getNamedRanges();
+ foreach ($namedRanges as $namedRange) {
+ $this->_writeDefinedNameForNamedRange($objWriter, $namedRange);
+ }
+ }
- /**
- * Write Defined Name for named range
- *
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel\NamedRange $pNamedRange
- * @throws PHPExcel\Writer_Exception
- */
- private function _writeDefinedNameForNamedRange(Shared_XMLWriter $objWriter = null, NamedRange $pNamedRange)
- {
- // definedName for named range
- $objWriter->startElement('definedName');
- $objWriter->writeAttribute('name', $pNamedRange->getName());
- if ($pNamedRange->getLocalOnly()) {
- $objWriter->writeAttribute('localSheetId', $pNamedRange->getScope()->getParent()->getIndex($pNamedRange->getScope()));
- }
+ /**
+ * Write Defined Name for named range
+ *
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel\NamedRange $pNamedRange
+ * @throws PHPExcel\Writer_Exception
+ */
+ private function _writeDefinedNameForNamedRange(Shared_XMLWriter $objWriter = null, NamedRange $pNamedRange)
+ {
+ // definedName for named range
+ $objWriter->startElement('definedName');
+ $objWriter->writeAttribute('name', $pNamedRange->getName());
+ if ($pNamedRange->getLocalOnly()) {
+ $objWriter->writeAttribute('localSheetId', $pNamedRange->getScope()->getParent()->getIndex($pNamedRange->getScope()));
+ }
- // Create absolute coordinate and write as raw text
- $range = Cell::splitRange($pNamedRange->getRange());
- for ($i = 0; $i < count($range); $i++) {
- $range[$i][0] = '\'' . str_replace("'", "''", $pNamedRange->getWorksheet()->getTitle()) . '\'!' . Cell::absoluteReference($range[$i][0]);
- if (isset($range[$i][1])) {
- $range[$i][1] = Cell::absoluteReference($range[$i][1]);
- }
- }
- $range = Cell::buildRange($range);
+ // Create absolute coordinate and write as raw text
+ $range = Cell::splitRange($pNamedRange->getRange());
+ for ($i = 0; $i < count($range); $i++) {
+ $range[$i][0] = '\'' . str_replace("'", "''", $pNamedRange->getWorksheet()->getTitle()) . '\'!' . Cell::absoluteReference($range[$i][0]);
+ if (isset($range[$i][1])) {
+ $range[$i][1] = Cell::absoluteReference($range[$i][1]);
+ }
+ }
+ $range = Cell::buildRange($range);
- $objWriter->writeRawData($range);
+ $objWriter->writeRawData($range);
- $objWriter->endElement();
- }
+ $objWriter->endElement();
+ }
- /**
- * Write Defined Name for autoFilter
- *
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel\Worksheet $pSheet
- * @param int $pSheetId
- * @throws PHPExcel\Writer_Exception
- */
- private function _writeDefinedNameForAutofilter(Shared_XMLWriter $objWriter = null, Worksheet $pSheet = null, $pSheetId = 0)
- {
- // definedName for autoFilter
- $autoFilterRange = $pSheet->getAutoFilter()->getRange();
- if (!empty($autoFilterRange)) {
- $objWriter->startElement('definedName');
- $objWriter->writeAttribute('name', '_xlnm._FilterDatabase');
- $objWriter->writeAttribute('localSheetId', $pSheetId);
- $objWriter->writeAttribute('hidden', '1');
+ /**
+ * Write Defined Name for autoFilter
+ *
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel\Worksheet $pSheet
+ * @param int $pSheetId
+ * @throws PHPExcel\Writer_Exception
+ */
+ private function _writeDefinedNameForAutofilter(Shared_XMLWriter $objWriter = null, Worksheet $pSheet = null, $pSheetId = 0)
+ {
+ // definedName for autoFilter
+ $autoFilterRange = $pSheet->getAutoFilter()->getRange();
+ if (!empty($autoFilterRange)) {
+ $objWriter->startElement('definedName');
+ $objWriter->writeAttribute('name', '_xlnm._FilterDatabase');
+ $objWriter->writeAttribute('localSheetId', $pSheetId);
+ $objWriter->writeAttribute('hidden', '1');
- // Create absolute coordinate and write as raw text
- $range = Cell::splitRange($autoFilterRange);
- $range = $range[0];
- // Strip any worksheet ref so we can make the cell ref absolute
- if (strpos($range[0],'!') !== false) {
- list($ws,$range[0]) = explode('!',$range[0]);
- }
+ // Create absolute coordinate and write as raw text
+ $range = Cell::splitRange($autoFilterRange);
+ $range = $range[0];
+ // Strip any worksheet ref so we can make the cell ref absolute
+ if (strpos($range[0],'!') !== false) {
+ list($ws,$range[0]) = explode('!',$range[0]);
+ }
- $range[0] = Cell::absoluteCoordinate($range[0]);
- $range[1] = Cell::absoluteCoordinate($range[1]);
- $range = implode(':', $range);
+ $range[0] = Cell::absoluteCoordinate($range[0]);
+ $range[1] = Cell::absoluteCoordinate($range[1]);
+ $range = implode(':', $range);
- $objWriter->writeRawData('\'' . str_replace("'", "''", $pSheet->getTitle()) . '\'!' . $range);
+ $objWriter->writeRawData('\'' . str_replace("'", "''", $pSheet->getTitle()) . '\'!' . $range);
- $objWriter->endElement();
- }
- }
+ $objWriter->endElement();
+ }
+ }
- /**
- * Write Defined Name for PrintTitles
- *
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel\Worksheet $pSheet
- * @param int $pSheetId
- * @throws PHPExcel\Writer_Exception
- */
- private function _writeDefinedNameForPrintTitles(Shared_XMLWriter $objWriter = null, Worksheet $pSheet = null, $pSheetId = 0)
- {
- // definedName for PrintTitles
- if ($pSheet->getPageSetup()->isColumnsToRepeatAtLeftSet() || $pSheet->getPageSetup()->isRowsToRepeatAtTopSet()) {
- $objWriter->startElement('definedName');
- $objWriter->writeAttribute('name', '_xlnm.Print_Titles');
- $objWriter->writeAttribute('localSheetId', $pSheetId);
+ /**
+ * Write Defined Name for PrintTitles
+ *
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel\Worksheet $pSheet
+ * @param int $pSheetId
+ * @throws PHPExcel\Writer_Exception
+ */
+ private function _writeDefinedNameForPrintTitles(Shared_XMLWriter $objWriter = null, Worksheet $pSheet = null, $pSheetId = 0)
+ {
+ // definedName for PrintTitles
+ if ($pSheet->getPageSetup()->isColumnsToRepeatAtLeftSet() || $pSheet->getPageSetup()->isRowsToRepeatAtTopSet()) {
+ $objWriter->startElement('definedName');
+ $objWriter->writeAttribute('name', '_xlnm.Print_Titles');
+ $objWriter->writeAttribute('localSheetId', $pSheetId);
- // Setting string
- $settingString = '';
+ // Setting string
+ $settingString = '';
- // Columns to repeat
- if ($pSheet->getPageSetup()->isColumnsToRepeatAtLeftSet()) {
- $repeat = $pSheet->getPageSetup()->getColumnsToRepeatAtLeft();
+ // Columns to repeat
+ if ($pSheet->getPageSetup()->isColumnsToRepeatAtLeftSet()) {
+ $repeat = $pSheet->getPageSetup()->getColumnsToRepeatAtLeft();
- $settingString .= '\'' . str_replace("'", "''", $pSheet->getTitle()) . '\'!$' . $repeat[0] . ':$' . $repeat[1];
- }
+ $settingString .= '\'' . str_replace("'", "''", $pSheet->getTitle()) . '\'!$' . $repeat[0] . ':$' . $repeat[1];
+ }
- // Rows to repeat
- if ($pSheet->getPageSetup()->isRowsToRepeatAtTopSet()) {
- if ($pSheet->getPageSetup()->isColumnsToRepeatAtLeftSet()) {
- $settingString .= ',';
- }
+ // Rows to repeat
+ if ($pSheet->getPageSetup()->isRowsToRepeatAtTopSet()) {
+ if ($pSheet->getPageSetup()->isColumnsToRepeatAtLeftSet()) {
+ $settingString .= ',';
+ }
- $repeat = $pSheet->getPageSetup()->getRowsToRepeatAtTop();
+ $repeat = $pSheet->getPageSetup()->getRowsToRepeatAtTop();
- $settingString .= '\'' . str_replace("'", "''", $pSheet->getTitle()) . '\'!$' . $repeat[0] . ':$' . $repeat[1];
- }
+ $settingString .= '\'' . str_replace("'", "''", $pSheet->getTitle()) . '\'!$' . $repeat[0] . ':$' . $repeat[1];
+ }
- $objWriter->writeRawData($settingString);
+ $objWriter->writeRawData($settingString);
- $objWriter->endElement();
- }
- }
+ $objWriter->endElement();
+ }
+ }
- /**
- * Write Defined Name for PrintTitles
- *
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel\Worksheet $pSheet
- * @param int $pSheetId
- * @throws PHPExcel\Writer_Exception
- */
- private function _writeDefinedNameForPrintArea(Shared_XMLWriter $objWriter = null, Worksheet $pSheet = null, $pSheetId = 0)
- {
- // definedName for PrintArea
- if ($pSheet->getPageSetup()->isPrintAreaSet()) {
- $objWriter->startElement('definedName');
- $objWriter->writeAttribute('name', '_xlnm.Print_Area');
- $objWriter->writeAttribute('localSheetId', $pSheetId);
+ /**
+ * Write Defined Name for PrintTitles
+ *
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel\Worksheet $pSheet
+ * @param int $pSheetId
+ * @throws PHPExcel\Writer_Exception
+ */
+ private function _writeDefinedNameForPrintArea(Shared_XMLWriter $objWriter = null, Worksheet $pSheet = null, $pSheetId = 0)
+ {
+ // definedName for PrintArea
+ if ($pSheet->getPageSetup()->isPrintAreaSet()) {
+ $objWriter->startElement('definedName');
+ $objWriter->writeAttribute('name', '_xlnm.Print_Area');
+ $objWriter->writeAttribute('localSheetId', $pSheetId);
- // Setting string
- $settingString = '';
+ // Setting string
+ $settingString = '';
- // Print area
- $printArea = Cell::splitRange($pSheet->getPageSetup()->getPrintArea());
+ // Print area
+ $printArea = Cell::splitRange($pSheet->getPageSetup()->getPrintArea());
- $chunks = array();
- foreach ($printArea as $printAreaRect) {
- $printAreaRect[0] = Cell::absoluteReference($printAreaRect[0]);
- $printAreaRect[1] = Cell::absoluteReference($printAreaRect[1]);
- $chunks[] = '\'' . str_replace("'", "''", $pSheet->getTitle()) . '\'!' . implode(':', $printAreaRect);
- }
+ $chunks = array();
+ foreach ($printArea as $printAreaRect) {
+ $printAreaRect[0] = Cell::absoluteReference($printAreaRect[0]);
+ $printAreaRect[1] = Cell::absoluteReference($printAreaRect[1]);
+ $chunks[] = '\'' . str_replace("'", "''", $pSheet->getTitle()) . '\'!' . implode(':', $printAreaRect);
+ }
- $objWriter->writeRawData(implode(',', $chunks));
+ $objWriter->writeRawData(implode(',', $chunks));
- $objWriter->endElement();
- }
- }
+ $objWriter->endElement();
+ }
+ }
}
diff --git a/Classes/PHPExcel/Writer/Excel2007/Worksheet.php b/Classes/PHPExcel/Writer/Excel2007/Worksheet.php
index 81e7162..592a669 100644
--- a/Classes/PHPExcel/Writer/Excel2007/Worksheet.php
+++ b/Classes/PHPExcel/Writer/Excel2007/Worksheet.php
@@ -19,10 +19,10 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category PHPExcel
- * @package PHPExcel\Writer_Excel2007
+ * @package PHPExcel\Writer_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##
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
+ * @version ##VERSION##, ##DATE##
*/
@@ -32,1185 +32,1185 @@ namespace PHPExcel;
* PHPExcel\Writer_Excel2007_Worksheet
*
* @category PHPExcel
- * @package PHPExcel\Writer_Excel2007
+ * @package PHPExcel\Writer_Excel2007
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
*/
class Writer_Excel2007_Worksheet extends Writer_Excel2007_WriterPart
{
- /**
- * Write worksheet to XML format
- *
- * @param PHPExcel\Worksheet $pSheet
- * @param string[] $pStringTable
- * @param boolean $includeCharts Flag indicating if we should write charts
- * @return string XML Output
- * @throws PHPExcel\Writer_Exception
- */
- public function writeWorksheet($pSheet = null, $pStringTable = null, $includeCharts = FALSE)
- {
- if (!is_null($pSheet)) {
- // Create XML writer
- $objWriter = null;
- if ($this->getParentWriter()->getUseDiskCaching()) {
- $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
- } else {
- $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_MEMORY);
- }
-
- // XML header
- $objWriter->startDocument('1.0','UTF-8','yes');
-
- // Worksheet
- $objWriter->startElement('worksheet');
- $objWriter->writeAttribute('xml:space', 'preserve');
- $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main');
- $objWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships');
-
- // sheetPr
- $this->_writeSheetPr($objWriter, $pSheet);
-
- // Dimension
- $this->_writeDimension($objWriter, $pSheet);
-
- // sheetViews
- $this->_writeSheetViews($objWriter, $pSheet);
-
- // sheetFormatPr
- $this->_writeSheetFormatPr($objWriter, $pSheet);
-
- // cols
- $this->_writeCols($objWriter, $pSheet);
-
- // sheetData
- $this->_writeSheetData($objWriter, $pSheet, $pStringTable);
-
- // sheetProtection
- $this->_writeSheetProtection($objWriter, $pSheet);
-
- // protectedRanges
- $this->_writeProtectedRanges($objWriter, $pSheet);
-
- // autoFilter
- $this->_writeAutoFilter($objWriter, $pSheet);
-
- // mergeCells
- $this->_writeMergeCells($objWriter, $pSheet);
-
- // conditionalFormatting
- $this->_writeConditionalFormatting($objWriter, $pSheet);
-
- // dataValidations
- $this->_writeDataValidations($objWriter, $pSheet);
-
- // hyperlinks
- $this->_writeHyperlinks($objWriter, $pSheet);
-
- // Print options
- $this->_writePrintOptions($objWriter, $pSheet);
-
- // Page margins
- $this->_writePageMargins($objWriter, $pSheet);
-
- // Page setup
- $this->_writePageSetup($objWriter, $pSheet);
-
- // Header / footer
- $this->_writeHeaderFooter($objWriter, $pSheet);
-
- // Breaks
- $this->_writeBreaks($objWriter, $pSheet);
-
- // Drawings and/or Charts
- $this->_writeDrawings($objWriter, $pSheet, $includeCharts);
-
- // LegacyDrawing
- $this->_writeLegacyDrawing($objWriter, $pSheet);
-
- // LegacyDrawingHF
- $this->_writeLegacyDrawingHF($objWriter, $pSheet);
-
- $objWriter->endElement();
-
- // Return
- return $objWriter->getData();
- } else {
- throw new Writer_Exception("Invalid PHPExcel\Worksheet object passed.");
- }
- }
-
- /**
- * Write SheetPr
- *
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel\Worksheet $pSheet Worksheet
- * @throws PHPExcel\Writer_Exception
- */
- private function _writeSheetPr(Shared_XMLWriter $objWriter = null, Worksheet $pSheet = null)
- {
- // sheetPr
- $objWriter->startElement('sheetPr');
- //$objWriter->writeAttribute('codeName', $pSheet->getTitle());
- $autoFilterRange = $pSheet->getAutoFilter()->getRange();
- if (!empty($autoFilterRange)) {
- $objWriter->writeAttribute('filterMode', 1);
- $pSheet->getAutoFilter()->showHideRows();
- }
-
- // tabColor
- if ($pSheet->isTabColorSet()) {
- $objWriter->startElement('tabColor');
- $objWriter->writeAttribute('rgb', $pSheet->getTabColor()->getARGB());
- $objWriter->endElement();
- }
-
- // outlinePr
- $objWriter->startElement('outlinePr');
- $objWriter->writeAttribute('summaryBelow', ($pSheet->getShowSummaryBelow() ? '1' : '0'));
- $objWriter->writeAttribute('summaryRight', ($pSheet->getShowSummaryRight() ? '1' : '0'));
- $objWriter->endElement();
-
- // pageSetUpPr
- if ($pSheet->getPageSetup()->getFitToPage()) {
- $objWriter->startElement('pageSetUpPr');
- $objWriter->writeAttribute('fitToPage', '1');
- $objWriter->endElement();
- }
-
- $objWriter->endElement();
- }
-
- /**
- * Write Dimension
- *
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel\Worksheet $pSheet Worksheet
- * @throws PHPExcel\Writer_Exception
- */
- private function _writeDimension(Shared_XMLWriter $objWriter = null, Worksheet $pSheet = null)
- {
- // dimension
- $objWriter->startElement('dimension');
- $objWriter->writeAttribute('ref', $pSheet->calculateWorksheetDimension());
- $objWriter->endElement();
- }
-
- /**
- * Write SheetViews
- *
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel\Worksheet $pSheet Worksheet
- * @throws PHPExcel\Writer_Exception
- */
- private function _writeSheetViews(Shared_XMLWriter $objWriter = NULL, Worksheet $pSheet = NULL)
- {
- // sheetViews
- $objWriter->startElement('sheetViews');
-
- // Sheet selected?
- $sheetSelected = false;
- if ($this->getParentWriter()->getPHPExcel()->getIndex($pSheet) == $this->getParentWriter()->getPHPExcel()->getActiveSheetIndex())
- $sheetSelected = true;
-
-
- // sheetView
- $objWriter->startElement('sheetView');
- $objWriter->writeAttribute('tabSelected', $sheetSelected ? '1' : '0');
- $objWriter->writeAttribute('workbookViewId', '0');
-
- // Zoom scales
- if ($pSheet->getSheetView()->getZoomScale() != 100) {
- $objWriter->writeAttribute('zoomScale', $pSheet->getSheetView()->getZoomScale());
- }
- if ($pSheet->getSheetView()->getZoomScaleNormal() != 100) {
- $objWriter->writeAttribute('zoomScaleNormal', $pSheet->getSheetView()->getZoomScaleNormal());
- }
-
- // View Layout Type
- if ($pSheet->getSheetView()->getView() !== Worksheet_SheetView::SHEETVIEW_NORMAL) {
- $objWriter->writeAttribute('view', $pSheet->getSheetView()->getView());
- }
-
- // Gridlines
- if ($pSheet->getShowGridlines()) {
- $objWriter->writeAttribute('showGridLines', 'true');
- } else {
- $objWriter->writeAttribute('showGridLines', 'false');
- }
-
- // Row and column headers
- if ($pSheet->getShowRowColHeaders()) {
- $objWriter->writeAttribute('showRowColHeaders', '1');
- } else {
- $objWriter->writeAttribute('showRowColHeaders', '0');
- }
-
- // Right-to-left
- if ($pSheet->getRightToLeft()) {
- $objWriter->writeAttribute('rightToLeft', 'true');
- }
-
- $activeCell = $pSheet->getActiveCell();
-
- // Pane
- $pane = '';
- $topLeftCell = $pSheet->getFreezePane();
- if (($topLeftCell != '') && ($topLeftCell != 'A1')) {
- $activeCell = $topLeftCell;
- // Calculate freeze coordinates
- $xSplit = $ySplit = 0;
-
- list($xSplit, $ySplit) = Cell::coordinateFromString($topLeftCell);
- $xSplit = Cell::columnIndexFromString($xSplit);
-
- // pane
- $pane = 'topRight';
- $objWriter->startElement('pane');
- if ($xSplit > 1)
- $objWriter->writeAttribute('xSplit', $xSplit - 1);
- if ($ySplit > 1) {
- $objWriter->writeAttribute('ySplit', $ySplit - 1);
- $pane = ($xSplit > 1) ? 'bottomRight' : 'bottomLeft';
- }
- $objWriter->writeAttribute('topLeftCell', $topLeftCell);
- $objWriter->writeAttribute('activePane', $pane);
- $objWriter->writeAttribute('state', 'frozen');
- $objWriter->endElement();
-
- if (($xSplit > 1) && ($ySplit > 1)) {
- // Write additional selections if more than two panes (ie both an X and a Y split)
- $objWriter->startElement('selection'); $objWriter->writeAttribute('pane', 'topRight'); $objWriter->endElement();
- $objWriter->startElement('selection'); $objWriter->writeAttribute('pane', 'bottomLeft'); $objWriter->endElement();
- }
- }
-
- // Selection
-// if ($pane != '') {
- // Only need to write selection element if we have a split pane
- // We cheat a little by over-riding the active cell selection, setting it to the split cell
- $objWriter->startElement('selection');
- if ($pane != '') {
- $objWriter->writeAttribute('pane', $pane);
- }
- $objWriter->writeAttribute('activeCell', $activeCell);
- $objWriter->writeAttribute('sqref', $activeCell);
- $objWriter->endElement();
-// }
-
- $objWriter->endElement();
-
- $objWriter->endElement();
- }
-
- /**
- * Write SheetFormatPr
- *
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel\Worksheet $pSheet Worksheet
- * @throws PHPExcel\Writer_Exception
- */
- private function _writeSheetFormatPr(Shared_XMLWriter $objWriter = null, Worksheet $pSheet = null)
- {
- // sheetFormatPr
- $objWriter->startElement('sheetFormatPr');
-
- // Default row height
- if ($pSheet->getDefaultRowDimension()->getRowHeight() >= 0) {
- $objWriter->writeAttribute('customHeight', 'true');
- $objWriter->writeAttribute('defaultRowHeight', Shared_String::FormatNumber($pSheet->getDefaultRowDimension()->getRowHeight()));
- } else {
- $objWriter->writeAttribute('defaultRowHeight', '14.4');
- }
-
- // Set Zero Height row
- if ((string)$pSheet->getDefaultRowDimension()->getzeroHeight() == '1' ||
- strtolower((string)$pSheet->getDefaultRowDimension()->getzeroHeight()) == 'true' ) {
- $objWriter->writeAttribute('zeroHeight', '1');
- }
-
- // Default column width
- if ($pSheet->getDefaultColumnDimension()->getWidth() >= 0) {
- $objWriter->writeAttribute('defaultColWidth', Shared_String::FormatNumber($pSheet->getDefaultColumnDimension()->getWidth()));
- }
-
- // Outline level - row
- $outlineLevelRow = 0;
- foreach ($pSheet->getRowDimensions() as $dimension) {
- if ($dimension->getOutlineLevel() > $outlineLevelRow) {
- $outlineLevelRow = $dimension->getOutlineLevel();
- }
- }
- $objWriter->writeAttribute('outlineLevelRow', (int)$outlineLevelRow);
-
- // Outline level - column
- $outlineLevelCol = 0;
- foreach ($pSheet->getColumnDimensions() as $dimension) {
- if ($dimension->getOutlineLevel() > $outlineLevelCol) {
- $outlineLevelCol = $dimension->getOutlineLevel();
- }
- }
- $objWriter->writeAttribute('outlineLevelCol', (int)$outlineLevelCol);
-
- $objWriter->endElement();
- }
-
- /**
- * Write Cols
- *
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel\Worksheet $pSheet Worksheet
- * @throws PHPExcel\Writer_Exception
- */
- private function _writeCols(Shared_XMLWriter $objWriter = null, Worksheet $pSheet = null)
- {
- // cols
- if (count($pSheet->getColumnDimensions()) > 0) {
- $objWriter->startElement('cols');
-
- $pSheet->calculateColumnWidths();
-
- // Loop through column dimensions
- foreach ($pSheet->getColumnDimensions() as $colDimension) {
- // col
- $objWriter->startElement('col');
- $objWriter->writeAttribute('min', Cell::columnIndexFromString($colDimension->getColumnIndex()));
- $objWriter->writeAttribute('max', Cell::columnIndexFromString($colDimension->getColumnIndex()));
-
- if ($colDimension->getWidth() < 0) {
- // No width set, apply default of 10
- $objWriter->writeAttribute('width', '9.10');
- } else {
- // Width set
- $objWriter->writeAttribute('width', Shared_String::FormatNumber($colDimension->getWidth()));
- }
-
- // Column visibility
- if ($colDimension->getVisible() == false) {
- $objWriter->writeAttribute('hidden', 'true');
- }
-
- // Auto size?
- if ($colDimension->getAutoSize()) {
- $objWriter->writeAttribute('bestFit', 'true');
- }
-
- // Custom width?
- if ($colDimension->getWidth() != $pSheet->getDefaultColumnDimension()->getWidth()) {
- $objWriter->writeAttribute('customWidth', 'true');
- }
-
- // Collapsed
- if ($colDimension->getCollapsed() == true) {
- $objWriter->writeAttribute('collapsed', 'true');
- }
-
- // Outline level
- if ($colDimension->getOutlineLevel() > 0) {
- $objWriter->writeAttribute('outlineLevel', $colDimension->getOutlineLevel());
- }
-
- // Style
- $objWriter->writeAttribute('style', $colDimension->getXfIndex());
-
- $objWriter->endElement();
- }
-
- $objWriter->endElement();
- }
- }
-
- /**
- * Write SheetProtection
- *
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel\Worksheet $pSheet Worksheet
- * @throws PHPExcel\Writer_Exception
- */
- private function _writeSheetProtection(Shared_XMLWriter $objWriter = null, Worksheet $pSheet = null)
- {
- // sheetProtection
- $objWriter->startElement('sheetProtection');
-
- if ($pSheet->getProtection()->getPassword() != '') {
- $objWriter->writeAttribute('password', $pSheet->getProtection()->getPassword());
- }
-
- $objWriter->writeAttribute('sheet', ($pSheet->getProtection()->getSheet() ? 'true' : 'false'));
- $objWriter->writeAttribute('objects', ($pSheet->getProtection()->getObjects() ? 'true' : 'false'));
- $objWriter->writeAttribute('scenarios', ($pSheet->getProtection()->getScenarios() ? 'true' : 'false'));
- $objWriter->writeAttribute('formatCells', ($pSheet->getProtection()->getFormatCells() ? 'true' : 'false'));
- $objWriter->writeAttribute('formatColumns', ($pSheet->getProtection()->getFormatColumns() ? 'true' : 'false'));
- $objWriter->writeAttribute('formatRows', ($pSheet->getProtection()->getFormatRows() ? 'true' : 'false'));
- $objWriter->writeAttribute('insertColumns', ($pSheet->getProtection()->getInsertColumns() ? 'true' : 'false'));
- $objWriter->writeAttribute('insertRows', ($pSheet->getProtection()->getInsertRows() ? 'true' : 'false'));
- $objWriter->writeAttribute('insertHyperlinks', ($pSheet->getProtection()->getInsertHyperlinks() ? 'true' : 'false'));
- $objWriter->writeAttribute('deleteColumns', ($pSheet->getProtection()->getDeleteColumns() ? 'true' : 'false'));
- $objWriter->writeAttribute('deleteRows', ($pSheet->getProtection()->getDeleteRows() ? 'true' : 'false'));
- $objWriter->writeAttribute('selectLockedCells', ($pSheet->getProtection()->getSelectLockedCells() ? 'true' : 'false'));
- $objWriter->writeAttribute('sort', ($pSheet->getProtection()->getSort() ? 'true' : 'false'));
- $objWriter->writeAttribute('autoFilter', ($pSheet->getProtection()->getAutoFilter() ? 'true' : 'false'));
- $objWriter->writeAttribute('pivotTables', ($pSheet->getProtection()->getPivotTables() ? 'true' : 'false'));
- $objWriter->writeAttribute('selectUnlockedCells', ($pSheet->getProtection()->getSelectUnlockedCells() ? 'true' : 'false'));
- $objWriter->endElement();
- }
-
- /**
- * Write ConditionalFormatting
- *
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel\Worksheet $pSheet Worksheet
- * @throws PHPExcel\Writer_Exception
- */
- private function _writeConditionalFormatting(Shared_XMLWriter $objWriter = null, Worksheet $pSheet = null)
- {
- // Conditional id
- $id = 1;
-
- // Loop through styles in the current worksheet
- foreach ($pSheet->getConditionalStylesCollection() as $cellCoordinate => $conditionalStyles) {
- foreach ($conditionalStyles as $conditional) {
- // WHY was this again?
- // if ($this->getParentWriter()->getStylesConditionalHashTable()->getIndexForHashCode( $conditional->getHashCode() ) == '') {
- // continue;
- // }
- if ($conditional->getConditionType() != Style_Conditional::CONDITION_NONE) {
- // conditionalFormatting
- $objWriter->startElement('conditionalFormatting');
- $objWriter->writeAttribute('sqref', $cellCoordinate);
-
- // cfRule
- $objWriter->startElement('cfRule');
- $objWriter->writeAttribute('type', $conditional->getConditionType());
- $objWriter->writeAttribute('dxfId', $this->getParentWriter()->getStylesConditionalHashTable()->getIndexForHashCode( $conditional->getHashCode() ));
- $objWriter->writeAttribute('priority', $id++);
-
- if (($conditional->getConditionType() == Style_Conditional::CONDITION_CELLIS
- ||
- $conditional->getConditionType() == Style_Conditional::CONDITION_CONTAINSTEXT)
- && $conditional->getOperatorType() != Style_Conditional::OPERATOR_NONE) {
- $objWriter->writeAttribute('operator', $conditional->getOperatorType());
- }
-
- if ($conditional->getConditionType() == Style_Conditional::CONDITION_CONTAINSTEXT
- && !is_null($conditional->getText())) {
- $objWriter->writeAttribute('text', $conditional->getText());
- }
-
- if ($conditional->getConditionType() == Style_Conditional::CONDITION_CONTAINSTEXT
- && $conditional->getOperatorType() == Style_Conditional::OPERATOR_CONTAINSTEXT
- && !is_null($conditional->getText())) {
- $objWriter->writeElement('formula', 'NOT(ISERROR(SEARCH("' . $conditional->getText() . '",' . $cellCoordinate . ')))');
- } else if ($conditional->getConditionType() == Style_Conditional::CONDITION_CONTAINSTEXT
- && $conditional->getOperatorType() == Style_Conditional::OPERATOR_BEGINSWITH
- && !is_null($conditional->getText())) {
- $objWriter->writeElement('formula', 'LEFT(' . $cellCoordinate . ',' . strlen($conditional->getText()) . ')="' . $conditional->getText() . '"');
- } else if ($conditional->getConditionType() == Style_Conditional::CONDITION_CONTAINSTEXT
- && $conditional->getOperatorType() == Style_Conditional::OPERATOR_ENDSWITH
- && !is_null($conditional->getText())) {
- $objWriter->writeElement('formula', 'RIGHT(' . $cellCoordinate . ',' . strlen($conditional->getText()) . ')="' . $conditional->getText() . '"');
- } else if ($conditional->getConditionType() == Style_Conditional::CONDITION_CONTAINSTEXT
- && $conditional->getOperatorType() == Style_Conditional::OPERATOR_NOTCONTAINS
- && !is_null($conditional->getText())) {
- $objWriter->writeElement('formula', 'ISERROR(SEARCH("' . $conditional->getText() . '",' . $cellCoordinate . '))');
- } else if ($conditional->getConditionType() == Style_Conditional::CONDITION_CELLIS
- || $conditional->getConditionType() == Style_Conditional::CONDITION_CONTAINSTEXT
- || $conditional->getConditionType() == Style_Conditional::CONDITION_EXPRESSION) {
- foreach ($conditional->getConditions() as $formula) {
- // Formula
- $objWriter->writeElement('formula', $formula);
- }
- }
-
- $objWriter->endElement();
-
- $objWriter->endElement();
- }
- }
- }
- }
-
- /**
- * Write DataValidations
- *
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel\Worksheet $pSheet Worksheet
- * @throws PHPExcel\Writer_Exception
- */
- private function _writeDataValidations(Shared_XMLWriter $objWriter = null, Worksheet $pSheet = null)
- {
- // Datavalidation collection
- $dataValidationCollection = $pSheet->getDataValidationCollection();
-
- // Write data validations?
- if (!empty($dataValidationCollection)) {
- $objWriter->startElement('dataValidations');
- $objWriter->writeAttribute('count', count($dataValidationCollection));
-
- foreach ($dataValidationCollection as $coordinate => $dv) {
- $objWriter->startElement('dataValidation');
-
- if ($dv->getType() != '') {
- $objWriter->writeAttribute('type', $dv->getType());
- }
-
- if ($dv->getErrorStyle() != '') {
- $objWriter->writeAttribute('errorStyle', $dv->getErrorStyle());
- }
-
- if ($dv->getOperator() != '') {
- $objWriter->writeAttribute('operator', $dv->getOperator());
- }
-
- $objWriter->writeAttribute('allowBlank', ($dv->getAllowBlank() ? '1' : '0'));
- $objWriter->writeAttribute('showDropDown', (!$dv->getShowDropDown() ? '1' : '0'));
- $objWriter->writeAttribute('showInputMessage', ($dv->getShowInputMessage() ? '1' : '0'));
- $objWriter->writeAttribute('showErrorMessage', ($dv->getShowErrorMessage() ? '1' : '0'));
-
- if ($dv->getErrorTitle() !== '') {
- $objWriter->writeAttribute('errorTitle', $dv->getErrorTitle());
- }
- if ($dv->getError() !== '') {
- $objWriter->writeAttribute('error', $dv->getError());
- }
- if ($dv->getPromptTitle() !== '') {
- $objWriter->writeAttribute('promptTitle', $dv->getPromptTitle());
- }
- if ($dv->getPrompt() !== '') {
- $objWriter->writeAttribute('prompt', $dv->getPrompt());
- }
-
- $objWriter->writeAttribute('sqref', $coordinate);
-
- if ($dv->getFormula1() !== '') {
- $objWriter->writeElement('formula1', $dv->getFormula1());
- }
- if ($dv->getFormula2() !== '') {
- $objWriter->writeElement('formula2', $dv->getFormula2());
- }
-
- $objWriter->endElement();
- }
-
- $objWriter->endElement();
- }
- }
-
- /**
- * Write Hyperlinks
- *
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel\Worksheet $pSheet Worksheet
- * @throws PHPExcel\Writer_Exception
- */
- private function _writeHyperlinks(Shared_XMLWriter $objWriter = null, Worksheet $pSheet = null)
- {
- // Hyperlink collection
- $hyperlinkCollection = $pSheet->getHyperlinkCollection();
-
- // Relation ID
- $relationId = 1;
-
- // Write hyperlinks?
- if (!empty($hyperlinkCollection)) {
- $objWriter->startElement('hyperlinks');
-
- foreach ($hyperlinkCollection as $coordinate => $hyperlink) {
- $objWriter->startElement('hyperlink');
-
- $objWriter->writeAttribute('ref', $coordinate);
- if (!$hyperlink->isInternal()) {
- $objWriter->writeAttribute('r:id', 'rId_hyperlink_' . $relationId);
- ++$relationId;
- } else {
- $objWriter->writeAttribute('location', str_replace('sheet://', '', $hyperlink->getUrl()));
- }
-
- if ($hyperlink->getTooltip() != '') {
- $objWriter->writeAttribute('tooltip', $hyperlink->getTooltip());
- }
-
- $objWriter->endElement();
- }
-
- $objWriter->endElement();
- }
- }
-
- /**
- * Write ProtectedRanges
- *
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel\Worksheet $pSheet Worksheet
- * @throws PHPExcel\Writer_Exception
- */
- private function _writeProtectedRanges(Shared_XMLWriter $objWriter = null, Worksheet $pSheet = null)
- {
- if (count($pSheet->getProtectedCells()) > 0) {
- // protectedRanges
- $objWriter->startElement('protectedRanges');
-
- // Loop protectedRanges
- foreach ($pSheet->getProtectedCells() as $protectedCell => $passwordHash) {
- // protectedRange
- $objWriter->startElement('protectedRange');
- $objWriter->writeAttribute('name', 'p' . md5($protectedCell));
- $objWriter->writeAttribute('sqref', $protectedCell);
- if (!empty($passwordHash)) {
- $objWriter->writeAttribute('password', $passwordHash);
- }
- $objWriter->endElement();
- }
-
- $objWriter->endElement();
- }
- }
-
- /**
- * Write MergeCells
- *
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel\Worksheet $pSheet Worksheet
- * @throws PHPExcel\Writer_Exception
- */
- private function _writeMergeCells(Shared_XMLWriter $objWriter = null, Worksheet $pSheet = null)
- {
- if (count($pSheet->getMergeCells()) > 0) {
- // mergeCells
- $objWriter->startElement('mergeCells');
-
- // Loop mergeCells
- foreach ($pSheet->getMergeCells() as $mergeCell) {
- // mergeCell
- $objWriter->startElement('mergeCell');
- $objWriter->writeAttribute('ref', $mergeCell);
- $objWriter->endElement();
- }
-
- $objWriter->endElement();
- }
- }
-
- /**
- * Write PrintOptions
- *
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel\Worksheet $pSheet Worksheet
- * @throws PHPExcel\Writer_Exception
- */
- private function _writePrintOptions(Shared_XMLWriter $objWriter = null, Worksheet $pSheet = null)
- {
- // printOptions
- $objWriter->startElement('printOptions');
-
- $objWriter->writeAttribute('gridLines', ($pSheet->getPrintGridlines() ? 'true': 'false'));
- $objWriter->writeAttribute('gridLinesSet', 'true');
-
- if ($pSheet->getPageSetup()->getHorizontalCentered()) {
- $objWriter->writeAttribute('horizontalCentered', 'true');
- }
-
- if ($pSheet->getPageSetup()->getVerticalCentered()) {
- $objWriter->writeAttribute('verticalCentered', 'true');
- }
-
- $objWriter->endElement();
- }
-
- /**
- * Write PageMargins
- *
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel\Worksheet $pSheet Worksheet
- * @throws PHPExcel|Writer_Exception
- */
- private function _writePageMargins(Shared_XMLWriter $objWriter = null, Worksheet $pSheet = null)
- {
- // pageMargins
- $objWriter->startElement('pageMargins');
- $objWriter->writeAttribute('left', Shared_String::FormatNumber($pSheet->getPageMargins()->getLeft()));
- $objWriter->writeAttribute('right', Shared_String::FormatNumber($pSheet->getPageMargins()->getRight()));
- $objWriter->writeAttribute('top', Shared_String::FormatNumber($pSheet->getPageMargins()->getTop()));
- $objWriter->writeAttribute('bottom', Shared_String::FormatNumber($pSheet->getPageMargins()->getBottom()));
- $objWriter->writeAttribute('header', Shared_String::FormatNumber($pSheet->getPageMargins()->getHeader()));
- $objWriter->writeAttribute('footer', Shared_String::FormatNumber($pSheet->getPageMargins()->getFooter()));
- $objWriter->endElement();
- }
-
- /**
- * Write AutoFilter
- *
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel\Worksheet $pSheet Worksheet
- * @throws PHPExcel\Writer_Exception
- */
- private function _writeAutoFilter(Shared_XMLWriter $objWriter = null, Worksheet $pSheet = null)
- {
- $autoFilterRange = $pSheet->getAutoFilter()->getRange();
- if (!empty($autoFilterRange)) {
- // autoFilter
- $objWriter->startElement('autoFilter');
-
- // Strip any worksheet reference from the filter coordinates
- $range = Cell::splitRange($autoFilterRange);
- $range = $range[0];
- // Strip any worksheet ref
- if (strpos($range[0],'!') !== false) {
- list($ws,$range[0]) = explode('!',$range[0]);
- }
- $range = implode(':', $range);
-
- $objWriter->writeAttribute('ref', str_replace('$','',$range));
-
- $columns = $pSheet->getAutoFilter()->getColumns();
- if (count($columns > 0)) {
- foreach($columns as $columnID => $column) {
- $rules = $column->getRules();
- if (count($rules > 0)) {
- $objWriter->startElement('filterColumn');
- $objWriter->writeAttribute('colId', $pSheet->getAutoFilter()->getColumnOffset($columnID));
-
- $objWriter->startElement( $column->getFilterType());
- if ($column->getJoin() == Worksheet_AutoFilter_Column::AUTOFILTER_COLUMN_JOIN_AND) {
- $objWriter->writeAttribute('and', 1);
- }
-
- foreach ($rules as $rule) {
- if (($column->getFilterType() === Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_FILTER) &&
- ($rule->getOperator() === Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_EQUAL) &&
- ($rule->getValue() === '')) {
- // Filter rule for Blanks
- $objWriter->writeAttribute('blank', 1);
- } elseif($rule->getRuleType() === Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMICFILTER) {
- // Dynamic Filter Rule
- $objWriter->writeAttribute('type', $rule->getGrouping());
- $val = $column->getAttribute('val');
- if ($val !== NULL) {
- $objWriter->writeAttribute('val', $val);
- }
- $maxVal = $column->getAttribute('maxVal');
- if ($maxVal !== NULL) {
- $objWriter->writeAttribute('maxVal', $maxVal);
- }
- } elseif($rule->getRuleType() === Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_TOPTENFILTER) {
- // Top 10 Filter Rule
- $objWriter->writeAttribute('val', $rule->getValue());
- $objWriter->writeAttribute('percent', (($rule->getOperator() === Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT) ? '1' : '0'));
- $objWriter->writeAttribute('top', (($rule->getGrouping() === Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP) ? '1': '0'));
- } else {
- // Filter, DateGroupItem or CustomFilter
- $objWriter->startElement($rule->getRuleType());
-
- if ($rule->getOperator() !== Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_EQUAL) {
- $objWriter->writeAttribute('operator', $rule->getOperator());
- }
- if ($rule->getRuleType() === Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP) {
- // Date Group filters
- foreach($rule->getValue() as $key => $value) {
- if ($value > '') $objWriter->writeAttribute($key, $value);
- }
- $objWriter->writeAttribute('dateTimeGrouping', $rule->getGrouping());
- } else {
- $objWriter->writeAttribute('val', $rule->getValue());
- }
-
- $objWriter->endElement();
- }
- }
-
- $objWriter->endElement();
-
- $objWriter->endElement();
- }
- }
- }
-
- $objWriter->endElement();
- }
- }
-
- /**
- * Write PageSetup
- *
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel\Worksheet $pSheet Worksheet
- * @throws PHPExcel\Writer_Exception
- */
- private function _writePageSetup(Shared_XMLWriter $objWriter = null, Worksheet $pSheet = null)
- {
- // pageSetup
- $objWriter->startElement('pageSetup');
- $objWriter->writeAttribute('paperSize', $pSheet->getPageSetup()->getPaperSize());
- $objWriter->writeAttribute('orientation', $pSheet->getPageSetup()->getOrientation());
-
- if (!is_null($pSheet->getPageSetup()->getScale())) {
- $objWriter->writeAttribute('scale', $pSheet->getPageSetup()->getScale());
- }
- if (!is_null($pSheet->getPageSetup()->getFitToHeight())) {
- $objWriter->writeAttribute('fitToHeight', $pSheet->getPageSetup()->getFitToHeight());
- } else {
- $objWriter->writeAttribute('fitToHeight', '0');
- }
- if (!is_null($pSheet->getPageSetup()->getFitToWidth())) {
- $objWriter->writeAttribute('fitToWidth', $pSheet->getPageSetup()->getFitToWidth());
- } else {
- $objWriter->writeAttribute('fitToWidth', '0');
- }
- if (!is_null($pSheet->getPageSetup()->getFirstPageNumber())) {
- $objWriter->writeAttribute('firstPageNumber', $pSheet->getPageSetup()->getFirstPageNumber());
- $objWriter->writeAttribute('useFirstPageNumber', '1');
- }
-
- $objWriter->endElement();
- }
-
- /**
- * Write Header / Footer
- *
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel\Worksheet $pSheet Worksheet
- * @throws PHPExcel\Writer_Exception
- */
- private function _writeHeaderFooter(Shared_XMLWriter $objWriter = null, Worksheet $pSheet = null)
- {
- // headerFooter
- $objWriter->startElement('headerFooter');
- $objWriter->writeAttribute('differentOddEven', ($pSheet->getHeaderFooter()->getDifferentOddEven() ? 'true' : 'false'));
- $objWriter->writeAttribute('differentFirst', ($pSheet->getHeaderFooter()->getDifferentFirst() ? 'true' : 'false'));
- $objWriter->writeAttribute('scaleWithDoc', ($pSheet->getHeaderFooter()->getScaleWithDocument() ? 'true' : 'false'));
- $objWriter->writeAttribute('alignWithMargins', ($pSheet->getHeaderFooter()->getAlignWithMargins() ? 'true' : 'false'));
-
- $objWriter->writeElement('oddHeader', $pSheet->getHeaderFooter()->getOddHeader());
- $objWriter->writeElement('oddFooter', $pSheet->getHeaderFooter()->getOddFooter());
- $objWriter->writeElement('evenHeader', $pSheet->getHeaderFooter()->getEvenHeader());
- $objWriter->writeElement('evenFooter', $pSheet->getHeaderFooter()->getEvenFooter());
- $objWriter->writeElement('firstHeader', $pSheet->getHeaderFooter()->getFirstHeader());
- $objWriter->writeElement('firstFooter', $pSheet->getHeaderFooter()->getFirstFooter());
- $objWriter->endElement();
- }
-
- /**
- * Write Breaks
- *
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel\Worksheet $pSheet Worksheet
- * @throws PHPExcel\Writer_Exception
- */
- private function _writeBreaks(Shared_XMLWriter $objWriter = null, Worksheet $pSheet = null)
- {
- // Get row and column breaks
- $aRowBreaks = array();
- $aColumnBreaks = array();
- foreach ($pSheet->getBreaks() as $cell => $breakType) {
- if ($breakType == Worksheet::BREAK_ROW) {
- $aRowBreaks[] = $cell;
- } else if ($breakType == Worksheet::BREAK_COLUMN) {
- $aColumnBreaks[] = $cell;
- }
- }
-
- // rowBreaks
- if (!empty($aRowBreaks)) {
- $objWriter->startElement('rowBreaks');
- $objWriter->writeAttribute('count', count($aRowBreaks));
- $objWriter->writeAttribute('manualBreakCount', count($aRowBreaks));
-
- foreach ($aRowBreaks as $cell) {
- $coords = Cell::coordinateFromString($cell);
-
- $objWriter->startElement('brk');
- $objWriter->writeAttribute('id', $coords[1]);
- $objWriter->writeAttribute('man', '1');
- $objWriter->endElement();
- }
-
- $objWriter->endElement();
- }
-
- // Second, write column breaks
- if (!empty($aColumnBreaks)) {
- $objWriter->startElement('colBreaks');
- $objWriter->writeAttribute('count', count($aColumnBreaks));
- $objWriter->writeAttribute('manualBreakCount', count($aColumnBreaks));
-
- foreach ($aColumnBreaks as $cell) {
- $coords = Cell::coordinateFromString($cell);
-
- $objWriter->startElement('brk');
- $objWriter->writeAttribute('id', Cell::columnIndexFromString($coords[0]) - 1);
- $objWriter->writeAttribute('man', '1');
- $objWriter->endElement();
- }
-
- $objWriter->endElement();
- }
- }
-
- /**
- * Write SheetData
- *
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel\Worksheet $pSheet Worksheet
- * @param string[] $pStringTable String table
- * @throws PHPExcel\Writer_Exception
- */
- private function _writeSheetData(Shared_XMLWriter $objWriter = null, Worksheet $pSheet = null, $pStringTable = null)
- {
- if (is_array($pStringTable)) {
- // Flipped stringtable, for faster index searching
- $aFlippedStringTable = $this->getParentWriter()->getWriterPart('stringtable')->flipStringTable($pStringTable);
-
- // sheetData
- $objWriter->startElement('sheetData');
-
- // Get column count
- $colCount = Cell::columnIndexFromString($pSheet->getHighestColumn());
-
- // Highest row number
- $highestRow = $pSheet->getHighestRow();
-
- // Loop through cells
- $cellsByRow = array();
- foreach ($pSheet->getCellCollection() as $cellID) {
- $cellAddress = Cell::coordinateFromString($cellID);
- $cellsByRow[$cellAddress[1]][] = $cellID;
- }
-
- $currentRow = 0;
- while($currentRow++ < $highestRow) {
- // Get row dimension
- $rowDimension = $pSheet->getRowDimension($currentRow);
-
- // Write current row?
- $writeCurrentRow = isset($cellsByRow[$currentRow]) ||
- $rowDimension->getRowHeight() >= 0 ||
- $rowDimension->getVisible() == false ||
- $rowDimension->getCollapsed() == true ||
- $rowDimension->getOutlineLevel() > 0 ||
- $rowDimension->getXfIndex() !== null;
-
- if ($writeCurrentRow) {
- // Start a new row
- $objWriter->startElement('row');
- $objWriter->writeAttribute('r', $currentRow);
- $objWriter->writeAttribute('spans', '1:' . $colCount);
-
- // Row dimensions
- if ($rowDimension->getRowHeight() >= 0) {
- $objWriter->writeAttribute('customHeight', '1');
- $objWriter->writeAttribute('ht', Shared_String::FormatNumber($rowDimension->getRowHeight()));
- }
-
- // Row visibility
- if ($rowDimension->getVisible() == false) {
- $objWriter->writeAttribute('hidden', 'true');
- }
-
- // Collapsed
- if ($rowDimension->getCollapsed() == true) {
- $objWriter->writeAttribute('collapsed', 'true');
- }
-
- // Outline level
- if ($rowDimension->getOutlineLevel() > 0) {
- $objWriter->writeAttribute('outlineLevel', $rowDimension->getOutlineLevel());
- }
-
- // Style
- if ($rowDimension->getXfIndex() !== null) {
- $objWriter->writeAttribute('s', $rowDimension->getXfIndex());
- $objWriter->writeAttribute('customFormat', '1');
- }
-
- // Write cells
- if (isset($cellsByRow[$currentRow])) {
- foreach($cellsByRow[$currentRow] as $cellAddress) {
- // Write cell
- $this->_writeCell($objWriter, $pSheet, $cellAddress, $pStringTable, $aFlippedStringTable);
- }
- }
-
- // End row
- $objWriter->endElement();
- }
- }
-
- $objWriter->endElement();
- } else {
- throw new Writer_Exception("Invalid parameters passed.");
- }
- }
-
- /**
- * Write Cell
- *
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel\Worksheet $pSheet Worksheet
- * @param PHPExcel\Cell $pCellAddress Cell Address
- * @param string[] $pStringTable String table
- * @param string[] $pFlippedStringTable String table (flipped), for faster index searching
- * @throws PHPExcel\Writer_Exception
- */
- private function _writeCell(Shared_XMLWriter $objWriter = null, Worksheet $pSheet = null, $pCellAddress = null, $pStringTable = null, $pFlippedStringTable = null)
- {
- if (is_array($pStringTable) && is_array($pFlippedStringTable)) {
- // Cell
- $pCell = $pSheet->getCell($pCellAddress);
- $objWriter->startElement('c');
- $objWriter->writeAttribute('r', $pCellAddress);
-
- // Sheet styles
- if ($pCell->getXfIndex() != '') {
- $objWriter->writeAttribute('s', $pCell->getXfIndex());
- }
-
- // If cell value is supplied, write cell value
- $cellValue = $pCell->getValue();
- if (is_object($cellValue) || $cellValue !== '') {
- // Map type
- $mappedType = $pCell->getDataType();
-
- // Write data type depending on its type
- switch (strtolower($mappedType)) {
- case 'inlinestr': // Inline string
- case 's': // String
- case 'b': // Boolean
- $objWriter->writeAttribute('t', $mappedType);
- break;
- case 'f': // Formula
- $calculatedValue = ($this->getParentWriter()->getPreCalculateFormulas()) ?
- $pCell->getCalculatedValue() :
- $cellValue;
- if (is_string($calculatedValue)) {
- $objWriter->writeAttribute('t', 'str');
- }
- break;
- case 'e': // Error
- $objWriter->writeAttribute('t', $mappedType);
- }
-
- // Write data depending on its type
- switch (strtolower($mappedType)) {
- case 'inlinestr': // Inline string
- if (! $cellValue instanceof RichText) {
- $objWriter->writeElement('t', Shared_String::ControlCharacterPHP2OOXML( htmlspecialchars($cellValue) ) );
- } else if ($cellValue instanceof RichText) {
- $objWriter->startElement('is');
- $this->getParentWriter()->getWriterPart('stringtable')->writeRichText($objWriter, $cellValue);
- $objWriter->endElement();
- }
-
- break;
- case 's': // String
- if (! $cellValue instanceof RichText) {
- if (isset($pFlippedStringTable[$cellValue])) {
- $objWriter->writeElement('v', $pFlippedStringTable[$cellValue]);
- }
- } else if ($cellValue instanceof RichText) {
- $objWriter->writeElement('v', $pFlippedStringTable[$cellValue->getHashCode()]);
- }
-
- break;
- case 'f': // Formula
- $attributes = $pCell->getFormulaAttributes();
- if($attributes['t'] == 'array') {
- $objWriter->startElement('f');
- $objWriter->writeAttribute('t', 'array');
- $objWriter->writeAttribute('ref', $pCellAddress);
- $objWriter->writeAttribute('aca', '1');
- $objWriter->writeAttribute('ca', '1');
- $objWriter->text(substr($cellValue, 1));
- $objWriter->endElement();
- } else {
- $objWriter->writeElement('f', substr($cellValue, 1));
- }
- if ($this->getParentWriter()->getOffice2003Compatibility() === false) {
- if ($this->getParentWriter()->getPreCalculateFormulas()) {
-// $calculatedValue = $pCell->getCalculatedValue();
- if (!is_array($calculatedValue) && substr($calculatedValue, 0, 1) != '#') {
- $objWriter->writeElement('v', Shared_String::FormatNumber($calculatedValue));
- } else {
- $objWriter->writeElement('v', '0');
- }
- } else {
- $objWriter->writeElement('v', '0');
- }
- }
- break;
- case 'n': // Numeric
- // force point as decimal separator in case current locale uses comma
- $objWriter->writeElement('v', str_replace(',', '.', $cellValue));
- break;
- case 'b': // Boolean
- $objWriter->writeElement('v', ($cellValue ? '1' : '0'));
- break;
- case 'e': // Error
- if (substr($cellValue, 0, 1) == '=') {
- $objWriter->writeElement('f', substr($cellValue, 1));
- $objWriter->writeElement('v', substr($cellValue, 1));
- } else {
- $objWriter->writeElement('v', $cellValue);
- }
-
- break;
- }
- }
-
- $objWriter->endElement();
- } else {
- throw new Writer_Exception("Invalid parameters passed.");
- }
- }
-
- /**
- * Write Drawings
- *
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel\Worksheet $pSheet Worksheet
- * @param boolean $includeCharts Flag indicating if we should include drawing details for charts
- * @throws PHPExcel\Writer_Exception
- */
- private function _writeDrawings(Shared_XMLWriter $objWriter = null, Worksheet $pSheet = null, $includeCharts = FALSE)
- {
- $chartCount = ($includeCharts) ? $pSheet->getChartCollection()->count() : 0;
- // If sheet contains drawings, add the relationships
- if (($pSheet->getDrawingCollection()->count() > 0) ||
- ($chartCount > 0)) {
- $objWriter->startElement('drawing');
- $objWriter->writeAttribute('r:id', 'rId1');
- $objWriter->endElement();
- }
- }
-
- /**
- * Write LegacyDrawing
- *
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel\Worksheet $pSheet Worksheet
- * @throws PHPExcel\Writer_Exception
- */
- private function _writeLegacyDrawing(Shared_XMLWriter $objWriter = null, Worksheet $pSheet = null)
- {
- // If sheet contains comments, add the relationships
- if (count($pSheet->getComments()) > 0) {
- $objWriter->startElement('legacyDrawing');
- $objWriter->writeAttribute('r:id', 'rId_comments_vml1');
- $objWriter->endElement();
- }
- }
-
- /**
- * Write LegacyDrawingHF
- *
- * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel\Worksheet $pSheet Worksheet
- * @throws PHPExcel\Writer_Exception
- */
- private function _writeLegacyDrawingHF(Shared_XMLWriter $objWriter = null, Worksheet $pSheet = null)
- {
- // If sheet contains images, add the relationships
- if (count($pSheet->getHeaderFooter()->getImages()) > 0) {
- $objWriter->startElement('legacyDrawingHF');
- $objWriter->writeAttribute('r:id', 'rId_headerfooter_vml1');
- $objWriter->endElement();
- }
- }
+ /**
+ * Write worksheet to XML format
+ *
+ * @param PHPExcel\Worksheet $pSheet
+ * @param string[] $pStringTable
+ * @param boolean $includeCharts Flag indicating if we should write charts
+ * @return string XML Output
+ * @throws PHPExcel\Writer_Exception
+ */
+ public function writeWorksheet($pSheet = null, $pStringTable = null, $includeCharts = false)
+ {
+ if (!is_null($pSheet)) {
+ // Create XML writer
+ $objWriter = null;
+ if ($this->getParentWriter()->getUseDiskCaching()) {
+ $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
+ } else {
+ $objWriter = new Shared_XMLWriter(Shared_XMLWriter::STORAGE_MEMORY);
+ }
+
+ // XML header
+ $objWriter->startDocument('1.0','UTF-8','yes');
+
+ // Worksheet
+ $objWriter->startElement('worksheet');
+ $objWriter->writeAttribute('xml:space', 'preserve');
+ $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main');
+ $objWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships');
+
+ // sheetPr
+ $this->_writeSheetPr($objWriter, $pSheet);
+
+ // Dimension
+ $this->_writeDimension($objWriter, $pSheet);
+
+ // sheetViews
+ $this->_writeSheetViews($objWriter, $pSheet);
+
+ // sheetFormatPr
+ $this->_writeSheetFormatPr($objWriter, $pSheet);
+
+ // cols
+ $this->_writeCols($objWriter, $pSheet);
+
+ // sheetData
+ $this->_writeSheetData($objWriter, $pSheet, $pStringTable);
+
+ // sheetProtection
+ $this->_writeSheetProtection($objWriter, $pSheet);
+
+ // protectedRanges
+ $this->_writeProtectedRanges($objWriter, $pSheet);
+
+ // autoFilter
+ $this->_writeAutoFilter($objWriter, $pSheet);
+
+ // mergeCells
+ $this->_writeMergeCells($objWriter, $pSheet);
+
+ // conditionalFormatting
+ $this->_writeConditionalFormatting($objWriter, $pSheet);
+
+ // dataValidations
+ $this->_writeDataValidations($objWriter, $pSheet);
+
+ // hyperlinks
+ $this->_writeHyperlinks($objWriter, $pSheet);
+
+ // Print options
+ $this->_writePrintOptions($objWriter, $pSheet);
+
+ // Page margins
+ $this->_writePageMargins($objWriter, $pSheet);
+
+ // Page setup
+ $this->_writePageSetup($objWriter, $pSheet);
+
+ // Header / footer
+ $this->_writeHeaderFooter($objWriter, $pSheet);
+
+ // Breaks
+ $this->_writeBreaks($objWriter, $pSheet);
+
+ // Drawings and/or Charts
+ $this->_writeDrawings($objWriter, $pSheet, $includeCharts);
+
+ // LegacyDrawing
+ $this->_writeLegacyDrawing($objWriter, $pSheet);
+
+ // LegacyDrawingHF
+ $this->_writeLegacyDrawingHF($objWriter, $pSheet);
+
+ $objWriter->endElement();
+
+ // Return
+ return $objWriter->getData();
+ } else {
+ throw new Writer_Exception("Invalid PHPExcel\Worksheet object passed.");
+ }
+ }
+
+ /**
+ * Write SheetPr
+ *
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel\Worksheet $pSheet Worksheet
+ * @throws PHPExcel\Writer_Exception
+ */
+ private function _writeSheetPr(Shared_XMLWriter $objWriter = null, Worksheet $pSheet = null)
+ {
+ // sheetPr
+ $objWriter->startElement('sheetPr');
+ //$objWriter->writeAttribute('codeName', $pSheet->getTitle());
+ $autoFilterRange = $pSheet->getAutoFilter()->getRange();
+ if (!empty($autoFilterRange)) {
+ $objWriter->writeAttribute('filterMode', 1);
+ $pSheet->getAutoFilter()->showHideRows();
+ }
+
+ // tabColor
+ if ($pSheet->isTabColorSet()) {
+ $objWriter->startElement('tabColor');
+ $objWriter->writeAttribute('rgb', $pSheet->getTabColor()->getARGB());
+ $objWriter->endElement();
+ }
+
+ // outlinePr
+ $objWriter->startElement('outlinePr');
+ $objWriter->writeAttribute('summaryBelow', ($pSheet->getShowSummaryBelow() ? '1' : '0'));
+ $objWriter->writeAttribute('summaryRight', ($pSheet->getShowSummaryRight() ? '1' : '0'));
+ $objWriter->endElement();
+
+ // pageSetUpPr
+ if ($pSheet->getPageSetup()->getFitToPage()) {
+ $objWriter->startElement('pageSetUpPr');
+ $objWriter->writeAttribute('fitToPage', '1');
+ $objWriter->endElement();
+ }
+
+ $objWriter->endElement();
+ }
+
+ /**
+ * Write Dimension
+ *
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel\Worksheet $pSheet Worksheet
+ * @throws PHPExcel\Writer_Exception
+ */
+ private function _writeDimension(Shared_XMLWriter $objWriter = null, Worksheet $pSheet = null)
+ {
+ // dimension
+ $objWriter->startElement('dimension');
+ $objWriter->writeAttribute('ref', $pSheet->calculateWorksheetDimension());
+ $objWriter->endElement();
+ }
+
+ /**
+ * Write SheetViews
+ *
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel\Worksheet $pSheet Worksheet
+ * @throws PHPExcel\Writer_Exception
+ */
+ private function _writeSheetViews(Shared_XMLWriter $objWriter = null, Worksheet $pSheet = null)
+ {
+ // sheetViews
+ $objWriter->startElement('sheetViews');
+
+ // Sheet selected?
+ $sheetSelected = false;
+ if ($this->getParentWriter()->getPHPExcel()->getIndex($pSheet) == $this->getParentWriter()->getPHPExcel()->getActiveSheetIndex())
+ $sheetSelected = true;
+
+
+ // sheetView
+ $objWriter->startElement('sheetView');
+ $objWriter->writeAttribute('tabSelected', $sheetSelected ? '1' : '0');
+ $objWriter->writeAttribute('workbookViewId', '0');
+
+ // Zoom scales
+ if ($pSheet->getSheetView()->getZoomScale() != 100) {
+ $objWriter->writeAttribute('zoomScale', $pSheet->getSheetView()->getZoomScale());
+ }
+ if ($pSheet->getSheetView()->getZoomScaleNormal() != 100) {
+ $objWriter->writeAttribute('zoomScaleNormal', $pSheet->getSheetView()->getZoomScaleNormal());
+ }
+
+ // View Layout Type
+ if ($pSheet->getSheetView()->getView() !== Worksheet_SheetView::SHEETVIEW_NORMAL) {
+ $objWriter->writeAttribute('view', $pSheet->getSheetView()->getView());
+ }
+
+ // Gridlines
+ if ($pSheet->getShowGridlines()) {
+ $objWriter->writeAttribute('showGridLines', 'true');
+ } else {
+ $objWriter->writeAttribute('showGridLines', 'false');
+ }
+
+ // Row and column headers
+ if ($pSheet->getShowRowColHeaders()) {
+ $objWriter->writeAttribute('showRowColHeaders', '1');
+ } else {
+ $objWriter->writeAttribute('showRowColHeaders', '0');
+ }
+
+ // Right-to-left
+ if ($pSheet->getRightToLeft()) {
+ $objWriter->writeAttribute('rightToLeft', 'true');
+ }
+
+ $activeCell = $pSheet->getActiveCell();
+
+ // Pane
+ $pane = '';
+ $topLeftCell = $pSheet->getFreezePane();
+ if (($topLeftCell != '') && ($topLeftCell != 'A1')) {
+ $activeCell = $topLeftCell;
+ // Calculate freeze coordinates
+ $xSplit = $ySplit = 0;
+
+ list($xSplit, $ySplit) = Cell::coordinateFromString($topLeftCell);
+ $xSplit = Cell::columnIndexFromString($xSplit);
+
+ // pane
+ $pane = 'topRight';
+ $objWriter->startElement('pane');
+ if ($xSplit > 1)
+ $objWriter->writeAttribute('xSplit', $xSplit - 1);
+ if ($ySplit > 1) {
+ $objWriter->writeAttribute('ySplit', $ySplit - 1);
+ $pane = ($xSplit > 1) ? 'bottomRight' : 'bottomLeft';
+ }
+ $objWriter->writeAttribute('topLeftCell', $topLeftCell);
+ $objWriter->writeAttribute('activePane', $pane);
+ $objWriter->writeAttribute('state', 'frozen');
+ $objWriter->endElement();
+
+ if (($xSplit > 1) && ($ySplit > 1)) {
+ // Write additional selections if more than two panes (ie both an X and a Y split)
+ $objWriter->startElement('selection'); $objWriter->writeAttribute('pane', 'topRight'); $objWriter->endElement();
+ $objWriter->startElement('selection'); $objWriter->writeAttribute('pane', 'bottomLeft'); $objWriter->endElement();
+ }
+ }
+
+ // Selection
+// if ($pane != '') {
+ // Only need to write selection element if we have a split pane
+ // We cheat a little by over-riding the active cell selection, setting it to the split cell
+ $objWriter->startElement('selection');
+ if ($pane != '') {
+ $objWriter->writeAttribute('pane', $pane);
+ }
+ $objWriter->writeAttribute('activeCell', $activeCell);
+ $objWriter->writeAttribute('sqref', $activeCell);
+ $objWriter->endElement();
+// }
+
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+ }
+
+ /**
+ * Write SheetFormatPr
+ *
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel\Worksheet $pSheet Worksheet
+ * @throws PHPExcel\Writer_Exception
+ */
+ private function _writeSheetFormatPr(Shared_XMLWriter $objWriter = null, Worksheet $pSheet = null)
+ {
+ // sheetFormatPr
+ $objWriter->startElement('sheetFormatPr');
+
+ // Default row height
+ if ($pSheet->getDefaultRowDimension()->getRowHeight() >= 0) {
+ $objWriter->writeAttribute('customHeight', 'true');
+ $objWriter->writeAttribute('defaultRowHeight', Shared_String::FormatNumber($pSheet->getDefaultRowDimension()->getRowHeight()));
+ } else {
+ $objWriter->writeAttribute('defaultRowHeight', '14.4');
+ }
+
+ // Set Zero Height row
+ if ((string)$pSheet->getDefaultRowDimension()->getzeroHeight() == '1' ||
+ strtolower((string)$pSheet->getDefaultRowDimension()->getzeroHeight()) == 'true' ) {
+ $objWriter->writeAttribute('zeroHeight', '1');
+ }
+
+ // Default column width
+ if ($pSheet->getDefaultColumnDimension()->getWidth() >= 0) {
+ $objWriter->writeAttribute('defaultColWidth', Shared_String::FormatNumber($pSheet->getDefaultColumnDimension()->getWidth()));
+ }
+
+ // Outline level - row
+ $outlineLevelRow = 0;
+ foreach ($pSheet->getRowDimensions() as $dimension) {
+ if ($dimension->getOutlineLevel() > $outlineLevelRow) {
+ $outlineLevelRow = $dimension->getOutlineLevel();
+ }
+ }
+ $objWriter->writeAttribute('outlineLevelRow', (int)$outlineLevelRow);
+
+ // Outline level - column
+ $outlineLevelCol = 0;
+ foreach ($pSheet->getColumnDimensions() as $dimension) {
+ if ($dimension->getOutlineLevel() > $outlineLevelCol) {
+ $outlineLevelCol = $dimension->getOutlineLevel();
+ }
+ }
+ $objWriter->writeAttribute('outlineLevelCol', (int)$outlineLevelCol);
+
+ $objWriter->endElement();
+ }
+
+ /**
+ * Write Cols
+ *
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel\Worksheet $pSheet Worksheet
+ * @throws PHPExcel\Writer_Exception
+ */
+ private function _writeCols(Shared_XMLWriter $objWriter = null, Worksheet $pSheet = null)
+ {
+ // cols
+ if (count($pSheet->getColumnDimensions()) > 0) {
+ $objWriter->startElement('cols');
+
+ $pSheet->calculateColumnWidths();
+
+ // Loop through column dimensions
+ foreach ($pSheet->getColumnDimensions() as $colDimension) {
+ // col
+ $objWriter->startElement('col');
+ $objWriter->writeAttribute('min', Cell::columnIndexFromString($colDimension->getColumnIndex()));
+ $objWriter->writeAttribute('max', Cell::columnIndexFromString($colDimension->getColumnIndex()));
+
+ if ($colDimension->getWidth() < 0) {
+ // No width set, apply default of 10
+ $objWriter->writeAttribute('width', '9.10');
+ } else {
+ // Width set
+ $objWriter->writeAttribute('width', Shared_String::FormatNumber($colDimension->getWidth()));
+ }
+
+ // Column visibility
+ if ($colDimension->getVisible() == false) {
+ $objWriter->writeAttribute('hidden', 'true');
+ }
+
+ // Auto size?
+ if ($colDimension->getAutoSize()) {
+ $objWriter->writeAttribute('bestFit', 'true');
+ }
+
+ // Custom width?
+ if ($colDimension->getWidth() != $pSheet->getDefaultColumnDimension()->getWidth()) {
+ $objWriter->writeAttribute('customWidth', 'true');
+ }
+
+ // Collapsed
+ if ($colDimension->getCollapsed() == true) {
+ $objWriter->writeAttribute('collapsed', 'true');
+ }
+
+ // Outline level
+ if ($colDimension->getOutlineLevel() > 0) {
+ $objWriter->writeAttribute('outlineLevel', $colDimension->getOutlineLevel());
+ }
+
+ // Style
+ $objWriter->writeAttribute('style', $colDimension->getXfIndex());
+
+ $objWriter->endElement();
+ }
+
+ $objWriter->endElement();
+ }
+ }
+
+ /**
+ * Write SheetProtection
+ *
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel\Worksheet $pSheet Worksheet
+ * @throws PHPExcel\Writer_Exception
+ */
+ private function _writeSheetProtection(Shared_XMLWriter $objWriter = null, Worksheet $pSheet = null)
+ {
+ // sheetProtection
+ $objWriter->startElement('sheetProtection');
+
+ if ($pSheet->getProtection()->getPassword() != '') {
+ $objWriter->writeAttribute('password', $pSheet->getProtection()->getPassword());
+ }
+
+ $objWriter->writeAttribute('sheet', ($pSheet->getProtection()->getSheet() ? 'true' : 'false'));
+ $objWriter->writeAttribute('objects', ($pSheet->getProtection()->getObjects() ? 'true' : 'false'));
+ $objWriter->writeAttribute('scenarios', ($pSheet->getProtection()->getScenarios() ? 'true' : 'false'));
+ $objWriter->writeAttribute('formatCells', ($pSheet->getProtection()->getFormatCells() ? 'true' : 'false'));
+ $objWriter->writeAttribute('formatColumns', ($pSheet->getProtection()->getFormatColumns() ? 'true' : 'false'));
+ $objWriter->writeAttribute('formatRows', ($pSheet->getProtection()->getFormatRows() ? 'true' : 'false'));
+ $objWriter->writeAttribute('insertColumns', ($pSheet->getProtection()->getInsertColumns() ? 'true' : 'false'));
+ $objWriter->writeAttribute('insertRows', ($pSheet->getProtection()->getInsertRows() ? 'true' : 'false'));
+ $objWriter->writeAttribute('insertHyperlinks', ($pSheet->getProtection()->getInsertHyperlinks() ? 'true' : 'false'));
+ $objWriter->writeAttribute('deleteColumns', ($pSheet->getProtection()->getDeleteColumns() ? 'true' : 'false'));
+ $objWriter->writeAttribute('deleteRows', ($pSheet->getProtection()->getDeleteRows() ? 'true' : 'false'));
+ $objWriter->writeAttribute('selectLockedCells', ($pSheet->getProtection()->getSelectLockedCells() ? 'true' : 'false'));
+ $objWriter->writeAttribute('sort', ($pSheet->getProtection()->getSort() ? 'true' : 'false'));
+ $objWriter->writeAttribute('autoFilter', ($pSheet->getProtection()->getAutoFilter() ? 'true' : 'false'));
+ $objWriter->writeAttribute('pivotTables', ($pSheet->getProtection()->getPivotTables() ? 'true' : 'false'));
+ $objWriter->writeAttribute('selectUnlockedCells', ($pSheet->getProtection()->getSelectUnlockedCells() ? 'true' : 'false'));
+ $objWriter->endElement();
+ }
+
+ /**
+ * Write ConditionalFormatting
+ *
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel\Worksheet $pSheet Worksheet
+ * @throws PHPExcel\Writer_Exception
+ */
+ private function _writeConditionalFormatting(Shared_XMLWriter $objWriter = null, Worksheet $pSheet = null)
+ {
+ // Conditional id
+ $id = 1;
+
+ // Loop through styles in the current worksheet
+ foreach ($pSheet->getConditionalStylesCollection() as $cellCoordinate => $conditionalStyles) {
+ foreach ($conditionalStyles as $conditional) {
+ // WHY was this again?
+ // if ($this->getParentWriter()->getStylesConditionalHashTable()->getIndexForHashCode( $conditional->getHashCode() ) == '') {
+ // continue;
+ // }
+ if ($conditional->getConditionType() != Style_Conditional::CONDITION_NONE) {
+ // conditionalFormatting
+ $objWriter->startElement('conditionalFormatting');
+ $objWriter->writeAttribute('sqref', $cellCoordinate);
+
+ // cfRule
+ $objWriter->startElement('cfRule');
+ $objWriter->writeAttribute('type', $conditional->getConditionType());
+ $objWriter->writeAttribute('dxfId', $this->getParentWriter()->getStylesConditionalHashTable()->getIndexForHashCode( $conditional->getHashCode() ));
+ $objWriter->writeAttribute('priority', $id++);
+
+ if (($conditional->getConditionType() == Style_Conditional::CONDITION_CELLIS
+ ||
+ $conditional->getConditionType() == Style_Conditional::CONDITION_CONTAINSTEXT)
+ && $conditional->getOperatorType() != Style_Conditional::OPERATOR_NONE) {
+ $objWriter->writeAttribute('operator', $conditional->getOperatorType());
+ }
+
+ if ($conditional->getConditionType() == Style_Conditional::CONDITION_CONTAINSTEXT
+ && !is_null($conditional->getText())) {
+ $objWriter->writeAttribute('text', $conditional->getText());
+ }
+
+ if ($conditional->getConditionType() == Style_Conditional::CONDITION_CONTAINSTEXT
+ && $conditional->getOperatorType() == Style_Conditional::OPERATOR_CONTAINSTEXT
+ && !is_null($conditional->getText())) {
+ $objWriter->writeElement('formula', 'NOT(ISERROR(SEARCH("' . $conditional->getText() . '",' . $cellCoordinate . ')))');
+ } else if ($conditional->getConditionType() == Style_Conditional::CONDITION_CONTAINSTEXT
+ && $conditional->getOperatorType() == Style_Conditional::OPERATOR_BEGINSWITH
+ && !is_null($conditional->getText())) {
+ $objWriter->writeElement('formula', 'LEFT(' . $cellCoordinate . ',' . strlen($conditional->getText()) . ')="' . $conditional->getText() . '"');
+ } else if ($conditional->getConditionType() == Style_Conditional::CONDITION_CONTAINSTEXT
+ && $conditional->getOperatorType() == Style_Conditional::OPERATOR_ENDSWITH
+ && !is_null($conditional->getText())) {
+ $objWriter->writeElement('formula', 'RIGHT(' . $cellCoordinate . ',' . strlen($conditional->getText()) . ')="' . $conditional->getText() . '"');
+ } else if ($conditional->getConditionType() == Style_Conditional::CONDITION_CONTAINSTEXT
+ && $conditional->getOperatorType() == Style_Conditional::OPERATOR_NOTCONTAINS
+ && !is_null($conditional->getText())) {
+ $objWriter->writeElement('formula', 'ISERROR(SEARCH("' . $conditional->getText() . '",' . $cellCoordinate . '))');
+ } else if ($conditional->getConditionType() == Style_Conditional::CONDITION_CELLIS
+ || $conditional->getConditionType() == Style_Conditional::CONDITION_CONTAINSTEXT
+ || $conditional->getConditionType() == Style_Conditional::CONDITION_EXPRESSION) {
+ foreach ($conditional->getConditions() as $formula) {
+ // Formula
+ $objWriter->writeElement('formula', $formula);
+ }
+ }
+
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+ }
+ }
+ }
+ }
+
+ /**
+ * Write DataValidations
+ *
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel\Worksheet $pSheet Worksheet
+ * @throws PHPExcel\Writer_Exception
+ */
+ private function _writeDataValidations(Shared_XMLWriter $objWriter = null, Worksheet $pSheet = null)
+ {
+ // Datavalidation collection
+ $dataValidationCollection = $pSheet->getDataValidationCollection();
+
+ // Write data validations?
+ if (!empty($dataValidationCollection)) {
+ $objWriter->startElement('dataValidations');
+ $objWriter->writeAttribute('count', count($dataValidationCollection));
+
+ foreach ($dataValidationCollection as $coordinate => $dv) {
+ $objWriter->startElement('dataValidation');
+
+ if ($dv->getType() != '') {
+ $objWriter->writeAttribute('type', $dv->getType());
+ }
+
+ if ($dv->getErrorStyle() != '') {
+ $objWriter->writeAttribute('errorStyle', $dv->getErrorStyle());
+ }
+
+ if ($dv->getOperator() != '') {
+ $objWriter->writeAttribute('operator', $dv->getOperator());
+ }
+
+ $objWriter->writeAttribute('allowBlank', ($dv->getAllowBlank() ? '1' : '0'));
+ $objWriter->writeAttribute('showDropDown', (!$dv->getShowDropDown() ? '1' : '0'));
+ $objWriter->writeAttribute('showInputMessage', ($dv->getShowInputMessage() ? '1' : '0'));
+ $objWriter->writeAttribute('showErrorMessage', ($dv->getShowErrorMessage() ? '1' : '0'));
+
+ if ($dv->getErrorTitle() !== '') {
+ $objWriter->writeAttribute('errorTitle', $dv->getErrorTitle());
+ }
+ if ($dv->getError() !== '') {
+ $objWriter->writeAttribute('error', $dv->getError());
+ }
+ if ($dv->getPromptTitle() !== '') {
+ $objWriter->writeAttribute('promptTitle', $dv->getPromptTitle());
+ }
+ if ($dv->getPrompt() !== '') {
+ $objWriter->writeAttribute('prompt', $dv->getPrompt());
+ }
+
+ $objWriter->writeAttribute('sqref', $coordinate);
+
+ if ($dv->getFormula1() !== '') {
+ $objWriter->writeElement('formula1', $dv->getFormula1());
+ }
+ if ($dv->getFormula2() !== '') {
+ $objWriter->writeElement('formula2', $dv->getFormula2());
+ }
+
+ $objWriter->endElement();
+ }
+
+ $objWriter->endElement();
+ }
+ }
+
+ /**
+ * Write Hyperlinks
+ *
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel\Worksheet $pSheet Worksheet
+ * @throws PHPExcel\Writer_Exception
+ */
+ private function _writeHyperlinks(Shared_XMLWriter $objWriter = null, Worksheet $pSheet = null)
+ {
+ // Hyperlink collection
+ $hyperlinkCollection = $pSheet->getHyperlinkCollection();
+
+ // Relation ID
+ $relationId = 1;
+
+ // Write hyperlinks?
+ if (!empty($hyperlinkCollection)) {
+ $objWriter->startElement('hyperlinks');
+
+ foreach ($hyperlinkCollection as $coordinate => $hyperlink) {
+ $objWriter->startElement('hyperlink');
+
+ $objWriter->writeAttribute('ref', $coordinate);
+ if (!$hyperlink->isInternal()) {
+ $objWriter->writeAttribute('r:id', 'rId_hyperlink_' . $relationId);
+ ++$relationId;
+ } else {
+ $objWriter->writeAttribute('location', str_replace('sheet://', '', $hyperlink->getUrl()));
+ }
+
+ if ($hyperlink->getTooltip() != '') {
+ $objWriter->writeAttribute('tooltip', $hyperlink->getTooltip());
+ }
+
+ $objWriter->endElement();
+ }
+
+ $objWriter->endElement();
+ }
+ }
+
+ /**
+ * Write ProtectedRanges
+ *
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel\Worksheet $pSheet Worksheet
+ * @throws PHPExcel\Writer_Exception
+ */
+ private function _writeProtectedRanges(Shared_XMLWriter $objWriter = null, Worksheet $pSheet = null)
+ {
+ if (count($pSheet->getProtectedCells()) > 0) {
+ // protectedRanges
+ $objWriter->startElement('protectedRanges');
+
+ // Loop protectedRanges
+ foreach ($pSheet->getProtectedCells() as $protectedCell => $passwordHash) {
+ // protectedRange
+ $objWriter->startElement('protectedRange');
+ $objWriter->writeAttribute('name', 'p' . md5($protectedCell));
+ $objWriter->writeAttribute('sqref', $protectedCell);
+ if (!empty($passwordHash)) {
+ $objWriter->writeAttribute('password', $passwordHash);
+ }
+ $objWriter->endElement();
+ }
+
+ $objWriter->endElement();
+ }
+ }
+
+ /**
+ * Write MergeCells
+ *
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel\Worksheet $pSheet Worksheet
+ * @throws PHPExcel\Writer_Exception
+ */
+ private function _writeMergeCells(Shared_XMLWriter $objWriter = null, Worksheet $pSheet = null)
+ {
+ if (count($pSheet->getMergeCells()) > 0) {
+ // mergeCells
+ $objWriter->startElement('mergeCells');
+
+ // Loop mergeCells
+ foreach ($pSheet->getMergeCells() as $mergeCell) {
+ // mergeCell
+ $objWriter->startElement('mergeCell');
+ $objWriter->writeAttribute('ref', $mergeCell);
+ $objWriter->endElement();
+ }
+
+ $objWriter->endElement();
+ }
+ }
+
+ /**
+ * Write PrintOptions
+ *
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel\Worksheet $pSheet Worksheet
+ * @throws PHPExcel\Writer_Exception
+ */
+ private function _writePrintOptions(Shared_XMLWriter $objWriter = null, Worksheet $pSheet = null)
+ {
+ // printOptions
+ $objWriter->startElement('printOptions');
+
+ $objWriter->writeAttribute('gridLines', ($pSheet->getPrintGridlines() ? 'true': 'false'));
+ $objWriter->writeAttribute('gridLinesSet', 'true');
+
+ if ($pSheet->getPageSetup()->getHorizontalCentered()) {
+ $objWriter->writeAttribute('horizontalCentered', 'true');
+ }
+
+ if ($pSheet->getPageSetup()->getVerticalCentered()) {
+ $objWriter->writeAttribute('verticalCentered', 'true');
+ }
+
+ $objWriter->endElement();
+ }
+
+ /**
+ * Write PageMargins
+ *
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel\Worksheet $pSheet Worksheet
+ * @throws PHPExcel|Writer_Exception
+ */
+ private function _writePageMargins(Shared_XMLWriter $objWriter = null, Worksheet $pSheet = null)
+ {
+ // pageMargins
+ $objWriter->startElement('pageMargins');
+ $objWriter->writeAttribute('left', Shared_String::FormatNumber($pSheet->getPageMargins()->getLeft()));
+ $objWriter->writeAttribute('right', Shared_String::FormatNumber($pSheet->getPageMargins()->getRight()));
+ $objWriter->writeAttribute('top', Shared_String::FormatNumber($pSheet->getPageMargins()->getTop()));
+ $objWriter->writeAttribute('bottom', Shared_String::FormatNumber($pSheet->getPageMargins()->getBottom()));
+ $objWriter->writeAttribute('header', Shared_String::FormatNumber($pSheet->getPageMargins()->getHeader()));
+ $objWriter->writeAttribute('footer', Shared_String::FormatNumber($pSheet->getPageMargins()->getFooter()));
+ $objWriter->endElement();
+ }
+
+ /**
+ * Write AutoFilter
+ *
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel\Worksheet $pSheet Worksheet
+ * @throws PHPExcel\Writer_Exception
+ */
+ private function _writeAutoFilter(Shared_XMLWriter $objWriter = null, Worksheet $pSheet = null)
+ {
+ $autoFilterRange = $pSheet->getAutoFilter()->getRange();
+ if (!empty($autoFilterRange)) {
+ // autoFilter
+ $objWriter->startElement('autoFilter');
+
+ // Strip any worksheet reference from the filter coordinates
+ $range = Cell::splitRange($autoFilterRange);
+ $range = $range[0];
+ // Strip any worksheet ref
+ if (strpos($range[0],'!') !== false) {
+ list($ws,$range[0]) = explode('!',$range[0]);
+ }
+ $range = implode(':', $range);
+
+ $objWriter->writeAttribute('ref', str_replace('$','',$range));
+
+ $columns = $pSheet->getAutoFilter()->getColumns();
+ if (count($columns > 0)) {
+ foreach($columns as $columnID => $column) {
+ $rules = $column->getRules();
+ if (count($rules > 0)) {
+ $objWriter->startElement('filterColumn');
+ $objWriter->writeAttribute('colId', $pSheet->getAutoFilter()->getColumnOffset($columnID));
+
+ $objWriter->startElement( $column->getFilterType());
+ if ($column->getJoin() == Worksheet_AutoFilter_Column::AUTOFILTER_COLUMN_JOIN_AND) {
+ $objWriter->writeAttribute('and', 1);
+ }
+
+ foreach ($rules as $rule) {
+ if (($column->getFilterType() === Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_FILTER) &&
+ ($rule->getOperator() === Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_EQUAL) &&
+ ($rule->getValue() === '')) {
+ // Filter rule for Blanks
+ $objWriter->writeAttribute('blank', 1);
+ } elseif($rule->getRuleType() === Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMICFILTER) {
+ // Dynamic Filter Rule
+ $objWriter->writeAttribute('type', $rule->getGrouping());
+ $val = $column->getAttribute('val');
+ if ($val !== null) {
+ $objWriter->writeAttribute('val', $val);
+ }
+ $maxVal = $column->getAttribute('maxVal');
+ if ($maxVal !== null) {
+ $objWriter->writeAttribute('maxVal', $maxVal);
+ }
+ } elseif($rule->getRuleType() === Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_TOPTENFILTER) {
+ // Top 10 Filter Rule
+ $objWriter->writeAttribute('val', $rule->getValue());
+ $objWriter->writeAttribute('percent', (($rule->getOperator() === Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT) ? '1' : '0'));
+ $objWriter->writeAttribute('top', (($rule->getGrouping() === Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP) ? '1': '0'));
+ } else {
+ // Filter, DateGroupItem or CustomFilter
+ $objWriter->startElement($rule->getRuleType());
+
+ if ($rule->getOperator() !== Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_EQUAL) {
+ $objWriter->writeAttribute('operator', $rule->getOperator());
+ }
+ if ($rule->getRuleType() === Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP) {
+ // Date Group filters
+ foreach($rule->getValue() as $key => $value) {
+ if ($value > '') $objWriter->writeAttribute($key, $value);
+ }
+ $objWriter->writeAttribute('dateTimeGrouping', $rule->getGrouping());
+ } else {
+ $objWriter->writeAttribute('val', $rule->getValue());
+ }
+
+ $objWriter->endElement();
+ }
+ }
+
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+ }
+ }
+ }
+
+ $objWriter->endElement();
+ }
+ }
+
+ /**
+ * Write PageSetup
+ *
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel\Worksheet $pSheet Worksheet
+ * @throws PHPExcel\Writer_Exception
+ */
+ private function _writePageSetup(Shared_XMLWriter $objWriter = null, Worksheet $pSheet = null)
+ {
+ // pageSetup
+ $objWriter->startElement('pageSetup');
+ $objWriter->writeAttribute('paperSize', $pSheet->getPageSetup()->getPaperSize());
+ $objWriter->writeAttribute('orientation', $pSheet->getPageSetup()->getOrientation());
+
+ if (!is_null($pSheet->getPageSetup()->getScale())) {
+ $objWriter->writeAttribute('scale', $pSheet->getPageSetup()->getScale());
+ }
+ if (!is_null($pSheet->getPageSetup()->getFitToHeight())) {
+ $objWriter->writeAttribute('fitToHeight', $pSheet->getPageSetup()->getFitToHeight());
+ } else {
+ $objWriter->writeAttribute('fitToHeight', '0');
+ }
+ if (!is_null($pSheet->getPageSetup()->getFitToWidth())) {
+ $objWriter->writeAttribute('fitToWidth', $pSheet->getPageSetup()->getFitToWidth());
+ } else {
+ $objWriter->writeAttribute('fitToWidth', '0');
+ }
+ if (!is_null($pSheet->getPageSetup()->getFirstPageNumber())) {
+ $objWriter->writeAttribute('firstPageNumber', $pSheet->getPageSetup()->getFirstPageNumber());
+ $objWriter->writeAttribute('useFirstPageNumber', '1');
+ }
+
+ $objWriter->endElement();
+ }
+
+ /**
+ * Write Header / Footer
+ *
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel\Worksheet $pSheet Worksheet
+ * @throws PHPExcel\Writer_Exception
+ */
+ private function _writeHeaderFooter(Shared_XMLWriter $objWriter = null, Worksheet $pSheet = null)
+ {
+ // headerFooter
+ $objWriter->startElement('headerFooter');
+ $objWriter->writeAttribute('differentOddEven', ($pSheet->getHeaderFooter()->getDifferentOddEven() ? 'true' : 'false'));
+ $objWriter->writeAttribute('differentFirst', ($pSheet->getHeaderFooter()->getDifferentFirst() ? 'true' : 'false'));
+ $objWriter->writeAttribute('scaleWithDoc', ($pSheet->getHeaderFooter()->getScaleWithDocument() ? 'true' : 'false'));
+ $objWriter->writeAttribute('alignWithMargins', ($pSheet->getHeaderFooter()->getAlignWithMargins() ? 'true' : 'false'));
+
+ $objWriter->writeElement('oddHeader', $pSheet->getHeaderFooter()->getOddHeader());
+ $objWriter->writeElement('oddFooter', $pSheet->getHeaderFooter()->getOddFooter());
+ $objWriter->writeElement('evenHeader', $pSheet->getHeaderFooter()->getEvenHeader());
+ $objWriter->writeElement('evenFooter', $pSheet->getHeaderFooter()->getEvenFooter());
+ $objWriter->writeElement('firstHeader', $pSheet->getHeaderFooter()->getFirstHeader());
+ $objWriter->writeElement('firstFooter', $pSheet->getHeaderFooter()->getFirstFooter());
+ $objWriter->endElement();
+ }
+
+ /**
+ * Write Breaks
+ *
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel\Worksheet $pSheet Worksheet
+ * @throws PHPExcel\Writer_Exception
+ */
+ private function _writeBreaks(Shared_XMLWriter $objWriter = null, Worksheet $pSheet = null)
+ {
+ // Get row and column breaks
+ $aRowBreaks = array();
+ $aColumnBreaks = array();
+ foreach ($pSheet->getBreaks() as $cell => $breakType) {
+ if ($breakType == Worksheet::BREAK_ROW) {
+ $aRowBreaks[] = $cell;
+ } else if ($breakType == Worksheet::BREAK_COLUMN) {
+ $aColumnBreaks[] = $cell;
+ }
+ }
+
+ // rowBreaks
+ if (!empty($aRowBreaks)) {
+ $objWriter->startElement('rowBreaks');
+ $objWriter->writeAttribute('count', count($aRowBreaks));
+ $objWriter->writeAttribute('manualBreakCount', count($aRowBreaks));
+
+ foreach ($aRowBreaks as $cell) {
+ $coords = Cell::coordinateFromString($cell);
+
+ $objWriter->startElement('brk');
+ $objWriter->writeAttribute('id', $coords[1]);
+ $objWriter->writeAttribute('man', '1');
+ $objWriter->endElement();
+ }
+
+ $objWriter->endElement();
+ }
+
+ // Second, write column breaks
+ if (!empty($aColumnBreaks)) {
+ $objWriter->startElement('colBreaks');
+ $objWriter->writeAttribute('count', count($aColumnBreaks));
+ $objWriter->writeAttribute('manualBreakCount', count($aColumnBreaks));
+
+ foreach ($aColumnBreaks as $cell) {
+ $coords = Cell::coordinateFromString($cell);
+
+ $objWriter->startElement('brk');
+ $objWriter->writeAttribute('id', Cell::columnIndexFromString($coords[0]) - 1);
+ $objWriter->writeAttribute('man', '1');
+ $objWriter->endElement();
+ }
+
+ $objWriter->endElement();
+ }
+ }
+
+ /**
+ * Write SheetData
+ *
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel\Worksheet $pSheet Worksheet
+ * @param string[] $pStringTable String table
+ * @throws PHPExcel\Writer_Exception
+ */
+ private function _writeSheetData(Shared_XMLWriter $objWriter = null, Worksheet $pSheet = null, $pStringTable = null)
+ {
+ if (is_array($pStringTable)) {
+ // Flipped stringtable, for faster index searching
+ $aFlippedStringTable = $this->getParentWriter()->getWriterPart('stringtable')->flipStringTable($pStringTable);
+
+ // sheetData
+ $objWriter->startElement('sheetData');
+
+ // Get column count
+ $colCount = Cell::columnIndexFromString($pSheet->getHighestColumn());
+
+ // Highest row number
+ $highestRow = $pSheet->getHighestRow();
+
+ // Loop through cells
+ $cellsByRow = array();
+ foreach ($pSheet->getCellCollection() as $cellID) {
+ $cellAddress = Cell::coordinateFromString($cellID);
+ $cellsByRow[$cellAddress[1]][] = $cellID;
+ }
+
+ $currentRow = 0;
+ while($currentRow++ < $highestRow) {
+ // Get row dimension
+ $rowDimension = $pSheet->getRowDimension($currentRow);
+
+ // Write current row?
+ $writeCurrentRow = isset($cellsByRow[$currentRow]) ||
+ $rowDimension->getRowHeight() >= 0 ||
+ $rowDimension->getVisible() == false ||
+ $rowDimension->getCollapsed() == true ||
+ $rowDimension->getOutlineLevel() > 0 ||
+ $rowDimension->getXfIndex() !== null;
+
+ if ($writeCurrentRow) {
+ // Start a new row
+ $objWriter->startElement('row');
+ $objWriter->writeAttribute('r', $currentRow);
+ $objWriter->writeAttribute('spans', '1:' . $colCount);
+
+ // Row dimensions
+ if ($rowDimension->getRowHeight() >= 0) {
+ $objWriter->writeAttribute('customHeight', '1');
+ $objWriter->writeAttribute('ht', Shared_String::FormatNumber($rowDimension->getRowHeight()));
+ }
+
+ // Row visibility
+ if ($rowDimension->getVisible() == false) {
+ $objWriter->writeAttribute('hidden', 'true');
+ }
+
+ // Collapsed
+ if ($rowDimension->getCollapsed() == true) {
+ $objWriter->writeAttribute('collapsed', 'true');
+ }
+
+ // Outline level
+ if ($rowDimension->getOutlineLevel() > 0) {
+ $objWriter->writeAttribute('outlineLevel', $rowDimension->getOutlineLevel());
+ }
+
+ // Style
+ if ($rowDimension->getXfIndex() !== null) {
+ $objWriter->writeAttribute('s', $rowDimension->getXfIndex());
+ $objWriter->writeAttribute('customFormat', '1');
+ }
+
+ // Write cells
+ if (isset($cellsByRow[$currentRow])) {
+ foreach($cellsByRow[$currentRow] as $cellAddress) {
+ // Write cell
+ $this->_writeCell($objWriter, $pSheet, $cellAddress, $pStringTable, $aFlippedStringTable);
+ }
+ }
+
+ // End row
+ $objWriter->endElement();
+ }
+ }
+
+ $objWriter->endElement();
+ } else {
+ throw new Writer_Exception("Invalid parameters passed.");
+ }
+ }
+
+ /**
+ * Write Cell
+ *
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel\Worksheet $pSheet Worksheet
+ * @param PHPExcel\Cell $pCellAddress Cell Address
+ * @param string[] $pStringTable String table
+ * @param string[] $pFlippedStringTable String table (flipped), for faster index searching
+ * @throws PHPExcel\Writer_Exception
+ */
+ private function _writeCell(Shared_XMLWriter $objWriter = null, Worksheet $pSheet = null, $pCellAddress = null, $pStringTable = null, $pFlippedStringTable = null)
+ {
+ if (is_array($pStringTable) && is_array($pFlippedStringTable)) {
+ // Cell
+ $pCell = $pSheet->getCell($pCellAddress);
+ $objWriter->startElement('c');
+ $objWriter->writeAttribute('r', $pCellAddress);
+
+ // Sheet styles
+ if ($pCell->getXfIndex() != '') {
+ $objWriter->writeAttribute('s', $pCell->getXfIndex());
+ }
+
+ // If cell value is supplied, write cell value
+ $cellValue = $pCell->getValue();
+ if (is_object($cellValue) || $cellValue !== '') {
+ // Map type
+ $mappedType = $pCell->getDataType();
+
+ // Write data type depending on its type
+ switch (strtolower($mappedType)) {
+ case 'inlinestr': // Inline string
+ case 's': // String
+ case 'b': // Boolean
+ $objWriter->writeAttribute('t', $mappedType);
+ break;
+ case 'f': // Formula
+ $calculatedValue = ($this->getParentWriter()->getPreCalculateFormulas()) ?
+ $pCell->getCalculatedValue() :
+ $cellValue;
+ if (is_string($calculatedValue)) {
+ $objWriter->writeAttribute('t', 'str');
+ }
+ break;
+ case 'e': // Error
+ $objWriter->writeAttribute('t', $mappedType);
+ }
+
+ // Write data depending on its type
+ switch (strtolower($mappedType)) {
+ case 'inlinestr': // Inline string
+ if (! $cellValue instanceof RichText) {
+ $objWriter->writeElement('t', Shared_String::ControlCharacterPHP2OOXML( htmlspecialchars($cellValue) ) );
+ } else if ($cellValue instanceof RichText) {
+ $objWriter->startElement('is');
+ $this->getParentWriter()->getWriterPart('stringtable')->writeRichText($objWriter, $cellValue);
+ $objWriter->endElement();
+ }
+
+ break;
+ case 's': // String
+ if (! $cellValue instanceof RichText) {
+ if (isset($pFlippedStringTable[$cellValue])) {
+ $objWriter->writeElement('v', $pFlippedStringTable[$cellValue]);
+ }
+ } else if ($cellValue instanceof RichText) {
+ $objWriter->writeElement('v', $pFlippedStringTable[$cellValue->getHashCode()]);
+ }
+
+ break;
+ case 'f': // Formula
+ $attributes = $pCell->getFormulaAttributes();
+ if($attributes['t'] == 'array') {
+ $objWriter->startElement('f');
+ $objWriter->writeAttribute('t', 'array');
+ $objWriter->writeAttribute('ref', $pCellAddress);
+ $objWriter->writeAttribute('aca', '1');
+ $objWriter->writeAttribute('ca', '1');
+ $objWriter->text(substr($cellValue, 1));
+ $objWriter->endElement();
+ } else {
+ $objWriter->writeElement('f', substr($cellValue, 1));
+ }
+ if ($this->getParentWriter()->getOffice2003Compatibility() === false) {
+ if ($this->getParentWriter()->getPreCalculateFormulas()) {
+// $calculatedValue = $pCell->getCalculatedValue();
+ if (!is_array($calculatedValue) && substr($calculatedValue, 0, 1) != '#') {
+ $objWriter->writeElement('v', Shared_String::FormatNumber($calculatedValue));
+ } else {
+ $objWriter->writeElement('v', '0');
+ }
+ } else {
+ $objWriter->writeElement('v', '0');
+ }
+ }
+ break;
+ case 'n': // Numeric
+ // force point as decimal separator in case current locale uses comma
+ $objWriter->writeElement('v', str_replace(',', '.', $cellValue));
+ break;
+ case 'b': // Boolean
+ $objWriter->writeElement('v', ($cellValue ? '1' : '0'));
+ break;
+ case 'e': // Error
+ if (substr($cellValue, 0, 1) == '=') {
+ $objWriter->writeElement('f', substr($cellValue, 1));
+ $objWriter->writeElement('v', substr($cellValue, 1));
+ } else {
+ $objWriter->writeElement('v', $cellValue);
+ }
+
+ break;
+ }
+ }
+
+ $objWriter->endElement();
+ } else {
+ throw new Writer_Exception("Invalid parameters passed.");
+ }
+ }
+
+ /**
+ * Write Drawings
+ *
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel\Worksheet $pSheet Worksheet
+ * @param boolean $includeCharts Flag indicating if we should include drawing details for charts
+ * @throws PHPExcel\Writer_Exception
+ */
+ private function _writeDrawings(Shared_XMLWriter $objWriter = null, Worksheet $pSheet = null, $includeCharts = false)
+ {
+ $chartCount = ($includeCharts) ? $pSheet->getChartCollection()->count() : 0;
+ // If sheet contains drawings, add the relationships
+ if (($pSheet->getDrawingCollection()->count() > 0) ||
+ ($chartCount > 0)) {
+ $objWriter->startElement('drawing');
+ $objWriter->writeAttribute('r:id', 'rId1');
+ $objWriter->endElement();
+ }
+ }
+
+ /**
+ * Write LegacyDrawing
+ *
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel\Worksheet $pSheet Worksheet
+ * @throws PHPExcel\Writer_Exception
+ */
+ private function _writeLegacyDrawing(Shared_XMLWriter $objWriter = null, Worksheet $pSheet = null)
+ {
+ // If sheet contains comments, add the relationships
+ if (count($pSheet->getComments()) > 0) {
+ $objWriter->startElement('legacyDrawing');
+ $objWriter->writeAttribute('r:id', 'rId_comments_vml1');
+ $objWriter->endElement();
+ }
+ }
+
+ /**
+ * Write LegacyDrawingHF
+ *
+ * @param PHPExcel\Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel\Worksheet $pSheet Worksheet
+ * @throws PHPExcel\Writer_Exception
+ */
+ private function _writeLegacyDrawingHF(Shared_XMLWriter $objWriter = null, Worksheet $pSheet = null)
+ {
+ // If sheet contains images, add the relationships
+ if (count($pSheet->getHeaderFooter()->getImages()) > 0) {
+ $objWriter->startElement('legacyDrawingHF');
+ $objWriter->writeAttribute('r:id', 'rId_headerfooter_vml1');
+ $objWriter->endElement();
+ }
+ }
}
diff --git a/Classes/PHPExcel/Writer/Excel2007/WriterPart.php b/Classes/PHPExcel/Writer/Excel2007/WriterPart.php
index bc0e56c..73635df 100644
--- a/Classes/PHPExcel/Writer/Excel2007/WriterPart.php
+++ b/Classes/PHPExcel/Writer/Excel2007/WriterPart.php
@@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\Writer_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,47 +37,47 @@ namespace PHPExcel;
*/
abstract class Writer_Excel2007_WriterPart
{
- /**
- * Parent IWriter object
- *
- * @var PHPExcel\Writer_IWriter
- */
- private $_parentWriter;
+ /**
+ * Parent IWriter object
+ *
+ * @var PHPExcel\Writer_IWriter
+ */
+ private $_parentWriter;
- /**
- * Set parent IWriter object
- *
- * @param PHPExcel\Writer_IWriter $pWriter
- * @throws PHPExcel\Writer_Exception
- */
- public function setParentWriter(Writer_IWriter $pWriter = null) {
- $this->_parentWriter = $pWriter;
- }
+ /**
+ * Set parent IWriter object
+ *
+ * @param PHPExcel\Writer_IWriter $pWriter
+ * @throws PHPExcel\Writer_Exception
+ */
+ public function setParentWriter(Writer_IWriter $pWriter = null) {
+ $this->_parentWriter = $pWriter;
+ }
- /**
- * Get parent IWriter object
- *
- * @return PHPExcel\Writer_IWriter
- * @throws PHPExcel\Writer_Exception
- */
- public function getParentWriter() {
- if (!is_null($this->_parentWriter)) {
- return $this->_parentWriter;
- } else {
- throw new Writer_Exception("No parent PHPExcel\Writer_IWriter assigned.");
- }
- }
+ /**
+ * Get parent IWriter object
+ *
+ * @return PHPExcel\Writer_IWriter
+ * @throws PHPExcel\Writer_Exception
+ */
+ public function getParentWriter() {
+ if (!is_null($this->_parentWriter)) {
+ return $this->_parentWriter;
+ } else {
+ throw new Writer_Exception("No parent PHPExcel\Writer_IWriter assigned.");
+ }
+ }
- /**
- * Set parent IWriter object
- *
- * @param PHPExcel\Writer_IWriter $pWriter
- * @throws PHPExcel\Writer_Exception
- */
- public function __construct(Writer_IWriter $pWriter = null) {
- if (!is_null($pWriter)) {
- $this->_parentWriter = $pWriter;
- }
- }
+ /**
+ * Set parent IWriter object
+ *
+ * @param PHPExcel\Writer_IWriter $pWriter
+ * @throws PHPExcel\Writer_Exception
+ */
+ public function __construct(Writer_IWriter $pWriter = null) {
+ if (!is_null($pWriter)) {
+ $this->_parentWriter = $pWriter;
+ }
+ }
}
diff --git a/Classes/PHPExcel/Writer/Excel5.php b/Classes/PHPExcel/Writer/Excel5.php
index 0c2f42f..e4d612a 100644
--- a/Classes/PHPExcel/Writer/Excel5.php
+++ b/Classes/PHPExcel/Writer/Excel5.php
@@ -21,8 +21,8 @@
* @category PHPExcel
* @package PHPExcel\Writer_Excel5
* @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##
*/
@@ -37,901 +37,901 @@ namespace PHPExcel;
*/
class Writer_Excel5 extends Writer_Abstract implements Writer_IWriter
{
- /**
- * PHPExcel object
- *
- * @var PHPExcel
- */
- private $_phpExcel;
-
- /**
- * Total number of shared strings in workbook
- *
- * @var int
- */
- private $_str_total = 0;
-
- /**
- * Number of unique shared strings in workbook
- *
- * @var int
- */
- private $_str_unique = 0;
-
- /**
- * Array of unique shared strings in workbook
- *
- * @var array
- */
- private $_str_table = array();
-
- /**
- * Color cache. Mapping between RGB value and color index.
- *
- * @var array
- */
- private $_colors;
-
- /**
- * Formula parser
- *
- * @var PHPExcel\Writer_Excel5_Parser
- */
- private $_parser;
-
- /**
- * Identifier clusters for drawings. Used in MSODRAWINGGROUP record.
- *
- * @var array
- */
- private $_IDCLs;
-
- /**
- * Basic OLE object summary information
- *
- * @var array
- */
- private $_summaryInformation;
-
- /**
- * Extended OLE object document summary information
- *
- * @var array
- */
- private $_documentSummaryInformation;
-
- /**
- * Create a new PHPExcel\Writer_Excel5
- *
- * @param PHPExcel\Workbook $phpExcel PHPExcel object
- */
- public function __construct(Workbook $phpExcel) {
- $this->_phpExcel = $phpExcel;
-
- $this->_parser = new Writer_Excel5_Parser();
- }
-
- /**
- * Save PHPExcel to file
- *
- * @param string $pFilename
- * @throws PHPExcel\Writer_Exception
- */
- public function save($pFilename = null) {
-
- // garbage collect
- $this->_phpExcel->garbageCollect();
-
- $saveDebugLog = Calculation::getInstance($this->_phpExcel)->getDebugLog()->getWriteDebugLog();
- Calculation::getInstance($this->_phpExcel)->getDebugLog()->setWriteDebugLog(FALSE);
- $saveDateReturnType = Calculation_Functions::getReturnDateType();
- Calculation_Functions::setReturnDateType(Calculation_Functions::RETURNDATE_EXCEL);
-
- // initialize colors array
- $this->_colors = array();
-
- // Initialise workbook writer
- $this->_writerWorkbook = new Writer_Excel5_Workbook($this->_phpExcel,
- $this->_str_total, $this->_str_unique, $this->_str_table,
- $this->_colors, $this->_parser);
-
- // Initialise worksheet writers
- $countSheets = $this->_phpExcel->getSheetCount();
- for ($i = 0; $i < $countSheets; ++$i) {
- $this->_writerWorksheets[$i] = new Writer_Excel5_Worksheet($this->_str_total, $this->_str_unique,
- $this->_str_table, $this->_colors,
- $this->_parser,
- $this->_preCalculateFormulas,
- $this->_phpExcel->getSheet($i));
- }
-
- // build Escher objects. Escher objects for workbooks needs to be build before Escher object for workbook.
- $this->_buildWorksheetEschers();
- $this->_buildWorkbookEscher();
-
- // add 15 identical cell style Xfs
- // for now, we use the first cellXf instead of cellStyleXf
- $cellXfCollection = $this->_phpExcel->getCellXfCollection();
- for ($i = 0; $i < 15; ++$i) {
- $this->_writerWorkbook->addXfWriter($cellXfCollection[0], true);
- }
-
- // add all the cell Xfs
- foreach ($this->_phpExcel->getCellXfCollection() as $style) {
- $this->_writerWorkbook->addXfWriter($style, false);
- }
-
- // add fonts from rich text eleemnts
- for ($i = 0; $i < $countSheets; ++$i) {
- foreach ($this->_writerWorksheets[$i]->_phpSheet->getCellCollection() as $cellID) {
- $cell = $this->_writerWorksheets[$i]->_phpSheet->getCell($cellID);
- $cVal = $cell->getValue();
- if ($cVal instanceof RichText) {
- $elements = $cVal->getRichTextElements();
- foreach ($elements as $element) {
- if ($element instanceof RichText_Run) {
- $font = $element->getFont();
- $this->_writerWorksheets[$i]->_fntHashIndex[$font->getHashCode()] = $this->_writerWorkbook->_addFont($font);
- }
- }
- }
- }
- }
-
- // initialize OLE file
- $workbookStreamName = 'Workbook';
- $OLE = new Shared_OLE_PPS_File(Shared_OLE::Asc2Ucs($workbookStreamName));
-
- // Write the worksheet streams before the global workbook stream,
- // because the byte sizes of these are needed in the global workbook stream
- $worksheetSizes = array();
- for ($i = 0; $i < $countSheets; ++$i) {
- $this->_writerWorksheets[$i]->close();
- $worksheetSizes[] = $this->_writerWorksheets[$i]->_datasize;
- }
-
- // add binary data for global workbook stream
- $OLE->append($this->_writerWorkbook->writeWorkbook($worksheetSizes));
-
- // add binary data for sheet streams
- for ($i = 0; $i < $countSheets; ++$i) {
- $OLE->append($this->_writerWorksheets[$i]->getData());
- }
-
- $this->_documentSummaryInformation = $this->_writeDocumentSummaryInformation();
- // initialize OLE Document Summary Information
- if(isset($this->_documentSummaryInformation) && !empty($this->_documentSummaryInformation)){
- $OLE_DocumentSummaryInformation = new Shared_OLE_PPS_File(Shared_OLE::Asc2Ucs(chr(5) . 'DocumentSummaryInformation'));
- $OLE_DocumentSummaryInformation->append($this->_documentSummaryInformation);
- }
-
- $this->_summaryInformation = $this->_writeSummaryInformation();
- // initialize OLE Summary Information
- if(isset($this->_summaryInformation) && !empty($this->_summaryInformation)){
- $OLE_SummaryInformation = new Shared_OLE_PPS_File(Shared_OLE::Asc2Ucs(chr(5) . 'SummaryInformation'));
- $OLE_SummaryInformation->append($this->_summaryInformation);
- }
-
- // define OLE Parts
- $arrRootData = array($OLE);
- // initialize OLE Properties file
- if(isset($OLE_SummaryInformation)){
- $arrRootData[] = $OLE_SummaryInformation;
- }
- // initialize OLE Extended Properties file
- if(isset($OLE_DocumentSummaryInformation)){
- $arrRootData[] = $OLE_DocumentSummaryInformation;
- }
-
- $root = new Shared_OLE_PPS_Root(time(), time(), $arrRootData);
- // save the OLE file
- $res = $root->save($pFilename);
-
- Calculation_Functions::setReturnDateType($saveDateReturnType);
- Calculation::getInstance($this->_phpExcel)->getDebugLog()->setWriteDebugLog($saveDebugLog);
- }
-
- /**
- * Set temporary storage directory
- *
- * @deprecated
- * @param string $pValue Temporary storage directory
- * @throws PHPExcel\Writer_Exception when directory does not exist
- * @return PHPExcel\Writer_Excel5
- */
- public function setTempDir($pValue = '') {
- return $this;
- }
-
- /**
- * Build the Worksheet Escher objects
- *
- */
- private function _buildWorksheetEschers()
- {
- // 1-based index to BstoreContainer
- $blipIndex = 0;
- $lastReducedSpId = 0;
- $lastSpId = 0;
-
- foreach ($this->_phpExcel->getAllsheets() as $sheet) {
- // sheet index
- $sheetIndex = $sheet->getParent()->getIndex($sheet);
-
- $escher = null;
-
- // check if there are any shapes for this sheet
- $filterRange = $sheet->getAutoFilter()->getRange();
- if (count($sheet->getDrawingCollection()) == 0 && empty($filterRange)) {
- continue;
- }
-
- // create intermediate Escher object
- $escher = new Shared_Escher();
-
- // dgContainer
- $dgContainer = new Shared_Escher_DgContainer();
-
- // set the drawing index (we use sheet index + 1)
- $dgId = $sheet->getParent()->getIndex($sheet) + 1;
- $dgContainer->setDgId($dgId);
- $escher->setDgContainer($dgContainer);
-
- // spgrContainer
- $spgrContainer = new Shared_Escher_DgContainer_SpgrContainer();
- $dgContainer->setSpgrContainer($spgrContainer);
-
- // add one shape which is the group shape
- $spContainer = new Shared_Escher_DgContainer_SpgrContainer_SpContainer();
- $spContainer->setSpgr(true);
- $spContainer->setSpType(0);
- $spContainer->setSpId(($sheet->getParent()->getIndex($sheet) + 1) << 10);
- $spgrContainer->addChild($spContainer);
-
- // add the shapes
-
- $countShapes[$sheetIndex] = 0; // count number of shapes (minus group shape), in sheet
-
- foreach ($sheet->getDrawingCollection() as $drawing) {
- ++$blipIndex;
-
- ++$countShapes[$sheetIndex];
-
- // add the shape
- $spContainer = new Shared_Escher_DgContainer_SpgrContainer_SpContainer();
-
- // set the shape type
- $spContainer->setSpType(0x004B);
- // set the shape flag
- $spContainer->setSpFlag(0x02);
-
- // set the shape index (we combine 1-based sheet index and $countShapes to create unique shape index)
- $reducedSpId = $countShapes[$sheetIndex];
- $spId = $reducedSpId
- | ($sheet->getParent()->getIndex($sheet) + 1) << 10;
- $spContainer->setSpId($spId);
-
- // keep track of last reducedSpId
- $lastReducedSpId = $reducedSpId;
-
- // keep track of last spId
- $lastSpId = $spId;
-
- // set the BLIP index
- $spContainer->setOPT(0x4104, $blipIndex);
-
- // set coordinates and offsets, client anchor
- $coordinates = $drawing->getCoordinates();
- $offsetX = $drawing->getOffsetX();
- $offsetY = $drawing->getOffsetY();
- $width = $drawing->getWidth();
- $height = $drawing->getHeight();
-
- $twoAnchor = Shared_Excel5::oneAnchor2twoAnchor($sheet, $coordinates, $offsetX, $offsetY, $width, $height);
-
- $spContainer->setStartCoordinates($twoAnchor['startCoordinates']);
- $spContainer->setStartOffsetX($twoAnchor['startOffsetX']);
- $spContainer->setStartOffsetY($twoAnchor['startOffsetY']);
- $spContainer->setEndCoordinates($twoAnchor['endCoordinates']);
- $spContainer->setEndOffsetX($twoAnchor['endOffsetX']);
- $spContainer->setEndOffsetY($twoAnchor['endOffsetY']);
-
- $spgrContainer->addChild($spContainer);
- }
-
- // AutoFilters
- if(!empty($filterRange)){
- $rangeBounds = Cell::rangeBoundaries($filterRange);
- $iNumColStart = $rangeBounds[0][0];
- $iNumColEnd = $rangeBounds[1][0];
-
- $iInc = $iNumColStart;
- while($iInc <= $iNumColEnd){
- ++$countShapes[$sheetIndex];
-
- // create an Drawing Object for the dropdown
- $oDrawing = new Worksheet_BaseDrawing();
- // get the coordinates of drawing
- $cDrawing = Cell::stringFromColumnIndex($iInc - 1) . $rangeBounds[0][1];
- $oDrawing->setCoordinates($cDrawing);
- $oDrawing->setWorksheet($sheet);
-
- // add the shape
- $spContainer = new Shared_Escher_DgContainer_SpgrContainer_SpContainer();
- // set the shape type
- $spContainer->setSpType(0x00C9);
- // set the shape flag
- $spContainer->setSpFlag(0x01);
-
- // set the shape index (we combine 1-based sheet index and $countShapes to create unique shape index)
- $reducedSpId = $countShapes[$sheetIndex];
- $spId = $reducedSpId
- | ($sheet->getParent()->getIndex($sheet) + 1) << 10;
- $spContainer->setSpId($spId);
-
- // keep track of last reducedSpId
- $lastReducedSpId = $reducedSpId;
-
- // keep track of last spId
- $lastSpId = $spId;
-
- $spContainer->setOPT(0x007F, 0x01040104); // Protection -> fLockAgainstGrouping
- $spContainer->setOPT(0x00BF, 0x00080008); // Text -> fFitTextToShape
- $spContainer->setOPT(0x01BF, 0x00010000); // Fill Style -> fNoFillHitTest
- $spContainer->setOPT(0x01FF, 0x00080000); // Line Style -> fNoLineDrawDash
- $spContainer->setOPT(0x03BF, 0x000A0000); // Group Shape -> fPrint
-
- // set coordinates and offsets, client anchor
- $endCoordinates = Cell::stringFromColumnIndex(Cell::stringFromColumnIndex($iInc - 1));
- $endCoordinates .= $rangeBounds[0][1] + 1;
-
- $spContainer->setStartCoordinates($cDrawing);
- $spContainer->setStartOffsetX(0);
- $spContainer->setStartOffsetY(0);
- $spContainer->setEndCoordinates($endCoordinates);
- $spContainer->setEndOffsetX(0);
- $spContainer->setEndOffsetY(0);
-
- $spgrContainer->addChild($spContainer);
- $iInc++;
- }
- }
-
- // identifier clusters, used for workbook Escher object
- $this->_IDCLs[$dgId] = $lastReducedSpId;
-
- // set last shape index
- $dgContainer->setLastSpId($lastSpId);
-
- // set the Escher object
- $this->_writerWorksheets[$sheetIndex]->setEscher($escher);
- }
- }
-
- /**
- * Build the Escher object corresponding to the MSODRAWINGGROUP record
- */
- private function _buildWorkbookEscher()
- {
- $escher = null;
-
- // any drawings in this workbook?
- $found = false;
- foreach ($this->_phpExcel->getAllSheets() as $sheet) {
- if (count($sheet->getDrawingCollection()) > 0) {
- $found = true;
- break;
- }
- }
-
- // nothing to do if there are no drawings
- if (!$found) {
- return;
- }
-
- // if we reach here, then there are drawings in the workbook
- $escher = new Shared_Escher();
-
- // dggContainer
- $dggContainer = new Shared_Escher_DggContainer();
- $escher->setDggContainer($dggContainer);
-
- // set IDCLs (identifier clusters)
- $dggContainer->setIDCLs($this->_IDCLs);
-
- // this loop is for determining maximum shape identifier of all drawing
- $spIdMax = 0;
- $totalCountShapes = 0;
- $countDrawings = 0;
-
- foreach ($this->_phpExcel->getAllsheets() as $sheet) {
- $sheetCountShapes = 0; // count number of shapes (minus group shape), in sheet
-
- if (count($sheet->getDrawingCollection()) > 0) {
- ++$countDrawings;
-
- foreach ($sheet->getDrawingCollection() as $drawing) {
- ++$sheetCountShapes;
- ++$totalCountShapes;
-
- $spId = $sheetCountShapes
- | ($this->_phpExcel->getIndex($sheet) + 1) << 10;
- $spIdMax = max($spId, $spIdMax);
- }
- }
- }
-
- $dggContainer->setSpIdMax($spIdMax + 1);
- $dggContainer->setCDgSaved($countDrawings);
- $dggContainer->setCSpSaved($totalCountShapes + $countDrawings); // total number of shapes incl. one group shapes per drawing
-
- // bstoreContainer
- $bstoreContainer = new Shared_Escher_DggContainer_BstoreContainer();
- $dggContainer->setBstoreContainer($bstoreContainer);
-
- // the BSE's (all the images)
- foreach ($this->_phpExcel->getAllsheets() as $sheet) {
- foreach ($sheet->getDrawingCollection() as $drawing) {
- if ($drawing instanceof Worksheet_Drawing) {
-
- $filename = $drawing->getPath();
-
- list($imagesx, $imagesy, $imageFormat) = getimagesize($filename);
-
- switch ($imageFormat) {
-
- case 1: // GIF, not supported by BIFF8, we convert to PNG
- $blipType = Shared_Escher_DggContainer_BstoreContainer_BSE::BLIPTYPE_PNG;
- ob_start();
- imagepng(imagecreatefromgif($filename));
- $blipData = ob_get_contents();
- ob_end_clean();
- break;
-
- case 2: // JPEG
- $blipType = Shared_Escher_DggContainer_BstoreContainer_BSE::BLIPTYPE_JPEG;
- $blipData = file_get_contents($filename);
- break;
-
- case 3: // PNG
- $blipType = Shared_Escher_DggContainer_BstoreContainer_BSE::BLIPTYPE_PNG;
- $blipData = file_get_contents($filename);
- break;
-
- case 6: // Windows DIB (BMP), we convert to PNG
- $blipType = Shared_Escher_DggContainer_BstoreContainer_BSE::BLIPTYPE_PNG;
- ob_start();
- imagepng(Shared_Drawing::imagecreatefrombmp($filename));
- $blipData = ob_get_contents();
- ob_end_clean();
- break;
-
- default: continue 2;
-
- }
-
- $blip = new Shared_Escher_DggContainer_BstoreContainer_BSE_Blip();
- $blip->setData($blipData);
-
- $BSE = new Shared_Escher_DggContainer_BstoreContainer_BSE();
- $BSE->setBlipType($blipType);
- $BSE->setBlip($blip);
-
- $bstoreContainer->addBSE($BSE);
-
- } else if ($drawing instanceof Worksheet_MemoryDrawing) {
-
- switch ($drawing->getRenderingFunction()) {
-
- case Worksheet_MemoryDrawing::RENDERING_JPEG:
- $blipType = Shared_Escher_DggContainer_BstoreContainer_BSE::BLIPTYPE_JPEG;
- $renderingFunction = 'imagejpeg';
- break;
-
- case Worksheet_MemoryDrawing::RENDERING_GIF:
- case Worksheet_MemoryDrawing::RENDERING_PNG:
- case Worksheet_MemoryDrawing::RENDERING_DEFAULT:
- $blipType = Shared_Escher_DggContainer_BstoreContainer_BSE::BLIPTYPE_PNG;
- $renderingFunction = 'imagepng';
- break;
-
- }
-
- ob_start();
- call_user_func($renderingFunction, $drawing->getImageResource());
- $blipData = ob_get_contents();
- ob_end_clean();
-
- $blip = new Shared_Escher_DggContainer_BstoreContainer_BSE_Blip();
- $blip->setData($blipData);
-
- $BSE = new Shared_Escher_DggContainer_BstoreContainer_BSE();
- $BSE->setBlipType($blipType);
- $BSE->setBlip($blip);
-
- $bstoreContainer->addBSE($BSE);
- }
- }
- }
-
- // Set the Escher object
- $this->_writerWorkbook->setEscher($escher);
- }
-
- /**
- * Build the OLE Part for DocumentSummary Information
- * @return string
- */
- private function _writeDocumentSummaryInformation(){
-
- // offset: 0; size: 2; must be 0xFE 0xFF (UTF-16 LE byte order mark)
- $data = pack('v', 0xFFFE);
- // offset: 2; size: 2;
- $data .= pack('v', 0x0000);
- // offset: 4; size: 2; OS version
- $data .= pack('v', 0x0106);
- // offset: 6; size: 2; OS indicator
- $data .= pack('v', 0x0002);
- // offset: 8; size: 16
- $data .= pack('VVVV', 0x00, 0x00, 0x00, 0x00);
- // offset: 24; size: 4; section count
- $data .= pack('V', 0x0001);
-
- // offset: 28; size: 16; first section's class id: 02 d5 cd d5 9c 2e 1b 10 93 97 08 00 2b 2c f9 ae
- $data .= pack('vvvvvvvv', 0xD502, 0xD5CD, 0x2E9C, 0x101B, 0x9793, 0x0008, 0x2C2B, 0xAEF9);
- // offset: 44; size: 4; offset of the start
- $data .= pack('V', 0x30);
-
- // SECTION
- $dataSection = array();
- $dataSection_NumProps = 0;
- $dataSection_Summary = '';
- $dataSection_Content = '';
-
- // GKPIDDSI_CODEPAGE: CodePage
- $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x01),
- 'offset' => array('pack' => 'V'),
- 'type' => array('pack' => 'V', 'data' => 0x02), // 2 byte signed integer
- 'data' => array('data' => 1252));
- $dataSection_NumProps++;
-
- // GKPIDDSI_CATEGORY : Category
- if($this->_phpExcel->getProperties()->getCategory()){
- $dataProp = $this->_phpExcel->getProperties()->getCategory();
- $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x02),
- 'offset' => array('pack' => 'V'),
- 'type' => array('pack' => 'V', 'data' => 0x1E),
- 'data' => array('data' => $dataProp, 'length' => strlen($dataProp)));
- $dataSection_NumProps++;
- }
- // GKPIDDSI_VERSION :Version of the application that wrote the property storage
- $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x17),
- 'offset' => array('pack' => 'V'),
- 'type' => array('pack' => 'V', 'data' => 0x03),
- 'data' => array('pack' => 'V', 'data' => 0x000C0000));
- $dataSection_NumProps++;
- // GKPIDDSI_SCALE : FALSE
- $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x0B),
- 'offset' => array('pack' => 'V'),
- 'type' => array('pack' => 'V', 'data' => 0x0B),
- 'data' => array('data' => false));
- $dataSection_NumProps++;
- // GKPIDDSI_LINKSDIRTY : True if any of the values for the linked properties have changed outside of the application
- $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x10),
- 'offset' => array('pack' => 'V'),
- 'type' => array('pack' => 'V', 'data' => 0x0B),
- 'data' => array('data' => false));
- $dataSection_NumProps++;
- // GKPIDDSI_SHAREDOC : FALSE
- $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x13),
- 'offset' => array('pack' => 'V'),
- 'type' => array('pack' => 'V', 'data' => 0x0B),
- 'data' => array('data' => false));
- $dataSection_NumProps++;
- // GKPIDDSI_HYPERLINKSCHANGED : True if any of the values for the _PID_LINKS (hyperlink text) have changed outside of the application
- $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x16),
- 'offset' => array('pack' => 'V'),
- 'type' => array('pack' => 'V', 'data' => 0x0B),
- 'data' => array('data' => false));
- $dataSection_NumProps++;
-
- // GKPIDDSI_DOCSPARTS
- // MS-OSHARED p75 (2.3.3.2.2.1)
- // Structure is VtVecUnalignedLpstrValue (2.3.3.1.9)
- // cElements
- $dataProp = pack('v', 0x0001);
- $dataProp .= pack('v', 0x0000);
- // array of UnalignedLpstr
- // cch
- $dataProp .= pack('v', 0x000A);
- $dataProp .= pack('v', 0x0000);
- // value
- $dataProp .= 'Worksheet'.chr(0);
-
- $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x0D),
- 'offset' => array('pack' => 'V'),
- 'type' => array('pack' => 'V', 'data' => 0x101E),
- 'data' => array('data' => $dataProp, 'length' => strlen($dataProp)));
- $dataSection_NumProps++;
-
- // GKPIDDSI_HEADINGPAIR
- // VtVecHeadingPairValue
- // cElements
- $dataProp = pack('v', 0x0002);
- $dataProp .= pack('v', 0x0000);
- // Array of vtHeadingPair
- // vtUnalignedString - headingString
- // stringType
- $dataProp .= pack('v', 0x001E);
- // padding
- $dataProp .= pack('v', 0x0000);
- // UnalignedLpstr
- // cch
- $dataProp .= pack('v', 0x0013);
- $dataProp .= pack('v', 0x0000);
- // value
- $dataProp .= 'Feuilles de calcul';
- // vtUnalignedString - headingParts
- // wType : 0x0003 = 32 bit signed integer
- $dataProp .= pack('v', 0x0300);
- // padding
- $dataProp .= pack('v', 0x0000);
- // value
- $dataProp .= pack('v', 0x0100);
- $dataProp .= pack('v', 0x0000);
- $dataProp .= pack('v', 0x0000);
- $dataProp .= pack('v', 0x0000);
-
- $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x0C),
- 'offset' => array('pack' => 'V'),
- 'type' => array('pack' => 'V', 'data' => 0x100C),
- 'data' => array('data' => $dataProp, 'length' => strlen($dataProp)));
+ /**
+ * PHPExcel object
+ *
+ * @var PHPExcel
+ */
+ private $_phpExcel;
+
+ /**
+ * Total number of shared strings in workbook
+ *
+ * @var int
+ */
+ private $_str_total = 0;
+
+ /**
+ * Number of unique shared strings in workbook
+ *
+ * @var int
+ */
+ private $_str_unique = 0;
+
+ /**
+ * Array of unique shared strings in workbook
+ *
+ * @var array
+ */
+ private $_str_table = array();
+
+ /**
+ * Color cache. Mapping between RGB value and color index.
+ *
+ * @var array
+ */
+ private $_colors;
+
+ /**
+ * Formula parser
+ *
+ * @var PHPExcel\Writer_Excel5_Parser
+ */
+ private $_parser;
+
+ /**
+ * Identifier clusters for drawings. Used in MSODRAWINGGROUP record.
+ *
+ * @var array
+ */
+ private $_IDCLs;
+
+ /**
+ * Basic OLE object summary information
+ *
+ * @var array
+ */
+ private $_summaryInformation;
+
+ /**
+ * Extended OLE object document summary information
+ *
+ * @var array
+ */
+ private $_documentSummaryInformation;
+
+ /**
+ * Create a new PHPExcel\Writer_Excel5
+ *
+ * @param PHPExcel\Workbook $phpExcel PHPExcel object
+ */
+ public function __construct(Workbook $phpExcel) {
+ $this->_phpExcel = $phpExcel;
+
+ $this->_parser = new Writer_Excel5_Parser();
+ }
+
+ /**
+ * Save PHPExcel to file
+ *
+ * @param string $pFilename
+ * @throws PHPExcel\Writer_Exception
+ */
+ public function save($pFilename = null) {
+
+ // garbage collect
+ $this->_phpExcel->garbageCollect();
+
+ $saveDebugLog = Calculation::getInstance($this->_phpExcel)->getDebugLog()->getWriteDebugLog();
+ Calculation::getInstance($this->_phpExcel)->getDebugLog()->setWriteDebugLog(false);
+ $saveDateReturnType = Calculation_Functions::getReturnDateType();
+ Calculation_Functions::setReturnDateType(Calculation_Functions::RETURNDATE_EXCEL);
+
+ // initialize colors array
+ $this->_colors = array();
+
+ // Initialise workbook writer
+ $this->_writerWorkbook = new Writer_Excel5_Workbook($this->_phpExcel,
+ $this->_str_total, $this->_str_unique, $this->_str_table,
+ $this->_colors, $this->_parser);
+
+ // Initialise worksheet writers
+ $countSheets = $this->_phpExcel->getSheetCount();
+ for ($i = 0; $i < $countSheets; ++$i) {
+ $this->_writerWorksheets[$i] = new Writer_Excel5_Worksheet($this->_str_total, $this->_str_unique,
+ $this->_str_table, $this->_colors,
+ $this->_parser,
+ $this->_preCalculateFormulas,
+ $this->_phpExcel->getSheet($i));
+ }
+
+ // build Escher objects. Escher objects for workbooks needs to be build before Escher object for workbook.
+ $this->_buildWorksheetEschers();
+ $this->_buildWorkbookEscher();
+
+ // add 15 identical cell style Xfs
+ // for now, we use the first cellXf instead of cellStyleXf
+ $cellXfCollection = $this->_phpExcel->getCellXfCollection();
+ for ($i = 0; $i < 15; ++$i) {
+ $this->_writerWorkbook->addXfWriter($cellXfCollection[0], true);
+ }
+
+ // add all the cell Xfs
+ foreach ($this->_phpExcel->getCellXfCollection() as $style) {
+ $this->_writerWorkbook->addXfWriter($style, false);
+ }
+
+ // add fonts from rich text eleemnts
+ for ($i = 0; $i < $countSheets; ++$i) {
+ foreach ($this->_writerWorksheets[$i]->_phpSheet->getCellCollection() as $cellID) {
+ $cell = $this->_writerWorksheets[$i]->_phpSheet->getCell($cellID);
+ $cVal = $cell->getValue();
+ if ($cVal instanceof RichText) {
+ $elements = $cVal->getRichTextElements();
+ foreach ($elements as $element) {
+ if ($element instanceof RichText_Run) {
+ $font = $element->getFont();
+ $this->_writerWorksheets[$i]->_fntHashIndex[$font->getHashCode()] = $this->_writerWorkbook->_addFont($font);
+ }
+ }
+ }
+ }
+ }
+
+ // initialize OLE file
+ $workbookStreamName = 'Workbook';
+ $OLE = new Shared_OLE_PPS_File(Shared_OLE::Asc2Ucs($workbookStreamName));
+
+ // Write the worksheet streams before the global workbook stream,
+ // because the byte sizes of these are needed in the global workbook stream
+ $worksheetSizes = array();
+ for ($i = 0; $i < $countSheets; ++$i) {
+ $this->_writerWorksheets[$i]->close();
+ $worksheetSizes[] = $this->_writerWorksheets[$i]->_datasize;
+ }
+
+ // add binary data for global workbook stream
+ $OLE->append($this->_writerWorkbook->writeWorkbook($worksheetSizes));
+
+ // add binary data for sheet streams
+ for ($i = 0; $i < $countSheets; ++$i) {
+ $OLE->append($this->_writerWorksheets[$i]->getData());
+ }
+
+ $this->_documentSummaryInformation = $this->_writeDocumentSummaryInformation();
+ // initialize OLE Document Summary Information
+ if(isset($this->_documentSummaryInformation) && !empty($this->_documentSummaryInformation)){
+ $OLE_DocumentSummaryInformation = new Shared_OLE_PPS_File(Shared_OLE::Asc2Ucs(chr(5) . 'DocumentSummaryInformation'));
+ $OLE_DocumentSummaryInformation->append($this->_documentSummaryInformation);
+ }
+
+ $this->_summaryInformation = $this->_writeSummaryInformation();
+ // initialize OLE Summary Information
+ if(isset($this->_summaryInformation) && !empty($this->_summaryInformation)){
+ $OLE_SummaryInformation = new Shared_OLE_PPS_File(Shared_OLE::Asc2Ucs(chr(5) . 'SummaryInformation'));
+ $OLE_SummaryInformation->append($this->_summaryInformation);
+ }
+
+ // define OLE Parts
+ $arrRootData = array($OLE);
+ // initialize OLE Properties file
+ if(isset($OLE_SummaryInformation)){
+ $arrRootData[] = $OLE_SummaryInformation;
+ }
+ // initialize OLE Extended Properties file
+ if(isset($OLE_DocumentSummaryInformation)){
+ $arrRootData[] = $OLE_DocumentSummaryInformation;
+ }
+
+ $root = new Shared_OLE_PPS_Root(time(), time(), $arrRootData);
+ // save the OLE file
+ $res = $root->save($pFilename);
+
+ Calculation_Functions::setReturnDateType($saveDateReturnType);
+ Calculation::getInstance($this->_phpExcel)->getDebugLog()->setWriteDebugLog($saveDebugLog);
+ }
+
+ /**
+ * Set temporary storage directory
+ *
+ * @deprecated
+ * @param string $pValue Temporary storage directory
+ * @throws PHPExcel\Writer_Exception when directory does not exist
+ * @return PHPExcel\Writer_Excel5
+ */
+ public function setTempDir($pValue = '') {
+ return $this;
+ }
+
+ /**
+ * Build the Worksheet Escher objects
+ *
+ */
+ private function _buildWorksheetEschers()
+ {
+ // 1-based index to BstoreContainer
+ $blipIndex = 0;
+ $lastReducedSpId = 0;
+ $lastSpId = 0;
+
+ foreach ($this->_phpExcel->getAllsheets() as $sheet) {
+ // sheet index
+ $sheetIndex = $sheet->getParent()->getIndex($sheet);
+
+ $escher = null;
+
+ // check if there are any shapes for this sheet
+ $filterRange = $sheet->getAutoFilter()->getRange();
+ if (count($sheet->getDrawingCollection()) == 0 && empty($filterRange)) {
+ continue;
+ }
+
+ // create intermediate Escher object
+ $escher = new Shared_Escher();
+
+ // dgContainer
+ $dgContainer = new Shared_Escher_DgContainer();
+
+ // set the drawing index (we use sheet index + 1)
+ $dgId = $sheet->getParent()->getIndex($sheet) + 1;
+ $dgContainer->setDgId($dgId);
+ $escher->setDgContainer($dgContainer);
+
+ // spgrContainer
+ $spgrContainer = new Shared_Escher_DgContainer_SpgrContainer();
+ $dgContainer->setSpgrContainer($spgrContainer);
+
+ // add one shape which is the group shape
+ $spContainer = new Shared_Escher_DgContainer_SpgrContainer_SpContainer();
+ $spContainer->setSpgr(true);
+ $spContainer->setSpType(0);
+ $spContainer->setSpId(($sheet->getParent()->getIndex($sheet) + 1) << 10);
+ $spgrContainer->addChild($spContainer);
+
+ // add the shapes
+
+ $countShapes[$sheetIndex] = 0; // count number of shapes (minus group shape), in sheet
+
+ foreach ($sheet->getDrawingCollection() as $drawing) {
+ ++$blipIndex;
+
+ ++$countShapes[$sheetIndex];
+
+ // add the shape
+ $spContainer = new Shared_Escher_DgContainer_SpgrContainer_SpContainer();
+
+ // set the shape type
+ $spContainer->setSpType(0x004B);
+ // set the shape flag
+ $spContainer->setSpFlag(0x02);
+
+ // set the shape index (we combine 1-based sheet index and $countShapes to create unique shape index)
+ $reducedSpId = $countShapes[$sheetIndex];
+ $spId = $reducedSpId
+ | ($sheet->getParent()->getIndex($sheet) + 1) << 10;
+ $spContainer->setSpId($spId);
+
+ // keep track of last reducedSpId
+ $lastReducedSpId = $reducedSpId;
+
+ // keep track of last spId
+ $lastSpId = $spId;
+
+ // set the BLIP index
+ $spContainer->setOPT(0x4104, $blipIndex);
+
+ // set coordinates and offsets, client anchor
+ $coordinates = $drawing->getCoordinates();
+ $offsetX = $drawing->getOffsetX();
+ $offsetY = $drawing->getOffsetY();
+ $width = $drawing->getWidth();
+ $height = $drawing->getHeight();
+
+ $twoAnchor = Shared_Excel5::oneAnchor2twoAnchor($sheet, $coordinates, $offsetX, $offsetY, $width, $height);
+
+ $spContainer->setStartCoordinates($twoAnchor['startCoordinates']);
+ $spContainer->setStartOffsetX($twoAnchor['startOffsetX']);
+ $spContainer->setStartOffsetY($twoAnchor['startOffsetY']);
+ $spContainer->setEndCoordinates($twoAnchor['endCoordinates']);
+ $spContainer->setEndOffsetX($twoAnchor['endOffsetX']);
+ $spContainer->setEndOffsetY($twoAnchor['endOffsetY']);
+
+ $spgrContainer->addChild($spContainer);
+ }
+
+ // AutoFilters
+ if(!empty($filterRange)){
+ $rangeBounds = Cell::rangeBoundaries($filterRange);
+ $iNumColStart = $rangeBounds[0][0];
+ $iNumColEnd = $rangeBounds[1][0];
+
+ $iInc = $iNumColStart;
+ while($iInc <= $iNumColEnd){
+ ++$countShapes[$sheetIndex];
+
+ // create an Drawing Object for the dropdown
+ $oDrawing = new Worksheet_BaseDrawing();
+ // get the coordinates of drawing
+ $cDrawing = Cell::stringFromColumnIndex($iInc - 1) . $rangeBounds[0][1];
+ $oDrawing->setCoordinates($cDrawing);
+ $oDrawing->setWorksheet($sheet);
+
+ // add the shape
+ $spContainer = new Shared_Escher_DgContainer_SpgrContainer_SpContainer();
+ // set the shape type
+ $spContainer->setSpType(0x00C9);
+ // set the shape flag
+ $spContainer->setSpFlag(0x01);
+
+ // set the shape index (we combine 1-based sheet index and $countShapes to create unique shape index)
+ $reducedSpId = $countShapes[$sheetIndex];
+ $spId = $reducedSpId
+ | ($sheet->getParent()->getIndex($sheet) + 1) << 10;
+ $spContainer->setSpId($spId);
+
+ // keep track of last reducedSpId
+ $lastReducedSpId = $reducedSpId;
+
+ // keep track of last spId
+ $lastSpId = $spId;
+
+ $spContainer->setOPT(0x007F, 0x01040104); // Protection -> fLockAgainstGrouping
+ $spContainer->setOPT(0x00BF, 0x00080008); // Text -> fFitTextToShape
+ $spContainer->setOPT(0x01BF, 0x00010000); // Fill Style -> fNoFillHitTest
+ $spContainer->setOPT(0x01FF, 0x00080000); // Line Style -> fNoLineDrawDash
+ $spContainer->setOPT(0x03BF, 0x000A0000); // Group Shape -> fPrint
+
+ // set coordinates and offsets, client anchor
+ $endCoordinates = Cell::stringFromColumnIndex(Cell::stringFromColumnIndex($iInc - 1));
+ $endCoordinates .= $rangeBounds[0][1] + 1;
+
+ $spContainer->setStartCoordinates($cDrawing);
+ $spContainer->setStartOffsetX(0);
+ $spContainer->setStartOffsetY(0);
+ $spContainer->setEndCoordinates($endCoordinates);
+ $spContainer->setEndOffsetX(0);
+ $spContainer->setEndOffsetY(0);
+
+ $spgrContainer->addChild($spContainer);
+ $iInc++;
+ }
+ }
+
+ // identifier clusters, used for workbook Escher object
+ $this->_IDCLs[$dgId] = $lastReducedSpId;
+
+ // set last shape index
+ $dgContainer->setLastSpId($lastSpId);
+
+ // set the Escher object
+ $this->_writerWorksheets[$sheetIndex]->setEscher($escher);
+ }
+ }
+
+ /**
+ * Build the Escher object corresponding to the MSODRAWINGGROUP record
+ */
+ private function _buildWorkbookEscher()
+ {
+ $escher = null;
+
+ // any drawings in this workbook?
+ $found = false;
+ foreach ($this->_phpExcel->getAllSheets() as $sheet) {
+ if (count($sheet->getDrawingCollection()) > 0) {
+ $found = true;
+ break;
+ }
+ }
+
+ // nothing to do if there are no drawings
+ if (!$found) {
+ return;
+ }
+
+ // if we reach here, then there are drawings in the workbook
+ $escher = new Shared_Escher();
+
+ // dggContainer
+ $dggContainer = new Shared_Escher_DggContainer();
+ $escher->setDggContainer($dggContainer);
+
+ // set IDCLs (identifier clusters)
+ $dggContainer->setIDCLs($this->_IDCLs);
+
+ // this loop is for determining maximum shape identifier of all drawing
+ $spIdMax = 0;
+ $totalCountShapes = 0;
+ $countDrawings = 0;
+
+ foreach ($this->_phpExcel->getAllsheets() as $sheet) {
+ $sheetCountShapes = 0; // count number of shapes (minus group shape), in sheet
+
+ if (count($sheet->getDrawingCollection()) > 0) {
+ ++$countDrawings;
+
+ foreach ($sheet->getDrawingCollection() as $drawing) {
+ ++$sheetCountShapes;
+ ++$totalCountShapes;
+
+ $spId = $sheetCountShapes
+ | ($this->_phpExcel->getIndex($sheet) + 1) << 10;
+ $spIdMax = max($spId, $spIdMax);
+ }
+ }
+ }
+
+ $dggContainer->setSpIdMax($spIdMax + 1);
+ $dggContainer->setCDgSaved($countDrawings);
+ $dggContainer->setCSpSaved($totalCountShapes + $countDrawings); // total number of shapes incl. one group shapes per drawing
+
+ // bstoreContainer
+ $bstoreContainer = new Shared_Escher_DggContainer_BstoreContainer();
+ $dggContainer->setBstoreContainer($bstoreContainer);
+
+ // the BSE's (all the images)
+ foreach ($this->_phpExcel->getAllsheets() as $sheet) {
+ foreach ($sheet->getDrawingCollection() as $drawing) {
+ if ($drawing instanceof Worksheet_Drawing) {
+
+ $filename = $drawing->getPath();
+
+ list($imagesx, $imagesy, $imageFormat) = getimagesize($filename);
+
+ switch ($imageFormat) {
+
+ case 1: // GIF, not supported by BIFF8, we convert to PNG
+ $blipType = Shared_Escher_DggContainer_BstoreContainer_BSE::BLIPTYPE_PNG;
+ ob_start();
+ imagepng(imagecreatefromgif($filename));
+ $blipData = ob_get_contents();
+ ob_end_clean();
+ break;
+
+ case 2: // JPEG
+ $blipType = Shared_Escher_DggContainer_BstoreContainer_BSE::BLIPTYPE_JPEG;
+ $blipData = file_get_contents($filename);
+ break;
+
+ case 3: // PNG
+ $blipType = Shared_Escher_DggContainer_BstoreContainer_BSE::BLIPTYPE_PNG;
+ $blipData = file_get_contents($filename);
+ break;
+
+ case 6: // Windows DIB (BMP), we convert to PNG
+ $blipType = Shared_Escher_DggContainer_BstoreContainer_BSE::BLIPTYPE_PNG;
+ ob_start();
+ imagepng(Shared_Drawing::imagecreatefrombmp($filename));
+ $blipData = ob_get_contents();
+ ob_end_clean();
+ break;
+
+ default: continue 2;
+
+ }
+
+ $blip = new Shared_Escher_DggContainer_BstoreContainer_BSE_Blip();
+ $blip->setData($blipData);
+
+ $BSE = new Shared_Escher_DggContainer_BstoreContainer_BSE();
+ $BSE->setBlipType($blipType);
+ $BSE->setBlip($blip);
+
+ $bstoreContainer->addBSE($BSE);
+
+ } else if ($drawing instanceof Worksheet_MemoryDrawing) {
+
+ switch ($drawing->getRenderingFunction()) {
+
+ case Worksheet_MemoryDrawing::RENDERING_JPEG:
+ $blipType = Shared_Escher_DggContainer_BstoreContainer_BSE::BLIPTYPE_JPEG;
+ $renderingFunction = 'imagejpeg';
+ break;
+
+ case Worksheet_MemoryDrawing::RENDERING_GIF:
+ case Worksheet_MemoryDrawing::RENDERING_PNG:
+ case Worksheet_MemoryDrawing::RENDERING_DEFAULT:
+ $blipType = Shared_Escher_DggContainer_BstoreContainer_BSE::BLIPTYPE_PNG;
+ $renderingFunction = 'imagepng';
+ break;
+
+ }
+
+ ob_start();
+ call_user_func($renderingFunction, $drawing->getImageResource());
+ $blipData = ob_get_contents();
+ ob_end_clean();
+
+ $blip = new Shared_Escher_DggContainer_BstoreContainer_BSE_Blip();
+ $blip->setData($blipData);
+
+ $BSE = new Shared_Escher_DggContainer_BstoreContainer_BSE();
+ $BSE->setBlipType($blipType);
+ $BSE->setBlip($blip);
+
+ $bstoreContainer->addBSE($BSE);
+ }
+ }
+ }
+
+ // Set the Escher object
+ $this->_writerWorkbook->setEscher($escher);
+ }
+
+ /**
+ * Build the OLE Part for DocumentSummary Information
+ * @return string
+ */
+ private function _writeDocumentSummaryInformation(){
+
+ // offset: 0; size: 2; must be 0xFE 0xFF (UTF-16 LE byte order mark)
+ $data = pack('v', 0xFFFE);
+ // offset: 2; size: 2;
+ $data .= pack('v', 0x0000);
+ // offset: 4; size: 2; OS version
+ $data .= pack('v', 0x0106);
+ // offset: 6; size: 2; OS indicator
+ $data .= pack('v', 0x0002);
+ // offset: 8; size: 16
+ $data .= pack('VVVV', 0x00, 0x00, 0x00, 0x00);
+ // offset: 24; size: 4; section count
+ $data .= pack('V', 0x0001);
+
+ // offset: 28; size: 16; first section's class id: 02 d5 cd d5 9c 2e 1b 10 93 97 08 00 2b 2c f9 ae
+ $data .= pack('vvvvvvvv', 0xD502, 0xD5CD, 0x2E9C, 0x101B, 0x9793, 0x0008, 0x2C2B, 0xAEF9);
+ // offset: 44; size: 4; offset of the start
+ $data .= pack('V', 0x30);
+
+ // SECTION
+ $dataSection = array();
+ $dataSection_NumProps = 0;
+ $dataSection_Summary = '';
+ $dataSection_Content = '';
+
+ // GKPIDDSI_CODEPAGE: CodePage
+ $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x01),
+ 'offset' => array('pack' => 'V'),
+ 'type' => array('pack' => 'V', 'data' => 0x02), // 2 byte signed integer
+ 'data' => array('data' => 1252));
$dataSection_NumProps++;
- // 4 Section Length
- // 4 Property count
- // 8 * $dataSection_NumProps (8 = ID (4) + OffSet(4))
- $dataSection_Content_Offset = 8 + $dataSection_NumProps * 8;
- foreach ($dataSection as $dataProp){
- // Summary
- $dataSection_Summary .= pack($dataProp['summary']['pack'], $dataProp['summary']['data']);
- // Offset
- $dataSection_Summary .= pack($dataProp['offset']['pack'], $dataSection_Content_Offset);
- // DataType
- $dataSection_Content .= pack($dataProp['type']['pack'], $dataProp['type']['data']);
- // Data
- if($dataProp['type']['data'] == 0x02){ // 2 byte signed integer
- $dataSection_Content .= pack('V', $dataProp['data']['data']);
+ // GKPIDDSI_CATEGORY : Category
+ if($this->_phpExcel->getProperties()->getCategory()){
+ $dataProp = $this->_phpExcel->getProperties()->getCategory();
+ $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x02),
+ 'offset' => array('pack' => 'V'),
+ 'type' => array('pack' => 'V', 'data' => 0x1E),
+ 'data' => array('data' => $dataProp, 'length' => strlen($dataProp)));
+ $dataSection_NumProps++;
+ }
+ // GKPIDDSI_VERSION :Version of the application that wrote the property storage
+ $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x17),
+ 'offset' => array('pack' => 'V'),
+ 'type' => array('pack' => 'V', 'data' => 0x03),
+ 'data' => array('pack' => 'V', 'data' => 0x000C0000));
+ $dataSection_NumProps++;
+ // GKPIDDSI_SCALE : false
+ $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x0B),
+ 'offset' => array('pack' => 'V'),
+ 'type' => array('pack' => 'V', 'data' => 0x0B),
+ 'data' => array('data' => false));
+ $dataSection_NumProps++;
+ // GKPIDDSI_LINKSDIRTY : True if any of the values for the linked properties have changed outside of the application
+ $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x10),
+ 'offset' => array('pack' => 'V'),
+ 'type' => array('pack' => 'V', 'data' => 0x0B),
+ 'data' => array('data' => false));
+ $dataSection_NumProps++;
+ // GKPIDDSI_SHAREDOC : false
+ $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x13),
+ 'offset' => array('pack' => 'V'),
+ 'type' => array('pack' => 'V', 'data' => 0x0B),
+ 'data' => array('data' => false));
+ $dataSection_NumProps++;
+ // GKPIDDSI_HYPERLINKSCHANGED : True if any of the values for the _PID_LINKS (hyperlink text) have changed outside of the application
+ $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x16),
+ 'offset' => array('pack' => 'V'),
+ 'type' => array('pack' => 'V', 'data' => 0x0B),
+ 'data' => array('data' => false));
+ $dataSection_NumProps++;
- $dataSection_Content_Offset += 4 + 4;
- }
- elseif($dataProp['type']['data'] == 0x03){ // 4 byte signed integer
- $dataSection_Content .= pack('V', $dataProp['data']['data']);
+ // GKPIDDSI_DOCSPARTS
+ // MS-OSHARED p75 (2.3.3.2.2.1)
+ // Structure is VtVecUnalignedLpstrValue (2.3.3.1.9)
+ // cElements
+ $dataProp = pack('v', 0x0001);
+ $dataProp .= pack('v', 0x0000);
+ // array of UnalignedLpstr
+ // cch
+ $dataProp .= pack('v', 0x000A);
+ $dataProp .= pack('v', 0x0000);
+ // value
+ $dataProp .= 'Worksheet'.chr(0);
- $dataSection_Content_Offset += 4 + 4;
- }
- elseif($dataProp['type']['data'] == 0x0B){ // Boolean
- if($dataProp['data']['data'] == false){
- $dataSection_Content .= pack('V', 0x0000);
- } else {
- $dataSection_Content .= pack('V', 0x0001);
- }
- $dataSection_Content_Offset += 4 + 4;
- }
- elseif($dataProp['type']['data'] == 0x1E){ // null-terminated string prepended by dword string length
- // Null-terminated string
- $dataProp['data']['data'] .= chr(0);
- $dataProp['data']['length'] += 1;
- // Complete the string with null string for being a %4
- $dataProp['data']['length'] = $dataProp['data']['length'] + ((4 - $dataProp['data']['length'] % 4)==4 ? 0 : (4 - $dataProp['data']['length'] % 4));
- $dataProp['data']['data'] = str_pad($dataProp['data']['data'], $dataProp['data']['length'], chr(0), STR_PAD_RIGHT);
+ $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x0D),
+ 'offset' => array('pack' => 'V'),
+ 'type' => array('pack' => 'V', 'data' => 0x101E),
+ 'data' => array('data' => $dataProp, 'length' => strlen($dataProp)));
+ $dataSection_NumProps++;
- $dataSection_Content .= pack('V', $dataProp['data']['length']);
- $dataSection_Content .= $dataProp['data']['data'];
+ // GKPIDDSI_HEADINGPAIR
+ // VtVecHeadingPairValue
+ // cElements
+ $dataProp = pack('v', 0x0002);
+ $dataProp .= pack('v', 0x0000);
+ // Array of vtHeadingPair
+ // vtUnalignedString - headingString
+ // stringType
+ $dataProp .= pack('v', 0x001E);
+ // padding
+ $dataProp .= pack('v', 0x0000);
+ // UnalignedLpstr
+ // cch
+ $dataProp .= pack('v', 0x0013);
+ $dataProp .= pack('v', 0x0000);
+ // value
+ $dataProp .= 'Feuilles de calcul';
+ // vtUnalignedString - headingParts
+ // wType : 0x0003 = 32 bit signed integer
+ $dataProp .= pack('v', 0x0300);
+ // padding
+ $dataProp .= pack('v', 0x0000);
+ // value
+ $dataProp .= pack('v', 0x0100);
+ $dataProp .= pack('v', 0x0000);
+ $dataProp .= pack('v', 0x0000);
+ $dataProp .= pack('v', 0x0000);
- $dataSection_Content_Offset += 4 + 4 + strlen($dataProp['data']['data']);
- }
- elseif($dataProp['type']['data'] == 0x40){ // Filetime (64-bit value representing the number of 100-nanosecond intervals since January 1, 1601)
- $dataSection_Content .= $dataProp['data']['data'];
+ $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x0C),
+ 'offset' => array('pack' => 'V'),
+ 'type' => array('pack' => 'V', 'data' => 0x100C),
+ 'data' => array('data' => $dataProp, 'length' => strlen($dataProp)));
+ $dataSection_NumProps++;
- $dataSection_Content_Offset += 4 + 8;
- }
- else {
- // Data Type Not Used at the moment
- $dataSection_Content .= $dataProp['data']['data'];
+ // 4 Section Length
+ // 4 Property count
+ // 8 * $dataSection_NumProps (8 = ID (4) + OffSet(4))
+ $dataSection_Content_Offset = 8 + $dataSection_NumProps * 8;
+ foreach ($dataSection as $dataProp){
+ // Summary
+ $dataSection_Summary .= pack($dataProp['summary']['pack'], $dataProp['summary']['data']);
+ // Offset
+ $dataSection_Summary .= pack($dataProp['offset']['pack'], $dataSection_Content_Offset);
+ // DataType
+ $dataSection_Content .= pack($dataProp['type']['pack'], $dataProp['type']['data']);
+ // Data
+ if($dataProp['type']['data'] == 0x02){ // 2 byte signed integer
+ $dataSection_Content .= pack('V', $dataProp['data']['data']);
- $dataSection_Content_Offset += 4 + $dataProp['data']['length'];
- }
- }
- // Now $dataSection_Content_Offset contains the size of the content
+ $dataSection_Content_Offset += 4 + 4;
+ }
+ elseif($dataProp['type']['data'] == 0x03){ // 4 byte signed integer
+ $dataSection_Content .= pack('V', $dataProp['data']['data']);
- // section header
- // offset: $secOffset; size: 4; section length
- // + x Size of the content (summary + content)
- $data .= pack('V', $dataSection_Content_Offset);
- // offset: $secOffset+4; size: 4; property count
- $data .= pack('V', $dataSection_NumProps);
- // Section Summary
- $data .= $dataSection_Summary;
- // Section Content
- $data .= $dataSection_Content;
+ $dataSection_Content_Offset += 4 + 4;
+ }
+ elseif($dataProp['type']['data'] == 0x0B){ // Boolean
+ if($dataProp['data']['data'] == false){
+ $dataSection_Content .= pack('V', 0x0000);
+ } else {
+ $dataSection_Content .= pack('V', 0x0001);
+ }
+ $dataSection_Content_Offset += 4 + 4;
+ }
+ elseif($dataProp['type']['data'] == 0x1E){ // null-terminated string prepended by dword string length
+ // Null-terminated string
+ $dataProp['data']['data'] .= chr(0);
+ $dataProp['data']['length'] += 1;
+ // Complete the string with null string for being a %4
+ $dataProp['data']['length'] = $dataProp['data']['length'] + ((4 - $dataProp['data']['length'] % 4)==4 ? 0 : (4 - $dataProp['data']['length'] % 4));
+ $dataProp['data']['data'] = str_pad($dataProp['data']['data'], $dataProp['data']['length'], chr(0), STR_PAD_RIGHT);
- return $data;
- }
+ $dataSection_Content .= pack('V', $dataProp['data']['length']);
+ $dataSection_Content .= $dataProp['data']['data'];
- /**
- * Build the OLE Part for Summary Information
- * @return string
- */
- private function _writeSummaryInformation(){
- // offset: 0; size: 2; must be 0xFE 0xFF (UTF-16 LE byte order mark)
- $data = pack('v', 0xFFFE);
- // offset: 2; size: 2;
- $data .= pack('v', 0x0000);
- // offset: 4; size: 2; OS version
- $data .= pack('v', 0x0106);
- // offset: 6; size: 2; OS indicator
- $data .= pack('v', 0x0002);
- // offset: 8; size: 16
- $data .= pack('VVVV', 0x00, 0x00, 0x00, 0x00);
- // offset: 24; size: 4; section count
- $data .= pack('V', 0x0001);
+ $dataSection_Content_Offset += 4 + 4 + strlen($dataProp['data']['data']);
+ }
+ elseif($dataProp['type']['data'] == 0x40){ // Filetime (64-bit value representing the number of 100-nanosecond intervals since January 1, 1601)
+ $dataSection_Content .= $dataProp['data']['data'];
- // offset: 28; size: 16; first section's class id: e0 85 9f f2 f9 4f 68 10 ab 91 08 00 2b 27 b3 d9
- $data .= pack('vvvvvvvv', 0x85E0, 0xF29F, 0x4FF9, 0x1068, 0x91AB, 0x0008, 0x272B, 0xD9B3);
- // offset: 44; size: 4; offset of the start
- $data .= pack('V', 0x30);
+ $dataSection_Content_Offset += 4 + 8;
+ }
+ else {
+ // Data Type Not Used at the moment
+ $dataSection_Content .= $dataProp['data']['data'];
- // SECTION
- $dataSection = array();
- $dataSection_NumProps = 0;
- $dataSection_Summary = '';
- $dataSection_Content = '';
+ $dataSection_Content_Offset += 4 + $dataProp['data']['length'];
+ }
+ }
+ // Now $dataSection_Content_Offset contains the size of the content
- // CodePage : CP-1252
- $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x01),
- 'offset' => array('pack' => 'V'),
- 'type' => array('pack' => 'V', 'data' => 0x02), // 2 byte signed integer
- 'data' => array('data' => 1252));
- $dataSection_NumProps++;
+ // section header
+ // offset: $secOffset; size: 4; section length
+ // + x Size of the content (summary + content)
+ $data .= pack('V', $dataSection_Content_Offset);
+ // offset: $secOffset+4; size: 4; property count
+ $data .= pack('V', $dataSection_NumProps);
+ // Section Summary
+ $data .= $dataSection_Summary;
+ // Section Content
+ $data .= $dataSection_Content;
- // Title
- if($this->_phpExcel->getProperties()->getTitle()){
- $dataProp = $this->_phpExcel->getProperties()->getTitle();
- $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x02),
- 'offset' => array('pack' => 'V'),
- 'type' => array('pack' => 'V', 'data' => 0x1E), // null-terminated string prepended by dword string length
- 'data' => array('data' => $dataProp, 'length' => strlen($dataProp)));
- $dataSection_NumProps++;
- }
- // Subject
- if($this->_phpExcel->getProperties()->getSubject()){
- $dataProp = $this->_phpExcel->getProperties()->getSubject();
- $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x03),
- 'offset' => array('pack' => 'V'),
- 'type' => array('pack' => 'V', 'data' => 0x1E), // null-terminated string prepended by dword string length
- 'data' => array('data' => $dataProp, 'length' => strlen($dataProp)));
- $dataSection_NumProps++;
- }
- // Author (Creator)
- if($this->_phpExcel->getProperties()->getCreator()){
- $dataProp = $this->_phpExcel->getProperties()->getCreator();
- $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x04),
- 'offset' => array('pack' => 'V'),
- 'type' => array('pack' => 'V', 'data' => 0x1E), // null-terminated string prepended by dword string length
- 'data' => array('data' => $dataProp, 'length' => strlen($dataProp)));
- $dataSection_NumProps++;
- }
- // Keywords
- if($this->_phpExcel->getProperties()->getKeywords()){
- $dataProp = $this->_phpExcel->getProperties()->getKeywords();
- $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x05),
- 'offset' => array('pack' => 'V'),
- 'type' => array('pack' => 'V', 'data' => 0x1E), // null-terminated string prepended by dword string length
- 'data' => array('data' => $dataProp, 'length' => strlen($dataProp)));
- $dataSection_NumProps++;
- }
- // Comments (Description)
- if($this->_phpExcel->getProperties()->getDescription()){
- $dataProp = $this->_phpExcel->getProperties()->getDescription();
- $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x06),
- 'offset' => array('pack' => 'V'),
- 'type' => array('pack' => 'V', 'data' => 0x1E), // null-terminated string prepended by dword string length
- 'data' => array('data' => $dataProp, 'length' => strlen($dataProp)));
- $dataSection_NumProps++;
- }
- // Last Saved By (LastModifiedBy)
- if($this->_phpExcel->getProperties()->getLastModifiedBy()){
- $dataProp = $this->_phpExcel->getProperties()->getLastModifiedBy();
- $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x08),
- 'offset' => array('pack' => 'V'),
- 'type' => array('pack' => 'V', 'data' => 0x1E), // null-terminated string prepended by dword string length
- 'data' => array('data' => $dataProp, 'length' => strlen($dataProp)));
- $dataSection_NumProps++;
- }
- // Created Date/Time
- if($this->_phpExcel->getProperties()->getCreated()){
- $dataProp = $this->_phpExcel->getProperties()->getCreated();
- $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x0C),
- 'offset' => array('pack' => 'V'),
- 'type' => array('pack' => 'V', 'data' => 0x40), // Filetime (64-bit value representing the number of 100-nanosecond intervals since January 1, 1601)
- 'data' => array('data' => Shared_OLE::LocalDate2OLE($dataProp)));
- $dataSection_NumProps++;
- }
- // Modified Date/Time
- if($this->_phpExcel->getProperties()->getModified()){
- $dataProp = $this->_phpExcel->getProperties()->getModified();
- $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x0D),
- 'offset' => array('pack' => 'V'),
- 'type' => array('pack' => 'V', 'data' => 0x40), // Filetime (64-bit value representing the number of 100-nanosecond intervals since January 1, 1601)
- 'data' => array('data' => Shared_OLE::LocalDate2OLE($dataProp)));
- $dataSection_NumProps++;
- }
- // Security
- $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x13),
- 'offset' => array('pack' => 'V'),
- 'type' => array('pack' => 'V', 'data' => 0x03), // 4 byte signed integer
- 'data' => array('data' => 0x00));
- $dataSection_NumProps++;
+ return $data;
+ }
+
+ /**
+ * Build the OLE Part for Summary Information
+ * @return string
+ */
+ private function _writeSummaryInformation(){
+ // offset: 0; size: 2; must be 0xFE 0xFF (UTF-16 LE byte order mark)
+ $data = pack('v', 0xFFFE);
+ // offset: 2; size: 2;
+ $data .= pack('v', 0x0000);
+ // offset: 4; size: 2; OS version
+ $data .= pack('v', 0x0106);
+ // offset: 6; size: 2; OS indicator
+ $data .= pack('v', 0x0002);
+ // offset: 8; size: 16
+ $data .= pack('VVVV', 0x00, 0x00, 0x00, 0x00);
+ // offset: 24; size: 4; section count
+ $data .= pack('V', 0x0001);
+
+ // offset: 28; size: 16; first section's class id: e0 85 9f f2 f9 4f 68 10 ab 91 08 00 2b 27 b3 d9
+ $data .= pack('vvvvvvvv', 0x85E0, 0xF29F, 0x4FF9, 0x1068, 0x91AB, 0x0008, 0x272B, 0xD9B3);
+ // offset: 44; size: 4; offset of the start
+ $data .= pack('V', 0x30);
+
+ // SECTION
+ $dataSection = array();
+ $dataSection_NumProps = 0;
+ $dataSection_Summary = '';
+ $dataSection_Content = '';
+
+ // CodePage : CP-1252
+ $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x01),
+ 'offset' => array('pack' => 'V'),
+ 'type' => array('pack' => 'V', 'data' => 0x02), // 2 byte signed integer
+ 'data' => array('data' => 1252));
+ $dataSection_NumProps++;
+
+ // Title
+ if($this->_phpExcel->getProperties()->getTitle()){
+ $dataProp = $this->_phpExcel->getProperties()->getTitle();
+ $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x02),
+ 'offset' => array('pack' => 'V'),
+ 'type' => array('pack' => 'V', 'data' => 0x1E), // null-terminated string prepended by dword string length
+ 'data' => array('data' => $dataProp, 'length' => strlen($dataProp)));
+ $dataSection_NumProps++;
+ }
+ // Subject
+ if($this->_phpExcel->getProperties()->getSubject()){
+ $dataProp = $this->_phpExcel->getProperties()->getSubject();
+ $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x03),
+ 'offset' => array('pack' => 'V'),
+ 'type' => array('pack' => 'V', 'data' => 0x1E), // null-terminated string prepended by dword string length
+ 'data' => array('data' => $dataProp, 'length' => strlen($dataProp)));
+ $dataSection_NumProps++;
+ }
+ // Author (Creator)
+ if($this->_phpExcel->getProperties()->getCreator()){
+ $dataProp = $this->_phpExcel->getProperties()->getCreator();
+ $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x04),
+ 'offset' => array('pack' => 'V'),
+ 'type' => array('pack' => 'V', 'data' => 0x1E), // null-terminated string prepended by dword string length
+ 'data' => array('data' => $dataProp, 'length' => strlen($dataProp)));
+ $dataSection_NumProps++;
+ }
+ // Keywords
+ if($this->_phpExcel->getProperties()->getKeywords()){
+ $dataProp = $this->_phpExcel->getProperties()->getKeywords();
+ $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x05),
+ 'offset' => array('pack' => 'V'),
+ 'type' => array('pack' => 'V', 'data' => 0x1E), // null-terminated string prepended by dword string length
+ 'data' => array('data' => $dataProp, 'length' => strlen($dataProp)));
+ $dataSection_NumProps++;
+ }
+ // Comments (Description)
+ if($this->_phpExcel->getProperties()->getDescription()){
+ $dataProp = $this->_phpExcel->getProperties()->getDescription();
+ $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x06),
+ 'offset' => array('pack' => 'V'),
+ 'type' => array('pack' => 'V', 'data' => 0x1E), // null-terminated string prepended by dword string length
+ 'data' => array('data' => $dataProp, 'length' => strlen($dataProp)));
+ $dataSection_NumProps++;
+ }
+ // Last Saved By (LastModifiedBy)
+ if($this->_phpExcel->getProperties()->getLastModifiedBy()){
+ $dataProp = $this->_phpExcel->getProperties()->getLastModifiedBy();
+ $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x08),
+ 'offset' => array('pack' => 'V'),
+ 'type' => array('pack' => 'V', 'data' => 0x1E), // null-terminated string prepended by dword string length
+ 'data' => array('data' => $dataProp, 'length' => strlen($dataProp)));
+ $dataSection_NumProps++;
+ }
+ // Created Date/Time
+ if($this->_phpExcel->getProperties()->getCreated()){
+ $dataProp = $this->_phpExcel->getProperties()->getCreated();
+ $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x0C),
+ 'offset' => array('pack' => 'V'),
+ 'type' => array('pack' => 'V', 'data' => 0x40), // Filetime (64-bit value representing the number of 100-nanosecond intervals since January 1, 1601)
+ 'data' => array('data' => Shared_OLE::LocalDate2OLE($dataProp)));
+ $dataSection_NumProps++;
+ }
+ // Modified Date/Time
+ if($this->_phpExcel->getProperties()->getModified()){
+ $dataProp = $this->_phpExcel->getProperties()->getModified();
+ $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x0D),
+ 'offset' => array('pack' => 'V'),
+ 'type' => array('pack' => 'V', 'data' => 0x40), // Filetime (64-bit value representing the number of 100-nanosecond intervals since January 1, 1601)
+ 'data' => array('data' => Shared_OLE::LocalDate2OLE($dataProp)));
+ $dataSection_NumProps++;
+ }
+ // Security
+ $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x13),
+ 'offset' => array('pack' => 'V'),
+ 'type' => array('pack' => 'V', 'data' => 0x03), // 4 byte signed integer
+ 'data' => array('data' => 0x00));
+ $dataSection_NumProps++;
- // 4 Section Length
- // 4 Property count
- // 8 * $dataSection_NumProps (8 = ID (4) + OffSet(4))
- $dataSection_Content_Offset = 8 + $dataSection_NumProps * 8;
- foreach ($dataSection as $dataProp){
- // Summary
- $dataSection_Summary .= pack($dataProp['summary']['pack'], $dataProp['summary']['data']);
- // Offset
- $dataSection_Summary .= pack($dataProp['offset']['pack'], $dataSection_Content_Offset);
- // DataType
- $dataSection_Content .= pack($dataProp['type']['pack'], $dataProp['type']['data']);
- // Data
- if($dataProp['type']['data'] == 0x02){ // 2 byte signed integer
- $dataSection_Content .= pack('V', $dataProp['data']['data']);
+ // 4 Section Length
+ // 4 Property count
+ // 8 * $dataSection_NumProps (8 = ID (4) + OffSet(4))
+ $dataSection_Content_Offset = 8 + $dataSection_NumProps * 8;
+ foreach ($dataSection as $dataProp){
+ // Summary
+ $dataSection_Summary .= pack($dataProp['summary']['pack'], $dataProp['summary']['data']);
+ // Offset
+ $dataSection_Summary .= pack($dataProp['offset']['pack'], $dataSection_Content_Offset);
+ // DataType
+ $dataSection_Content .= pack($dataProp['type']['pack'], $dataProp['type']['data']);
+ // Data
+ if($dataProp['type']['data'] == 0x02){ // 2 byte signed integer
+ $dataSection_Content .= pack('V', $dataProp['data']['data']);
- $dataSection_Content_Offset += 4 + 4;
- }
- elseif($dataProp['type']['data'] == 0x03){ // 4 byte signed integer
- $dataSection_Content .= pack('V', $dataProp['data']['data']);
+ $dataSection_Content_Offset += 4 + 4;
+ }
+ elseif($dataProp['type']['data'] == 0x03){ // 4 byte signed integer
+ $dataSection_Content .= pack('V', $dataProp['data']['data']);
- $dataSection_Content_Offset += 4 + 4;
- }
- elseif($dataProp['type']['data'] == 0x1E){ // null-terminated string prepended by dword string length
- // Null-terminated string
- $dataProp['data']['data'] .= chr(0);
- $dataProp['data']['length'] += 1;
- // Complete the string with null string for being a %4
- $dataProp['data']['length'] = $dataProp['data']['length'] + ((4 - $dataProp['data']['length'] % 4)==4 ? 0 : (4 - $dataProp['data']['length'] % 4));
- $dataProp['data']['data'] = str_pad($dataProp['data']['data'], $dataProp['data']['length'], chr(0), STR_PAD_RIGHT);
+ $dataSection_Content_Offset += 4 + 4;
+ }
+ elseif($dataProp['type']['data'] == 0x1E){ // null-terminated string prepended by dword string length
+ // Null-terminated string
+ $dataProp['data']['data'] .= chr(0);
+ $dataProp['data']['length'] += 1;
+ // Complete the string with null string for being a %4
+ $dataProp['data']['length'] = $dataProp['data']['length'] + ((4 - $dataProp['data']['length'] % 4)==4 ? 0 : (4 - $dataProp['data']['length'] % 4));
+ $dataProp['data']['data'] = str_pad($dataProp['data']['data'], $dataProp['data']['length'], chr(0), STR_PAD_RIGHT);
- $dataSection_Content .= pack('V', $dataProp['data']['length']);
- $dataSection_Content .= $dataProp['data']['data'];
+ $dataSection_Content .= pack('V', $dataProp['data']['length']);
+ $dataSection_Content .= $dataProp['data']['data'];
- $dataSection_Content_Offset += 4 + 4 + strlen($dataProp['data']['data']);
- }
- elseif($dataProp['type']['data'] == 0x40){ // Filetime (64-bit value representing the number of 100-nanosecond intervals since January 1, 1601)
- $dataSection_Content .= $dataProp['data']['data'];
+ $dataSection_Content_Offset += 4 + 4 + strlen($dataProp['data']['data']);
+ }
+ elseif($dataProp['type']['data'] == 0x40){ // Filetime (64-bit value representing the number of 100-nanosecond intervals since January 1, 1601)
+ $dataSection_Content .= $dataProp['data']['data'];
- $dataSection_Content_Offset += 4 + 8;
- }
- else {
- // Data Type Not Used at the moment
- }
- }
- // Now $dataSection_Content_Offset contains the size of the content
+ $dataSection_Content_Offset += 4 + 8;
+ }
+ else {
+ // Data Type Not Used at the moment
+ }
+ }
+ // Now $dataSection_Content_Offset contains the size of the content
- // section header
- // offset: $secOffset; size: 4; section length
- // + x Size of the content (summary + content)
- $data .= pack('V', $dataSection_Content_Offset);
- // offset: $secOffset+4; size: 4; property count
- $data .= pack('V', $dataSection_NumProps);
- // Section Summary
- $data .= $dataSection_Summary;
- // Section Content
- $data .= $dataSection_Content;
+ // section header
+ // offset: $secOffset; size: 4; section length
+ // + x Size of the content (summary + content)
+ $data .= pack('V', $dataSection_Content_Offset);
+ // offset: $secOffset+4; size: 4; property count
+ $data .= pack('V', $dataSection_NumProps);
+ // Section Summary
+ $data .= $dataSection_Summary;
+ // Section Content
+ $data .= $dataSection_Content;
- return $data;
- }
+ return $data;
+ }
}
diff --git a/Classes/PHPExcel/Writer/Excel5/BIFFwriter.php b/Classes/PHPExcel/Writer/Excel5/BIFFwriter.php
index 58acb50..143abdf 100644
--- a/Classes/PHPExcel/Writer/Excel5/BIFFwriter.php
+++ b/Classes/PHPExcel/Writer/Excel5/BIFFwriter.php
@@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\Writer_Excel5
* @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##
*/
@@ -71,187 +71,187 @@ namespace PHPExcel;
*/
class Writer_Excel5_BIFFwriter
{
- /**
- * The byte order of this architecture. 0 => little endian, 1 => big endian
- * @var integer
- */
- private static $_byte_order;
+ /**
+ * The byte order of this architecture. 0 => little endian, 1 => big endian
+ * @var integer
+ */
+ private static $_byte_order;
- /**
- * The string containing the data of the BIFF stream
- * @var string
- */
- public $_data;
+ /**
+ * The string containing the data of the BIFF stream
+ * @var string
+ */
+ public $_data;
- /**
- * The size of the data in bytes. Should be the same as strlen($this->_data)
- * @var integer
- */
- public $_datasize;
+ /**
+ * The size of the data in bytes. Should be the same as strlen($this->_data)
+ * @var integer
+ */
+ public $_datasize;
- /**
- * The maximum length for a BIFF record (excluding record header and length field). See _addContinue()
- * @var integer
- * @see _addContinue()
- */
- public $_limit = 8224;
+ /**
+ * The maximum length for a BIFF record (excluding record header and length field). See _addContinue()
+ * @var integer
+ * @see _addContinue()
+ */
+ public $_limit = 8224;
- /**
- * Constructor
- */
- public function __construct()
- {
- $this->_data = '';
- $this->_datasize = 0;
-// $this->_limit = 8224;
- }
+ /**
+ * Constructor
+ */
+ public function __construct()
+ {
+ $this->_data = '';
+ $this->_datasize = 0;
+// $this->_limit = 8224;
+ }
- /**
- * Determine the byte order and store it as class data to avoid
- * recalculating it for each call to new().
- *
- * @return int
- */
- public static function getByteOrder()
- {
- if (!isset(self::$_byte_order)) {
- // Check if "pack" gives the required IEEE 64bit float
- $teststr = pack("d", 1.2345);
- $number = pack("C8", 0x8D, 0x97, 0x6E, 0x12, 0x83, 0xC0, 0xF3, 0x3F);
- if ($number == $teststr) {
- $byte_order = 0; // Little Endian
- } elseif ($number == strrev($teststr)){
- $byte_order = 1; // Big Endian
- } else {
- // Give up. I'll fix this in a later version.
- throw new Writer_Exception("Required floating point format not supported on this platform.");
- }
- self::$_byte_order = $byte_order;
- }
+ /**
+ * Determine the byte order and store it as class data to avoid
+ * recalculating it for each call to new().
+ *
+ * @return int
+ */
+ public static function getByteOrder()
+ {
+ if (!isset(self::$_byte_order)) {
+ // Check if "pack" gives the required IEEE 64bit float
+ $teststr = pack("d", 1.2345);
+ $number = pack("C8", 0x8D, 0x97, 0x6E, 0x12, 0x83, 0xC0, 0xF3, 0x3F);
+ if ($number == $teststr) {
+ $byte_order = 0; // Little Endian
+ } elseif ($number == strrev($teststr)){
+ $byte_order = 1; // Big Endian
+ } else {
+ // Give up. I'll fix this in a later version.
+ throw new Writer_Exception("Required floating point format not supported on this platform.");
+ }
+ self::$_byte_order = $byte_order;
+ }
- return self::$_byte_order;
- }
+ return self::$_byte_order;
+ }
- /**
- * General storage function
- *
- * @param string $data binary data to append
- * @access private
- */
- function _append($data)
- {
- if (strlen($data) - 4 > $this->_limit) {
- $data = $this->_addContinue($data);
- }
- $this->_data .= $data;
- $this->_datasize += strlen($data);
- }
+ /**
+ * General storage function
+ *
+ * @param string $data binary data to append
+ * @access private
+ */
+ function _append($data)
+ {
+ if (strlen($data) - 4 > $this->_limit) {
+ $data = $this->_addContinue($data);
+ }
+ $this->_data .= $data;
+ $this->_datasize += strlen($data);
+ }
- /**
- * General storage function like _append, but returns string instead of modifying $this->_data
- *
- * @param string $data binary data to write
- * @return string
- */
- public function writeData($data)
- {
- if (strlen($data) - 4 > $this->_limit) {
- $data = $this->_addContinue($data);
- }
- $this->_datasize += strlen($data);
+ /**
+ * General storage function like _append, but returns string instead of modifying $this->_data
+ *
+ * @param string $data binary data to write
+ * @return string
+ */
+ public function writeData($data)
+ {
+ if (strlen($data) - 4 > $this->_limit) {
+ $data = $this->_addContinue($data);
+ }
+ $this->_datasize += strlen($data);
- return $data;
- }
+ return $data;
+ }
- /**
- * Writes Excel BOF record to indicate the beginning of a stream or
- * sub-stream in the BIFF file.
- *
- * @param integer $type Type of BIFF file to write: 0x0005 Workbook,
- * 0x0010 Worksheet.
- * @access private
- */
- function _storeBof($type)
- {
- $record = 0x0809; // Record identifier (BIFF5-BIFF8)
- $length = 0x0010;
+ /**
+ * Writes Excel BOF record to indicate the beginning of a stream or
+ * sub-stream in the BIFF file.
+ *
+ * @param integer $type Type of BIFF file to write: 0x0005 Workbook,
+ * 0x0010 Worksheet.
+ * @access private
+ */
+ function _storeBof($type)
+ {
+ $record = 0x0809; // Record identifier (BIFF5-BIFF8)
+ $length = 0x0010;
- // by inspection of real files, MS Office Excel 2007 writes the following
- $unknown = pack("VV", 0x000100D1, 0x00000406);
+ // by inspection of real files, MS Office Excel 2007 writes the following
+ $unknown = pack("VV", 0x000100D1, 0x00000406);
- $build = 0x0DBB; // Excel 97
- $year = 0x07CC; // Excel 97
+ $build = 0x0DBB; // Excel 97
+ $year = 0x07CC; // Excel 97
- $version = 0x0600; // BIFF8
+ $version = 0x0600; // BIFF8
- $header = pack("vv", $record, $length);
- $data = pack("vvvv", $version, $type, $build, $year);
- $this->_append($header . $data . $unknown);
- }
+ $header = pack("vv", $record, $length);
+ $data = pack("vvvv", $version, $type, $build, $year);
+ $this->_append($header . $data . $unknown);
+ }
- /**
- * Writes Excel EOF record to indicate the end of a BIFF stream.
- *
- * @access private
- */
- function _storeEof()
- {
- $record = 0x000A; // Record identifier
- $length = 0x0000; // Number of bytes to follow
+ /**
+ * Writes Excel EOF record to indicate the end of a BIFF stream.
+ *
+ * @access private
+ */
+ function _storeEof()
+ {
+ $record = 0x000A; // Record identifier
+ $length = 0x0000; // Number of bytes to follow
- $header = pack("vv", $record, $length);
- $this->_append($header);
- }
+ $header = pack("vv", $record, $length);
+ $this->_append($header);
+ }
- /**
- * Writes Excel EOF record to indicate the end of a BIFF stream.
- *
- * @access private
- */
- public function writeEof()
- {
- $record = 0x000A; // Record identifier
- $length = 0x0000; // Number of bytes to follow
- $header = pack("vv", $record, $length);
- return $this->writeData($header);
- }
+ /**
+ * Writes Excel EOF record to indicate the end of a BIFF stream.
+ *
+ * @access private
+ */
+ public function writeEof()
+ {
+ $record = 0x000A; // Record identifier
+ $length = 0x0000; // Number of bytes to follow
+ $header = pack("vv", $record, $length);
+ return $this->writeData($header);
+ }
- /**
- * Excel limits the size of BIFF records. In Excel 5 the limit is 2084 bytes. In
- * Excel 97 the limit is 8228 bytes. Records that are longer than these limits
- * must be split up into CONTINUE blocks.
- *
- * This function takes a long BIFF record and inserts CONTINUE records as
- * necessary.
- *
- * @param string $data The original binary data to be written
- * @return string A very convenient string of continue blocks
- * @access private
- */
- function _addContinue($data)
- {
- $limit = $this->_limit;
- $record = 0x003C; // Record identifier
+ /**
+ * Excel limits the size of BIFF records. In Excel 5 the limit is 2084 bytes. In
+ * Excel 97 the limit is 8228 bytes. Records that are longer than these limits
+ * must be split up into CONTINUE blocks.
+ *
+ * This function takes a long BIFF record and inserts CONTINUE records as
+ * necessary.
+ *
+ * @param string $data The original binary data to be written
+ * @return string A very convenient string of continue blocks
+ * @access private
+ */
+ function _addContinue($data)
+ {
+ $limit = $this->_limit;
+ $record = 0x003C; // Record identifier
- // The first 2080/8224 bytes remain intact. However, we have to change
- // the length field of the record.
- $tmp = substr($data, 0, 2) . pack("v", $limit) . substr($data, 4, $limit);
+ // The first 2080/8224 bytes remain intact. However, we have to change
+ // the length field of the record.
+ $tmp = substr($data, 0, 2) . pack("v", $limit) . substr($data, 4, $limit);
- $header = pack("vv", $record, $limit); // Headers for continue records
+ $header = pack("vv", $record, $limit); // Headers for continue records
- // Retrieve chunks of 2080/8224 bytes +4 for the header.
- $data_length = strlen($data);
- for ($i = $limit + 4; $i < ($data_length - $limit); $i += $limit) {
- $tmp .= $header;
- $tmp .= substr($data, $i, $limit);
- }
+ // Retrieve chunks of 2080/8224 bytes +4 for the header.
+ $data_length = strlen($data);
+ for ($i = $limit + 4; $i < ($data_length - $limit); $i += $limit) {
+ $tmp .= $header;
+ $tmp .= substr($data, $i, $limit);
+ }
- // Retrieve the last chunk of data
- $header = pack("vv", $record, strlen($data) - $i);
- $tmp .= $header;
- $tmp .= substr($data, $i, strlen($data) - $i);
+ // Retrieve the last chunk of data
+ $header = pack("vv", $record, strlen($data) - $i);
+ $tmp .= $header;
+ $tmp .= substr($data, $i, strlen($data) - $i);
- return $tmp;
- }
+ return $tmp;
+ }
}
diff --git a/Classes/PHPExcel/Writer/Excel5/Escher.php b/Classes/PHPExcel/Writer/Excel5/Escher.php
index 9b68859..767e4c4 100644
--- a/Classes/PHPExcel/Writer/Excel5/Escher.php
+++ b/Classes/PHPExcel/Writer/Excel5/Escher.php
@@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\Writer_Excel5
* @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,503 +37,503 @@ namespace PHPExcel;
*/
class Writer_Excel5_Escher
{
- /**
- * The object we are writing
- */
- private $_object;
-
- /**
- * The written binary data
- */
- private $_data;
-
- /**
- * Shape offsets. Positions in binary stream where a new shape record begins
- *
- * @var array
- */
- private $_spOffsets;
-
- /**
- * Shape types.
- *
- * @var array
- */
- private $_spTypes;
-
- /**
- * Constructor
- *
- * @param mixed
- */
- public function __construct($object)
- {
- $this->_object = $object;
- }
-
- /**
- * Process the object to be written
- */
- public function close()
- {
- // initialize
- $this->_data = '';
-
- switch (get_class($this->_object)) {
-
- case __NAMESPACE__ . '\Shared_Escher':
- if ($dggContainer = $this->_object->getDggContainer()) {
- $writer = new Writer_Excel5_Escher($dggContainer);
- $this->_data = $writer->close();
- } else if ($dgContainer = $this->_object->getDgContainer()) {
- $writer = new Writer_Excel5_Escher($dgContainer);
- $this->_data = $writer->close();
- $this->_spOffsets = $writer->getSpOffsets();
- $this->_spTypes = $writer->getSpTypes();
- }
- break;
-
- case __NAMESPACE__ . '\Shared_Escher_DggContainer':
- // this is a container record
-
- // initialize
- $innerData = '';
-
- // write the dgg
- $recVer = 0x0;
- $recInstance = 0x0000;
- $recType = 0xF006;
-
- $recVerInstance = $recVer;
- $recVerInstance |= $recInstance << 4;
-
- // dgg data
- $dggData =
- pack('VVVV'
- , $this->_object->getSpIdMax() // maximum shape identifier increased by one
- , $this->_object->getCDgSaved() + 1 // number of file identifier clusters increased by one
- , $this->_object->getCSpSaved()
- , $this->_object->getCDgSaved() // count total number of drawings saved
- );
-
- // add file identifier clusters (one per drawing)
- $IDCLs = $this->_object->getIDCLs();
-
- foreach ($IDCLs as $dgId => $maxReducedSpId) {
- $dggData .= pack('VV', $dgId, $maxReducedSpId + 1);
- }
-
- $header = pack('vvV', $recVerInstance, $recType, strlen($dggData));
- $innerData .= $header . $dggData;
-
- // write the bstoreContainer
- if ($bstoreContainer = $this->_object->getBstoreContainer()) {
- $writer = new Writer_Excel5_Escher($bstoreContainer);
- $innerData .= $writer->close();
- }
-
- // write the record
- $recVer = 0xF;
- $recInstance = 0x0000;
- $recType = 0xF000;
- $length = strlen($innerData);
-
- $recVerInstance = $recVer;
- $recVerInstance |= $recInstance << 4;
-
- $header = pack('vvV', $recVerInstance, $recType, $length);
-
- $this->_data = $header . $innerData;
- break;
-
- case __NAMESPACE__ . '\Shared_Escher_DggContainer_BstoreContainer':
- // this is a container record
-
- // initialize
- $innerData = '';
-
- // treat the inner data
- if ($BSECollection = $this->_object->getBSECollection()) {
- foreach ($BSECollection as $BSE) {
- $writer = new Writer_Excel5_Escher($BSE);
- $innerData .= $writer->close();
- }
- }
-
- // write the record
- $recVer = 0xF;
- $recInstance = count($this->_object->getBSECollection());
- $recType = 0xF001;
- $length = strlen($innerData);
+ /**
+ * The object we are writing
+ */
+ private $_object;
+
+ /**
+ * The written binary data
+ */
+ private $_data;
+
+ /**
+ * Shape offsets. Positions in binary stream where a new shape record begins
+ *
+ * @var array
+ */
+ private $_spOffsets;
+
+ /**
+ * Shape types.
+ *
+ * @var array
+ */
+ private $_spTypes;
+
+ /**
+ * Constructor
+ *
+ * @param mixed
+ */
+ public function __construct($object)
+ {
+ $this->_object = $object;
+ }
+
+ /**
+ * Process the object to be written
+ */
+ public function close()
+ {
+ // initialize
+ $this->_data = '';
+
+ switch (get_class($this->_object)) {
+
+ case __NAMESPACE__ . '\Shared_Escher':
+ if ($dggContainer = $this->_object->getDggContainer()) {
+ $writer = new Writer_Excel5_Escher($dggContainer);
+ $this->_data = $writer->close();
+ } else if ($dgContainer = $this->_object->getDgContainer()) {
+ $writer = new Writer_Excel5_Escher($dgContainer);
+ $this->_data = $writer->close();
+ $this->_spOffsets = $writer->getSpOffsets();
+ $this->_spTypes = $writer->getSpTypes();
+ }
+ break;
+
+ case __NAMESPACE__ . '\Shared_Escher_DggContainer':
+ // this is a container record
+
+ // initialize
+ $innerData = '';
+
+ // write the dgg
+ $recVer = 0x0;
+ $recInstance = 0x0000;
+ $recType = 0xF006;
+
+ $recVerInstance = $recVer;
+ $recVerInstance |= $recInstance << 4;
+
+ // dgg data
+ $dggData =
+ pack('VVVV'
+ , $this->_object->getSpIdMax() // maximum shape identifier increased by one
+ , $this->_object->getCDgSaved() + 1 // number of file identifier clusters increased by one
+ , $this->_object->getCSpSaved()
+ , $this->_object->getCDgSaved() // count total number of drawings saved
+ );
+
+ // add file identifier clusters (one per drawing)
+ $IDCLs = $this->_object->getIDCLs();
+
+ foreach ($IDCLs as $dgId => $maxReducedSpId) {
+ $dggData .= pack('VV', $dgId, $maxReducedSpId + 1);
+ }
+
+ $header = pack('vvV', $recVerInstance, $recType, strlen($dggData));
+ $innerData .= $header . $dggData;
+
+ // write the bstoreContainer
+ if ($bstoreContainer = $this->_object->getBstoreContainer()) {
+ $writer = new Writer_Excel5_Escher($bstoreContainer);
+ $innerData .= $writer->close();
+ }
+
+ // write the record
+ $recVer = 0xF;
+ $recInstance = 0x0000;
+ $recType = 0xF000;
+ $length = strlen($innerData);
+
+ $recVerInstance = $recVer;
+ $recVerInstance |= $recInstance << 4;
+
+ $header = pack('vvV', $recVerInstance, $recType, $length);
+
+ $this->_data = $header . $innerData;
+ break;
+
+ case __NAMESPACE__ . '\Shared_Escher_DggContainer_BstoreContainer':
+ // this is a container record
+
+ // initialize
+ $innerData = '';
+
+ // treat the inner data
+ if ($BSECollection = $this->_object->getBSECollection()) {
+ foreach ($BSECollection as $BSE) {
+ $writer = new Writer_Excel5_Escher($BSE);
+ $innerData .= $writer->close();
+ }
+ }
+
+ // write the record
+ $recVer = 0xF;
+ $recInstance = count($this->_object->getBSECollection());
+ $recType = 0xF001;
+ $length = strlen($innerData);
- $recVerInstance = $recVer;
- $recVerInstance |= $recInstance << 4;
+ $recVerInstance = $recVer;
+ $recVerInstance |= $recInstance << 4;
- $header = pack('vvV', $recVerInstance, $recType, $length);
+ $header = pack('vvV', $recVerInstance, $recType, $length);
- $this->_data = $header . $innerData;
- break;
+ $this->_data = $header . $innerData;
+ break;
- case __NAMESPACE__ . '\Shared_Escher_DggContainer_BstoreContainer_BSE':
- // this is a semi-container record
+ case __NAMESPACE__ . '\Shared_Escher_DggContainer_BstoreContainer_BSE':
+ // this is a semi-container record
- // initialize
- $innerData = '';
+ // initialize
+ $innerData = '';
- // here we treat the inner data
- if ($blip = $this->_object->getBlip()) {
- $writer = new Writer_Excel5_Escher($blip);
- $innerData .= $writer->close();
- }
+ // here we treat the inner data
+ if ($blip = $this->_object->getBlip()) {
+ $writer = new Writer_Excel5_Escher($blip);
+ $innerData .= $writer->close();
+ }
- // initialize
- $data = '';
+ // initialize
+ $data = '';
- $btWin32 = $this->_object->getBlipType();
- $btMacOS = $this->_object->getBlipType();
- $data .= pack('CC', $btWin32, $btMacOS);
+ $btWin32 = $this->_object->getBlipType();
+ $btMacOS = $this->_object->getBlipType();
+ $data .= pack('CC', $btWin32, $btMacOS);
- $rgbUid = pack('VVVV', 0,0,0,0); // todo
- $data .= $rgbUid;
+ $rgbUid = pack('VVVV', 0,0,0,0); // todo
+ $data .= $rgbUid;
- $tag = 0;
- $size = strlen($innerData);
- $cRef = 1;
- $foDelay = 0; //todo
- $unused1 = 0x0;
- $cbName = 0x0;
- $unused2 = 0x0;
- $unused3 = 0x0;
- $data .= pack('vVVVCCCC', $tag, $size, $cRef, $foDelay, $unused1, $cbName, $unused2, $unused3);
+ $tag = 0;
+ $size = strlen($innerData);
+ $cRef = 1;
+ $foDelay = 0; //todo
+ $unused1 = 0x0;
+ $cbName = 0x0;
+ $unused2 = 0x0;
+ $unused3 = 0x0;
+ $data .= pack('vVVVCCCC', $tag, $size, $cRef, $foDelay, $unused1, $cbName, $unused2, $unused3);
- $data .= $innerData;
+ $data .= $innerData;
- // write the record
- $recVer = 0x2;
- $recInstance = $this->_object->getBlipType();
- $recType = 0xF007;
- $length = strlen($data);
+ // write the record
+ $recVer = 0x2;
+ $recInstance = $this->_object->getBlipType();
+ $recType = 0xF007;
+ $length = strlen($data);
- $recVerInstance = $recVer;
- $recVerInstance |= $recInstance << 4;
+ $recVerInstance = $recVer;
+ $recVerInstance |= $recInstance << 4;
- $header = pack('vvV', $recVerInstance, $recType, $length);
+ $header = pack('vvV', $recVerInstance, $recType, $length);
- $this->_data = $header;
+ $this->_data = $header;
- $this->_data .= $data;
- break;
+ $this->_data .= $data;
+ break;
- case __NAMESPACE__ . '\Shared_Escher_DggContainer_BstoreContainer_BSE_Blip':
- // this is an atom record
+ case __NAMESPACE__ . '\Shared_Escher_DggContainer_BstoreContainer_BSE_Blip':
+ // this is an atom record
- // write the record
- switch ($this->_object->getParent()->getBlipType()) {
+ // write the record
+ switch ($this->_object->getParent()->getBlipType()) {
- case Shared_Escher_DggContainer_BstoreContainer_BSE::BLIPTYPE_JPEG:
- // initialize
- $innerData = '';
+ case Shared_Escher_DggContainer_BstoreContainer_BSE::BLIPTYPE_JPEG:
+ // initialize
+ $innerData = '';
- $rgbUid1 = pack('VVVV', 0,0,0,0); // todo
- $innerData .= $rgbUid1;
+ $rgbUid1 = pack('VVVV', 0,0,0,0); // todo
+ $innerData .= $rgbUid1;
- $tag = 0xFF; // todo
- $innerData .= pack('C', $tag);
+ $tag = 0xFF; // todo
+ $innerData .= pack('C', $tag);
- $innerData .= $this->_object->getData();
+ $innerData .= $this->_object->getData();
- $recVer = 0x0;
- $recInstance = 0x46A;
- $recType = 0xF01D;
- $length = strlen($innerData);
+ $recVer = 0x0;
+ $recInstance = 0x46A;
+ $recType = 0xF01D;
+ $length = strlen($innerData);
- $recVerInstance = $recVer;
- $recVerInstance |= $recInstance << 4;
+ $recVerInstance = $recVer;
+ $recVerInstance |= $recInstance << 4;
- $header = pack('vvV', $recVerInstance, $recType, $length);
+ $header = pack('vvV', $recVerInstance, $recType, $length);
- $this->_data = $header;
+ $this->_data = $header;
- $this->_data .= $innerData;
- break;
+ $this->_data .= $innerData;
+ break;
- case Shared_Escher_DggContainer_BstoreContainer_BSE::BLIPTYPE_PNG:
- // initialize
- $innerData = '';
+ case Shared_Escher_DggContainer_BstoreContainer_BSE::BLIPTYPE_PNG:
+ // initialize
+ $innerData = '';
- $rgbUid1 = pack('VVVV', 0,0,0,0); // todo
- $innerData .= $rgbUid1;
+ $rgbUid1 = pack('VVVV', 0,0,0,0); // todo
+ $innerData .= $rgbUid1;
- $tag = 0xFF; // todo
- $innerData .= pack('C', $tag);
+ $tag = 0xFF; // todo
+ $innerData .= pack('C', $tag);
- $innerData .= $this->_object->getData();
+ $innerData .= $this->_object->getData();
- $recVer = 0x0;
- $recInstance = 0x6E0;
- $recType = 0xF01E;
- $length = strlen($innerData);
+ $recVer = 0x0;
+ $recInstance = 0x6E0;
+ $recType = 0xF01E;
+ $length = strlen($innerData);
- $recVerInstance = $recVer;
- $recVerInstance |= $recInstance << 4;
+ $recVerInstance = $recVer;
+ $recVerInstance |= $recInstance << 4;
- $header = pack('vvV', $recVerInstance, $recType, $length);
+ $header = pack('vvV', $recVerInstance, $recType, $length);
- $this->_data = $header;
+ $this->_data = $header;
- $this->_data .= $innerData;
- break;
+ $this->_data .= $innerData;
+ break;
- }
- break;
+ }
+ break;
- case __NAMESPACE__ . '\Shared_Escher_DgContainer':
- // this is a container record
+ case __NAMESPACE__ . '\Shared_Escher_DgContainer':
+ // this is a container record
- // initialize
- $innerData = '';
+ // initialize
+ $innerData = '';
- // write the dg
- $recVer = 0x0;
- $recInstance = $this->_object->getDgId();
- $recType = 0xF008;
- $length = 8;
+ // write the dg
+ $recVer = 0x0;
+ $recInstance = $this->_object->getDgId();
+ $recType = 0xF008;
+ $length = 8;
- $recVerInstance = $recVer;
- $recVerInstance |= $recInstance << 4;
+ $recVerInstance = $recVer;
+ $recVerInstance |= $recInstance << 4;
- $header = pack('vvV', $recVerInstance, $recType, $length);
+ $header = pack('vvV', $recVerInstance, $recType, $length);
- // number of shapes in this drawing (including group shape)
- $countShapes = count($this->_object->getSpgrContainer()->getChildren());
- $innerData .= $header . pack('VV', $countShapes, $this->_object->getLastSpId());
- //$innerData .= $header . pack('VV', 0, 0);
+ // number of shapes in this drawing (including group shape)
+ $countShapes = count($this->_object->getSpgrContainer()->getChildren());
+ $innerData .= $header . pack('VV', $countShapes, $this->_object->getLastSpId());
+ //$innerData .= $header . pack('VV', 0, 0);
- // write the spgrContainer
- if ($spgrContainer = $this->_object->getSpgrContainer()) {
- $writer = new Writer_Excel5_Escher($spgrContainer);
- $innerData .= $writer->close();
+ // write the spgrContainer
+ if ($spgrContainer = $this->_object->getSpgrContainer()) {
+ $writer = new Writer_Excel5_Escher($spgrContainer);
+ $innerData .= $writer->close();
- // get the shape offsets relative to the spgrContainer record
- $spOffsets = $writer->getSpOffsets();
- $spTypes = $writer->getSpTypes();
-
- // save the shape offsets relative to dgContainer
- foreach ($spOffsets as & $spOffset) {
- $spOffset += 24; // add length of dgContainer header data (8 bytes) plus dg data (16 bytes)
- }
+ // get the shape offsets relative to the spgrContainer record
+ $spOffsets = $writer->getSpOffsets();
+ $spTypes = $writer->getSpTypes();
+
+ // save the shape offsets relative to dgContainer
+ foreach ($spOffsets as & $spOffset) {
+ $spOffset += 24; // add length of dgContainer header data (8 bytes) plus dg data (16 bytes)
+ }
- $this->_spOffsets = $spOffsets;
- $this->_spTypes = $spTypes;
- }
+ $this->_spOffsets = $spOffsets;
+ $this->_spTypes = $spTypes;
+ }
- // write the record
- $recVer = 0xF;
- $recInstance = 0x0000;
- $recType = 0xF002;
- $length = strlen($innerData);
+ // write the record
+ $recVer = 0xF;
+ $recInstance = 0x0000;
+ $recType = 0xF002;
+ $length = strlen($innerData);
- $recVerInstance = $recVer;
- $recVerInstance |= $recInstance << 4;
+ $recVerInstance = $recVer;
+ $recVerInstance |= $recInstance << 4;
- $header = pack('vvV', $recVerInstance, $recType, $length);
+ $header = pack('vvV', $recVerInstance, $recType, $length);
- $this->_data = $header . $innerData;
- break;
+ $this->_data = $header . $innerData;
+ break;
- case __NAMESPACE__ . '\Shared_Escher_DgContainer_SpgrContainer':
- // this is a container record
+ case __NAMESPACE__ . '\Shared_Escher_DgContainer_SpgrContainer':
+ // this is a container record
- // initialize
- $innerData = '';
+ // initialize
+ $innerData = '';
- // initialize spape offsets
- $totalSize = 8;
- $spOffsets = array();
- $spTypes = array();
+ // initialize spape offsets
+ $totalSize = 8;
+ $spOffsets = array();
+ $spTypes = array();
- // treat the inner data
- foreach ($this->_object->getChildren() as $spContainer) {
- $writer = new Writer_Excel5_Escher($spContainer);
- $spData = $writer->close();
- $innerData .= $spData;
+ // treat the inner data
+ foreach ($this->_object->getChildren() as $spContainer) {
+ $writer = new Writer_Excel5_Escher($spContainer);
+ $spData = $writer->close();
+ $innerData .= $spData;
- // save the shape offsets (where new shape records begin)
- $totalSize += strlen($spData);
- $spOffsets[] = $totalSize;
-
- $spTypes = array_merge($spTypes, $writer->getSpTypes());
- }
+ // save the shape offsets (where new shape records begin)
+ $totalSize += strlen($spData);
+ $spOffsets[] = $totalSize;
+
+ $spTypes = array_merge($spTypes, $writer->getSpTypes());
+ }
- // write the record
- $recVer = 0xF;
- $recInstance = 0x0000;
- $recType = 0xF003;
- $length = strlen($innerData);
+ // write the record
+ $recVer = 0xF;
+ $recInstance = 0x0000;
+ $recType = 0xF003;
+ $length = strlen($innerData);
- $recVerInstance = $recVer;
- $recVerInstance |= $recInstance << 4;
+ $recVerInstance = $recVer;
+ $recVerInstance |= $recInstance << 4;
- $header = pack('vvV', $recVerInstance, $recType, $length);
+ $header = pack('vvV', $recVerInstance, $recType, $length);
- $this->_data = $header . $innerData;
- $this->_spOffsets = $spOffsets;
- $this->_spTypes = $spTypes;
- break;
+ $this->_data = $header . $innerData;
+ $this->_spOffsets = $spOffsets;
+ $this->_spTypes = $spTypes;
+ break;
- case __NAMESPACE__ . '\Shared_Escher_DgContainer_SpgrContainer_SpContainer':
- // initialize
- $data = '';
+ case __NAMESPACE__ . '\Shared_Escher_DgContainer_SpgrContainer_SpContainer':
+ // initialize
+ $data = '';
- // build the data
+ // build the data
- // write group shape record, if necessary?
- if ($this->_object->getSpgr()) {
- $recVer = 0x1;
- $recInstance = 0x0000;
- $recType = 0xF009;
- $length = 0x00000010;
+ // write group shape record, if necessary?
+ if ($this->_object->getSpgr()) {
+ $recVer = 0x1;
+ $recInstance = 0x0000;
+ $recType = 0xF009;
+ $length = 0x00000010;
- $recVerInstance = $recVer;
- $recVerInstance |= $recInstance << 4;
+ $recVerInstance = $recVer;
+ $recVerInstance |= $recInstance << 4;
- $header = pack('vvV', $recVerInstance, $recType, $length);
+ $header = pack('vvV', $recVerInstance, $recType, $length);
- $data .= $header . pack('VVVV', 0,0,0,0);
- }
- $this->_spTypes[] = ($this->_object->getSpType());
+ $data .= $header . pack('VVVV', 0,0,0,0);
+ }
+ $this->_spTypes[] = ($this->_object->getSpType());
- // write the shape record
- $recVer = 0x2;
- $recInstance = $this->_object->getSpType(); // shape type
- $recType = 0xF00A;
- $length = 0x00000008;
+ // write the shape record
+ $recVer = 0x2;
+ $recInstance = $this->_object->getSpType(); // shape type
+ $recType = 0xF00A;
+ $length = 0x00000008;
- $recVerInstance = $recVer;
- $recVerInstance |= $recInstance << 4;
+ $recVerInstance = $recVer;
+ $recVerInstance |= $recInstance << 4;
- $header = pack('vvV', $recVerInstance, $recType, $length);
+ $header = pack('vvV', $recVerInstance, $recType, $length);
- $data .= $header . pack('VV', $this->_object->getSpId(), $this->_object->getSpgr() ? 0x0005 : 0x0A00);
+ $data .= $header . pack('VV', $this->_object->getSpId(), $this->_object->getSpgr() ? 0x0005 : 0x0A00);
- // the options
- if ($this->_object->getOPTCollection()) {
- $optData = '';
+ // the options
+ if ($this->_object->getOPTCollection()) {
+ $optData = '';
- $recVer = 0x3;
- $recInstance = count($this->_object->getOPTCollection());
- $recType = 0xF00B;
- foreach ($this->_object->getOPTCollection() as $property => $value) {
- $optData .= pack('vV', $property, $value);
- }
- $length = strlen($optData);
+ $recVer = 0x3;
+ $recInstance = count($this->_object->getOPTCollection());
+ $recType = 0xF00B;
+ foreach ($this->_object->getOPTCollection() as $property => $value) {
+ $optData .= pack('vV', $property, $value);
+ }
+ $length = strlen($optData);
- $recVerInstance = $recVer;
- $recVerInstance |= $recInstance << 4;
+ $recVerInstance = $recVer;
+ $recVerInstance |= $recInstance << 4;
- $header = pack('vvV', $recVerInstance, $recType, $length);
- $data .= $header . $optData;
- }
+ $header = pack('vvV', $recVerInstance, $recType, $length);
+ $data .= $header . $optData;
+ }
- // the client anchor
- if ($this->_object->getStartCoordinates()) {
- $clientAnchorData = '';
-
- $recVer = 0x0;
- $recInstance = 0x0;
- $recType = 0xF010;
-
- // start coordinates
- list($column, $row) = Cell::coordinateFromString($this->_object->getStartCoordinates());
- $c1 = Cell::columnIndexFromString($column) - 1;
- $r1 = $row - 1;
-
- // start offsetX
- $startOffsetX = $this->_object->getStartOffsetX();
-
- // start offsetY
- $startOffsetY = $this->_object->getStartOffsetY();
-
- // end coordinates
- list($column, $row) = Cell::coordinateFromString($this->_object->getEndCoordinates());
- $c2 = Cell::columnIndexFromString($column) - 1;
- $r2 = $row - 1;
-
- // end offsetX
- $endOffsetX = $this->_object->getEndOffsetX();
+ // the client anchor
+ if ($this->_object->getStartCoordinates()) {
+ $clientAnchorData = '';
+
+ $recVer = 0x0;
+ $recInstance = 0x0;
+ $recType = 0xF010;
+
+ // start coordinates
+ list($column, $row) = Cell::coordinateFromString($this->_object->getStartCoordinates());
+ $c1 = Cell::columnIndexFromString($column) - 1;
+ $r1 = $row - 1;
+
+ // start offsetX
+ $startOffsetX = $this->_object->getStartOffsetX();
+
+ // start offsetY
+ $startOffsetY = $this->_object->getStartOffsetY();
+
+ // end coordinates
+ list($column, $row) = Cell::coordinateFromString($this->_object->getEndCoordinates());
+ $c2 = Cell::columnIndexFromString($column) - 1;
+ $r2 = $row - 1;
+
+ // end offsetX
+ $endOffsetX = $this->_object->getEndOffsetX();
- // end offsetY
- $endOffsetY = $this->_object->getEndOffsetY();
+ // end offsetY
+ $endOffsetY = $this->_object->getEndOffsetY();
- $clientAnchorData = pack('vvvvvvvvv', $this->_object->getSpFlag(),
- $c1, $startOffsetX, $r1, $startOffsetY,
- $c2, $endOffsetX, $r2, $endOffsetY);
-
- $length = strlen($clientAnchorData);
+ $clientAnchorData = pack('vvvvvvvvv', $this->_object->getSpFlag(),
+ $c1, $startOffsetX, $r1, $startOffsetY,
+ $c2, $endOffsetX, $r2, $endOffsetY);
+
+ $length = strlen($clientAnchorData);
- $recVerInstance = $recVer;
- $recVerInstance |= $recInstance << 4;
+ $recVerInstance = $recVer;
+ $recVerInstance |= $recInstance << 4;
- $header = pack('vvV', $recVerInstance, $recType, $length);
- $data .= $header . $clientAnchorData;
- }
+ $header = pack('vvV', $recVerInstance, $recType, $length);
+ $data .= $header . $clientAnchorData;
+ }
- // the client data, just empty for now
- if (!$this->_object->getSpgr()) {
- $clientDataData = '';
+ // the client data, just empty for now
+ if (!$this->_object->getSpgr()) {
+ $clientDataData = '';
- $recVer = 0x0;
- $recInstance = 0x0;
- $recType = 0xF011;
+ $recVer = 0x0;
+ $recInstance = 0x0;
+ $recType = 0xF011;
- $length = strlen($clientDataData);
-
- $recVerInstance = $recVer;
- $recVerInstance |= $recInstance << 4;
+ $length = strlen($clientDataData);
+
+ $recVerInstance = $recVer;
+ $recVerInstance |= $recInstance << 4;
- $header = pack('vvV', $recVerInstance, $recType, $length);
- $data .= $header . $clientDataData;
- }
+ $header = pack('vvV', $recVerInstance, $recType, $length);
+ $data .= $header . $clientDataData;
+ }
- // write the record
- $recVer = 0xF;
- $recInstance = 0x0000;
- $recType = 0xF004;
- $length = strlen($data);
+ // write the record
+ $recVer = 0xF;
+ $recInstance = 0x0000;
+ $recType = 0xF004;
+ $length = strlen($data);
- $recVerInstance = $recVer;
- $recVerInstance |= $recInstance << 4;
-
- $header = pack('vvV', $recVerInstance, $recType, $length);
+ $recVerInstance = $recVer;
+ $recVerInstance |= $recInstance << 4;
+
+ $header = pack('vvV', $recVerInstance, $recType, $length);
- $this->_data = $header . $data;
- break;
+ $this->_data = $header . $data;
+ break;
- }
+ }
- return $this->_data;
- }
-
- /**
- * Gets the shape offsets
- *
- * @return array
- */
- public function getSpOffsets()
- {
- return $this->_spOffsets;
- }
-
- /**
- * Gets the shape types
- *
- * @return array
- */
- public function getSpTypes()
- {
- return $this->_spTypes;
- }
-
-
+ return $this->_data;
+ }
+
+ /**
+ * Gets the shape offsets
+ *
+ * @return array
+ */
+ public function getSpOffsets()
+ {
+ return $this->_spOffsets;
+ }
+
+ /**
+ * Gets the shape types
+ *
+ * @return array
+ */
+ public function getSpTypes()
+ {
+ return $this->_spTypes;
+ }
+
+
}
diff --git a/Classes/PHPExcel/Writer/Excel5/Font.php b/Classes/PHPExcel/Writer/Excel5/Font.php
index 8955bf2..f9d42ec 100644
--- a/Classes/PHPExcel/Writer/Excel5/Font.php
+++ b/Classes/PHPExcel/Writer/Excel5/Font.php
@@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\Writer_Excel5
* @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,131 +37,131 @@ namespace PHPExcel;
*/
class Writer_Excel5_Font
{
- /**
- * Color index
- *
- * @var int
- */
- private $_colorIndex;
+ /**
+ * Color index
+ *
+ * @var int
+ */
+ private $_colorIndex;
- /**
- * Font
- *
- * @var PHPExcel\Style_Font
- */
- private $_font;
+ /**
+ * Font
+ *
+ * @var PHPExcel\Style_Font
+ */
+ private $_font;
- /**
- * Constructor
- *
- * @param PHPExcel\Style_Font $font
- */
- public function __construct(Style_Font $font = null)
- {
- $this->_colorIndex = 0x7FFF;
- $this->_font = $font;
- }
+ /**
+ * Constructor
+ *
+ * @param PHPExcel\Style_Font $font
+ */
+ public function __construct(Style_Font $font = null)
+ {
+ $this->_colorIndex = 0x7FFF;
+ $this->_font = $font;
+ }
- /**
- * Set the color index
- *
- * @param int $colorIndex
- */
- public function setColorIndex($colorIndex)
- {
- $this->_colorIndex = $colorIndex;
- }
+ /**
+ * Set the color index
+ *
+ * @param int $colorIndex
+ */
+ public function setColorIndex($colorIndex)
+ {
+ $this->_colorIndex = $colorIndex;
+ }
- /**
- * Get font record data
- *
- * @return string
- */
- public function writeFont()
- {
- $font_outline = 0;
- $font_shadow = 0;
+ /**
+ * Get font record data
+ *
+ * @return string
+ */
+ public function writeFont()
+ {
+ $font_outline = 0;
+ $font_shadow = 0;
- $icv = $this->_colorIndex; // Index to color palette
- if ($this->_font->getSuperScript()) {
- $sss = 1;
- } else if ($this->_font->getSubScript()) {
- $sss = 2;
- } else {
- $sss = 0;
- }
- $bFamily = 0; // Font family
- $bCharSet = Shared_Font::getCharsetFromFontName($this->_font->getName()); // Character set
+ $icv = $this->_colorIndex; // Index to color palette
+ if ($this->_font->getSuperScript()) {
+ $sss = 1;
+ } else if ($this->_font->getSubScript()) {
+ $sss = 2;
+ } else {
+ $sss = 0;
+ }
+ $bFamily = 0; // Font family
+ $bCharSet = Shared_Font::getCharsetFromFontName($this->_font->getName()); // Character set
- $record = 0x31; // Record identifier
- $reserved = 0x00; // Reserved
- $grbit = 0x00; // Font attributes
- if ($this->_font->getItalic()) {
- $grbit |= 0x02;
- }
- if ($this->_font->getStrikethrough()) {
- $grbit |= 0x08;
- }
- if ($font_outline) {
- $grbit |= 0x10;
- }
- if ($font_shadow) {
- $grbit |= 0x20;
- }
+ $record = 0x31; // Record identifier
+ $reserved = 0x00; // Reserved
+ $grbit = 0x00; // Font attributes
+ if ($this->_font->getItalic()) {
+ $grbit |= 0x02;
+ }
+ if ($this->_font->getStrikethrough()) {
+ $grbit |= 0x08;
+ }
+ if ($font_outline) {
+ $grbit |= 0x10;
+ }
+ if ($font_shadow) {
+ $grbit |= 0x20;
+ }
- $data = pack("vvvvvCCCC",
- $this->_font->getSize() * 20, // Fontsize (in twips)
- $grbit,
- $icv, // Colour
- self::_mapBold($this->_font->getBold()), // Font weight
- $sss, // Superscript/Subscript
- self::_mapUnderline($this->_font->getUnderline()),
- $bFamily,
- $bCharSet,
- $reserved
- );
- $data .= Shared_String::UTF8toBIFF8UnicodeShort($this->_font->getName());
+ $data = pack("vvvvvCCCC",
+ $this->_font->getSize() * 20, // Fontsize (in twips)
+ $grbit,
+ $icv, // Colour
+ self::_mapBold($this->_font->getBold()), // Font weight
+ $sss, // Superscript/Subscript
+ self::_mapUnderline($this->_font->getUnderline()),
+ $bFamily,
+ $bCharSet,
+ $reserved
+ );
+ $data .= Shared_String::UTF8toBIFF8UnicodeShort($this->_font->getName());
- $length = strlen($data);
- $header = pack("vv", $record, $length);
+ $length = strlen($data);
+ $header = pack("vv", $record, $length);
- return($header . $data);
- }
+ return($header . $data);
+ }
- /**
- * Map to BIFF5-BIFF8 codes for bold
- *
- * @param boolean $bold
- * @return int
- */
- private static function _mapBold($bold) {
- if ($bold) {
- return 0x2BC; // 700 = Bold font weight
- }
- return 0x190; // 400 = Normal font weight
- }
+ /**
+ * Map to BIFF5-BIFF8 codes for bold
+ *
+ * @param boolean $bold
+ * @return int
+ */
+ private static function _mapBold($bold) {
+ if ($bold) {
+ return 0x2BC; // 700 = Bold font weight
+ }
+ return 0x190; // 400 = Normal font weight
+ }
- /**
- * Map of BIFF2-BIFF8 codes for underline styles
- * @static array of int
- *
- */
- private static $_mapUnderline = array( Style_Font::UNDERLINE_NONE => 0x00,
- Style_Font::UNDERLINE_SINGLE => 0x01,
- Style_Font::UNDERLINE_DOUBLE => 0x02,
- Style_Font::UNDERLINE_SINGLEACCOUNTING => 0x21,
- Style_Font::UNDERLINE_DOUBLEACCOUNTING => 0x22,
- );
- /**
- * Map underline
- *
- * @param string
- * @return int
- */
- private static function _mapUnderline($underline) {
- if (isset(self::$_mapUnderline[$underline]))
- return self::$_mapUnderline[$underline];
- return 0x00;
- }
+ /**
+ * Map of BIFF2-BIFF8 codes for underline styles
+ * @static array of int
+ *
+ */
+ private static $_mapUnderline = array( Style_Font::UNDERLINE_NONE => 0x00,
+ Style_Font::UNDERLINE_SINGLE => 0x01,
+ Style_Font::UNDERLINE_DOUBLE => 0x02,
+ Style_Font::UNDERLINE_SINGLEACCOUNTING => 0x21,
+ Style_Font::UNDERLINE_DOUBLEACCOUNTING => 0x22,
+ );
+ /**
+ * Map underline
+ *
+ * @param string
+ * @return int
+ */
+ private static function _mapUnderline($underline) {
+ if (isset(self::$_mapUnderline[$underline]))
+ return self::$_mapUnderline[$underline];
+ return 0x00;
+ }
}
diff --git a/Classes/PHPExcel/Writer/Excel5/Parser.php b/Classes/PHPExcel/Writer/Excel5/Parser.php
index e7e2524..211bb96 100644
--- a/Classes/PHPExcel/Writer/Excel5/Parser.php
+++ b/Classes/PHPExcel/Writer/Excel5/Parser.php
@@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\Writer_Excel5
* @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##
*/
@@ -61,1524 +61,1524 @@ namespace PHPExcel;
*/
class Writer_Excel5_Parser
{
- /** Constants */
- // Sheet title in unquoted form
- // Invalid sheet title characters cannot occur in the sheet title:
- // *:/\?[]
- // Moreover, there are valid sheet title characters that cannot occur in unquoted form (there may be more?)
- // +-% '^&<>=,;#()"{}
- const REGEX_SHEET_TITLE_UNQUOTED = '[^\*\:\/\\\\\?\[\]\+\-\% \\\'\^\&\<\>\=\,\;\#\(\)\"\{\}]+';
+ /** Constants */
+ // Sheet title in unquoted form
+ // Invalid sheet title characters cannot occur in the sheet title:
+ // *:/\?[]
+ // Moreover, there are valid sheet title characters that cannot occur in unquoted form (there may be more?)
+ // +-% '^&<>=,;#()"{}
+ const REGEX_SHEET_TITLE_UNQUOTED = '[^\*\:\/\\\\\?\[\]\+\-\% \\\'\^\&\<\>\=\,\;\#\(\)\"\{\}]+';
- // Sheet title in quoted form (without surrounding quotes)
- // Invalid sheet title characters cannot occur in the sheet title:
- // *:/\?[] (usual invalid sheet title characters)
- // Single quote is represented as a pair ''
- const REGEX_SHEET_TITLE_QUOTED = '(([^\*\:\/\\\\\?\[\]\\\'])+|(\\\'\\\')+)+';
+ // Sheet title in quoted form (without surrounding quotes)
+ // Invalid sheet title characters cannot occur in the sheet title:
+ // *:/\?[] (usual invalid sheet title characters)
+ // Single quote is represented as a pair ''
+ const REGEX_SHEET_TITLE_QUOTED = '(([^\*\:\/\\\\\?\[\]\\\'])+|(\\\'\\\')+)+';
- /**
- * The index of the character we are currently looking at
- * @var integer
- */
- public $_current_char;
+ /**
+ * The index of the character we are currently looking at
+ * @var integer
+ */
+ public $_current_char;
- /**
- * The token we are working on.
- * @var string
- */
- public $_current_token;
+ /**
+ * The token we are working on.
+ * @var string
+ */
+ public $_current_token;
- /**
- * The formula to parse
- * @var string
- */
- public $_formula;
+ /**
+ * The formula to parse
+ * @var string
+ */
+ public $_formula;
- /**
- * The character ahead of the current char
- * @var string
- */
- public $_lookahead;
+ /**
+ * The character ahead of the current char
+ * @var string
+ */
+ public $_lookahead;
- /**
- * The parse tree to be generated
- * @var string
- */
- public $_parse_tree;
+ /**
+ * The parse tree to be generated
+ * @var string
+ */
+ public $_parse_tree;
- /**
- * Array of external sheets
- * @var array
- */
- public $_ext_sheets;
+ /**
+ * Array of external sheets
+ * @var array
+ */
+ public $_ext_sheets;
- /**
- * Array of sheet references in the form of REF structures
- * @var array
- */
- public $_references;
+ /**
+ * Array of sheet references in the form of REF structures
+ * @var array
+ */
+ public $_references;
- /**
- * The class constructor
- *
- */
- public function __construct()
- {
- $this->_current_char = 0;
- $this->_current_token = ''; // The token we are working on.
- $this->_formula = ''; // The formula to parse.
- $this->_lookahead = ''; // The character ahead of the current char.
- $this->_parse_tree = ''; // The parse tree to be generated.
- $this->_initializeHashes(); // Initialize the hashes: ptg's and function's ptg's
- $this->_ext_sheets = array();
- $this->_references = array();
- }
+ /**
+ * The class constructor
+ *
+ */
+ public function __construct()
+ {
+ $this->_current_char = 0;
+ $this->_current_token = ''; // The token we are working on.
+ $this->_formula = ''; // The formula to parse.
+ $this->_lookahead = ''; // The character ahead of the current char.
+ $this->_parse_tree = ''; // The parse tree to be generated.
+ $this->_initializeHashes(); // Initialize the hashes: ptg's and function's ptg's
+ $this->_ext_sheets = array();
+ $this->_references = array();
+ }
- /**
- * Initialize the ptg and function hashes.
- *
- * @access private
- */
- function _initializeHashes()
- {
- // The Excel ptg indices
- $this->ptg = array(
- 'ptgExp' => 0x01,
- 'ptgTbl' => 0x02,
- 'ptgAdd' => 0x03,
- 'ptgSub' => 0x04,
- 'ptgMul' => 0x05,
- 'ptgDiv' => 0x06,
- 'ptgPower' => 0x07,
- 'ptgConcat' => 0x08,
- 'ptgLT' => 0x09,
- 'ptgLE' => 0x0A,
- 'ptgEQ' => 0x0B,
- 'ptgGE' => 0x0C,
- 'ptgGT' => 0x0D,
- 'ptgNE' => 0x0E,
- 'ptgIsect' => 0x0F,
- 'ptgUnion' => 0x10,
- 'ptgRange' => 0x11,
- 'ptgUplus' => 0x12,
- 'ptgUminus' => 0x13,
- 'ptgPercent' => 0x14,
- 'ptgParen' => 0x15,
- 'ptgMissArg' => 0x16,
- 'ptgStr' => 0x17,
- 'ptgAttr' => 0x19,
- 'ptgSheet' => 0x1A,
- 'ptgEndSheet' => 0x1B,
- 'ptgErr' => 0x1C,
- 'ptgBool' => 0x1D,
- 'ptgInt' => 0x1E,
- 'ptgNum' => 0x1F,
- 'ptgArray' => 0x20,
- 'ptgFunc' => 0x21,
- 'ptgFuncVar' => 0x22,
- 'ptgName' => 0x23,
- 'ptgRef' => 0x24,
- 'ptgArea' => 0x25,
- 'ptgMemArea' => 0x26,
- 'ptgMemErr' => 0x27,
- 'ptgMemNoMem' => 0x28,
- 'ptgMemFunc' => 0x29,
- 'ptgRefErr' => 0x2A,
- 'ptgAreaErr' => 0x2B,
- 'ptgRefN' => 0x2C,
- 'ptgAreaN' => 0x2D,
- 'ptgMemAreaN' => 0x2E,
- 'ptgMemNoMemN' => 0x2F,
- 'ptgNameX' => 0x39,
- 'ptgRef3d' => 0x3A,
- 'ptgArea3d' => 0x3B,
- 'ptgRefErr3d' => 0x3C,
- 'ptgAreaErr3d' => 0x3D,
- 'ptgArrayV' => 0x40,
- 'ptgFuncV' => 0x41,
- 'ptgFuncVarV' => 0x42,
- 'ptgNameV' => 0x43,
- 'ptgRefV' => 0x44,
- 'ptgAreaV' => 0x45,
- 'ptgMemAreaV' => 0x46,
- 'ptgMemErrV' => 0x47,
- 'ptgMemNoMemV' => 0x48,
- 'ptgMemFuncV' => 0x49,
- 'ptgRefErrV' => 0x4A,
- 'ptgAreaErrV' => 0x4B,
- 'ptgRefNV' => 0x4C,
- 'ptgAreaNV' => 0x4D,
- 'ptgMemAreaNV' => 0x4E,
- 'ptgMemNoMemN' => 0x4F,
- 'ptgFuncCEV' => 0x58,
- 'ptgNameXV' => 0x59,
- 'ptgRef3dV' => 0x5A,
- 'ptgArea3dV' => 0x5B,
- 'ptgRefErr3dV' => 0x5C,
- 'ptgAreaErr3d' => 0x5D,
- 'ptgArrayA' => 0x60,
- 'ptgFuncA' => 0x61,
- 'ptgFuncVarA' => 0x62,
- 'ptgNameA' => 0x63,
- 'ptgRefA' => 0x64,
- 'ptgAreaA' => 0x65,
- 'ptgMemAreaA' => 0x66,
- 'ptgMemErrA' => 0x67,
- 'ptgMemNoMemA' => 0x68,
- 'ptgMemFuncA' => 0x69,
- 'ptgRefErrA' => 0x6A,
- 'ptgAreaErrA' => 0x6B,
- 'ptgRefNA' => 0x6C,
- 'ptgAreaNA' => 0x6D,
- 'ptgMemAreaNA' => 0x6E,
- 'ptgMemNoMemN' => 0x6F,
- 'ptgFuncCEA' => 0x78,
- 'ptgNameXA' => 0x79,
- 'ptgRef3dA' => 0x7A,
- 'ptgArea3dA' => 0x7B,
- 'ptgRefErr3dA' => 0x7C,
- 'ptgAreaErr3d' => 0x7D
- );
+ /**
+ * Initialize the ptg and function hashes.
+ *
+ * @access private
+ */
+ function _initializeHashes()
+ {
+ // The Excel ptg indices
+ $this->ptg = array(
+ 'ptgExp' => 0x01,
+ 'ptgTbl' => 0x02,
+ 'ptgAdd' => 0x03,
+ 'ptgSub' => 0x04,
+ 'ptgMul' => 0x05,
+ 'ptgDiv' => 0x06,
+ 'ptgPower' => 0x07,
+ 'ptgConcat' => 0x08,
+ 'ptgLT' => 0x09,
+ 'ptgLE' => 0x0A,
+ 'ptgEQ' => 0x0B,
+ 'ptgGE' => 0x0C,
+ 'ptgGT' => 0x0D,
+ 'ptgNE' => 0x0E,
+ 'ptgIsect' => 0x0F,
+ 'ptgUnion' => 0x10,
+ 'ptgRange' => 0x11,
+ 'ptgUplus' => 0x12,
+ 'ptgUminus' => 0x13,
+ 'ptgPercent' => 0x14,
+ 'ptgParen' => 0x15,
+ 'ptgMissArg' => 0x16,
+ 'ptgStr' => 0x17,
+ 'ptgAttr' => 0x19,
+ 'ptgSheet' => 0x1A,
+ 'ptgEndSheet' => 0x1B,
+ 'ptgErr' => 0x1C,
+ 'ptgBool' => 0x1D,
+ 'ptgInt' => 0x1E,
+ 'ptgNum' => 0x1F,
+ 'ptgArray' => 0x20,
+ 'ptgFunc' => 0x21,
+ 'ptgFuncVar' => 0x22,
+ 'ptgName' => 0x23,
+ 'ptgRef' => 0x24,
+ 'ptgArea' => 0x25,
+ 'ptgMemArea' => 0x26,
+ 'ptgMemErr' => 0x27,
+ 'ptgMemNoMem' => 0x28,
+ 'ptgMemFunc' => 0x29,
+ 'ptgRefErr' => 0x2A,
+ 'ptgAreaErr' => 0x2B,
+ 'ptgRefN' => 0x2C,
+ 'ptgAreaN' => 0x2D,
+ 'ptgMemAreaN' => 0x2E,
+ 'ptgMemNoMemN' => 0x2F,
+ 'ptgNameX' => 0x39,
+ 'ptgRef3d' => 0x3A,
+ 'ptgArea3d' => 0x3B,
+ 'ptgRefErr3d' => 0x3C,
+ 'ptgAreaErr3d' => 0x3D,
+ 'ptgArrayV' => 0x40,
+ 'ptgFuncV' => 0x41,
+ 'ptgFuncVarV' => 0x42,
+ 'ptgNameV' => 0x43,
+ 'ptgRefV' => 0x44,
+ 'ptgAreaV' => 0x45,
+ 'ptgMemAreaV' => 0x46,
+ 'ptgMemErrV' => 0x47,
+ 'ptgMemNoMemV' => 0x48,
+ 'ptgMemFuncV' => 0x49,
+ 'ptgRefErrV' => 0x4A,
+ 'ptgAreaErrV' => 0x4B,
+ 'ptgRefNV' => 0x4C,
+ 'ptgAreaNV' => 0x4D,
+ 'ptgMemAreaNV' => 0x4E,
+ 'ptgMemNoMemN' => 0x4F,
+ 'ptgFuncCEV' => 0x58,
+ 'ptgNameXV' => 0x59,
+ 'ptgRef3dV' => 0x5A,
+ 'ptgArea3dV' => 0x5B,
+ 'ptgRefErr3dV' => 0x5C,
+ 'ptgAreaErr3d' => 0x5D,
+ 'ptgArrayA' => 0x60,
+ 'ptgFuncA' => 0x61,
+ 'ptgFuncVarA' => 0x62,
+ 'ptgNameA' => 0x63,
+ 'ptgRefA' => 0x64,
+ 'ptgAreaA' => 0x65,
+ 'ptgMemAreaA' => 0x66,
+ 'ptgMemErrA' => 0x67,
+ 'ptgMemNoMemA' => 0x68,
+ 'ptgMemFuncA' => 0x69,
+ 'ptgRefErrA' => 0x6A,
+ 'ptgAreaErrA' => 0x6B,
+ 'ptgRefNA' => 0x6C,
+ 'ptgAreaNA' => 0x6D,
+ 'ptgMemAreaNA' => 0x6E,
+ 'ptgMemNoMemN' => 0x6F,
+ 'ptgFuncCEA' => 0x78,
+ 'ptgNameXA' => 0x79,
+ 'ptgRef3dA' => 0x7A,
+ 'ptgArea3dA' => 0x7B,
+ 'ptgRefErr3dA' => 0x7C,
+ 'ptgAreaErr3d' => 0x7D
+ );
- // Thanks to Michael Meeks and Gnumeric for the initial arg values.
- //
- // The following hash was generated by "function_locale.pl" in the distro.
- // Refer to function_locale.pl for non-English function names.
- //
- // The array elements are as follow:
- // ptg: The Excel function ptg code.
- // args: The number of arguments that the function takes:
- // >=0 is a fixed number of arguments.
- // -1 is a variable number of arguments.
- // class: The reference, value or array class of the function args.
- // vol: The function is volatile.
- //
- $this->_functions = array(
- // function ptg args class vol
- 'COUNT' => array( 0, -1, 0, 0 ),
- 'IF' => array( 1, -1, 1, 0 ),
- 'ISNA' => array( 2, 1, 1, 0 ),
- 'ISERROR' => array( 3, 1, 1, 0 ),
- 'SUM' => array( 4, -1, 0, 0 ),
- 'AVERAGE' => array( 5, -1, 0, 0 ),
- 'MIN' => array( 6, -1, 0, 0 ),
- 'MAX' => array( 7, -1, 0, 0 ),
- 'ROW' => array( 8, -1, 0, 0 ),
- 'COLUMN' => array( 9, -1, 0, 0 ),
- 'NA' => array( 10, 0, 0, 0 ),
- 'NPV' => array( 11, -1, 1, 0 ),
- 'STDEV' => array( 12, -1, 0, 0 ),
- 'DOLLAR' => array( 13, -1, 1, 0 ),
- 'FIXED' => array( 14, -1, 1, 0 ),
- 'SIN' => array( 15, 1, 1, 0 ),
- 'COS' => array( 16, 1, 1, 0 ),
- 'TAN' => array( 17, 1, 1, 0 ),
- 'ATAN' => array( 18, 1, 1, 0 ),
- 'PI' => array( 19, 0, 1, 0 ),
- 'SQRT' => array( 20, 1, 1, 0 ),
- 'EXP' => array( 21, 1, 1, 0 ),
- 'LN' => array( 22, 1, 1, 0 ),
- 'LOG10' => array( 23, 1, 1, 0 ),
- 'ABS' => array( 24, 1, 1, 0 ),
- 'INT' => array( 25, 1, 1, 0 ),
- 'SIGN' => array( 26, 1, 1, 0 ),
- 'ROUND' => array( 27, 2, 1, 0 ),
- 'LOOKUP' => array( 28, -1, 0, 0 ),
- 'INDEX' => array( 29, -1, 0, 1 ),
- 'REPT' => array( 30, 2, 1, 0 ),
- 'MID' => array( 31, 3, 1, 0 ),
- 'LEN' => array( 32, 1, 1, 0 ),
- 'VALUE' => array( 33, 1, 1, 0 ),
- 'TRUE' => array( 34, 0, 1, 0 ),
- 'FALSE' => array( 35, 0, 1, 0 ),
- 'AND' => array( 36, -1, 0, 0 ),
- 'OR' => array( 37, -1, 0, 0 ),
- 'NOT' => array( 38, 1, 1, 0 ),
- 'MOD' => array( 39, 2, 1, 0 ),
- 'DCOUNT' => array( 40, 3, 0, 0 ),
- 'DSUM' => array( 41, 3, 0, 0 ),
- 'DAVERAGE' => array( 42, 3, 0, 0 ),
- 'DMIN' => array( 43, 3, 0, 0 ),
- 'DMAX' => array( 44, 3, 0, 0 ),
- 'DSTDEV' => array( 45, 3, 0, 0 ),
- 'VAR' => array( 46, -1, 0, 0 ),
- 'DVAR' => array( 47, 3, 0, 0 ),
- 'TEXT' => array( 48, 2, 1, 0 ),
- 'LINEST' => array( 49, -1, 0, 0 ),
- 'TREND' => array( 50, -1, 0, 0 ),
- 'LOGEST' => array( 51, -1, 0, 0 ),
- 'GROWTH' => array( 52, -1, 0, 0 ),
- 'PV' => array( 56, -1, 1, 0 ),
- 'FV' => array( 57, -1, 1, 0 ),
- 'NPER' => array( 58, -1, 1, 0 ),
- 'PMT' => array( 59, -1, 1, 0 ),
- 'RATE' => array( 60, -1, 1, 0 ),
- 'MIRR' => array( 61, 3, 0, 0 ),
- 'IRR' => array( 62, -1, 0, 0 ),
- 'RAND' => array( 63, 0, 1, 1 ),
- 'MATCH' => array( 64, -1, 0, 0 ),
- 'DATE' => array( 65, 3, 1, 0 ),
- 'TIME' => array( 66, 3, 1, 0 ),
- 'DAY' => array( 67, 1, 1, 0 ),
- 'MONTH' => array( 68, 1, 1, 0 ),
- 'YEAR' => array( 69, 1, 1, 0 ),
- 'WEEKDAY' => array( 70, -1, 1, 0 ),
- 'HOUR' => array( 71, 1, 1, 0 ),
- 'MINUTE' => array( 72, 1, 1, 0 ),
- 'SECOND' => array( 73, 1, 1, 0 ),
- 'NOW' => array( 74, 0, 1, 1 ),
- 'AREAS' => array( 75, 1, 0, 1 ),
- 'ROWS' => array( 76, 1, 0, 1 ),
- 'COLUMNS' => array( 77, 1, 0, 1 ),
- 'OFFSET' => array( 78, -1, 0, 1 ),
- 'SEARCH' => array( 82, -1, 1, 0 ),
- 'TRANSPOSE' => array( 83, 1, 1, 0 ),
- 'TYPE' => array( 86, 1, 1, 0 ),
- 'ATAN2' => array( 97, 2, 1, 0 ),
- 'ASIN' => array( 98, 1, 1, 0 ),
- 'ACOS' => array( 99, 1, 1, 0 ),
- 'CHOOSE' => array( 100, -1, 1, 0 ),
- 'HLOOKUP' => array( 101, -1, 0, 0 ),
- 'VLOOKUP' => array( 102, -1, 0, 0 ),
- 'ISREF' => array( 105, 1, 0, 0 ),
- 'LOG' => array( 109, -1, 1, 0 ),
- 'CHAR' => array( 111, 1, 1, 0 ),
- 'LOWER' => array( 112, 1, 1, 0 ),
- 'UPPER' => array( 113, 1, 1, 0 ),
- 'PROPER' => array( 114, 1, 1, 0 ),
- 'LEFT' => array( 115, -1, 1, 0 ),
- 'RIGHT' => array( 116, -1, 1, 0 ),
- 'EXACT' => array( 117, 2, 1, 0 ),
- 'TRIM' => array( 118, 1, 1, 0 ),
- 'REPLACE' => array( 119, 4, 1, 0 ),
- 'SUBSTITUTE' => array( 120, -1, 1, 0 ),
- 'CODE' => array( 121, 1, 1, 0 ),
- 'FIND' => array( 124, -1, 1, 0 ),
- 'CELL' => array( 125, -1, 0, 1 ),
- 'ISERR' => array( 126, 1, 1, 0 ),
- 'ISTEXT' => array( 127, 1, 1, 0 ),
- 'ISNUMBER' => array( 128, 1, 1, 0 ),
- 'ISBLANK' => array( 129, 1, 1, 0 ),
- 'T' => array( 130, 1, 0, 0 ),
- 'N' => array( 131, 1, 0, 0 ),
- 'DATEVALUE' => array( 140, 1, 1, 0 ),
- 'TIMEVALUE' => array( 141, 1, 1, 0 ),
- 'SLN' => array( 142, 3, 1, 0 ),
- 'SYD' => array( 143, 4, 1, 0 ),
- 'DDB' => array( 144, -1, 1, 0 ),
- 'INDIRECT' => array( 148, -1, 1, 1 ),
- 'CALL' => array( 150, -1, 1, 0 ),
- 'CLEAN' => array( 162, 1, 1, 0 ),
- 'MDETERM' => array( 163, 1, 2, 0 ),
- 'MINVERSE' => array( 164, 1, 2, 0 ),
- 'MMULT' => array( 165, 2, 2, 0 ),
- 'IPMT' => array( 167, -1, 1, 0 ),
- 'PPMT' => array( 168, -1, 1, 0 ),
- 'COUNTA' => array( 169, -1, 0, 0 ),
- 'PRODUCT' => array( 183, -1, 0, 0 ),
- 'FACT' => array( 184, 1, 1, 0 ),
- 'DPRODUCT' => array( 189, 3, 0, 0 ),
- 'ISNONTEXT' => array( 190, 1, 1, 0 ),
- 'STDEVP' => array( 193, -1, 0, 0 ),
- 'VARP' => array( 194, -1, 0, 0 ),
- 'DSTDEVP' => array( 195, 3, 0, 0 ),
- 'DVARP' => array( 196, 3, 0, 0 ),
- 'TRUNC' => array( 197, -1, 1, 0 ),
- 'ISLOGICAL' => array( 198, 1, 1, 0 ),
- 'DCOUNTA' => array( 199, 3, 0, 0 ),
- 'USDOLLAR' => array( 204, -1, 1, 0 ),
- 'FINDB' => array( 205, -1, 1, 0 ),
- 'SEARCHB' => array( 206, -1, 1, 0 ),
- 'REPLACEB' => array( 207, 4, 1, 0 ),
- 'LEFTB' => array( 208, -1, 1, 0 ),
- 'RIGHTB' => array( 209, -1, 1, 0 ),
- 'MIDB' => array( 210, 3, 1, 0 ),
- 'LENB' => array( 211, 1, 1, 0 ),
- 'ROUNDUP' => array( 212, 2, 1, 0 ),
- 'ROUNDDOWN' => array( 213, 2, 1, 0 ),
- 'ASC' => array( 214, 1, 1, 0 ),
- 'DBCS' => array( 215, 1, 1, 0 ),
- 'RANK' => array( 216, -1, 0, 0 ),
- 'ADDRESS' => array( 219, -1, 1, 0 ),
- 'DAYS360' => array( 220, -1, 1, 0 ),
- 'TODAY' => array( 221, 0, 1, 1 ),
- 'VDB' => array( 222, -1, 1, 0 ),
- 'MEDIAN' => array( 227, -1, 0, 0 ),
- 'SUMPRODUCT' => array( 228, -1, 2, 0 ),
- 'SINH' => array( 229, 1, 1, 0 ),
- 'COSH' => array( 230, 1, 1, 0 ),
- 'TANH' => array( 231, 1, 1, 0 ),
- 'ASINH' => array( 232, 1, 1, 0 ),
- 'ACOSH' => array( 233, 1, 1, 0 ),
- 'ATANH' => array( 234, 1, 1, 0 ),
- 'DGET' => array( 235, 3, 0, 0 ),
- 'INFO' => array( 244, 1, 1, 1 ),
- 'DB' => array( 247, -1, 1, 0 ),
- 'FREQUENCY' => array( 252, 2, 0, 0 ),
- 'ERROR.TYPE' => array( 261, 1, 1, 0 ),
- 'REGISTER.ID' => array( 267, -1, 1, 0 ),
- 'AVEDEV' => array( 269, -1, 0, 0 ),
- 'BETADIST' => array( 270, -1, 1, 0 ),
- 'GAMMALN' => array( 271, 1, 1, 0 ),
- 'BETAINV' => array( 272, -1, 1, 0 ),
- 'BINOMDIST' => array( 273, 4, 1, 0 ),
- 'CHIDIST' => array( 274, 2, 1, 0 ),
- 'CHIINV' => array( 275, 2, 1, 0 ),
- 'COMBIN' => array( 276, 2, 1, 0 ),
- 'CONFIDENCE' => array( 277, 3, 1, 0 ),
- 'CRITBINOM' => array( 278, 3, 1, 0 ),
- 'EVEN' => array( 279, 1, 1, 0 ),
- 'EXPONDIST' => array( 280, 3, 1, 0 ),
- 'FDIST' => array( 281, 3, 1, 0 ),
- 'FINV' => array( 282, 3, 1, 0 ),
- 'FISHER' => array( 283, 1, 1, 0 ),
- 'FISHERINV' => array( 284, 1, 1, 0 ),
- 'FLOOR' => array( 285, 2, 1, 0 ),
- 'GAMMADIST' => array( 286, 4, 1, 0 ),
- 'GAMMAINV' => array( 287, 3, 1, 0 ),
- 'CEILING' => array( 288, 2, 1, 0 ),
- 'HYPGEOMDIST' => array( 289, 4, 1, 0 ),
- 'LOGNORMDIST' => array( 290, 3, 1, 0 ),
- 'LOGINV' => array( 291, 3, 1, 0 ),
- 'NEGBINOMDIST' => array( 292, 3, 1, 0 ),
- 'NORMDIST' => array( 293, 4, 1, 0 ),
- 'NORMSDIST' => array( 294, 1, 1, 0 ),
- 'NORMINV' => array( 295, 3, 1, 0 ),
- 'NORMSINV' => array( 296, 1, 1, 0 ),
- 'STANDARDIZE' => array( 297, 3, 1, 0 ),
- 'ODD' => array( 298, 1, 1, 0 ),
- 'PERMUT' => array( 299, 2, 1, 0 ),
- 'POISSON' => array( 300, 3, 1, 0 ),
- 'TDIST' => array( 301, 3, 1, 0 ),
- 'WEIBULL' => array( 302, 4, 1, 0 ),
- 'SUMXMY2' => array( 303, 2, 2, 0 ),
- 'SUMX2MY2' => array( 304, 2, 2, 0 ),
- 'SUMX2PY2' => array( 305, 2, 2, 0 ),
- 'CHITEST' => array( 306, 2, 2, 0 ),
- 'CORREL' => array( 307, 2, 2, 0 ),
- 'COVAR' => array( 308, 2, 2, 0 ),
- 'FORECAST' => array( 309, 3, 2, 0 ),
- 'FTEST' => array( 310, 2, 2, 0 ),
- 'INTERCEPT' => array( 311, 2, 2, 0 ),
- 'PEARSON' => array( 312, 2, 2, 0 ),
- 'RSQ' => array( 313, 2, 2, 0 ),
- 'STEYX' => array( 314, 2, 2, 0 ),
- 'SLOPE' => array( 315, 2, 2, 0 ),
- 'TTEST' => array( 316, 4, 2, 0 ),
- 'PROB' => array( 317, -1, 2, 0 ),
- 'DEVSQ' => array( 318, -1, 0, 0 ),
- 'GEOMEAN' => array( 319, -1, 0, 0 ),
- 'HARMEAN' => array( 320, -1, 0, 0 ),
- 'SUMSQ' => array( 321, -1, 0, 0 ),
- 'KURT' => array( 322, -1, 0, 0 ),
- 'SKEW' => array( 323, -1, 0, 0 ),
- 'ZTEST' => array( 324, -1, 0, 0 ),
- 'LARGE' => array( 325, 2, 0, 0 ),
- 'SMALL' => array( 326, 2, 0, 0 ),
- 'QUARTILE' => array( 327, 2, 0, 0 ),
- 'PERCENTILE' => array( 328, 2, 0, 0 ),
- 'PERCENTRANK' => array( 329, -1, 0, 0 ),
- 'MODE' => array( 330, -1, 2, 0 ),
- 'TRIMMEAN' => array( 331, 2, 0, 0 ),
- 'TINV' => array( 332, 2, 1, 0 ),
- 'CONCATENATE' => array( 336, -1, 1, 0 ),
- 'POWER' => array( 337, 2, 1, 0 ),
- 'RADIANS' => array( 342, 1, 1, 0 ),
- 'DEGREES' => array( 343, 1, 1, 0 ),
- 'SUBTOTAL' => array( 344, -1, 0, 0 ),
- 'SUMIF' => array( 345, -1, 0, 0 ),
- 'COUNTIF' => array( 346, 2, 0, 0 ),
- 'COUNTBLANK' => array( 347, 1, 0, 0 ),
- 'ISPMT' => array( 350, 4, 1, 0 ),
- 'DATEDIF' => array( 351, 3, 1, 0 ),
- 'DATESTRING' => array( 352, 1, 1, 0 ),
- 'NUMBERSTRING' => array( 353, 2, 1, 0 ),
- 'ROMAN' => array( 354, -1, 1, 0 ),
- 'GETPIVOTDATA' => array( 358, -1, 0, 0 ),
- 'HYPERLINK' => array( 359, -1, 1, 0 ),
- 'PHONETIC' => array( 360, 1, 0, 0 ),
- 'AVERAGEA' => array( 361, -1, 0, 0 ),
- 'MAXA' => array( 362, -1, 0, 0 ),
- 'MINA' => array( 363, -1, 0, 0 ),
- 'STDEVPA' => array( 364, -1, 0, 0 ),
- 'VARPA' => array( 365, -1, 0, 0 ),
- 'STDEVA' => array( 366, -1, 0, 0 ),
- 'VARA' => array( 367, -1, 0, 0 ),
- 'BAHTTEXT' => array( 368, 1, 0, 0 ),
- );
- }
+ // Thanks to Michael Meeks and Gnumeric for the initial arg values.
+ //
+ // The following hash was generated by "function_locale.pl" in the distro.
+ // Refer to function_locale.pl for non-English function names.
+ //
+ // The array elements are as follow:
+ // ptg: The Excel function ptg code.
+ // args: The number of arguments that the function takes:
+ // >=0 is a fixed number of arguments.
+ // -1 is a variable number of arguments.
+ // class: The reference, value or array class of the function args.
+ // vol: The function is volatile.
+ //
+ $this->_functions = array(
+ // function ptg args class vol
+ 'COUNT' => array( 0, -1, 0, 0 ),
+ 'IF' => array( 1, -1, 1, 0 ),
+ 'ISNA' => array( 2, 1, 1, 0 ),
+ 'ISERROR' => array( 3, 1, 1, 0 ),
+ 'SUM' => array( 4, -1, 0, 0 ),
+ 'AVERAGE' => array( 5, -1, 0, 0 ),
+ 'MIN' => array( 6, -1, 0, 0 ),
+ 'MAX' => array( 7, -1, 0, 0 ),
+ 'ROW' => array( 8, -1, 0, 0 ),
+ 'COLUMN' => array( 9, -1, 0, 0 ),
+ 'NA' => array( 10, 0, 0, 0 ),
+ 'NPV' => array( 11, -1, 1, 0 ),
+ 'STDEV' => array( 12, -1, 0, 0 ),
+ 'DOLLAR' => array( 13, -1, 1, 0 ),
+ 'FIXED' => array( 14, -1, 1, 0 ),
+ 'SIN' => array( 15, 1, 1, 0 ),
+ 'COS' => array( 16, 1, 1, 0 ),
+ 'TAN' => array( 17, 1, 1, 0 ),
+ 'ATAN' => array( 18, 1, 1, 0 ),
+ 'PI' => array( 19, 0, 1, 0 ),
+ 'SQRT' => array( 20, 1, 1, 0 ),
+ 'EXP' => array( 21, 1, 1, 0 ),
+ 'LN' => array( 22, 1, 1, 0 ),
+ 'LOG10' => array( 23, 1, 1, 0 ),
+ 'ABS' => array( 24, 1, 1, 0 ),
+ 'INT' => array( 25, 1, 1, 0 ),
+ 'SIGN' => array( 26, 1, 1, 0 ),
+ 'ROUND' => array( 27, 2, 1, 0 ),
+ 'LOOKUP' => array( 28, -1, 0, 0 ),
+ 'INDEX' => array( 29, -1, 0, 1 ),
+ 'REPT' => array( 30, 2, 1, 0 ),
+ 'MID' => array( 31, 3, 1, 0 ),
+ 'LEN' => array( 32, 1, 1, 0 ),
+ 'VALUE' => array( 33, 1, 1, 0 ),
+ 'TRUE' => array( 34, 0, 1, 0 ),
+ 'FALSE' => array( 35, 0, 1, 0 ),
+ 'AND' => array( 36, -1, 0, 0 ),
+ 'OR' => array( 37, -1, 0, 0 ),
+ 'NOT' => array( 38, 1, 1, 0 ),
+ 'MOD' => array( 39, 2, 1, 0 ),
+ 'DCOUNT' => array( 40, 3, 0, 0 ),
+ 'DSUM' => array( 41, 3, 0, 0 ),
+ 'DAVERAGE' => array( 42, 3, 0, 0 ),
+ 'DMIN' => array( 43, 3, 0, 0 ),
+ 'DMAX' => array( 44, 3, 0, 0 ),
+ 'DSTDEV' => array( 45, 3, 0, 0 ),
+ 'VAR' => array( 46, -1, 0, 0 ),
+ 'DVAR' => array( 47, 3, 0, 0 ),
+ 'TEXT' => array( 48, 2, 1, 0 ),
+ 'LINEST' => array( 49, -1, 0, 0 ),
+ 'TREND' => array( 50, -1, 0, 0 ),
+ 'LOGEST' => array( 51, -1, 0, 0 ),
+ 'GROWTH' => array( 52, -1, 0, 0 ),
+ 'PV' => array( 56, -1, 1, 0 ),
+ 'FV' => array( 57, -1, 1, 0 ),
+ 'NPER' => array( 58, -1, 1, 0 ),
+ 'PMT' => array( 59, -1, 1, 0 ),
+ 'RATE' => array( 60, -1, 1, 0 ),
+ 'MIRR' => array( 61, 3, 0, 0 ),
+ 'IRR' => array( 62, -1, 0, 0 ),
+ 'RAND' => array( 63, 0, 1, 1 ),
+ 'MATCH' => array( 64, -1, 0, 0 ),
+ 'DATE' => array( 65, 3, 1, 0 ),
+ 'TIME' => array( 66, 3, 1, 0 ),
+ 'DAY' => array( 67, 1, 1, 0 ),
+ 'MONTH' => array( 68, 1, 1, 0 ),
+ 'YEAR' => array( 69, 1, 1, 0 ),
+ 'WEEKDAY' => array( 70, -1, 1, 0 ),
+ 'HOUR' => array( 71, 1, 1, 0 ),
+ 'MINUTE' => array( 72, 1, 1, 0 ),
+ 'SECOND' => array( 73, 1, 1, 0 ),
+ 'NOW' => array( 74, 0, 1, 1 ),
+ 'AREAS' => array( 75, 1, 0, 1 ),
+ 'ROWS' => array( 76, 1, 0, 1 ),
+ 'COLUMNS' => array( 77, 1, 0, 1 ),
+ 'OFFSET' => array( 78, -1, 0, 1 ),
+ 'SEARCH' => array( 82, -1, 1, 0 ),
+ 'TRANSPOSE' => array( 83, 1, 1, 0 ),
+ 'TYPE' => array( 86, 1, 1, 0 ),
+ 'ATAN2' => array( 97, 2, 1, 0 ),
+ 'ASIN' => array( 98, 1, 1, 0 ),
+ 'ACOS' => array( 99, 1, 1, 0 ),
+ 'CHOOSE' => array( 100, -1, 1, 0 ),
+ 'HLOOKUP' => array( 101, -1, 0, 0 ),
+ 'VLOOKUP' => array( 102, -1, 0, 0 ),
+ 'ISREF' => array( 105, 1, 0, 0 ),
+ 'LOG' => array( 109, -1, 1, 0 ),
+ 'CHAR' => array( 111, 1, 1, 0 ),
+ 'LOWER' => array( 112, 1, 1, 0 ),
+ 'UPPER' => array( 113, 1, 1, 0 ),
+ 'PROPER' => array( 114, 1, 1, 0 ),
+ 'LEFT' => array( 115, -1, 1, 0 ),
+ 'RIGHT' => array( 116, -1, 1, 0 ),
+ 'EXACT' => array( 117, 2, 1, 0 ),
+ 'TRIM' => array( 118, 1, 1, 0 ),
+ 'REPLACE' => array( 119, 4, 1, 0 ),
+ 'SUBSTITUTE' => array( 120, -1, 1, 0 ),
+ 'CODE' => array( 121, 1, 1, 0 ),
+ 'FIND' => array( 124, -1, 1, 0 ),
+ 'CELL' => array( 125, -1, 0, 1 ),
+ 'ISERR' => array( 126, 1, 1, 0 ),
+ 'ISTEXT' => array( 127, 1, 1, 0 ),
+ 'ISNUMBER' => array( 128, 1, 1, 0 ),
+ 'ISBLANK' => array( 129, 1, 1, 0 ),
+ 'T' => array( 130, 1, 0, 0 ),
+ 'N' => array( 131, 1, 0, 0 ),
+ 'DATEVALUE' => array( 140, 1, 1, 0 ),
+ 'TIMEVALUE' => array( 141, 1, 1, 0 ),
+ 'SLN' => array( 142, 3, 1, 0 ),
+ 'SYD' => array( 143, 4, 1, 0 ),
+ 'DDB' => array( 144, -1, 1, 0 ),
+ 'INDIRECT' => array( 148, -1, 1, 1 ),
+ 'CALL' => array( 150, -1, 1, 0 ),
+ 'CLEAN' => array( 162, 1, 1, 0 ),
+ 'MDETERM' => array( 163, 1, 2, 0 ),
+ 'MINVERSE' => array( 164, 1, 2, 0 ),
+ 'MMULT' => array( 165, 2, 2, 0 ),
+ 'IPMT' => array( 167, -1, 1, 0 ),
+ 'PPMT' => array( 168, -1, 1, 0 ),
+ 'COUNTA' => array( 169, -1, 0, 0 ),
+ 'PRODUCT' => array( 183, -1, 0, 0 ),
+ 'FACT' => array( 184, 1, 1, 0 ),
+ 'DPRODUCT' => array( 189, 3, 0, 0 ),
+ 'ISNONTEXT' => array( 190, 1, 1, 0 ),
+ 'STDEVP' => array( 193, -1, 0, 0 ),
+ 'VARP' => array( 194, -1, 0, 0 ),
+ 'DSTDEVP' => array( 195, 3, 0, 0 ),
+ 'DVARP' => array( 196, 3, 0, 0 ),
+ 'TRUNC' => array( 197, -1, 1, 0 ),
+ 'ISLOGICAL' => array( 198, 1, 1, 0 ),
+ 'DCOUNTA' => array( 199, 3, 0, 0 ),
+ 'USDOLLAR' => array( 204, -1, 1, 0 ),
+ 'FINDB' => array( 205, -1, 1, 0 ),
+ 'SEARCHB' => array( 206, -1, 1, 0 ),
+ 'REPLACEB' => array( 207, 4, 1, 0 ),
+ 'LEFTB' => array( 208, -1, 1, 0 ),
+ 'RIGHTB' => array( 209, -1, 1, 0 ),
+ 'MIDB' => array( 210, 3, 1, 0 ),
+ 'LENB' => array( 211, 1, 1, 0 ),
+ 'ROUNDUP' => array( 212, 2, 1, 0 ),
+ 'ROUNDDOWN' => array( 213, 2, 1, 0 ),
+ 'ASC' => array( 214, 1, 1, 0 ),
+ 'DBCS' => array( 215, 1, 1, 0 ),
+ 'RANK' => array( 216, -1, 0, 0 ),
+ 'ADDRESS' => array( 219, -1, 1, 0 ),
+ 'DAYS360' => array( 220, -1, 1, 0 ),
+ 'TODAY' => array( 221, 0, 1, 1 ),
+ 'VDB' => array( 222, -1, 1, 0 ),
+ 'MEDIAN' => array( 227, -1, 0, 0 ),
+ 'SUMPRODUCT' => array( 228, -1, 2, 0 ),
+ 'SINH' => array( 229, 1, 1, 0 ),
+ 'COSH' => array( 230, 1, 1, 0 ),
+ 'TANH' => array( 231, 1, 1, 0 ),
+ 'ASINH' => array( 232, 1, 1, 0 ),
+ 'ACOSH' => array( 233, 1, 1, 0 ),
+ 'ATANH' => array( 234, 1, 1, 0 ),
+ 'DGET' => array( 235, 3, 0, 0 ),
+ 'INFO' => array( 244, 1, 1, 1 ),
+ 'DB' => array( 247, -1, 1, 0 ),
+ 'FREQUENCY' => array( 252, 2, 0, 0 ),
+ 'ERROR.TYPE' => array( 261, 1, 1, 0 ),
+ 'REGISTER.ID' => array( 267, -1, 1, 0 ),
+ 'AVEDEV' => array( 269, -1, 0, 0 ),
+ 'BETADIST' => array( 270, -1, 1, 0 ),
+ 'GAMMALN' => array( 271, 1, 1, 0 ),
+ 'BETAINV' => array( 272, -1, 1, 0 ),
+ 'BINOMDIST' => array( 273, 4, 1, 0 ),
+ 'CHIDIST' => array( 274, 2, 1, 0 ),
+ 'CHIINV' => array( 275, 2, 1, 0 ),
+ 'COMBIN' => array( 276, 2, 1, 0 ),
+ 'CONFIDENCE' => array( 277, 3, 1, 0 ),
+ 'CRITBINOM' => array( 278, 3, 1, 0 ),
+ 'EVEN' => array( 279, 1, 1, 0 ),
+ 'EXPONDIST' => array( 280, 3, 1, 0 ),
+ 'FDIST' => array( 281, 3, 1, 0 ),
+ 'FINV' => array( 282, 3, 1, 0 ),
+ 'FISHER' => array( 283, 1, 1, 0 ),
+ 'FISHERINV' => array( 284, 1, 1, 0 ),
+ 'FLOOR' => array( 285, 2, 1, 0 ),
+ 'GAMMADIST' => array( 286, 4, 1, 0 ),
+ 'GAMMAINV' => array( 287, 3, 1, 0 ),
+ 'CEILING' => array( 288, 2, 1, 0 ),
+ 'HYPGEOMDIST' => array( 289, 4, 1, 0 ),
+ 'LOGNORMDIST' => array( 290, 3, 1, 0 ),
+ 'LOGINV' => array( 291, 3, 1, 0 ),
+ 'NEGBINOMDIST' => array( 292, 3, 1, 0 ),
+ 'NORMDIST' => array( 293, 4, 1, 0 ),
+ 'NORMSDIST' => array( 294, 1, 1, 0 ),
+ 'NORMINV' => array( 295, 3, 1, 0 ),
+ 'NORMSINV' => array( 296, 1, 1, 0 ),
+ 'STANDARDIZE' => array( 297, 3, 1, 0 ),
+ 'ODD' => array( 298, 1, 1, 0 ),
+ 'PERMUT' => array( 299, 2, 1, 0 ),
+ 'POISSON' => array( 300, 3, 1, 0 ),
+ 'TDIST' => array( 301, 3, 1, 0 ),
+ 'WEIBULL' => array( 302, 4, 1, 0 ),
+ 'SUMXMY2' => array( 303, 2, 2, 0 ),
+ 'SUMX2MY2' => array( 304, 2, 2, 0 ),
+ 'SUMX2PY2' => array( 305, 2, 2, 0 ),
+ 'CHITEST' => array( 306, 2, 2, 0 ),
+ 'CORREL' => array( 307, 2, 2, 0 ),
+ 'COVAR' => array( 308, 2, 2, 0 ),
+ 'FORECAST' => array( 309, 3, 2, 0 ),
+ 'FTEST' => array( 310, 2, 2, 0 ),
+ 'INTERCEPT' => array( 311, 2, 2, 0 ),
+ 'PEARSON' => array( 312, 2, 2, 0 ),
+ 'RSQ' => array( 313, 2, 2, 0 ),
+ 'STEYX' => array( 314, 2, 2, 0 ),
+ 'SLOPE' => array( 315, 2, 2, 0 ),
+ 'TTEST' => array( 316, 4, 2, 0 ),
+ 'PROB' => array( 317, -1, 2, 0 ),
+ 'DEVSQ' => array( 318, -1, 0, 0 ),
+ 'GEOMEAN' => array( 319, -1, 0, 0 ),
+ 'HARMEAN' => array( 320, -1, 0, 0 ),
+ 'SUMSQ' => array( 321, -1, 0, 0 ),
+ 'KURT' => array( 322, -1, 0, 0 ),
+ 'SKEW' => array( 323, -1, 0, 0 ),
+ 'ZTEST' => array( 324, -1, 0, 0 ),
+ 'LARGE' => array( 325, 2, 0, 0 ),
+ 'SMALL' => array( 326, 2, 0, 0 ),
+ 'QUARTILE' => array( 327, 2, 0, 0 ),
+ 'PERCENTILE' => array( 328, 2, 0, 0 ),
+ 'PERCENTRANK' => array( 329, -1, 0, 0 ),
+ 'MODE' => array( 330, -1, 2, 0 ),
+ 'TRIMMEAN' => array( 331, 2, 0, 0 ),
+ 'TINV' => array( 332, 2, 1, 0 ),
+ 'CONCATENATE' => array( 336, -1, 1, 0 ),
+ 'POWER' => array( 337, 2, 1, 0 ),
+ 'RADIANS' => array( 342, 1, 1, 0 ),
+ 'DEGREES' => array( 343, 1, 1, 0 ),
+ 'SUBTOTAL' => array( 344, -1, 0, 0 ),
+ 'SUMIF' => array( 345, -1, 0, 0 ),
+ 'COUNTIF' => array( 346, 2, 0, 0 ),
+ 'COUNTBLANK' => array( 347, 1, 0, 0 ),
+ 'ISPMT' => array( 350, 4, 1, 0 ),
+ 'DATEDIF' => array( 351, 3, 1, 0 ),
+ 'DATESTRING' => array( 352, 1, 1, 0 ),
+ 'NUMBERSTRING' => array( 353, 2, 1, 0 ),
+ 'ROMAN' => array( 354, -1, 1, 0 ),
+ 'GETPIVOTDATA' => array( 358, -1, 0, 0 ),
+ 'HYPERLINK' => array( 359, -1, 1, 0 ),
+ 'PHONETIC' => array( 360, 1, 0, 0 ),
+ 'AVERAGEA' => array( 361, -1, 0, 0 ),
+ 'MAXA' => array( 362, -1, 0, 0 ),
+ 'MINA' => array( 363, -1, 0, 0 ),
+ 'STDEVPA' => array( 364, -1, 0, 0 ),
+ 'VARPA' => array( 365, -1, 0, 0 ),
+ 'STDEVA' => array( 366, -1, 0, 0 ),
+ 'VARA' => array( 367, -1, 0, 0 ),
+ 'BAHTTEXT' => array( 368, 1, 0, 0 ),
+ );
+ }
- /**
- * Convert a token to the proper ptg value.
- *
- * @access private
- * @param mixed $token The token to convert.
- * @return mixed the converted token on success
- */
- function _convert($token)
- {
- if (preg_match("/\"([^\"]|\"\"){0,255}\"/", $token)) {
- return $this->_convertString($token);
+ /**
+ * Convert a token to the proper ptg value.
+ *
+ * @access private
+ * @param mixed $token The token to convert.
+ * @return mixed the converted token on success
+ */
+ function _convert($token)
+ {
+ if (preg_match("/\"([^\"]|\"\"){0,255}\"/", $token)) {
+ return $this->_convertString($token);
- } elseif (is_numeric($token)) {
- return $this->_convertNumber($token);
+ } elseif (is_numeric($token)) {
+ return $this->_convertNumber($token);
- // match references like A1 or $A$1
- } elseif (preg_match('/^\$?([A-Ia-i]?[A-Za-z])\$?(\d+)$/',$token)) {
- return $this->_convertRef2d($token);
+ // match references like A1 or $A$1
+ } elseif (preg_match('/^\$?([A-Ia-i]?[A-Za-z])\$?(\d+)$/',$token)) {
+ return $this->_convertRef2d($token);
- // match external references like Sheet1!A1 or Sheet1:Sheet2!A1 or Sheet1!$A$1 or Sheet1:Sheet2!$A$1
- } elseif (preg_match("/^" . self::REGEX_SHEET_TITLE_UNQUOTED . "(\:" . self::REGEX_SHEET_TITLE_UNQUOTED . ")?\!\\$?[A-Ia-i]?[A-Za-z]\\$?(\d+)$/u",$token)) {
- return $this->_convertRef3d($token);
+ // match external references like Sheet1!A1 or Sheet1:Sheet2!A1 or Sheet1!$A$1 or Sheet1:Sheet2!$A$1
+ } elseif (preg_match("/^" . self::REGEX_SHEET_TITLE_UNQUOTED . "(\:" . self::REGEX_SHEET_TITLE_UNQUOTED . ")?\!\\$?[A-Ia-i]?[A-Za-z]\\$?(\d+)$/u",$token)) {
+ return $this->_convertRef3d($token);
- // match external references like 'Sheet1'!A1 or 'Sheet1:Sheet2'!A1 or 'Sheet1'!$A$1 or 'Sheet1:Sheet2'!$A$1
- } elseif (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . "(\:" . self::REGEX_SHEET_TITLE_QUOTED . ")?'\!\\$?[A-Ia-i]?[A-Za-z]\\$?(\d+)$/u",$token)) {
- return $this->_convertRef3d($token);
+ // match external references like 'Sheet1'!A1 or 'Sheet1:Sheet2'!A1 or 'Sheet1'!$A$1 or 'Sheet1:Sheet2'!$A$1
+ } elseif (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . "(\:" . self::REGEX_SHEET_TITLE_QUOTED . ")?'\!\\$?[A-Ia-i]?[A-Za-z]\\$?(\d+)$/u",$token)) {
+ return $this->_convertRef3d($token);
- // match ranges like A1:B2 or $A$1:$B$2
- } elseif (preg_match('/^(\$)?[A-Ia-i]?[A-Za-z](\$)?(\d+)\:(\$)?[A-Ia-i]?[A-Za-z](\$)?(\d+)$/', $token)) {
- return $this->_convertRange2d($token);
+ // match ranges like A1:B2 or $A$1:$B$2
+ } elseif (preg_match('/^(\$)?[A-Ia-i]?[A-Za-z](\$)?(\d+)\:(\$)?[A-Ia-i]?[A-Za-z](\$)?(\d+)$/', $token)) {
+ return $this->_convertRange2d($token);
- // match external ranges like Sheet1!A1:B2 or Sheet1:Sheet2!A1:B2 or Sheet1!$A$1:$B$2 or Sheet1:Sheet2!$A$1:$B$2
- } elseif (preg_match("/^" . self::REGEX_SHEET_TITLE_UNQUOTED . "(\:" . self::REGEX_SHEET_TITLE_UNQUOTED . ")?\!\\$?([A-Ia-i]?[A-Za-z])?\\$?(\d+)\:\\$?([A-Ia-i]?[A-Za-z])?\\$?(\d+)$/u",$token)) {
- return $this->_convertRange3d($token);
+ // match external ranges like Sheet1!A1:B2 or Sheet1:Sheet2!A1:B2 or Sheet1!$A$1:$B$2 or Sheet1:Sheet2!$A$1:$B$2
+ } elseif (preg_match("/^" . self::REGEX_SHEET_TITLE_UNQUOTED . "(\:" . self::REGEX_SHEET_TITLE_UNQUOTED . ")?\!\\$?([A-Ia-i]?[A-Za-z])?\\$?(\d+)\:\\$?([A-Ia-i]?[A-Za-z])?\\$?(\d+)$/u",$token)) {
+ return $this->_convertRange3d($token);
- // match external ranges like 'Sheet1'!A1:B2 or 'Sheet1:Sheet2'!A1:B2 or 'Sheet1'!$A$1:$B$2 or 'Sheet1:Sheet2'!$A$1:$B$2
- } elseif (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . "(\:" . self::REGEX_SHEET_TITLE_QUOTED . ")?'\!\\$?([A-Ia-i]?[A-Za-z])?\\$?(\d+)\:\\$?([A-Ia-i]?[A-Za-z])?\\$?(\d+)$/u",$token)) {
- return $this->_convertRange3d($token);
+ // match external ranges like 'Sheet1'!A1:B2 or 'Sheet1:Sheet2'!A1:B2 or 'Sheet1'!$A$1:$B$2 or 'Sheet1:Sheet2'!$A$1:$B$2
+ } elseif (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . "(\:" . self::REGEX_SHEET_TITLE_QUOTED . ")?'\!\\$?([A-Ia-i]?[A-Za-z])?\\$?(\d+)\:\\$?([A-Ia-i]?[A-Za-z])?\\$?(\d+)$/u",$token)) {
+ return $this->_convertRange3d($token);
- // operators (including parentheses)
- } elseif (isset($this->ptg[$token])) {
- return pack("C", $this->ptg[$token]);
+ // operators (including parentheses)
+ } elseif (isset($this->ptg[$token])) {
+ return pack("C", $this->ptg[$token]);
// match error codes
- } elseif (preg_match("/^#[A-Z0\/]{3,5}[!?]{1}$/", $token) or $token == '#N/A') {
- return $this->_convertError($token);
+ } elseif (preg_match("/^#[A-Z0\/]{3,5}[!?]{1}$/", $token) or $token == '#N/A') {
+ return $this->_convertError($token);
- // commented so argument number can be processed correctly. See toReversePolish().
- /*elseif (preg_match("/[A-Z0-9\xc0-\xdc\.]+/",$token))
- {
- return($this->_convertFunction($token,$this->_func_args));
- }*/
+ // commented so argument number can be processed correctly. See toReversePolish().
+ /*elseif (preg_match("/[A-Z0-9\xc0-\xdc\.]+/",$token))
+ {
+ return($this->_convertFunction($token,$this->_func_args));
+ }*/
- // if it's an argument, ignore the token (the argument remains)
- } elseif ($token == 'arg') {
- return '';
- }
+ // if it's an argument, ignore the token (the argument remains)
+ } elseif ($token == 'arg') {
+ return '';
+ }
- // TODO: use real error codes
- throw new Writer_Exception("Unknown token $token");
- }
+ // TODO: use real error codes
+ throw new Writer_Exception("Unknown token $token");
+ }
- /**
- * Convert a number token to ptgInt or ptgNum
- *
- * @access private
- * @param mixed $num an integer or double for conversion to its ptg value
- */
- function _convertNumber($num)
- {
- // Integer in the range 0..2**16-1
- if ((preg_match("/^\d+$/", $num)) and ($num <= 65535)) {
- return pack("Cv", $this->ptg['ptgInt'], $num);
- } else { // A float
- if (Writer_Excel5_BIFFwriter::getByteOrder()) { // if it's Big Endian
- $num = strrev($num);
- }
- return pack("Cd", $this->ptg['ptgNum'], $num);
- }
- }
+ /**
+ * Convert a number token to ptgInt or ptgNum
+ *
+ * @access private
+ * @param mixed $num an integer or double for conversion to its ptg value
+ */
+ function _convertNumber($num)
+ {
+ // Integer in the range 0..2**16-1
+ if ((preg_match("/^\d+$/", $num)) and ($num <= 65535)) {
+ return pack("Cv", $this->ptg['ptgInt'], $num);
+ } else { // A float
+ if (Writer_Excel5_BIFFwriter::getByteOrder()) { // if it's Big Endian
+ $num = strrev($num);
+ }
+ return pack("Cd", $this->ptg['ptgNum'], $num);
+ }
+ }
- /**
- * Convert a string token to ptgStr
- *
- * @access private
- * @param string $string A string for conversion to its ptg value.
- * @return mixed the converted token on success
- */
- function _convertString($string)
- {
- // chop away beggining and ending quotes
- $string = substr($string, 1, strlen($string) - 2);
- if (strlen($string) > 255) {
- throw new Writer_Exception("String is too long");
- }
+ /**
+ * Convert a string token to ptgStr
+ *
+ * @access private
+ * @param string $string A string for conversion to its ptg value.
+ * @return mixed the converted token on success
+ */
+ function _convertString($string)
+ {
+ // chop away beggining and ending quotes
+ $string = substr($string, 1, strlen($string) - 2);
+ if (strlen($string) > 255) {
+ throw new Writer_Exception("String is too long");
+ }
- return pack('C', $this->ptg['ptgStr']) . Shared_String::UTF8toBIFF8UnicodeShort($string);
- }
+ return pack('C', $this->ptg['ptgStr']) . Shared_String::UTF8toBIFF8UnicodeShort($string);
+ }
- /**
- * Convert a function to a ptgFunc or ptgFuncVarV depending on the number of
- * args that it takes.
- *
- * @access private
- * @param string $token The name of the function for convertion to ptg value.
- * @param integer $num_args The number of arguments the function receives.
- * @return string The packed ptg for the function
- */
- function _convertFunction($token, $num_args)
- {
- $args = $this->_functions[$token][1];
-// $volatile = $this->_functions[$token][3];
+ /**
+ * Convert a function to a ptgFunc or ptgFuncVarV depending on the number of
+ * args that it takes.
+ *
+ * @access private
+ * @param string $token The name of the function for convertion to ptg value.
+ * @param integer $num_args The number of arguments the function receives.
+ * @return string The packed ptg for the function
+ */
+ function _convertFunction($token, $num_args)
+ {
+ $args = $this->_functions[$token][1];
+// $volatile = $this->_functions[$token][3];
- // Fixed number of args eg. TIME($i,$j,$k).
- if ($args >= 0) {
- return pack("Cv", $this->ptg['ptgFuncV'], $this->_functions[$token][0]);
- }
- // Variable number of args eg. SUM($i,$j,$k, ..).
- if ($args == -1) {
- return pack("CCv", $this->ptg['ptgFuncVarV'], $num_args, $this->_functions[$token][0]);
- }
- }
+ // Fixed number of args eg. TIME($i,$j,$k).
+ if ($args >= 0) {
+ return pack("Cv", $this->ptg['ptgFuncV'], $this->_functions[$token][0]);
+ }
+ // Variable number of args eg. SUM($i,$j,$k, ..).
+ if ($args == -1) {
+ return pack("CCv", $this->ptg['ptgFuncVarV'], $num_args, $this->_functions[$token][0]);
+ }
+ }
- /**
- * Convert an Excel range such as A1:D4 to a ptgRefV.
- *
- * @access private
- * @param string $range An Excel range in the A1:A2
- * @param int $class
- */
- function _convertRange2d($range, $class=0)
- {
+ /**
+ * Convert an Excel range such as A1:D4 to a ptgRefV.
+ *
+ * @access private
+ * @param string $range An Excel range in the A1:A2
+ * @param int $class
+ */
+ function _convertRange2d($range, $class=0)
+ {
- // TODO: possible class value 0,1,2 check Formula.pm
- // Split the range into 2 cell refs
- if (preg_match('/^(\$)?([A-Ia-i]?[A-Za-z])(\$)?(\d+)\:(\$)?([A-Ia-i]?[A-Za-z])(\$)?(\d+)$/', $range)) {
- list($cell1, $cell2) = explode(':', $range);
- } else {
- // TODO: use real error codes
- throw new Writer_Exception("Unknown range separator");
- }
+ // TODO: possible class value 0,1,2 check Formula.pm
+ // Split the range into 2 cell refs
+ if (preg_match('/^(\$)?([A-Ia-i]?[A-Za-z])(\$)?(\d+)\:(\$)?([A-Ia-i]?[A-Za-z])(\$)?(\d+)$/', $range)) {
+ list($cell1, $cell2) = explode(':', $range);
+ } else {
+ // TODO: use real error codes
+ throw new Writer_Exception("Unknown range separator");
+ }
- // Convert the cell references
- list($row1, $col1) = $this->_cellToPackedRowcol($cell1);
- list($row2, $col2) = $this->_cellToPackedRowcol($cell2);
+ // Convert the cell references
+ list($row1, $col1) = $this->_cellToPackedRowcol($cell1);
+ list($row2, $col2) = $this->_cellToPackedRowcol($cell2);
- // The ptg value depends on the class of the ptg.
- if ($class == 0) {
- $ptgArea = pack("C", $this->ptg['ptgArea']);
- } elseif ($class == 1) {
- $ptgArea = pack("C", $this->ptg['ptgAreaV']);
- } elseif ($class == 2) {
- $ptgArea = pack("C", $this->ptg['ptgAreaA']);
- } else {
- // TODO: use real error codes
- throw new Writer_Exception("Unknown class $class");
- }
- return $ptgArea . $row1 . $row2 . $col1. $col2;
- }
+ // The ptg value depends on the class of the ptg.
+ if ($class == 0) {
+ $ptgArea = pack("C", $this->ptg['ptgArea']);
+ } elseif ($class == 1) {
+ $ptgArea = pack("C", $this->ptg['ptgAreaV']);
+ } elseif ($class == 2) {
+ $ptgArea = pack("C", $this->ptg['ptgAreaA']);
+ } else {
+ // TODO: use real error codes
+ throw new Writer_Exception("Unknown class $class");
+ }
+ return $ptgArea . $row1 . $row2 . $col1. $col2;
+ }
- /**
- * Convert an Excel 3d range such as "Sheet1!A1:D4" or "Sheet1:Sheet2!A1:D4" to
- * a ptgArea3d.
- *
- * @access private
- * @param string $token An Excel range in the Sheet1!A1:A2 format.
- * @return mixed The packed ptgArea3d token on success.
- */
- function _convertRange3d($token)
- {
-// $class = 0; // formulas like Sheet1!$A$1:$A$2 in list type data validation need this class (0x3B)
+ /**
+ * Convert an Excel 3d range such as "Sheet1!A1:D4" or "Sheet1:Sheet2!A1:D4" to
+ * a ptgArea3d.
+ *
+ * @access private
+ * @param string $token An Excel range in the Sheet1!A1:A2 format.
+ * @return mixed The packed ptgArea3d token on success.
+ */
+ function _convertRange3d($token)
+ {
+// $class = 0; // formulas like Sheet1!$A$1:$A$2 in list type data validation need this class (0x3B)
- // Split the ref at the ! symbol
- list($ext_ref, $range) = explode('!', $token);
+ // Split the ref at the ! symbol
+ list($ext_ref, $range) = explode('!', $token);
- // Convert the external reference part (different for BIFF8)
- $ext_ref = $this->_getRefIndex($ext_ref);
+ // Convert the external reference part (different for BIFF8)
+ $ext_ref = $this->_getRefIndex($ext_ref);
- // Split the range into 2 cell refs
- list($cell1, $cell2) = explode(':', $range);
+ // Split the range into 2 cell refs
+ list($cell1, $cell2) = explode(':', $range);
- // Convert the cell references
- if (preg_match("/^(\\$)?[A-Ia-i]?[A-Za-z](\\$)?(\d+)$/", $cell1)) {
- list($row1, $col1) = $this->_cellToPackedRowcol($cell1);
- list($row2, $col2) = $this->_cellToPackedRowcol($cell2);
- } else { // It's a rows range (like 26:27)
- list($row1, $col1, $row2, $col2) = $this->_rangeToPackedRange($cell1.':'.$cell2);
- }
+ // Convert the cell references
+ if (preg_match("/^(\\$)?[A-Ia-i]?[A-Za-z](\\$)?(\d+)$/", $cell1)) {
+ list($row1, $col1) = $this->_cellToPackedRowcol($cell1);
+ list($row2, $col2) = $this->_cellToPackedRowcol($cell2);
+ } else { // It's a rows range (like 26:27)
+ list($row1, $col1, $row2, $col2) = $this->_rangeToPackedRange($cell1.':'.$cell2);
+ }
- // The ptg value depends on the class of the ptg.
-// if ($class == 0) {
- $ptgArea = pack("C", $this->ptg['ptgArea3d']);
-// } elseif ($class == 1) {
-// $ptgArea = pack("C", $this->ptg['ptgArea3dV']);
-// } elseif ($class == 2) {
-// $ptgArea = pack("C", $this->ptg['ptgArea3dA']);
-// } else {
-// throw new Writer_Exception("Unknown class $class");
-// }
+ // The ptg value depends on the class of the ptg.
+// if ($class == 0) {
+ $ptgArea = pack("C", $this->ptg['ptgArea3d']);
+// } elseif ($class == 1) {
+// $ptgArea = pack("C", $this->ptg['ptgArea3dV']);
+// } elseif ($class == 2) {
+// $ptgArea = pack("C", $this->ptg['ptgArea3dA']);
+// } else {
+// throw new Writer_Exception("Unknown class $class");
+// }
- return $ptgArea . $ext_ref . $row1 . $row2 . $col1. $col2;
- }
+ return $ptgArea . $ext_ref . $row1 . $row2 . $col1. $col2;
+ }
- /**
- * Convert an Excel reference such as A1, $B2, C$3 or $D$4 to a ptgRefV.
- *
- * @access private
- * @param string $cell An Excel cell reference
- * @return string The cell in packed() format with the corresponding ptg
- */
- function _convertRef2d($cell)
- {
-// $class = 2; // as far as I know, this is magick.
+ /**
+ * Convert an Excel reference such as A1, $B2, C$3 or $D$4 to a ptgRefV.
+ *
+ * @access private
+ * @param string $cell An Excel cell reference
+ * @return string The cell in packed() format with the corresponding ptg
+ */
+ function _convertRef2d($cell)
+ {
+// $class = 2; // as far as I know, this is magick.
- // Convert the cell reference
- $cell_array = $this->_cellToPackedRowcol($cell);
- list($row, $col) = $cell_array;
+ // Convert the cell reference
+ $cell_array = $this->_cellToPackedRowcol($cell);
+ list($row, $col) = $cell_array;
- // The ptg value depends on the class of the ptg.
-// if ($class == 0) {
-// $ptgRef = pack("C", $this->ptg['ptgRef']);
-// } elseif ($class == 1) {
-// $ptgRef = pack("C", $this->ptg['ptgRefV']);
-// } elseif ($class == 2) {
- $ptgRef = pack("C", $this->ptg['ptgRefA']);
-// } else {
-// // TODO: use real error codes
-// throw new Writer_Exception("Unknown class $class");
-// }
- return $ptgRef.$row.$col;
- }
+ // The ptg value depends on the class of the ptg.
+// if ($class == 0) {
+// $ptgRef = pack("C", $this->ptg['ptgRef']);
+// } elseif ($class == 1) {
+// $ptgRef = pack("C", $this->ptg['ptgRefV']);
+// } elseif ($class == 2) {
+ $ptgRef = pack("C", $this->ptg['ptgRefA']);
+// } else {
+// // TODO: use real error codes
+// throw new Writer_Exception("Unknown class $class");
+// }
+ return $ptgRef.$row.$col;
+ }
- /**
- * Convert an Excel 3d reference such as "Sheet1!A1" or "Sheet1:Sheet2!A1" to a
- * ptgRef3d.
- *
- * @access private
- * @param string $cell An Excel cell reference
- * @return mixed The packed ptgRef3d token on success.
- */
- function _convertRef3d($cell)
- {
-// $class = 2; // as far as I know, this is magick.
+ /**
+ * Convert an Excel 3d reference such as "Sheet1!A1" or "Sheet1:Sheet2!A1" to a
+ * ptgRef3d.
+ *
+ * @access private
+ * @param string $cell An Excel cell reference
+ * @return mixed The packed ptgRef3d token on success.
+ */
+ function _convertRef3d($cell)
+ {
+// $class = 2; // as far as I know, this is magick.
- // Split the ref at the ! symbol
- list($ext_ref, $cell) = explode('!', $cell);
+ // Split the ref at the ! symbol
+ list($ext_ref, $cell) = explode('!', $cell);
- // Convert the external reference part (different for BIFF8)
- $ext_ref = $this->_getRefIndex($ext_ref);
+ // Convert the external reference part (different for BIFF8)
+ $ext_ref = $this->_getRefIndex($ext_ref);
- // Convert the cell reference part
- list($row, $col) = $this->_cellToPackedRowcol($cell);
+ // Convert the cell reference part
+ list($row, $col) = $this->_cellToPackedRowcol($cell);
- // The ptg value depends on the class of the ptg.
-// if ($class == 0) {
-// $ptgRef = pack("C", $this->ptg['ptgRef3d']);
-// } elseif ($class == 1) {
-// $ptgRef = pack("C", $this->ptg['ptgRef3dV']);
-// } elseif ($class == 2) {
- $ptgRef = pack("C", $this->ptg['ptgRef3dA']);
-// } else {
-// throw new Writer_Exception("Unknown class $class");
-// }
+ // The ptg value depends on the class of the ptg.
+// if ($class == 0) {
+// $ptgRef = pack("C", $this->ptg['ptgRef3d']);
+// } elseif ($class == 1) {
+// $ptgRef = pack("C", $this->ptg['ptgRef3dV']);
+// } elseif ($class == 2) {
+ $ptgRef = pack("C", $this->ptg['ptgRef3dA']);
+// } else {
+// throw new Writer_Exception("Unknown class $class");
+// }
- return $ptgRef . $ext_ref. $row . $col;
- }
+ return $ptgRef . $ext_ref. $row . $col;
+ }
/**
* Convert an error code to a ptgErr
*
- * @access private
- * @param string $errorCode The error code for conversion to its ptg value
- * @return string The error code ptgErr
+ * @access private
+ * @param string $errorCode The error code for conversion to its ptg value
+ * @return string The error code ptgErr
*/
function _convertError($errorCode)
{
- switch ($errorCode) {
- case '#NULL!': return pack("C", 0x00);
- case '#DIV/0!': return pack("C", 0x07);
- case '#VALUE!': return pack("C", 0x0F);
- case '#REF!': return pack("C", 0x17);
- case '#NAME?': return pack("C", 0x1D);
- case '#NUM!': return pack("C", 0x24);
- case '#N/A': return pack("C", 0x2A);
- }
- return pack("C", 0xFF);
+ switch ($errorCode) {
+ case '#NULL!': return pack("C", 0x00);
+ case '#DIV/0!': return pack("C", 0x07);
+ case '#VALUE!': return pack("C", 0x0F);
+ case '#REF!': return pack("C", 0x17);
+ case '#NAME?': return pack("C", 0x1D);
+ case '#NUM!': return pack("C", 0x24);
+ case '#N/A': return pack("C", 0x2A);
+ }
+ return pack("C", 0xFF);
}
- /**
- * Convert the sheet name part of an external reference, for example "Sheet1" or
- * "Sheet1:Sheet2", to a packed structure.
- *
- * @access private
- * @param string $ext_ref The name of the external reference
- * @return string The reference index in packed() format
- */
- function _packExtRef($ext_ref)
- {
- $ext_ref = preg_replace("/^'/", '', $ext_ref); // Remove leading ' if any.
- $ext_ref = preg_replace("/'$/", '', $ext_ref); // Remove trailing ' if any.
+ /**
+ * Convert the sheet name part of an external reference, for example "Sheet1" or
+ * "Sheet1:Sheet2", to a packed structure.
+ *
+ * @access private
+ * @param string $ext_ref The name of the external reference
+ * @return string The reference index in packed() format
+ */
+ function _packExtRef($ext_ref)
+ {
+ $ext_ref = preg_replace("/^'/", '', $ext_ref); // Remove leading ' if any.
+ $ext_ref = preg_replace("/'$/", '', $ext_ref); // Remove trailing ' if any.
- // Check if there is a sheet range eg., Sheet1:Sheet2.
- if (preg_match("/:/", $ext_ref)) {
- list($sheet_name1, $sheet_name2) = explode(':', $ext_ref);
+ // Check if there is a sheet range eg., Sheet1:Sheet2.
+ if (preg_match("/:/", $ext_ref)) {
+ list($sheet_name1, $sheet_name2) = explode(':', $ext_ref);
- $sheet1 = $this->_getSheetIndex($sheet_name1);
- if ($sheet1 == -1) {
- throw new Writer_Exception("Unknown sheet name $sheet_name1 in formula");
- }
- $sheet2 = $this->_getSheetIndex($sheet_name2);
- if ($sheet2 == -1) {
- throw new Writer_Exception("Unknown sheet name $sheet_name2 in formula");
- }
+ $sheet1 = $this->_getSheetIndex($sheet_name1);
+ if ($sheet1 == -1) {
+ throw new Writer_Exception("Unknown sheet name $sheet_name1 in formula");
+ }
+ $sheet2 = $this->_getSheetIndex($sheet_name2);
+ if ($sheet2 == -1) {
+ throw new Writer_Exception("Unknown sheet name $sheet_name2 in formula");
+ }
- // Reverse max and min sheet numbers if necessary
- if ($sheet1 > $sheet2) {
- list($sheet1, $sheet2) = array($sheet2, $sheet1);
- }
- } else { // Single sheet name only.
- $sheet1 = $this->_getSheetIndex($ext_ref);
- if ($sheet1 == -1) {
- throw new Writer_Exception("Unknown sheet name $ext_ref in formula");
- }
- $sheet2 = $sheet1;
- }
+ // Reverse max and min sheet numbers if necessary
+ if ($sheet1 > $sheet2) {
+ list($sheet1, $sheet2) = array($sheet2, $sheet1);
+ }
+ } else { // Single sheet name only.
+ $sheet1 = $this->_getSheetIndex($ext_ref);
+ if ($sheet1 == -1) {
+ throw new Writer_Exception("Unknown sheet name $ext_ref in formula");
+ }
+ $sheet2 = $sheet1;
+ }
- // References are stored relative to 0xFFFF.
- $offset = -1 - $sheet1;
+ // References are stored relative to 0xFFFF.
+ $offset = -1 - $sheet1;
- return pack('vdvv', $offset, 0x00, $sheet1, $sheet2);
- }
+ return pack('vdvv', $offset, 0x00, $sheet1, $sheet2);
+ }
- /**
- * Look up the REF index that corresponds to an external sheet name
- * (or range). If it doesn't exist yet add it to the workbook's references
- * array. It assumes all sheet names given must exist.
- *
- * @access private
- * @param string $ext_ref The name of the external reference
- * @return mixed The reference index in packed() format on success
- */
- function _getRefIndex($ext_ref)
- {
- $ext_ref = preg_replace("/^'/", '', $ext_ref); // Remove leading ' if any.
- $ext_ref = preg_replace("/'$/", '', $ext_ref); // Remove trailing ' if any.
- $ext_ref = str_replace('\'\'', '\'', $ext_ref); // Replace escaped '' with '
+ /**
+ * Look up the REF index that corresponds to an external sheet name
+ * (or range). If it doesn't exist yet add it to the workbook's references
+ * array. It assumes all sheet names given must exist.
+ *
+ * @access private
+ * @param string $ext_ref The name of the external reference
+ * @return mixed The reference index in packed() format on success
+ */
+ function _getRefIndex($ext_ref)
+ {
+ $ext_ref = preg_replace("/^'/", '', $ext_ref); // Remove leading ' if any.
+ $ext_ref = preg_replace("/'$/", '', $ext_ref); // Remove trailing ' if any.
+ $ext_ref = str_replace('\'\'', '\'', $ext_ref); // Replace escaped '' with '
- // Check if there is a sheet range eg., Sheet1:Sheet2.
- if (preg_match("/:/", $ext_ref)) {
- list($sheet_name1, $sheet_name2) = explode(':', $ext_ref);
+ // Check if there is a sheet range eg., Sheet1:Sheet2.
+ if (preg_match("/:/", $ext_ref)) {
+ list($sheet_name1, $sheet_name2) = explode(':', $ext_ref);
- $sheet1 = $this->_getSheetIndex($sheet_name1);
- if ($sheet1 == -1) {
- throw new Writer_Exception("Unknown sheet name $sheet_name1 in formula");
- }
- $sheet2 = $this->_getSheetIndex($sheet_name2);
- if ($sheet2 == -1) {
- throw new Writer_Exception("Unknown sheet name $sheet_name2 in formula");
- }
+ $sheet1 = $this->_getSheetIndex($sheet_name1);
+ if ($sheet1 == -1) {
+ throw new Writer_Exception("Unknown sheet name $sheet_name1 in formula");
+ }
+ $sheet2 = $this->_getSheetIndex($sheet_name2);
+ if ($sheet2 == -1) {
+ throw new Writer_Exception("Unknown sheet name $sheet_name2 in formula");
+ }
- // Reverse max and min sheet numbers if necessary
- if ($sheet1 > $sheet2) {
- list($sheet1, $sheet2) = array($sheet2, $sheet1);
- }
- } else { // Single sheet name only.
- $sheet1 = $this->_getSheetIndex($ext_ref);
- if ($sheet1 == -1) {
- throw new Writer_Exception("Unknown sheet name $ext_ref in formula");
- }
- $sheet2 = $sheet1;
- }
+ // Reverse max and min sheet numbers if necessary
+ if ($sheet1 > $sheet2) {
+ list($sheet1, $sheet2) = array($sheet2, $sheet1);
+ }
+ } else { // Single sheet name only.
+ $sheet1 = $this->_getSheetIndex($ext_ref);
+ if ($sheet1 == -1) {
+ throw new Writer_Exception("Unknown sheet name $ext_ref in formula");
+ }
+ $sheet2 = $sheet1;
+ }
- // assume all references belong to this document
- $supbook_index = 0x00;
- $ref = pack('vvv', $supbook_index, $sheet1, $sheet2);
- $total_references = count($this->_references);
- $index = -1;
- for ($i = 0; $i < $total_references; ++$i) {
- if ($ref == $this->_references[$i]) {
- $index = $i;
- break;
- }
- }
- // if REF was not found add it to references array
- if ($index == -1) {
- $this->_references[$total_references] = $ref;
- $index = $total_references;
- }
+ // assume all references belong to this document
+ $supbook_index = 0x00;
+ $ref = pack('vvv', $supbook_index, $sheet1, $sheet2);
+ $total_references = count($this->_references);
+ $index = -1;
+ for ($i = 0; $i < $total_references; ++$i) {
+ if ($ref == $this->_references[$i]) {
+ $index = $i;
+ break;
+ }
+ }
+ // if REF was not found add it to references array
+ if ($index == -1) {
+ $this->_references[$total_references] = $ref;
+ $index = $total_references;
+ }
- return pack('v', $index);
- }
+ return pack('v', $index);
+ }
- /**
- * Look up the index that corresponds to an external sheet name. The hash of
- * sheet names is updated by the addworksheet() method of the
- * PHPExcel\Writer_Excel5_Workbook class.
- *
- * @access private
- * @param string $sheet_name Sheet name
- * @return integer The sheet index, -1 if the sheet was not found
- */
- function _getSheetIndex($sheet_name)
- {
- if (!isset($this->_ext_sheets[$sheet_name])) {
- return -1;
- } else {
- return $this->_ext_sheets[$sheet_name];
- }
- }
+ /**
+ * Look up the index that corresponds to an external sheet name. The hash of
+ * sheet names is updated by the addworksheet() method of the
+ * PHPExcel\Writer_Excel5_Workbook class.
+ *
+ * @access private
+ * @param string $sheet_name Sheet name
+ * @return integer The sheet index, -1 if the sheet was not found
+ */
+ function _getSheetIndex($sheet_name)
+ {
+ if (!isset($this->_ext_sheets[$sheet_name])) {
+ return -1;
+ } else {
+ return $this->_ext_sheets[$sheet_name];
+ }
+ }
- /**
- * This method is used to update the array of sheet names. It is
- * called by the addWorksheet() method of the
- * PHPExcel\Writer_Excel5_Workbook class.
- *
- * @access public
- * @see PHPExcel\Writer_Excel5_Workbook::addWorksheet()
- * @param string $name The name of the worksheet being added
- * @param integer $index The index of the worksheet being added
- */
- function setExtSheet($name, $index)
- {
- $this->_ext_sheets[$name] = $index;
- }
+ /**
+ * This method is used to update the array of sheet names. It is
+ * called by the addWorksheet() method of the
+ * PHPExcel\Writer_Excel5_Workbook class.
+ *
+ * @access public
+ * @see PHPExcel\Writer_Excel5_Workbook::addWorksheet()
+ * @param string $name The name of the worksheet being added
+ * @param integer $index The index of the worksheet being added
+ */
+ function setExtSheet($name, $index)
+ {
+ $this->_ext_sheets[$name] = $index;
+ }
- /**
- * pack() row and column into the required 3 or 4 byte format.
- *
- * @access private
- * @param string $cell The Excel cell reference to be packed
- * @return array Array containing the row and column in packed() format
- */
- function _cellToPackedRowcol($cell)
- {
- $cell = strtoupper($cell);
- list($row, $col, $row_rel, $col_rel) = $this->_cellToRowcol($cell);
- if ($col >= 256) {
- throw new Writer_Exception("Column in: $cell greater than 255");
- }
- if ($row >= 65536) {
- throw new Writer_Exception("Row in: $cell greater than 65536 ");
- }
+ /**
+ * pack() row and column into the required 3 or 4 byte format.
+ *
+ * @access private
+ * @param string $cell The Excel cell reference to be packed
+ * @return array Array containing the row and column in packed() format
+ */
+ function _cellToPackedRowcol($cell)
+ {
+ $cell = strtoupper($cell);
+ list($row, $col, $row_rel, $col_rel) = $this->_cellToRowcol($cell);
+ if ($col >= 256) {
+ throw new Writer_Exception("Column in: $cell greater than 255");
+ }
+ if ($row >= 65536) {
+ throw new Writer_Exception("Row in: $cell greater than 65536 ");
+ }
- // Set the high bits to indicate if row or col are relative.
- $col |= $col_rel << 14;
- $col |= $row_rel << 15;
- $col = pack('v', $col);
+ // Set the high bits to indicate if row or col are relative.
+ $col |= $col_rel << 14;
+ $col |= $row_rel << 15;
+ $col = pack('v', $col);
- $row = pack('v', $row);
+ $row = pack('v', $row);
- return array($row, $col);
- }
+ return array($row, $col);
+ }
- /**
- * pack() row range into the required 3 or 4 byte format.
- * Just using maximum col/rows, which is probably not the correct solution
- *
- * @access private
- * @param string $range The Excel range to be packed
- * @return array Array containing (row1,col1,row2,col2) in packed() format
- */
- function _rangeToPackedRange($range)
- {
- preg_match('/(\$)?(\d+)\:(\$)?(\d+)/', $range, $match);
- // return absolute rows if there is a $ in the ref
- $row1_rel = empty($match[1]) ? 1 : 0;
- $row1 = $match[2];
- $row2_rel = empty($match[3]) ? 1 : 0;
- $row2 = $match[4];
- // Convert 1-index to zero-index
- --$row1;
- --$row2;
- // Trick poor inocent Excel
- $col1 = 0;
- $col2 = 65535; // FIXME: maximum possible value for Excel 5 (change this!!!)
+ /**
+ * pack() row range into the required 3 or 4 byte format.
+ * Just using maximum col/rows, which is probably not the correct solution
+ *
+ * @access private
+ * @param string $range The Excel range to be packed
+ * @return array Array containing (row1,col1,row2,col2) in packed() format
+ */
+ function _rangeToPackedRange($range)
+ {
+ preg_match('/(\$)?(\d+)\:(\$)?(\d+)/', $range, $match);
+ // return absolute rows if there is a $ in the ref
+ $row1_rel = empty($match[1]) ? 1 : 0;
+ $row1 = $match[2];
+ $row2_rel = empty($match[3]) ? 1 : 0;
+ $row2 = $match[4];
+ // Convert 1-index to zero-index
+ --$row1;
+ --$row2;
+ // Trick poor inocent Excel
+ $col1 = 0;
+ $col2 = 65535; // FIXME: maximum possible value for Excel 5 (change this!!!)
- // FIXME: this changes for BIFF8
- if (($row1 >= 65536) or ($row2 >= 65536)) {
- throw new Writer_Exception("Row in: $range greater than 65536 ");
- }
+ // FIXME: this changes for BIFF8
+ if (($row1 >= 65536) or ($row2 >= 65536)) {
+ throw new Writer_Exception("Row in: $range greater than 65536 ");
+ }
- // Set the high bits to indicate if rows are relative.
- $col1 |= $row1_rel << 15;
- $col2 |= $row2_rel << 15;
- $col1 = pack('v', $col1);
- $col2 = pack('v', $col2);
+ // Set the high bits to indicate if rows are relative.
+ $col1 |= $row1_rel << 15;
+ $col2 |= $row2_rel << 15;
+ $col1 = pack('v', $col1);
+ $col2 = pack('v', $col2);
- $row1 = pack('v', $row1);
- $row2 = pack('v', $row2);
+ $row1 = pack('v', $row1);
+ $row2 = pack('v', $row2);
- return array($row1, $col1, $row2, $col2);
- }
+ return array($row1, $col1, $row2, $col2);
+ }
- /**
- * Convert an Excel cell reference such as A1 or $B2 or C$3 or $D$4 to a zero
- * indexed row and column number. Also returns two (0,1) values to indicate
- * whether the row or column are relative references.
- *
- * @access private
- * @param string $cell The Excel cell reference in A1 format.
- * @return array
- */
- function _cellToRowcol($cell)
- {
- preg_match('/(\$)?([A-I]?[A-Z])(\$)?(\d+)/',$cell,$match);
- // return absolute column if there is a $ in the ref
- $col_rel = empty($match[1]) ? 1 : 0;
- $col_ref = $match[2];
- $row_rel = empty($match[3]) ? 1 : 0;
- $row = $match[4];
+ /**
+ * Convert an Excel cell reference such as A1 or $B2 or C$3 or $D$4 to a zero
+ * indexed row and column number. Also returns two (0,1) values to indicate
+ * whether the row or column are relative references.
+ *
+ * @access private
+ * @param string $cell The Excel cell reference in A1 format.
+ * @return array
+ */
+ function _cellToRowcol($cell)
+ {
+ preg_match('/(\$)?([A-I]?[A-Z])(\$)?(\d+)/',$cell,$match);
+ // return absolute column if there is a $ in the ref
+ $col_rel = empty($match[1]) ? 1 : 0;
+ $col_ref = $match[2];
+ $row_rel = empty($match[3]) ? 1 : 0;
+ $row = $match[4];
- // Convert base26 column string to a number.
- $expn = strlen($col_ref) - 1;
- $col = 0;
- $col_ref_length = strlen($col_ref);
- for ($i = 0; $i < $col_ref_length; ++$i) {
- $col += (ord($col_ref{$i}) - 64) * pow(26, $expn);
- --$expn;
- }
+ // Convert base26 column string to a number.
+ $expn = strlen($col_ref) - 1;
+ $col = 0;
+ $col_ref_length = strlen($col_ref);
+ for ($i = 0; $i < $col_ref_length; ++$i) {
+ $col += (ord($col_ref{$i}) - 64) * pow(26, $expn);
+ --$expn;
+ }
- // Convert 1-index to zero-index
- --$row;
- --$col;
+ // Convert 1-index to zero-index
+ --$row;
+ --$col;
- return array($row, $col, $row_rel, $col_rel);
- }
+ return array($row, $col, $row_rel, $col_rel);
+ }
- /**
- * Advance to the next valid token.
- *
- * @access private
- */
- function _advance()
- {
- $i = $this->_current_char;
- $formula_length = strlen($this->_formula);
- // eat up white spaces
- if ($i < $formula_length) {
- while ($this->_formula{$i} == " ") {
- ++$i;
- }
+ /**
+ * Advance to the next valid token.
+ *
+ * @access private
+ */
+ function _advance()
+ {
+ $i = $this->_current_char;
+ $formula_length = strlen($this->_formula);
+ // eat up white spaces
+ if ($i < $formula_length) {
+ while ($this->_formula{$i} == " ") {
+ ++$i;
+ }
- if ($i < ($formula_length - 1)) {
- $this->_lookahead = $this->_formula{$i+1};
- }
- $token = '';
- }
+ if ($i < ($formula_length - 1)) {
+ $this->_lookahead = $this->_formula{$i+1};
+ }
+ $token = '';
+ }
- while ($i < $formula_length) {
- $token .= $this->_formula{$i};
+ while ($i < $formula_length) {
+ $token .= $this->_formula{$i};
- if ($i < ($formula_length - 1)) {
- $this->_lookahead = $this->_formula{$i+1};
- } else {
- $this->_lookahead = '';
- }
+ if ($i < ($formula_length - 1)) {
+ $this->_lookahead = $this->_formula{$i+1};
+ } else {
+ $this->_lookahead = '';
+ }
- if ($this->_match($token) != '') {
- //if ($i < strlen($this->_formula) - 1) {
- // $this->_lookahead = $this->_formula{$i+1};
- //}
- $this->_current_char = $i + 1;
- $this->_current_token = $token;
- return 1;
- }
+ if ($this->_match($token) != '') {
+ //if ($i < strlen($this->_formula) - 1) {
+ // $this->_lookahead = $this->_formula{$i+1};
+ //}
+ $this->_current_char = $i + 1;
+ $this->_current_token = $token;
+ return 1;
+ }
- if ($i < ($formula_length - 2)) {
- $this->_lookahead = $this->_formula{$i+2};
- } else { // if we run out of characters _lookahead becomes empty
- $this->_lookahead = '';
- }
- ++$i;
- }
- //die("Lexical error ".$this->_current_char);
- }
+ if ($i < ($formula_length - 2)) {
+ $this->_lookahead = $this->_formula{$i+2};
+ } else { // if we run out of characters _lookahead becomes empty
+ $this->_lookahead = '';
+ }
+ ++$i;
+ }
+ //die("Lexical error ".$this->_current_char);
+ }
- /**
- * Checks if it's a valid token.
- *
- * @access private
- * @param mixed $token The token to check.
- * @return mixed The checked token or false on failure
- */
- function _match($token)
- {
- switch($token) {
- case "+":
- case "-":
- case "*":
- case "/":
- case "(":
- case ")":
- case ",":
- case ";":
- case ">=":
- case "<=":
- case "=":
- case "<>":
- case "^":
- case "&":
- case "%":
- return $token;
- break;
- case ">":
- if ($this->_lookahead == '=') { // it's a GE token
- break;
- }
- return $token;
- break;
- case "<":
- // it's a LE or a NE token
- if (($this->_lookahead == '=') or ($this->_lookahead == '>')) {
- break;
- }
- return $token;
- break;
- default:
- // if it's a reference A1 or $A$1 or $A1 or A$1
- if (preg_match('/^\$?[A-Ia-i]?[A-Za-z]\$?[0-9]+$/',$token) and
- !preg_match("/[0-9]/",$this->_lookahead) and
- ($this->_lookahead != ':') and ($this->_lookahead != '.') and
- ($this->_lookahead != '!'))
- {
- return $token;
- }
- // If it's an external reference (Sheet1!A1 or Sheet1:Sheet2!A1 or Sheet1!$A$1 or Sheet1:Sheet2!$A$1)
- elseif (preg_match("/^" . self::REGEX_SHEET_TITLE_UNQUOTED . "(\:" . self::REGEX_SHEET_TITLE_UNQUOTED . ")?\!\\$?[A-Ia-i]?[A-Za-z]\\$?[0-9]+$/u",$token) and
- !preg_match("/[0-9]/",$this->_lookahead) and
- ($this->_lookahead != ':') and ($this->_lookahead != '.'))
- {
- return $token;
- }
- // If it's an external reference ('Sheet1'!A1 or 'Sheet1:Sheet2'!A1 or 'Sheet1'!$A$1 or 'Sheet1:Sheet2'!$A$1)
- elseif (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . "(\:" . self::REGEX_SHEET_TITLE_QUOTED . ")?'\!\\$?[A-Ia-i]?[A-Za-z]\\$?[0-9]+$/u",$token) and
- !preg_match("/[0-9]/",$this->_lookahead) and
- ($this->_lookahead != ':') and ($this->_lookahead != '.'))
- {
- return $token;
- }
- // if it's a range A1:A2 or $A$1:$A$2
- elseif (preg_match('/^(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+:(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+$/', $token) and
- !preg_match("/[0-9]/",$this->_lookahead))
- {
- return $token;
- }
- // If it's an external range like Sheet1!A1:B2 or Sheet1:Sheet2!A1:B2 or Sheet1!$A$1:$B$2 or Sheet1:Sheet2!$A$1:$B$2
- elseif (preg_match("/^" . self::REGEX_SHEET_TITLE_UNQUOTED . "(\:" . self::REGEX_SHEET_TITLE_UNQUOTED . ")?\!\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+:\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+$/u",$token) and
- !preg_match("/[0-9]/",$this->_lookahead))
- {
- return $token;
- }
- // If it's an external range like 'Sheet1'!A1:B2 or 'Sheet1:Sheet2'!A1:B2 or 'Sheet1'!$A$1:$B$2 or 'Sheet1:Sheet2'!$A$1:$B$2
- elseif (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . "(\:" . self::REGEX_SHEET_TITLE_QUOTED . ")?'\!\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+:\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+$/u",$token) and
- !preg_match("/[0-9]/",$this->_lookahead))
- {
- return $token;
- }
- // If it's a number (check that it's not a sheet name or range)
- elseif (is_numeric($token) and
- (!is_numeric($token.$this->_lookahead) or ($this->_lookahead == '')) and
- ($this->_lookahead != '!') and ($this->_lookahead != ':'))
- {
- return $token;
- }
- // If it's a string (of maximum 255 characters)
- elseif (preg_match("/\"([^\"]|\"\"){0,255}\"/",$token) and $this->_lookahead != '"' and (substr_count($token, '"')%2 == 0))
- {
- return $token;
- }
- // If it's an error code
- elseif (preg_match("/^#[A-Z0\/]{3,5}[!?]{1}$/", $token) or $token == '#N/A')
- {
- return $token;
- }
- // if it's a function call
- elseif (preg_match("/^[A-Z0-9\xc0-\xdc\.]+$/i",$token) and ($this->_lookahead == "("))
- {
- return $token;
- }
- // It's an argument of some description (e.g. a named range),
- // precise nature yet to be determined
- elseif(substr($token,-1) == ')') {
- return $token;
- }
- return '';
- }
- }
+ /**
+ * Checks if it's a valid token.
+ *
+ * @access private
+ * @param mixed $token The token to check.
+ * @return mixed The checked token or false on failure
+ */
+ function _match($token)
+ {
+ switch($token) {
+ case "+":
+ case "-":
+ case "*":
+ case "/":
+ case "(":
+ case ")":
+ case ",":
+ case ";":
+ case ">=":
+ case "<=":
+ case "=":
+ case "<>":
+ case "^":
+ case "&":
+ case "%":
+ return $token;
+ break;
+ case ">":
+ if ($this->_lookahead == '=') { // it's a GE token
+ break;
+ }
+ return $token;
+ break;
+ case "<":
+ // it's a LE or a NE token
+ if (($this->_lookahead == '=') or ($this->_lookahead == '>')) {
+ break;
+ }
+ return $token;
+ break;
+ default:
+ // if it's a reference A1 or $A$1 or $A1 or A$1
+ if (preg_match('/^\$?[A-Ia-i]?[A-Za-z]\$?[0-9]+$/',$token) and
+ !preg_match("/[0-9]/",$this->_lookahead) and
+ ($this->_lookahead != ':') and ($this->_lookahead != '.') and
+ ($this->_lookahead != '!'))
+ {
+ return $token;
+ }
+ // If it's an external reference (Sheet1!A1 or Sheet1:Sheet2!A1 or Sheet1!$A$1 or Sheet1:Sheet2!$A$1)
+ elseif (preg_match("/^" . self::REGEX_SHEET_TITLE_UNQUOTED . "(\:" . self::REGEX_SHEET_TITLE_UNQUOTED . ")?\!\\$?[A-Ia-i]?[A-Za-z]\\$?[0-9]+$/u",$token) and
+ !preg_match("/[0-9]/",$this->_lookahead) and
+ ($this->_lookahead != ':') and ($this->_lookahead != '.'))
+ {
+ return $token;
+ }
+ // If it's an external reference ('Sheet1'!A1 or 'Sheet1:Sheet2'!A1 or 'Sheet1'!$A$1 or 'Sheet1:Sheet2'!$A$1)
+ elseif (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . "(\:" . self::REGEX_SHEET_TITLE_QUOTED . ")?'\!\\$?[A-Ia-i]?[A-Za-z]\\$?[0-9]+$/u",$token) and
+ !preg_match("/[0-9]/",$this->_lookahead) and
+ ($this->_lookahead != ':') and ($this->_lookahead != '.'))
+ {
+ return $token;
+ }
+ // if it's a range A1:A2 or $A$1:$A$2
+ elseif (preg_match('/^(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+:(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+$/', $token) and
+ !preg_match("/[0-9]/",$this->_lookahead))
+ {
+ return $token;
+ }
+ // If it's an external range like Sheet1!A1:B2 or Sheet1:Sheet2!A1:B2 or Sheet1!$A$1:$B$2 or Sheet1:Sheet2!$A$1:$B$2
+ elseif (preg_match("/^" . self::REGEX_SHEET_TITLE_UNQUOTED . "(\:" . self::REGEX_SHEET_TITLE_UNQUOTED . ")?\!\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+:\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+$/u",$token) and
+ !preg_match("/[0-9]/",$this->_lookahead))
+ {
+ return $token;
+ }
+ // If it's an external range like 'Sheet1'!A1:B2 or 'Sheet1:Sheet2'!A1:B2 or 'Sheet1'!$A$1:$B$2 or 'Sheet1:Sheet2'!$A$1:$B$2
+ elseif (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . "(\:" . self::REGEX_SHEET_TITLE_QUOTED . ")?'\!\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+:\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+$/u",$token) and
+ !preg_match("/[0-9]/",$this->_lookahead))
+ {
+ return $token;
+ }
+ // If it's a number (check that it's not a sheet name or range)
+ elseif (is_numeric($token) and
+ (!is_numeric($token.$this->_lookahead) or ($this->_lookahead == '')) and
+ ($this->_lookahead != '!') and ($this->_lookahead != ':'))
+ {
+ return $token;
+ }
+ // If it's a string (of maximum 255 characters)
+ elseif (preg_match("/\"([^\"]|\"\"){0,255}\"/",$token) and $this->_lookahead != '"' and (substr_count($token, '"')%2 == 0))
+ {
+ return $token;
+ }
+ // If it's an error code
+ elseif (preg_match("/^#[A-Z0\/]{3,5}[!?]{1}$/", $token) or $token == '#N/A')
+ {
+ return $token;
+ }
+ // if it's a function call
+ elseif (preg_match("/^[A-Z0-9\xc0-\xdc\.]+$/i",$token) and ($this->_lookahead == "("))
+ {
+ return $token;
+ }
+ // It's an argument of some description (e.g. a named range),
+ // precise nature yet to be determined
+ elseif(substr($token,-1) == ')') {
+ return $token;
+ }
+ return '';
+ }
+ }
- /**
- * The parsing method. It parses a formula.
- *
- * @access public
- * @param string $formula The formula to parse, without the initial equal
- * sign (=).
- * @return mixed true on success
- */
- function parse($formula)
- {
- $this->_current_char = 0;
- $this->_formula = $formula;
- $this->_lookahead = isset($formula{1}) ? $formula{1} : '';
- $this->_advance();
- $this->_parse_tree = $this->_condition();
- return true;
- }
+ /**
+ * The parsing method. It parses a formula.
+ *
+ * @access public
+ * @param string $formula The formula to parse, without the initial equal
+ * sign (=).
+ * @return mixed true on success
+ */
+ function parse($formula)
+ {
+ $this->_current_char = 0;
+ $this->_formula = $formula;
+ $this->_lookahead = isset($formula{1}) ? $formula{1} : '';
+ $this->_advance();
+ $this->_parse_tree = $this->_condition();
+ return true;
+ }
- /**
- * It parses a condition. It assumes the following rule:
- * Cond -> Expr [(">" | "<") Expr]
- *
- * @access private
- * @return mixed The parsed ptg'd tree on success
- */
- function _condition()
- {
- $result = $this->_expression();
- if ($this->_current_token == "<") {
- $this->_advance();
- $result2 = $this->_expression();
- $result = $this->_createTree('ptgLT', $result, $result2);
- } elseif ($this->_current_token == ">") {
- $this->_advance();
- $result2 = $this->_expression();
- $result = $this->_createTree('ptgGT', $result, $result2);
- } elseif ($this->_current_token == "<=") {
- $this->_advance();
- $result2 = $this->_expression();
- $result = $this->_createTree('ptgLE', $result, $result2);
- } elseif ($this->_current_token == ">=") {
- $this->_advance();
- $result2 = $this->_expression();
- $result = $this->_createTree('ptgGE', $result, $result2);
- } elseif ($this->_current_token == "=") {
- $this->_advance();
- $result2 = $this->_expression();
- $result = $this->_createTree('ptgEQ', $result, $result2);
- } elseif ($this->_current_token == "<>") {
- $this->_advance();
- $result2 = $this->_expression();
- $result = $this->_createTree('ptgNE', $result, $result2);
- } elseif ($this->_current_token == "&") {
- $this->_advance();
- $result2 = $this->_expression();
- $result = $this->_createTree('ptgConcat', $result, $result2);
- }
- return $result;
- }
+ /**
+ * It parses a condition. It assumes the following rule:
+ * Cond -> Expr [(">" | "<") Expr]
+ *
+ * @access private
+ * @return mixed The parsed ptg'd tree on success
+ */
+ function _condition()
+ {
+ $result = $this->_expression();
+ if ($this->_current_token == "<") {
+ $this->_advance();
+ $result2 = $this->_expression();
+ $result = $this->_createTree('ptgLT', $result, $result2);
+ } elseif ($this->_current_token == ">") {
+ $this->_advance();
+ $result2 = $this->_expression();
+ $result = $this->_createTree('ptgGT', $result, $result2);
+ } elseif ($this->_current_token == "<=") {
+ $this->_advance();
+ $result2 = $this->_expression();
+ $result = $this->_createTree('ptgLE', $result, $result2);
+ } elseif ($this->_current_token == ">=") {
+ $this->_advance();
+ $result2 = $this->_expression();
+ $result = $this->_createTree('ptgGE', $result, $result2);
+ } elseif ($this->_current_token == "=") {
+ $this->_advance();
+ $result2 = $this->_expression();
+ $result = $this->_createTree('ptgEQ', $result, $result2);
+ } elseif ($this->_current_token == "<>") {
+ $this->_advance();
+ $result2 = $this->_expression();
+ $result = $this->_createTree('ptgNE', $result, $result2);
+ } elseif ($this->_current_token == "&") {
+ $this->_advance();
+ $result2 = $this->_expression();
+ $result = $this->_createTree('ptgConcat', $result, $result2);
+ }
+ return $result;
+ }
- /**
- * It parses a expression. It assumes the following rule:
- * Expr -> Term [("+" | "-") Term]
- * -> "string"
- * -> "-" Term : Negative value
- * -> "+" Term : Positive value
- * -> Error code
- *
- * @access private
- * @return mixed The parsed ptg'd tree on success
- */
- function _expression()
- {
- // If it's a string return a string node
- if (preg_match("/\"([^\"]|\"\"){0,255}\"/", $this->_current_token)) {
- $tmp = str_replace('""', '"', $this->_current_token);
- if (($tmp == '"') || ($tmp == '')) $tmp = '""'; // Trap for "" that has been used for an empty string
- $result = $this->_createTree($tmp, '', '');
- $this->_advance();
- return $result;
+ /**
+ * It parses a expression. It assumes the following rule:
+ * Expr -> Term [("+" | "-") Term]
+ * -> "string"
+ * -> "-" Term : Negative value
+ * -> "+" Term : Positive value
+ * -> Error code
+ *
+ * @access private
+ * @return mixed The parsed ptg'd tree on success
+ */
+ function _expression()
+ {
+ // If it's a string return a string node
+ if (preg_match("/\"([^\"]|\"\"){0,255}\"/", $this->_current_token)) {
+ $tmp = str_replace('""', '"', $this->_current_token);
+ if (($tmp == '"') || ($tmp == '')) $tmp = '""'; // Trap for "" that has been used for an empty string
+ $result = $this->_createTree($tmp, '', '');
+ $this->_advance();
+ return $result;
// If it's an error code
} elseif (preg_match("/^#[A-Z0\/]{3,5}[!?]{1}$/", $this->_current_token) or $this->_current_token == '#N/A'){
- $result = $this->_createTree($this->_current_token, 'ptgErr', '');
- $this->_advance();
- return $result;
- // If it's a negative value
+ $result = $this->_createTree($this->_current_token, 'ptgErr', '');
+ $this->_advance();
+ return $result;
+ // If it's a negative value
} elseif ($this->_current_token == "-") {
- // catch "-" Term
- $this->_advance();
- $result2 = $this->_expression();
- $result = $this->_createTree('ptgUminus', $result2, '');
- return $result;
+ // catch "-" Term
+ $this->_advance();
+ $result2 = $this->_expression();
+ $result = $this->_createTree('ptgUminus', $result2, '');
+ return $result;
// If it's a positive value
- } elseif ($this->_current_token == "+") {
- // catch "+" Term
- $this->_advance();
- $result2 = $this->_expression();
- $result = $this->_createTree('ptgUplus', $result2, '');
- return $result;
- }
- $result = $this->_term();
- while (($this->_current_token == "+") or
- ($this->_current_token == "-") or
- ($this->_current_token == "^")) {
- /**/
- if ($this->_current_token == "+") {
- $this->_advance();
- $result2 = $this->_term();
- $result = $this->_createTree('ptgAdd', $result, $result2);
- } elseif ($this->_current_token == "-") {
- $this->_advance();
- $result2 = $this->_term();
- $result = $this->_createTree('ptgSub', $result, $result2);
- } else {
- $this->_advance();
- $result2 = $this->_term();
- $result = $this->_createTree('ptgPower', $result, $result2);
- }
- }
- return $result;
- }
+ } elseif ($this->_current_token == "+") {
+ // catch "+" Term
+ $this->_advance();
+ $result2 = $this->_expression();
+ $result = $this->_createTree('ptgUplus', $result2, '');
+ return $result;
+ }
+ $result = $this->_term();
+ while (($this->_current_token == "+") or
+ ($this->_current_token == "-") or
+ ($this->_current_token == "^")) {
+ /**/
+ if ($this->_current_token == "+") {
+ $this->_advance();
+ $result2 = $this->_term();
+ $result = $this->_createTree('ptgAdd', $result, $result2);
+ } elseif ($this->_current_token == "-") {
+ $this->_advance();
+ $result2 = $this->_term();
+ $result = $this->_createTree('ptgSub', $result, $result2);
+ } else {
+ $this->_advance();
+ $result2 = $this->_term();
+ $result = $this->_createTree('ptgPower', $result, $result2);
+ }
+ }
+ return $result;
+ }
- /**
- * This function just introduces a ptgParen element in the tree, so that Excel
- * doesn't get confused when working with a parenthesized formula afterwards.
- *
- * @access private
- * @see _fact()
- * @return array The parsed ptg'd tree
- */
- function _parenthesizedExpression()
- {
- $result = $this->_createTree('ptgParen', $this->_expression(), '');
- return $result;
- }
+ /**
+ * This function just introduces a ptgParen element in the tree, so that Excel
+ * doesn't get confused when working with a parenthesized formula afterwards.
+ *
+ * @access private
+ * @see _fact()
+ * @return array The parsed ptg'd tree
+ */
+ function _parenthesizedExpression()
+ {
+ $result = $this->_createTree('ptgParen', $this->_expression(), '');
+ return $result;
+ }
- /**
- * It parses a term. It assumes the following rule:
- * Term -> Fact [("*" | "/") Fact]
- *
- * @access private
- * @return mixed The parsed ptg'd tree on success
- */
- function _term()
- {
- $result = $this->_fact();
- while (($this->_current_token == "*") or
- ($this->_current_token == "/")) {
- /**/
- if ($this->_current_token == "*") {
- $this->_advance();
- $result2 = $this->_fact();
- $result = $this->_createTree('ptgMul', $result, $result2);
- } else {
- $this->_advance();
- $result2 = $this->_fact();
- $result = $this->_createTree('ptgDiv', $result, $result2);
- }
- }
- return $result;
- }
+ /**
+ * It parses a term. It assumes the following rule:
+ * Term -> Fact [("*" | "/") Fact]
+ *
+ * @access private
+ * @return mixed The parsed ptg'd tree on success
+ */
+ function _term()
+ {
+ $result = $this->_fact();
+ while (($this->_current_token == "*") or
+ ($this->_current_token == "/")) {
+ /**/
+ if ($this->_current_token == "*") {
+ $this->_advance();
+ $result2 = $this->_fact();
+ $result = $this->_createTree('ptgMul', $result, $result2);
+ } else {
+ $this->_advance();
+ $result2 = $this->_fact();
+ $result = $this->_createTree('ptgDiv', $result, $result2);
+ }
+ }
+ return $result;
+ }
- /**
- * It parses a factor. It assumes the following rule:
- * Fact -> ( Expr )
- * | CellRef
- * | CellRange
- * | Number
- * | Function
- *
- * @access private
- * @return mixed The parsed ptg'd tree on success
- */
- function _fact()
- {
- if ($this->_current_token == "(") {
- $this->_advance(); // eat the "("
- $result = $this->_parenthesizedExpression();
- if ($this->_current_token != ")") {
- throw new Writer_Exception("')' token expected.");
- }
- $this->_advance(); // eat the ")"
- return $result;
- }
- // if it's a reference
- if (preg_match('/^\$?[A-Ia-i]?[A-Za-z]\$?[0-9]+$/',$this->_current_token))
- {
- $result = $this->_createTree($this->_current_token, '', '');
- $this->_advance();
- return $result;
- }
- // If it's an external reference (Sheet1!A1 or Sheet1:Sheet2!A1 or Sheet1!$A$1 or Sheet1:Sheet2!$A$1)
- elseif (preg_match("/^" . self::REGEX_SHEET_TITLE_UNQUOTED . "(\:" . self::REGEX_SHEET_TITLE_UNQUOTED . ")?\!\\$?[A-Ia-i]?[A-Za-z]\\$?[0-9]+$/u",$this->_current_token))
- {
- $result = $this->_createTree($this->_current_token, '', '');
- $this->_advance();
- return $result;
- }
- // If it's an external reference ('Sheet1'!A1 or 'Sheet1:Sheet2'!A1 or 'Sheet1'!$A$1 or 'Sheet1:Sheet2'!$A$1)
- elseif (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . "(\:" . self::REGEX_SHEET_TITLE_QUOTED . ")?'\!\\$?[A-Ia-i]?[A-Za-z]\\$?[0-9]+$/u",$this->_current_token))
- {
- $result = $this->_createTree($this->_current_token, '', '');
- $this->_advance();
- return $result;
- }
- // if it's a range A1:B2 or $A$1:$B$2
- elseif (preg_match('/^(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+:(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+$/',$this->_current_token) or
- preg_match('/^(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+\.\.(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+$/',$this->_current_token))
- {
- // must be an error?
- $result = $this->_createTree($this->_current_token, '', '');
- $this->_advance();
- return $result;
- }
- // If it's an external range (Sheet1!A1:B2 or Sheet1:Sheet2!A1:B2 or Sheet1!$A$1:$B$2 or Sheet1:Sheet2!$A$1:$B$2)
- elseif (preg_match("/^" . self::REGEX_SHEET_TITLE_UNQUOTED . "(\:" . self::REGEX_SHEET_TITLE_UNQUOTED . ")?\!\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+:\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+$/u",$this->_current_token))
- {
- // must be an error?
- //$result = $this->_current_token;
- $result = $this->_createTree($this->_current_token, '', '');
- $this->_advance();
- return $result;
- }
- // If it's an external range ('Sheet1'!A1:B2 or 'Sheet1'!A1:B2 or 'Sheet1'!$A$1:$B$2 or 'Sheet1'!$A$1:$B$2)
- elseif (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . "(\:" . self::REGEX_SHEET_TITLE_QUOTED . ")?'\!\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+:\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+$/u",$this->_current_token))
- {
- // must be an error?
- //$result = $this->_current_token;
- $result = $this->_createTree($this->_current_token, '', '');
- $this->_advance();
- return $result;
- }
- // If it's a number or a percent
- elseif (is_numeric($this->_current_token))
- {
- if($this->_lookahead == '%'){
- $result = $this->_createTree('ptgPercent', $this->_current_token, '');
- } else {
- $result = $this->_createTree($this->_current_token, '', '');
- }
- $this->_advance();
- return $result;
- }
- // if it's a function call
- elseif (preg_match("/^[A-Z0-9\xc0-\xdc\.]+$/i",$this->_current_token))
- {
- $result = $this->_func();
- return $result;
- }
- throw new Writer_Exception("Syntax error: ".$this->_current_token.
- ", lookahead: ".$this->_lookahead.
- ", current char: ".$this->_current_char);
- }
+ /**
+ * It parses a factor. It assumes the following rule:
+ * Fact -> ( Expr )
+ * | CellRef
+ * | CellRange
+ * | Number
+ * | Function
+ *
+ * @access private
+ * @return mixed The parsed ptg'd tree on success
+ */
+ function _fact()
+ {
+ if ($this->_current_token == "(") {
+ $this->_advance(); // eat the "("
+ $result = $this->_parenthesizedExpression();
+ if ($this->_current_token != ")") {
+ throw new Writer_Exception("')' token expected.");
+ }
+ $this->_advance(); // eat the ")"
+ return $result;
+ }
+ // if it's a reference
+ if (preg_match('/^\$?[A-Ia-i]?[A-Za-z]\$?[0-9]+$/',$this->_current_token))
+ {
+ $result = $this->_createTree($this->_current_token, '', '');
+ $this->_advance();
+ return $result;
+ }
+ // If it's an external reference (Sheet1!A1 or Sheet1:Sheet2!A1 or Sheet1!$A$1 or Sheet1:Sheet2!$A$1)
+ elseif (preg_match("/^" . self::REGEX_SHEET_TITLE_UNQUOTED . "(\:" . self::REGEX_SHEET_TITLE_UNQUOTED . ")?\!\\$?[A-Ia-i]?[A-Za-z]\\$?[0-9]+$/u",$this->_current_token))
+ {
+ $result = $this->_createTree($this->_current_token, '', '');
+ $this->_advance();
+ return $result;
+ }
+ // If it's an external reference ('Sheet1'!A1 or 'Sheet1:Sheet2'!A1 or 'Sheet1'!$A$1 or 'Sheet1:Sheet2'!$A$1)
+ elseif (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . "(\:" . self::REGEX_SHEET_TITLE_QUOTED . ")?'\!\\$?[A-Ia-i]?[A-Za-z]\\$?[0-9]+$/u",$this->_current_token))
+ {
+ $result = $this->_createTree($this->_current_token, '', '');
+ $this->_advance();
+ return $result;
+ }
+ // if it's a range A1:B2 or $A$1:$B$2
+ elseif (preg_match('/^(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+:(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+$/',$this->_current_token) or
+ preg_match('/^(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+\.\.(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+$/',$this->_current_token))
+ {
+ // must be an error?
+ $result = $this->_createTree($this->_current_token, '', '');
+ $this->_advance();
+ return $result;
+ }
+ // If it's an external range (Sheet1!A1:B2 or Sheet1:Sheet2!A1:B2 or Sheet1!$A$1:$B$2 or Sheet1:Sheet2!$A$1:$B$2)
+ elseif (preg_match("/^" . self::REGEX_SHEET_TITLE_UNQUOTED . "(\:" . self::REGEX_SHEET_TITLE_UNQUOTED . ")?\!\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+:\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+$/u",$this->_current_token))
+ {
+ // must be an error?
+ //$result = $this->_current_token;
+ $result = $this->_createTree($this->_current_token, '', '');
+ $this->_advance();
+ return $result;
+ }
+ // If it's an external range ('Sheet1'!A1:B2 or 'Sheet1'!A1:B2 or 'Sheet1'!$A$1:$B$2 or 'Sheet1'!$A$1:$B$2)
+ elseif (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . "(\:" . self::REGEX_SHEET_TITLE_QUOTED . ")?'\!\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+:\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+$/u",$this->_current_token))
+ {
+ // must be an error?
+ //$result = $this->_current_token;
+ $result = $this->_createTree($this->_current_token, '', '');
+ $this->_advance();
+ return $result;
+ }
+ // If it's a number or a percent
+ elseif (is_numeric($this->_current_token))
+ {
+ if($this->_lookahead == '%'){
+ $result = $this->_createTree('ptgPercent', $this->_current_token, '');
+ } else {
+ $result = $this->_createTree($this->_current_token, '', '');
+ }
+ $this->_advance();
+ return $result;
+ }
+ // if it's a function call
+ elseif (preg_match("/^[A-Z0-9\xc0-\xdc\.]+$/i",$this->_current_token))
+ {
+ $result = $this->_func();
+ return $result;
+ }
+ throw new Writer_Exception("Syntax error: ".$this->_current_token.
+ ", lookahead: ".$this->_lookahead.
+ ", current char: ".$this->_current_char);
+ }
- /**
- * It parses a function call. It assumes the following rule:
- * Func -> ( Expr [,Expr]* )
- *
- * @access private
- * @return mixed The parsed ptg'd tree on success
- */
- function _func()
- {
- $num_args = 0; // number of arguments received
- $function = strtoupper($this->_current_token);
- $result = ''; // initialize result
- $this->_advance();
- $this->_advance(); // eat the "("
- while ($this->_current_token != ')') {
- /**/
- if ($num_args > 0) {
- if ($this->_current_token == "," or
- $this->_current_token == ";")
- {
- $this->_advance(); // eat the "," or ";"
- } else {
- throw new Writer_Exception("Syntax error: comma expected in ".
- "function $function, arg #{$num_args}");
- }
- $result2 = $this->_condition();
- $result = $this->_createTree('arg', $result, $result2);
- } else { // first argument
- $result2 = $this->_condition();
- $result = $this->_createTree('arg', '', $result2);
- }
- ++$num_args;
- }
- if (!isset($this->_functions[$function])) {
- throw new Writer_Exception("Function $function() doesn't exist");
- }
- $args = $this->_functions[$function][1];
- // If fixed number of args eg. TIME($i,$j,$k). Check that the number of args is valid.
- if (($args >= 0) and ($args != $num_args)) {
- throw new Writer_Exception("Incorrect number of arguments in function $function() ");
- }
+ /**
+ * It parses a function call. It assumes the following rule:
+ * Func -> ( Expr [,Expr]* )
+ *
+ * @access private
+ * @return mixed The parsed ptg'd tree on success
+ */
+ function _func()
+ {
+ $num_args = 0; // number of arguments received
+ $function = strtoupper($this->_current_token);
+ $result = ''; // initialize result
+ $this->_advance();
+ $this->_advance(); // eat the "("
+ while ($this->_current_token != ')') {
+ /**/
+ if ($num_args > 0) {
+ if ($this->_current_token == "," or
+ $this->_current_token == ";")
+ {
+ $this->_advance(); // eat the "," or ";"
+ } else {
+ throw new Writer_Exception("Syntax error: comma expected in ".
+ "function $function, arg #{$num_args}");
+ }
+ $result2 = $this->_condition();
+ $result = $this->_createTree('arg', $result, $result2);
+ } else { // first argument
+ $result2 = $this->_condition();
+ $result = $this->_createTree('arg', '', $result2);
+ }
+ ++$num_args;
+ }
+ if (!isset($this->_functions[$function])) {
+ throw new Writer_Exception("Function $function() doesn't exist");
+ }
+ $args = $this->_functions[$function][1];
+ // If fixed number of args eg. TIME($i,$j,$k). Check that the number of args is valid.
+ if (($args >= 0) and ($args != $num_args)) {
+ throw new Writer_Exception("Incorrect number of arguments in function $function() ");
+ }
- $result = $this->_createTree($function, $result, $num_args);
- $this->_advance(); // eat the ")"
- return $result;
- }
+ $result = $this->_createTree($function, $result, $num_args);
+ $this->_advance(); // eat the ")"
+ return $result;
+ }
- /**
- * Creates a tree. In fact an array which may have one or two arrays (sub-trees)
- * as elements.
- *
- * @access private
- * @param mixed $value The value of this node.
- * @param mixed $left The left array (sub-tree) or a final node.
- * @param mixed $right The right array (sub-tree) or a final node.
- * @return array A tree
- */
- function _createTree($value, $left, $right)
- {
- return array('value' => $value, 'left' => $left, 'right' => $right);
- }
+ /**
+ * Creates a tree. In fact an array which may have one or two arrays (sub-trees)
+ * as elements.
+ *
+ * @access private
+ * @param mixed $value The value of this node.
+ * @param mixed $left The left array (sub-tree) or a final node.
+ * @param mixed $right The right array (sub-tree) or a final node.
+ * @return array A tree
+ */
+ function _createTree($value, $left, $right)
+ {
+ return array('value' => $value, 'left' => $left, 'right' => $right);
+ }
- /**
- * Builds a string containing the tree in reverse polish notation (What you
- * would use in a HP calculator stack).
- * The following tree:
- *
- * +
- * / \
- * 2 3
- *
- * produces: "23+"
- *
- * The following tree:
- *
- * +
- * / \
- * 3 *
- * / \
- * 6 A1
- *
- * produces: "36A1*+"
- *
- * In fact all operands, functions, references, etc... are written as ptg's
- *
- * @access public
- * @param array $tree The optional tree to convert.
- * @return string The tree in reverse polish notation
- */
- function toReversePolish($tree = array())
- {
- $polish = ""; // the string we are going to return
- if (empty($tree)) { // If it's the first call use _parse_tree
- $tree = $this->_parse_tree;
- }
+ /**
+ * Builds a string containing the tree in reverse polish notation (What you
+ * would use in a HP calculator stack).
+ * The following tree:
+ *
+ * +
+ * / \
+ * 2 3
+ *
+ * produces: "23+"
+ *
+ * The following tree:
+ *
+ * +
+ * / \
+ * 3 *
+ * / \
+ * 6 A1
+ *
+ * produces: "36A1*+"
+ *
+ * In fact all operands, functions, references, etc... are written as ptg's
+ *
+ * @access public
+ * @param array $tree The optional tree to convert.
+ * @return string The tree in reverse polish notation
+ */
+ function toReversePolish($tree = array())
+ {
+ $polish = ""; // the string we are going to return
+ if (empty($tree)) { // If it's the first call use _parse_tree
+ $tree = $this->_parse_tree;
+ }
- if (is_array($tree['left'])) {
- $converted_tree = $this->toReversePolish($tree['left']);
- $polish .= $converted_tree;
- } elseif ($tree['left'] != '') { // It's a final node
- $converted_tree = $this->_convert($tree['left']);
- $polish .= $converted_tree;
- }
- if (is_array($tree['right'])) {
- $converted_tree = $this->toReversePolish($tree['right']);
- $polish .= $converted_tree;
- } elseif ($tree['right'] != '') { // It's a final node
- $converted_tree = $this->_convert($tree['right']);
- $polish .= $converted_tree;
- }
- // if it's a function convert it here (so we can set it's arguments)
- if (preg_match("/^[A-Z0-9\xc0-\xdc\.]+$/",$tree['value']) and
- !preg_match('/^([A-Ia-i]?[A-Za-z])(\d+)$/',$tree['value']) and
- !preg_match("/^[A-Ia-i]?[A-Za-z](\d+)\.\.[A-Ia-i]?[A-Za-z](\d+)$/",$tree['value']) and
- !is_numeric($tree['value']) and
- !isset($this->ptg[$tree['value']]))
- {
- // left subtree for a function is always an array.
- if ($tree['left'] != '') {
- $left_tree = $this->toReversePolish($tree['left']);
- } else {
- $left_tree = '';
- }
- // add it's left subtree and return.
- return $left_tree.$this->_convertFunction($tree['value'], $tree['right']);
- } else {
- $converted_tree = $this->_convert($tree['value']);
- }
- $polish .= $converted_tree;
- return $polish;
- }
+ if (is_array($tree['left'])) {
+ $converted_tree = $this->toReversePolish($tree['left']);
+ $polish .= $converted_tree;
+ } elseif ($tree['left'] != '') { // It's a final node
+ $converted_tree = $this->_convert($tree['left']);
+ $polish .= $converted_tree;
+ }
+ if (is_array($tree['right'])) {
+ $converted_tree = $this->toReversePolish($tree['right']);
+ $polish .= $converted_tree;
+ } elseif ($tree['right'] != '') { // It's a final node
+ $converted_tree = $this->_convert($tree['right']);
+ $polish .= $converted_tree;
+ }
+ // if it's a function convert it here (so we can set it's arguments)
+ if (preg_match("/^[A-Z0-9\xc0-\xdc\.]+$/",$tree['value']) and
+ !preg_match('/^([A-Ia-i]?[A-Za-z])(\d+)$/',$tree['value']) and
+ !preg_match("/^[A-Ia-i]?[A-Za-z](\d+)\.\.[A-Ia-i]?[A-Za-z](\d+)$/",$tree['value']) and
+ !is_numeric($tree['value']) and
+ !isset($this->ptg[$tree['value']]))
+ {
+ // left subtree for a function is always an array.
+ if ($tree['left'] != '') {
+ $left_tree = $this->toReversePolish($tree['left']);
+ } else {
+ $left_tree = '';
+ }
+ // add it's left subtree and return.
+ return $left_tree.$this->_convertFunction($tree['value'], $tree['right']);
+ } else {
+ $converted_tree = $this->_convert($tree['value']);
+ }
+ $polish .= $converted_tree;
+ return $polish;
+ }
}
diff --git a/Classes/PHPExcel/Writer/Excel5/Workbook.php b/Classes/PHPExcel/Writer/Excel5/Workbook.php
index aa2c517..5185a42 100644
--- a/Classes/PHPExcel/Writer/Excel5/Workbook.php
+++ b/Classes/PHPExcel/Writer/Excel5/Workbook.php
@@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\Writer_Excel5
* @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##
*/
@@ -72,1381 +72,1381 @@ namespace PHPExcel;
*/
class Writer_Excel5_Workbook extends Writer_Excel5_BIFFwriter
{
- /**
- * Formula parser
- *
- * @var PHPExcel\Writer_Excel5_Parser
- */
- private $_parser;
-
- /**
- * The BIFF file size for the workbook.
- * @var integer
- * @see _calcSheetOffsets()
- */
- public $_biffsize;
-
- /**
- * XF Writers
- * @var PHPExcel\Writer_Excel5_Xf[]
- */
- private $_xfWriters = array();
-
- /**
- * Array containing the colour palette
- * @var array
- */
- public $_palette;
-
- /**
- * The codepage indicates the text encoding used for strings
- * @var integer
- */
- public $_codepage;
-
- /**
- * The country code used for localization
- * @var integer
- */
- public $_country_code;
-
- /**
- * Workbook
- * @var PHPExcel
- */
- private $_phpExcel;
-
- /**
- * Fonts writers
- *
- * @var PHPExcel\Writer_Excel5_Font[]
- */
- private $_fontWriters = array();
-
- /**
- * Added fonts. Maps from font's hash => index in workbook
- *
- * @var array
- */
- private $_addedFonts = array();
-
- /**
- * Shared number formats
- *
- * @var array
- */
- private $_numberFormats = array();
-
- /**
- * Added number formats. Maps from numberFormat's hash => index in workbook
- *
- * @var array
- */
- private $_addedNumberFormats = array();
-
- /**
- * Sizes of the binary worksheet streams
- *
- * @var array
- */
- private $_worksheetSizes = array();
-
- /**
- * Offsets of the binary worksheet streams relative to the start of the global workbook stream
- *
- * @var array
- */
- private $_worksheetOffsets = array();
-
- /**
- * Total number of shared strings in workbook
- *
- * @var int
- */
- private $_str_total;
-
- /**
- * Number of unique shared strings in workbook
- *
- * @var int
- */
- private $_str_unique;
-
- /**
- * Array of unique shared strings in workbook
- *
- * @var array
- */
- private $_str_table;
-
- /**
- * Color cache
- */
- private $_colors;
-
- /**
- * Escher object corresponding to MSODRAWINGGROUP
- *
- * @var PHPExcel\Shared_Escher
- */
- private $_escher;
-
-
- /**
- * Class constructor
- *
- * @param PHPExcel\Workbook $phpExcel The Workbook
- * @param int &$str_total Total number of strings
- * @param int &$str_unique Total number of unique strings
- * @param array &$str_table String Table
- * @param array &$colors Colour Table
- * @param mixed $parser The formula parser created for the Workbook
- */
- public function __construct(Workbook $phpExcel = null,
- &$str_total, &$str_unique, &$str_table, &$colors,
- $parser )
- {
- // It needs to call its parent's constructor explicitly
- parent::__construct();
-
- $this->_parser = $parser;
- $this->_biffsize = 0;
- $this->_palette = array();
- $this->_country_code = -1;
-
- $this->_str_total = &$str_total;
- $this->_str_unique = &$str_unique;
- $this->_str_table = &$str_table;
- $this->_colors = &$colors;
- $this->_setPaletteXl97();
-
- $this->_phpExcel = $phpExcel;
-
- // set BIFFwriter limit for CONTINUE records
- // $this->_limit = 8224;
- $this->_codepage = 0x04B0;
-
- // Add empty sheets and Build color cache
- $countSheets = $phpExcel->getSheetCount();
- for ($i = 0; $i < $countSheets; ++$i) {
- $phpSheet = $phpExcel->getSheet($i);
-
- $this->_parser->setExtSheet($phpSheet->getTitle(), $i); // Register worksheet name with parser
-
- $supbook_index = 0x00;
- $ref = pack('vvv', $supbook_index, $i, $i);
- $this->_parser->_references[] = $ref; // Register reference with parser
-
- // Sheet tab colors?
- if ($phpSheet->isTabColorSet()) {
- $this->_addColor($phpSheet->getTabColor()->getRGB());
- }
- }
-
- }
-
- /**
- * Add a new XF writer
- *
- * @param PHPExcel\Style
- * @param boolean Is it a style XF?
- * @return int Index to XF record
- */
- public function addXfWriter($style, $isStyleXf = false)
- {
- $xfWriter = new Writer_Excel5_Xf($style);
- $xfWriter->setIsStyleXf($isStyleXf);
-
- // Add the font if not already added
- $fontIndex = $this->_addFont($style->getFont());
-
- // Assign the font index to the xf record
- $xfWriter->setFontIndex($fontIndex);
-
- // Background colors, best to treat these after the font so black will come after white in custom palette
- $xfWriter->setFgColor($this->_addColor($style->getFill()->getStartColor()->getRGB()));
- $xfWriter->setBgColor($this->_addColor($style->getFill()->getEndColor()->getRGB()));
- $xfWriter->setBottomColor($this->_addColor($style->getBorders()->getBottom()->getColor()->getRGB()));
- $xfWriter->setTopColor($this->_addColor($style->getBorders()->getTop()->getColor()->getRGB()));
- $xfWriter->setRightColor($this->_addColor($style->getBorders()->getRight()->getColor()->getRGB()));
- $xfWriter->setLeftColor($this->_addColor($style->getBorders()->getLeft()->getColor()->getRGB()));
- $xfWriter->setDiagColor($this->_addColor($style->getBorders()->getDiagonal()->getColor()->getRGB()));
-
- // Add the number format if it is not a built-in one and not already added
- if ($style->getNumberFormat()->getBuiltInFormatCode() === false) {
- $numberFormatHashCode = $style->getNumberFormat()->getHashCode();
-
- if (isset($this->_addedNumberFormats[$numberFormatHashCode])) {
- $numberFormatIndex = $this->_addedNumberFormats[$numberFormatHashCode];
- } else {
- $numberFormatIndex = 164 + count($this->_numberFormats);
- $this->_numberFormats[$numberFormatIndex] = $style->getNumberFormat();
- $this->_addedNumberFormats[$numberFormatHashCode] = $numberFormatIndex;
- }
- } else {
- $numberFormatIndex = (int) $style->getNumberFormat()->getBuiltInFormatCode();
- }
-
- // Assign the number format index to xf record
- $xfWriter->setNumberFormatIndex($numberFormatIndex);
-
- $this->_xfWriters[] = $xfWriter;
-
- $xfIndex = count($this->_xfWriters) - 1;
- return $xfIndex;
- }
-
- /**
- * Add a font to added fonts
- *
- * @param PHPExcel\Style_Font $font
- * @return int Index to FONT record
- */
- public function _addFont(Style_Font $font)
- {
- $fontHashCode = $font->getHashCode();
- if(isset($this->_addedFonts[$fontHashCode])){
- $fontIndex = $this->_addedFonts[$fontHashCode];
- } else {
- $countFonts = count($this->_fontWriters);
- $fontIndex = ($countFonts < 4) ? $countFonts : $countFonts + 1;
-
- $fontWriter = new Writer_Excel5_Font($font);
- $fontWriter->setColorIndex($this->_addColor($font->getColor()->getRGB()));
- $this->_fontWriters[] = $fontWriter;
-
- $this->_addedFonts[$fontHashCode] = $fontIndex;
- }
- return $fontIndex;
- }
-
- /**
- * Alter color palette adding a custom color
- *
- * @param string $rgb E.g. 'FF00AA'
- * @return int Color index
- */
- private function _addColor($rgb) {
- if (!isset($this->_colors[$rgb])) {
- if (count($this->_colors) < 57) {
- // then we add a custom color altering the palette
- $colorIndex = 8 + count($this->_colors);
- $this->_palette[$colorIndex] =
- array(
- hexdec(substr($rgb, 0, 2)),
- hexdec(substr($rgb, 2, 2)),
- hexdec(substr($rgb, 4)),
- 0
- );
- $this->_colors[$rgb] = $colorIndex;
- } else {
- // no room for more custom colors, just map to black
- $colorIndex = 0;
- }
- } else {
- // fetch already added custom color
- $colorIndex = $this->_colors[$rgb];
- }
-
- return $colorIndex;
- }
-
- /**
- * Sets the colour palette to the Excel 97+ default.
- *
- * @access private
- */
- function _setPaletteXl97()
- {
- $this->_palette = array(
- 0x08 => array(0x00, 0x00, 0x00, 0x00),
- 0x09 => array(0xff, 0xff, 0xff, 0x00),
- 0x0A => array(0xff, 0x00, 0x00, 0x00),
- 0x0B => array(0x00, 0xff, 0x00, 0x00),
- 0x0C => array(0x00, 0x00, 0xff, 0x00),
- 0x0D => array(0xff, 0xff, 0x00, 0x00),
- 0x0E => array(0xff, 0x00, 0xff, 0x00),
- 0x0F => array(0x00, 0xff, 0xff, 0x00),
- 0x10 => array(0x80, 0x00, 0x00, 0x00),
- 0x11 => array(0x00, 0x80, 0x00, 0x00),
- 0x12 => array(0x00, 0x00, 0x80, 0x00),
- 0x13 => array(0x80, 0x80, 0x00, 0x00),
- 0x14 => array(0x80, 0x00, 0x80, 0x00),
- 0x15 => array(0x00, 0x80, 0x80, 0x00),
- 0x16 => array(0xc0, 0xc0, 0xc0, 0x00),
- 0x17 => array(0x80, 0x80, 0x80, 0x00),
- 0x18 => array(0x99, 0x99, 0xff, 0x00),
- 0x19 => array(0x99, 0x33, 0x66, 0x00),
- 0x1A => array(0xff, 0xff, 0xcc, 0x00),
- 0x1B => array(0xcc, 0xff, 0xff, 0x00),
- 0x1C => array(0x66, 0x00, 0x66, 0x00),
- 0x1D => array(0xff, 0x80, 0x80, 0x00),
- 0x1E => array(0x00, 0x66, 0xcc, 0x00),
- 0x1F => array(0xcc, 0xcc, 0xff, 0x00),
- 0x20 => array(0x00, 0x00, 0x80, 0x00),
- 0x21 => array(0xff, 0x00, 0xff, 0x00),
- 0x22 => array(0xff, 0xff, 0x00, 0x00),
- 0x23 => array(0x00, 0xff, 0xff, 0x00),
- 0x24 => array(0x80, 0x00, 0x80, 0x00),
- 0x25 => array(0x80, 0x00, 0x00, 0x00),
- 0x26 => array(0x00, 0x80, 0x80, 0x00),
- 0x27 => array(0x00, 0x00, 0xff, 0x00),
- 0x28 => array(0x00, 0xcc, 0xff, 0x00),
- 0x29 => array(0xcc, 0xff, 0xff, 0x00),
- 0x2A => array(0xcc, 0xff, 0xcc, 0x00),
- 0x2B => array(0xff, 0xff, 0x99, 0x00),
- 0x2C => array(0x99, 0xcc, 0xff, 0x00),
- 0x2D => array(0xff, 0x99, 0xcc, 0x00),
- 0x2E => array(0xcc, 0x99, 0xff, 0x00),
- 0x2F => array(0xff, 0xcc, 0x99, 0x00),
- 0x30 => array(0x33, 0x66, 0xff, 0x00),
- 0x31 => array(0x33, 0xcc, 0xcc, 0x00),
- 0x32 => array(0x99, 0xcc, 0x00, 0x00),
- 0x33 => array(0xff, 0xcc, 0x00, 0x00),
- 0x34 => array(0xff, 0x99, 0x00, 0x00),
- 0x35 => array(0xff, 0x66, 0x00, 0x00),
- 0x36 => array(0x66, 0x66, 0x99, 0x00),
- 0x37 => array(0x96, 0x96, 0x96, 0x00),
- 0x38 => array(0x00, 0x33, 0x66, 0x00),
- 0x39 => array(0x33, 0x99, 0x66, 0x00),
- 0x3A => array(0x00, 0x33, 0x00, 0x00),
- 0x3B => array(0x33, 0x33, 0x00, 0x00),
- 0x3C => array(0x99, 0x33, 0x00, 0x00),
- 0x3D => array(0x99, 0x33, 0x66, 0x00),
- 0x3E => array(0x33, 0x33, 0x99, 0x00),
- 0x3F => array(0x33, 0x33, 0x33, 0x00),
- );
- }
-
- /**
- * Assemble worksheets into a workbook and send the BIFF data to an OLE
- * storage.
- *
- * @param array $pWorksheetSizes The sizes in bytes of the binary worksheet streams
- * @return string Binary data for workbook stream
- */
- public function writeWorkbook($pWorksheetSizes = null)
- {
- $this->_worksheetSizes = $pWorksheetSizes;
-
- // Calculate the number of selected worksheet tabs and call the finalization
- // methods for each worksheet
- $total_worksheets = $this->_phpExcel->getSheetCount();
-
- // Add part 1 of the Workbook globals, what goes before the SHEET records
- $this->_storeBof(0x0005);
- $this->_writeCodepage();
- $this->_writeWindow1();
-
- $this->_writeDatemode();
- $this->_writeAllFonts();
- $this->_writeAllNumFormats();
- $this->_writeAllXfs();
- $this->_writeAllStyles();
- $this->_writePalette();
-
- // Prepare part 3 of the workbook global stream, what goes after the SHEET records
- $part3 = '';
- if ($this->_country_code != -1) {
- $part3 .= $this->_writeCountry();
- }
- $part3 .= $this->_writeRecalcId();
-
- $part3 .= $this->_writeSupbookInternal();
- /* TODO: store external SUPBOOK records and XCT and CRN records
- in case of external references for BIFF8 */
- $part3 .= $this->_writeExternsheetBiff8();
- $part3 .= $this->_writeAllDefinedNamesBiff8();
- $part3 .= $this->_writeMsoDrawingGroup();
- $part3 .= $this->_writeSharedStringsTable();
-
- $part3 .= $this->writeEof();
-
- // Add part 2 of the Workbook globals, the SHEET records
- $this->_calcSheetOffsets();
- for ($i = 0; $i < $total_worksheets; ++$i) {
- $this->_writeBoundsheet($this->_phpExcel->getSheet($i), $this->_worksheetOffsets[$i]);
- }
-
- // Add part 3 of the Workbook globals
- $this->_data .= $part3;
-
- return $this->_data;
- }
-
- /**
- * Calculate offsets for Worksheet BOF records.
- *
- * @access private
- */
- function _calcSheetOffsets()
- {
- $boundsheet_length = 10; // fixed length for a BOUNDSHEET record
-
- // size of Workbook globals part 1 + 3
- $offset = $this->_datasize;
-
- // add size of Workbook globals part 2, the length of the SHEET records
- $total_worksheets = count($this->_phpExcel->getAllSheets());
- foreach ($this->_phpExcel->getWorksheetIterator() as $sheet) {
- $offset += $boundsheet_length + strlen(Shared_String::UTF8toBIFF8UnicodeShort($sheet->getTitle()));
- }
-
- // add the sizes of each of the Sheet substreams, respectively
- for ($i = 0; $i < $total_worksheets; ++$i) {
- $this->_worksheetOffsets[$i] = $offset;
- $offset += $this->_worksheetSizes[$i];
- }
- $this->_biffsize = $offset;
- }
-
- /**
- * Store the Excel FONT records.
- */
- private function _writeAllFonts()
- {
- foreach ($this->_fontWriters as $fontWriter) {
- $this->_append($fontWriter->writeFont());
- }
- }
-
- /**
- * Store user defined numerical formats i.e. FORMAT records
- */
- private function _writeAllNumFormats()
- {
- foreach ($this->_numberFormats as $numberFormatIndex => $numberFormat) {
- $this->_writeNumFormat($numberFormat->getFormatCode(), $numberFormatIndex);
- }
- }
-
- /**
- * Write all XF records.
- */
- private function _writeAllXfs()
- {
- foreach ($this->_xfWriters as $xfWriter) {
- $this->_append($xfWriter->writeXf());
- }
- }
-
- /**
- * Write all STYLE records.
- */
- private function _writeAllStyles()
- {
- $this->_writeStyle();
- }
-
- /**
- * Write the EXTERNCOUNT and EXTERNSHEET records. These are used as indexes for
- * the NAME records.
- */
- private function _writeExterns()
- {
- $countSheets = $this->_phpExcel->getSheetCount();
- // Create EXTERNCOUNT with number of worksheets
- $this->_writeExterncount($countSheets);
-
- // Create EXTERNSHEET for each worksheet
- for ($i = 0; $i < $countSheets; ++$i) {
- $this->_writeExternsheet($this->_phpExcel->getSheet($i)->getTitle());
- }
- }
-
- /**
- * Write the NAME record to define the print area and the repeat rows and cols.
- */
- private function _writeNames()
- {
- // total number of sheets
- $total_worksheets = $this->_phpExcel->getSheetCount();
-
- // Create the print area NAME records
- for ($i = 0; $i < $total_worksheets; ++$i) {
- $sheetSetup = $this->_phpExcel->getSheet($i)->getPageSetup();
- // Write a Name record if the print area has been defined
- if ($sheetSetup->isPrintAreaSet()) {
- // Print area
- $printArea = Cell::splitRange($sheetSetup->getPrintArea());
- $printArea = $printArea[0];
- $printArea[0] = Cell::coordinateFromString($printArea[0]);
- $printArea[1] = Cell::coordinateFromString($printArea[1]);
-
- $print_rowmin = $printArea[0][1] - 1;
- $print_rowmax = $printArea[1][1] - 1;
- $print_colmin = Cell::columnIndexFromString($printArea[0][0]) - 1;
- $print_colmax = Cell::columnIndexFromString($printArea[1][0]) - 1;
-
- $this->_writeNameShort(
- $i, // sheet index
- 0x06, // NAME type
- $print_rowmin,
- $print_rowmax,
- $print_colmin,
- $print_colmax
- );
- }
- }
-
- // Create the print title NAME records
- for ($i = 0; $i < $total_worksheets; ++$i) {
- $sheetSetup = $this->_phpExcel->getSheet($i)->getPageSetup();
-
- // simultaneous repeatColumns repeatRows
- if ($sheetSetup->isColumnsToRepeatAtLeftSet() && $sheetSetup->isRowsToRepeatAtTopSet()) {
- $repeat = $sheetSetup->getColumnsToRepeatAtLeft();
- $colmin = Cell::columnIndexFromString($repeat[0]) - 1;
- $colmax = Cell::columnIndexFromString($repeat[1]) - 1;
-
- $repeat = $sheetSetup->getRowsToRepeatAtTop();
- $rowmin = $repeat[0] - 1;
- $rowmax = $repeat[1] - 1;
-
- $this->_writeNameLong(
- $i, // sheet index
- 0x07, // NAME type
- $rowmin,
- $rowmax,
- $colmin,
- $colmax
- );
-
- // (exclusive) either repeatColumns or repeatRows
- } else if ($sheetSetup->isColumnsToRepeatAtLeftSet() || $sheetSetup->isRowsToRepeatAtTopSet()) {
-
- // Columns to repeat
- if ($sheetSetup->isColumnsToRepeatAtLeftSet()) {
- $repeat = $sheetSetup->getColumnsToRepeatAtLeft();
- $colmin = Cell::columnIndexFromString($repeat[0]) - 1;
- $colmax = Cell::columnIndexFromString($repeat[1]) - 1;
- } else {
- $colmin = 0;
- $colmax = 255;
- }
-
- // Rows to repeat
- if ($sheetSetup->isRowsToRepeatAtTopSet()) {
- $repeat = $sheetSetup->getRowsToRepeatAtTop();
- $rowmin = $repeat[0] - 1;
- $rowmax = $repeat[1] - 1;
- } else {
- $rowmin = 0;
- $rowmax = 65535;
- }
-
- $this->_writeNameShort(
- $i, // sheet index
- 0x07, // NAME type
- $rowmin,
- $rowmax,
- $colmin,
- $colmax
- );
- }
- }
- }
-
- /**
- * Writes all the DEFINEDNAME records (BIFF8).
- * So far this is only used for repeating rows/columns (print titles) and print areas
- */
- private function _writeAllDefinedNamesBiff8()
- {
- $chunk = '';
-
- // Named ranges
- if (count($this->_phpExcel->getNamedRanges()) > 0) {
- // Loop named ranges
- $namedRanges = $this->_phpExcel->getNamedRanges();
- foreach ($namedRanges as $namedRange) {
-
- // Create absolute coordinate
- $range = Cell::splitRange($namedRange->getRange());
- for ($i = 0; $i < count($range); $i++) {
- $range[$i][0] = '\'' . str_replace("'", "''", $namedRange->getWorksheet()->getTitle()) . '\'!' . Cell::absoluteCoordinate($range[$i][0]);
- if (isset($range[$i][1])) {
- $range[$i][1] = Cell::absoluteCoordinate($range[$i][1]);
- }
- }
- $range = Cell::buildRange($range); // e.g. Sheet1!$A$1:$B$2
-
- // parse formula
- try {
- $error = $this->_parser->parse($range);
- $formulaData = $this->_parser->toReversePolish();
-
- // make sure tRef3d is of type tRef3dR (0x3A)
- if (isset($formulaData{0}) and ($formulaData{0} == "\x7A" or $formulaData{0} == "\x5A")) {
- $formulaData = "\x3A" . substr($formulaData, 1);
- }
-
- if ($namedRange->getLocalOnly()) {
- // local scope
- $scope = $this->_phpExcel->getIndex($namedRange->getScope()) + 1;
- } else {
- // global scope
- $scope = 0;
- }
- $chunk .= $this->writeData($this->_writeDefinedNameBiff8($namedRange->getName(), $formulaData, $scope, false));
-
- } catch(Exception $e) {
- // do nothing
- }
- }
- }
-
- // total number of sheets
- $total_worksheets = $this->_phpExcel->getSheetCount();
-
- // write the print titles (repeating rows, columns), if any
- for ($i = 0; $i < $total_worksheets; ++$i) {
- $sheetSetup = $this->_phpExcel->getSheet($i)->getPageSetup();
- // simultaneous repeatColumns repeatRows
- if ($sheetSetup->isColumnsToRepeatAtLeftSet() && $sheetSetup->isRowsToRepeatAtTopSet()) {
- $repeat = $sheetSetup->getColumnsToRepeatAtLeft();
- $colmin = Cell::columnIndexFromString($repeat[0]) - 1;
- $colmax = Cell::columnIndexFromString($repeat[1]) - 1;
-
- $repeat = $sheetSetup->getRowsToRepeatAtTop();
- $rowmin = $repeat[0] - 1;
- $rowmax = $repeat[1] - 1;
-
- // construct formula data manually
- $formulaData = pack('Cv', 0x29, 0x17); // tMemFunc
- $formulaData .= pack('Cvvvvv', 0x3B, $i, 0, 65535, $colmin, $colmax); // tArea3d
- $formulaData .= pack('Cvvvvv', 0x3B, $i, $rowmin, $rowmax, 0, 255); // tArea3d
- $formulaData .= pack('C', 0x10); // tList
-
- // store the DEFINEDNAME record
- $chunk .= $this->writeData($this->_writeDefinedNameBiff8(pack('C', 0x07), $formulaData, $i + 1, true));
-
- // (exclusive) either repeatColumns or repeatRows
- } else if ($sheetSetup->isColumnsToRepeatAtLeftSet() || $sheetSetup->isRowsToRepeatAtTopSet()) {
-
- // Columns to repeat
- if ($sheetSetup->isColumnsToRepeatAtLeftSet()) {
- $repeat = $sheetSetup->getColumnsToRepeatAtLeft();
- $colmin = Cell::columnIndexFromString($repeat[0]) - 1;
- $colmax = Cell::columnIndexFromString($repeat[1]) - 1;
- } else {
- $colmin = 0;
- $colmax = 255;
- }
- // Rows to repeat
- if ($sheetSetup->isRowsToRepeatAtTopSet()) {
- $repeat = $sheetSetup->getRowsToRepeatAtTop();
- $rowmin = $repeat[0] - 1;
- $rowmax = $repeat[1] - 1;
- } else {
- $rowmin = 0;
- $rowmax = 65535;
- }
-
- // construct formula data manually because parser does not recognize absolute 3d cell references
- $formulaData = pack('Cvvvvv', 0x3B, $i, $rowmin, $rowmax, $colmin, $colmax);
-
- // store the DEFINEDNAME record
- $chunk .= $this->writeData($this->_writeDefinedNameBiff8(pack('C', 0x07), $formulaData, $i + 1, true));
- }
- }
-
- // write the print areas, if any
- for ($i = 0; $i < $total_worksheets; ++$i) {
- $sheetSetup = $this->_phpExcel->getSheet($i)->getPageSetup();
- if ($sheetSetup->isPrintAreaSet()) {
- // Print area, e.g. A3:J6,H1:X20
- $printArea = Cell::splitRange($sheetSetup->getPrintArea());
- $countPrintArea = count($printArea);
-
- $formulaData = '';
- for ($j = 0; $j < $countPrintArea; ++$j) {
- $printAreaRect = $printArea[$j]; // e.g. A3:J6
- $printAreaRect[0] = Cell::coordinateFromString($printAreaRect[0]);
- $printAreaRect[1] = Cell::coordinateFromString($printAreaRect[1]);
-
- $print_rowmin = $printAreaRect[0][1] - 1;
- $print_rowmax = $printAreaRect[1][1] - 1;
- $print_colmin = Cell::columnIndexFromString($printAreaRect[0][0]) - 1;
- $print_colmax = Cell::columnIndexFromString($printAreaRect[1][0]) - 1;
-
- // construct formula data manually because parser does not recognize absolute 3d cell references
- $formulaData .= pack('Cvvvvv', 0x3B, $i, $print_rowmin, $print_rowmax, $print_colmin, $print_colmax);
-
- if ($j > 0) {
- $formulaData .= pack('C', 0x10); // list operator token ','
- }
- }
-
- // store the DEFINEDNAME record
- $chunk .= $this->writeData($this->_writeDefinedNameBiff8(pack('C', 0x06), $formulaData, $i + 1, true));
- }
- }
-
- // write autofilters, if any
- for ($i = 0; $i < $total_worksheets; ++$i) {
- $sheetAutoFilter = $this->_phpExcel->getSheet($i)->getAutoFilter();
- $autoFilterRange = $sheetAutoFilter->getRange();
- if(!empty($autoFilterRange)) {
- $rangeBounds = Cell::rangeBoundaries($autoFilterRange);
-
- //Autofilter built in name
- $name = pack('C', 0x0D);
-
- $chunk .= $this->writeData($this->_writeShortNameBiff8($name, $i + 1, $rangeBounds, true));
- }
- }
-
- return $chunk;
- }
-
- /**
- * Write a DEFINEDNAME record for BIFF8 using explicit binary formula data
- *
- * @param string $name The name in UTF-8
- * @param string $formulaData The binary formula data
- * @param string $sheetIndex 1-based sheet index the defined name applies to. 0 = global
- * @param boolean $isBuiltIn Built-in name?
- * @return string Complete binary record data
- */
- private function _writeDefinedNameBiff8($name, $formulaData, $sheetIndex = 0, $isBuiltIn = false)
- {
- $record = 0x0018;
-
- // option flags
- $options = $isBuiltIn ? 0x20 : 0x00;
-
- // length of the name, character count
- $nlen = Shared_String::CountCharacters($name);
-
- // name with stripped length field
- $name = substr(Shared_String::UTF8toBIFF8UnicodeLong($name), 2);
-
- // size of the formula (in bytes)
- $sz = strlen($formulaData);
-
- // combine the parts
- $data = pack('vCCvvvCCCC', $options, 0, $nlen, $sz, 0, $sheetIndex, 0, 0, 0, 0)
- . $name . $formulaData;
- $length = strlen($data);
-
- $header = pack('vv', $record, $length);
-
- return $header . $data;
- }
-
- /**
- * Write a short NAME record
- *
- * @param string $name
- * @param string $sheetIndex 1-based sheet index the defined name applies to. 0 = global
- * @param integer[][] $rangeBounds range boundaries
- * @param boolean $isHidden
- * @return string Complete binary record data
- * */
- private function _writeShortNameBiff8($name, $sheetIndex = 0, $rangeBounds, $isHidden = false){
- $record = 0x0018;
-
- // option flags
- $options = ($isHidden ? 0x21 : 0x00);
-
- $extra = pack('Cvvvvv',
- 0x3B,
- $sheetIndex - 1,
- $rangeBounds[0][1] - 1,
- $rangeBounds[1][1] - 1,
- $rangeBounds[0][0] - 1,
- $rangeBounds[1][0] - 1);
-
- // size of the formula (in bytes)
- $sz = strlen($extra);
-
- // combine the parts
- $data = pack('vCCvvvCCCCC', $options, 0, 1, $sz, 0, $sheetIndex, 0, 0, 0, 0, 0)
- . $name . $extra;
- $length = strlen($data);
-
- $header = pack('vv', $record, $length);
-
- return $header . $data;
- }
-
- /**
- * Stores the CODEPAGE biff record.
- */
- private function _writeCodepage()
- {
- $record = 0x0042; // Record identifier
- $length = 0x0002; // Number of bytes to follow
- $cv = $this->_codepage; // The code page
-
- $header = pack('vv', $record, $length);
- $data = pack('v', $cv);
-
- $this->_append($header . $data);
- }
-
- /**
- * Write Excel BIFF WINDOW1 record.
- */
- private function _writeWindow1()
- {
- $record = 0x003D; // Record identifier
- $length = 0x0012; // Number of bytes to follow
-
- $xWn = 0x0000; // Horizontal position of window
- $yWn = 0x0000; // Vertical position of window
- $dxWn = 0x25BC; // Width of window
- $dyWn = 0x1572; // Height of window
-
- $grbit = 0x0038; // Option flags
-
- // not supported by PHPExcel, so there is only one selected sheet, the active
- $ctabsel = 1; // Number of workbook tabs selected
-
- $wTabRatio = 0x0258; // Tab to scrollbar ratio
-
- // not supported by PHPExcel, set to 0
- $itabFirst = 0; // 1st displayed worksheet
- $itabCur = $this->_phpExcel->getActiveSheetIndex(); // Active worksheet
-
- $header = pack("vv", $record, $length);
- $data = pack("vvvvvvvvv", $xWn, $yWn, $dxWn, $dyWn,
- $grbit,
- $itabCur, $itabFirst,
- $ctabsel, $wTabRatio);
- $this->_append($header . $data);
- }
-
- /**
- * Writes Excel BIFF BOUNDSHEET record.
- *
- * @param PHPExcel\Worksheet $sheet Worksheet name
- * @param integer $offset Location of worksheet BOF
- */
- private function _writeBoundsheet($sheet, $offset)
- {
- $sheetname = $sheet->getTitle();
- $record = 0x0085; // Record identifier
-
- // sheet state
- switch ($sheet->getSheetState()) {
- case Worksheet::SHEETSTATE_VISIBLE: $ss = 0x00; break;
- case Worksheet::SHEETSTATE_HIDDEN: $ss = 0x01; break;
- case Worksheet::SHEETSTATE_VERYHIDDEN: $ss = 0x02; break;
- default: $ss = 0x00; break;
- }
-
- // sheet type
- $st = 0x00;
-
- $grbit = 0x0000; // Visibility and sheet type
-
- $data = pack("VCC", $offset, $ss, $st);
- $data .= Shared_String::UTF8toBIFF8UnicodeShort($sheetname);
-
- $length = strlen($data);
- $header = pack("vv", $record, $length);
- $this->_append($header . $data);
- }
-
- /**
- * Write Internal SUPBOOK record
- */
- private function _writeSupbookInternal()
- {
- $record = 0x01AE; // Record identifier
- $length = 0x0004; // Bytes to follow
-
- $header = pack("vv", $record, $length);
- $data = pack("vv", $this->_phpExcel->getSheetCount(), 0x0401);
- return $this->writeData($header . $data);
- }
-
- /**
- * Writes the Excel BIFF EXTERNSHEET record. These references are used by
- * formulas.
- *
- */
- private function _writeExternsheetBiff8()
- {
- $total_references = count($this->_parser->_references);
- $record = 0x0017; // Record identifier
- $length = 2 + 6 * $total_references; // Number of bytes to follow
-
- $supbook_index = 0; // FIXME: only using internal SUPBOOK record
- $header = pack("vv", $record, $length);
- $data = pack('v', $total_references);
- for ($i = 0; $i < $total_references; ++$i) {
- $data .= $this->_parser->_references[$i];
- }
- return $this->writeData($header . $data);
- }
-
- /**
- * Write Excel BIFF STYLE records.
- */
- private function _writeStyle()
- {
- $record = 0x0293; // Record identifier
- $length = 0x0004; // Bytes to follow
-
- $ixfe = 0x8000; // Index to cell style XF
- $BuiltIn = 0x00; // Built-in style
- $iLevel = 0xff; // Outline style level
-
- $header = pack("vv", $record, $length);
- $data = pack("vCC", $ixfe, $BuiltIn, $iLevel);
- $this->_append($header . $data);
- }
-
- /**
- * Writes Excel FORMAT record for non "built-in" numerical formats.
- *
- * @param string $format Custom format string
- * @param integer $ifmt Format index code
- */
- private function _writeNumFormat($format, $ifmt)
- {
- $record = 0x041E; // Record identifier
-
- $numberFormatString = Shared_String::UTF8toBIFF8UnicodeLong($format);
- $length = 2 + strlen($numberFormatString); // Number of bytes to follow
-
-
- $header = pack("vv", $record, $length);
- $data = pack("v", $ifmt) . $numberFormatString;
- $this->_append($header . $data);
- }
-
- /**
- * Write DATEMODE record to indicate the date system in use (1904 or 1900).
- */
- private function _writeDatemode()
- {
- $record = 0x0022; // Record identifier
- $length = 0x0002; // Bytes to follow
-
- $f1904 = (Shared_Date::getExcelCalendar() == Shared_Date::CALENDAR_MAC_1904) ?
- 1 : 0; // Flag for 1904 date system
-
- $header = pack("vv", $record, $length);
- $data = pack("v", $f1904);
- $this->_append($header . $data);
- }
-
- /**
- * Write BIFF record EXTERNCOUNT to indicate the number of external sheet
- * references in the workbook.
- *
- * Excel only stores references to external sheets that are used in NAME.
- * The workbook NAME record is required to define the print area and the repeat
- * rows and columns.
- *
- * A similar method is used in Worksheet.php for a slightly different purpose.
- *
- * @param integer $cxals Number of external references
- */
- private function _writeExterncount($cxals)
- {
- $record = 0x0016; // Record identifier
- $length = 0x0002; // Number of bytes to follow
-
- $header = pack("vv", $record, $length);
- $data = pack("v", $cxals);
- $this->_append($header . $data);
- }
-
- /**
- * Writes the Excel BIFF EXTERNSHEET record. These references are used by
- * formulas. NAME record is required to define the print area and the repeat
- * rows and columns.
- *
- * A similar method is used in Worksheet.php for a slightly different purpose.
- *
- * @param string $sheetname Worksheet name
- */
- private function _writeExternsheet($sheetname)
- {
- $record = 0x0017; // Record identifier
- $length = 0x02 + strlen($sheetname); // Number of bytes to follow
-
- $cch = strlen($sheetname); // Length of sheet name
- $rgch = 0x03; // Filename encoding
-
- $header = pack("vv", $record, $length);
- $data = pack("CC", $cch, $rgch);
- $this->_append($header . $data . $sheetname);
- }
-
- /**
- * Store the NAME record in the short format that is used for storing the print
- * area, repeat rows only and repeat columns only.
- *
- * @param integer $index Sheet index
- * @param integer $type Built-in name type
- * @param integer $rowmin Start row
- * @param integer $rowmax End row
- * @param integer $colmin Start colum
- * @param integer $colmax End column
- */
- private function _writeNameShort($index, $type, $rowmin, $rowmax, $colmin, $colmax)
- {
- $record = 0x0018; // Record identifier
- $length = 0x0024; // Number of bytes to follow
-
- $grbit = 0x0020; // Option flags
- $chKey = 0x00; // Keyboard shortcut
- $cch = 0x01; // Length of text name
- $cce = 0x0015; // Length of text definition
- $ixals = $index + 1; // Sheet index
- $itab = $ixals; // Equal to ixals
- $cchCustMenu = 0x00; // Length of cust menu text
- $cchDescription = 0x00; // Length of description text
- $cchHelptopic = 0x00; // Length of help topic text
- $cchStatustext = 0x00; // Length of status bar text
- $rgch = $type; // Built-in name type
-
- $unknown03 = 0x3b;
- $unknown04 = 0xffff-$index;
- $unknown05 = 0x0000;
- $unknown06 = 0x0000;
- $unknown07 = 0x1087;
- $unknown08 = 0x8005;
-
- $header = pack("vv", $record, $length);
- $data = pack("v", $grbit);
- $data .= pack("C", $chKey);
- $data .= pack("C", $cch);
- $data .= pack("v", $cce);
- $data .= pack("v", $ixals);
- $data .= pack("v", $itab);
- $data .= pack("C", $cchCustMenu);
- $data .= pack("C", $cchDescription);
- $data .= pack("C", $cchHelptopic);
- $data .= pack("C", $cchStatustext);
- $data .= pack("C", $rgch);
- $data .= pack("C", $unknown03);
- $data .= pack("v", $unknown04);
- $data .= pack("v", $unknown05);
- $data .= pack("v", $unknown06);
- $data .= pack("v", $unknown07);
- $data .= pack("v", $unknown08);
- $data .= pack("v", $index);
- $data .= pack("v", $index);
- $data .= pack("v", $rowmin);
- $data .= pack("v", $rowmax);
- $data .= pack("C", $colmin);
- $data .= pack("C", $colmax);
- $this->_append($header . $data);
- }
-
- /**
- * Store the NAME record in the long format that is used for storing the repeat
- * rows and columns when both are specified. This shares a lot of code with
- * _writeNameShort() but we use a separate method to keep the code clean.
- * Code abstraction for reuse can be carried too far, and I should know. ;-)
- *
- * @param integer $index Sheet index
- * @param integer $type Built-in name type
- * @param integer $rowmin Start row
- * @param integer $rowmax End row
- * @param integer $colmin Start colum
- * @param integer $colmax End column
- */
- private function _writeNameLong($index, $type, $rowmin, $rowmax, $colmin, $colmax)
- {
- $record = 0x0018; // Record identifier
- $length = 0x003d; // Number of bytes to follow
- $grbit = 0x0020; // Option flags
- $chKey = 0x00; // Keyboard shortcut
- $cch = 0x01; // Length of text name
- $cce = 0x002e; // Length of text definition
- $ixals = $index + 1; // Sheet index
- $itab = $ixals; // Equal to ixals
- $cchCustMenu = 0x00; // Length of cust menu text
- $cchDescription = 0x00; // Length of description text
- $cchHelptopic = 0x00; // Length of help topic text
- $cchStatustext = 0x00; // Length of status bar text
- $rgch = $type; // Built-in name type
-
- $unknown01 = 0x29;
- $unknown02 = 0x002b;
- $unknown03 = 0x3b;
- $unknown04 = 0xffff-$index;
- $unknown05 = 0x0000;
- $unknown06 = 0x0000;
- $unknown07 = 0x1087;
- $unknown08 = 0x8008;
-
- $header = pack("vv", $record, $length);
- $data = pack("v", $grbit);
- $data .= pack("C", $chKey);
- $data .= pack("C", $cch);
- $data .= pack("v", $cce);
- $data .= pack("v", $ixals);
- $data .= pack("v", $itab);
- $data .= pack("C", $cchCustMenu);
- $data .= pack("C", $cchDescription);
- $data .= pack("C", $cchHelptopic);
- $data .= pack("C", $cchStatustext);
- $data .= pack("C", $rgch);
- $data .= pack("C", $unknown01);
- $data .= pack("v", $unknown02);
- // Column definition
- $data .= pack("C", $unknown03);
- $data .= pack("v", $unknown04);
- $data .= pack("v", $unknown05);
- $data .= pack("v", $unknown06);
- $data .= pack("v", $unknown07);
- $data .= pack("v", $unknown08);
- $data .= pack("v", $index);
- $data .= pack("v", $index);
- $data .= pack("v", 0x0000);
- $data .= pack("v", 0x3fff);
- $data .= pack("C", $colmin);
- $data .= pack("C", $colmax);
- // Row definition
- $data .= pack("C", $unknown03);
- $data .= pack("v", $unknown04);
- $data .= pack("v", $unknown05);
- $data .= pack("v", $unknown06);
- $data .= pack("v", $unknown07);
- $data .= pack("v", $unknown08);
- $data .= pack("v", $index);
- $data .= pack("v", $index);
- $data .= pack("v", $rowmin);
- $data .= pack("v", $rowmax);
- $data .= pack("C", 0x00);
- $data .= pack("C", 0xff);
- // End of data
- $data .= pack("C", 0x10);
- $this->_append($header . $data);
- }
-
- /**
- * Stores the COUNTRY record for localization
- *
- * @return string
- */
- private function _writeCountry()
- {
- $record = 0x008C; // Record identifier
- $length = 4; // Number of bytes to follow
-
- $header = pack('vv', $record, $length);
- /* using the same country code always for simplicity */
- $data = pack('vv', $this->_country_code, $this->_country_code);
- //$this->_append($header . $data);
- return $this->writeData($header . $data);
- }
-
- /**
- * Write the RECALCID record
- *
- * @return string
- */
- private function _writeRecalcId()
- {
- $record = 0x01C1; // Record identifier
- $length = 8; // Number of bytes to follow
-
- $header = pack('vv', $record, $length);
-
- // by inspection of real Excel files, MS Office Excel 2007 writes this
- $data = pack('VV', 0x000001C1, 0x00001E667);
-
- return $this->writeData($header . $data);
- }
-
- /**
- * Stores the PALETTE biff record.
- */
- private function _writePalette()
- {
- $aref = $this->_palette;
-
- $record = 0x0092; // Record identifier
- $length = 2 + 4 * count($aref); // Number of bytes to follow
- $ccv = count($aref); // Number of RGB values to follow
- $data = ''; // The RGB data
-
- // Pack the RGB data
- foreach ($aref as $color) {
- foreach ($color as $byte) {
- $data .= pack("C",$byte);
- }
- }
-
- $header = pack("vvv", $record, $length, $ccv);
- $this->_append($header . $data);
- }
-
- /**
- * Handling of the SST continue blocks is complicated by the need to include an
- * additional continuation byte depending on whether the string is split between
- * blocks or whether it starts at the beginning of the block. (There are also
- * additional complications that will arise later when/if Rich Strings are
- * supported).
- *
- * The Excel documentation says that the SST record should be followed by an
- * EXTSST record. The EXTSST record is a hash table that is used to optimise
- * access to SST. However, despite the documentation it doesn't seem to be
- * required so we will ignore it.
- *
- * @return string Binary data
- */
- private function _writeSharedStringsTable()
- {
- // maximum size of record data (excluding record header)
- $continue_limit = 8224;
-
- // initialize array of record data blocks
- $recordDatas = array();
-
- // start SST record data block with total number of strings, total number of unique strings
- $recordData = pack("VV", $this->_str_total, $this->_str_unique);
-
- // loop through all (unique) strings in shared strings table
- foreach (array_keys($this->_str_table) as $string) {
-
- // here $string is a BIFF8 encoded string
-
- // length = character count
- $headerinfo = unpack("vlength/Cencoding", $string);
-
- // currently, this is always 1 = uncompressed
- $encoding = $headerinfo["encoding"];
-
- // initialize finished writing current $string
- $finished = false;
-
- while ($finished === false) {
-
- // normally, there will be only one cycle, but if string cannot immediately be written as is
- // there will be need for more than one cylcle, if string longer than one record data block, there
- // may be need for even more cycles
-
- if (strlen($recordData) + strlen($string) <= $continue_limit) {
- // then we can write the string (or remainder of string) without any problems
- $recordData .= $string;
-
- if (strlen($recordData) + strlen($string) == $continue_limit) {
- // we close the record data block, and initialize a new one
- $recordDatas[] = $recordData;
- $recordData = '';
- }
-
- // we are finished writing this string
- $finished = true;
- } else {
- // special treatment writing the string (or remainder of the string)
- // If the string is very long it may need to be written in more than one CONTINUE record.
-
- // check how many bytes more there is room for in the current record
- $space_remaining = $continue_limit - strlen($recordData);
-
- // minimum space needed
- // uncompressed: 2 byte string length length field + 1 byte option flags + 2 byte character
- // compressed: 2 byte string length length field + 1 byte option flags + 1 byte character
- $min_space_needed = ($encoding == 1) ? 5 : 4;
-
- // We have two cases
- // 1. space remaining is less than minimum space needed
- // here we must waste the space remaining and move to next record data block
- // 2. space remaining is greater than or equal to minimum space needed
- // here we write as much as we can in the current block, then move to next record data block
-
- // 1. space remaining is less than minimum space needed
- if ($space_remaining < $min_space_needed) {
- // we close the block, store the block data
- $recordDatas[] = $recordData;
-
- // and start new record data block where we start writing the string
- $recordData = '';
-
- // 2. space remaining is greater than or equal to minimum space needed
- } else {
- // initialize effective remaining space, for Unicode strings this may need to be reduced by 1, see below
- $effective_space_remaining = $space_remaining;
-
- // for uncompressed strings, sometimes effective space remaining is reduced by 1
- if ( $encoding == 1 && (strlen($string) - $space_remaining) % 2 == 1 ) {
- --$effective_space_remaining;
- }
-
- // one block fininshed, store the block data
- $recordData .= substr($string, 0, $effective_space_remaining);
-
- $string = substr($string, $effective_space_remaining); // for next cycle in while loop
- $recordDatas[] = $recordData;
-
- // start new record data block with the repeated option flags
- $recordData = pack('C', $encoding);
- }
- }
- }
- }
-
- // Store the last record data block unless it is empty
- // if there was no need for any continue records, this will be the for SST record data block itself
- if (strlen($recordData) > 0) {
- $recordDatas[] = $recordData;
- }
-
- // combine into one chunk with all the blocks SST, CONTINUE,...
- $chunk = '';
- foreach ($recordDatas as $i => $recordData) {
- // first block should have the SST record header, remaing should have CONTINUE header
- $record = ($i == 0) ? 0x00FC : 0x003C;
-
- $header = pack("vv", $record, strlen($recordData));
- $data = $header . $recordData;
-
- $chunk .= $this->writeData($data);
- }
-
- return $chunk;
- }
-
- /**
- * Writes the MSODRAWINGGROUP record if needed. Possibly split using CONTINUE records.
- */
- private function _writeMsoDrawingGroup()
- {
- // write the Escher stream if necessary
- if (isset($this->_escher)) {
- $writer = new Writer_Excel5_Escher($this->_escher);
- $data = $writer->close();
-
- $record = 0x00EB;
- $length = strlen($data);
- $header = pack("vv", $record, $length);
-
- return $this->writeData($header . $data);
-
- } else {
- return '';
- }
- }
-
- /**
- * Get Escher object
- *
- * @return PHPExcel\Shared_Escher
- */
- public function getEscher()
- {
- return $this->_escher;
- }
-
- /**
- * Set Escher object
- *
- * @param PHPExcel\Shared_Escher $pValue
- */
- public function setEscher(Shared_Escher $pValue = null)
- {
- $this->_escher = $pValue;
- }
+ /**
+ * Formula parser
+ *
+ * @var PHPExcel\Writer_Excel5_Parser
+ */
+ private $_parser;
+
+ /**
+ * The BIFF file size for the workbook.
+ * @var integer
+ * @see _calcSheetOffsets()
+ */
+ public $_biffsize;
+
+ /**
+ * XF Writers
+ * @var PHPExcel\Writer_Excel5_Xf[]
+ */
+ private $_xfWriters = array();
+
+ /**
+ * Array containing the colour palette
+ * @var array
+ */
+ public $_palette;
+
+ /**
+ * The codepage indicates the text encoding used for strings
+ * @var integer
+ */
+ public $_codepage;
+
+ /**
+ * The country code used for localization
+ * @var integer
+ */
+ public $_country_code;
+
+ /**
+ * Workbook
+ * @var PHPExcel
+ */
+ private $_phpExcel;
+
+ /**
+ * Fonts writers
+ *
+ * @var PHPExcel\Writer_Excel5_Font[]
+ */
+ private $_fontWriters = array();
+
+ /**
+ * Added fonts. Maps from font's hash => index in workbook
+ *
+ * @var array
+ */
+ private $_addedFonts = array();
+
+ /**
+ * Shared number formats
+ *
+ * @var array
+ */
+ private $_numberFormats = array();
+
+ /**
+ * Added number formats. Maps from numberFormat's hash => index in workbook
+ *
+ * @var array
+ */
+ private $_addedNumberFormats = array();
+
+ /**
+ * Sizes of the binary worksheet streams
+ *
+ * @var array
+ */
+ private $_worksheetSizes = array();
+
+ /**
+ * Offsets of the binary worksheet streams relative to the start of the global workbook stream
+ *
+ * @var array
+ */
+ private $_worksheetOffsets = array();
+
+ /**
+ * Total number of shared strings in workbook
+ *
+ * @var int
+ */
+ private $_str_total;
+
+ /**
+ * Number of unique shared strings in workbook
+ *
+ * @var int
+ */
+ private $_str_unique;
+
+ /**
+ * Array of unique shared strings in workbook
+ *
+ * @var array
+ */
+ private $_str_table;
+
+ /**
+ * Color cache
+ */
+ private $_colors;
+
+ /**
+ * Escher object corresponding to MSODRAWINGGROUP
+ *
+ * @var PHPExcel\Shared_Escher
+ */
+ private $_escher;
+
+
+ /**
+ * Class constructor
+ *
+ * @param PHPExcel\Workbook $phpExcel The Workbook
+ * @param int &$str_total Total number of strings
+ * @param int &$str_unique Total number of unique strings
+ * @param array &$str_table String Table
+ * @param array &$colors Colour Table
+ * @param mixed $parser The formula parser created for the Workbook
+ */
+ public function __construct(Workbook $phpExcel = null,
+ &$str_total, &$str_unique, &$str_table, &$colors,
+ $parser )
+ {
+ // It needs to call its parent's constructor explicitly
+ parent::__construct();
+
+ $this->_parser = $parser;
+ $this->_biffsize = 0;
+ $this->_palette = array();
+ $this->_country_code = -1;
+
+ $this->_str_total = &$str_total;
+ $this->_str_unique = &$str_unique;
+ $this->_str_table = &$str_table;
+ $this->_colors = &$colors;
+ $this->_setPaletteXl97();
+
+ $this->_phpExcel = $phpExcel;
+
+ // set BIFFwriter limit for CONTINUE records
+ // $this->_limit = 8224;
+ $this->_codepage = 0x04B0;
+
+ // Add empty sheets and Build color cache
+ $countSheets = $phpExcel->getSheetCount();
+ for ($i = 0; $i < $countSheets; ++$i) {
+ $phpSheet = $phpExcel->getSheet($i);
+
+ $this->_parser->setExtSheet($phpSheet->getTitle(), $i); // Register worksheet name with parser
+
+ $supbook_index = 0x00;
+ $ref = pack('vvv', $supbook_index, $i, $i);
+ $this->_parser->_references[] = $ref; // Register reference with parser
+
+ // Sheet tab colors?
+ if ($phpSheet->isTabColorSet()) {
+ $this->_addColor($phpSheet->getTabColor()->getRGB());
+ }
+ }
+
+ }
+
+ /**
+ * Add a new XF writer
+ *
+ * @param PHPExcel\Style
+ * @param boolean Is it a style XF?
+ * @return int Index to XF record
+ */
+ public function addXfWriter($style, $isStyleXf = false)
+ {
+ $xfWriter = new Writer_Excel5_Xf($style);
+ $xfWriter->setIsStyleXf($isStyleXf);
+
+ // Add the font if not already added
+ $fontIndex = $this->_addFont($style->getFont());
+
+ // Assign the font index to the xf record
+ $xfWriter->setFontIndex($fontIndex);
+
+ // Background colors, best to treat these after the font so black will come after white in custom palette
+ $xfWriter->setFgColor($this->_addColor($style->getFill()->getStartColor()->getRGB()));
+ $xfWriter->setBgColor($this->_addColor($style->getFill()->getEndColor()->getRGB()));
+ $xfWriter->setBottomColor($this->_addColor($style->getBorders()->getBottom()->getColor()->getRGB()));
+ $xfWriter->setTopColor($this->_addColor($style->getBorders()->getTop()->getColor()->getRGB()));
+ $xfWriter->setRightColor($this->_addColor($style->getBorders()->getRight()->getColor()->getRGB()));
+ $xfWriter->setLeftColor($this->_addColor($style->getBorders()->getLeft()->getColor()->getRGB()));
+ $xfWriter->setDiagColor($this->_addColor($style->getBorders()->getDiagonal()->getColor()->getRGB()));
+
+ // Add the number format if it is not a built-in one and not already added
+ if ($style->getNumberFormat()->getBuiltInFormatCode() === false) {
+ $numberFormatHashCode = $style->getNumberFormat()->getHashCode();
+
+ if (isset($this->_addedNumberFormats[$numberFormatHashCode])) {
+ $numberFormatIndex = $this->_addedNumberFormats[$numberFormatHashCode];
+ } else {
+ $numberFormatIndex = 164 + count($this->_numberFormats);
+ $this->_numberFormats[$numberFormatIndex] = $style->getNumberFormat();
+ $this->_addedNumberFormats[$numberFormatHashCode] = $numberFormatIndex;
+ }
+ } else {
+ $numberFormatIndex = (int) $style->getNumberFormat()->getBuiltInFormatCode();
+ }
+
+ // Assign the number format index to xf record
+ $xfWriter->setNumberFormatIndex($numberFormatIndex);
+
+ $this->_xfWriters[] = $xfWriter;
+
+ $xfIndex = count($this->_xfWriters) - 1;
+ return $xfIndex;
+ }
+
+ /**
+ * Add a font to added fonts
+ *
+ * @param PHPExcel\Style_Font $font
+ * @return int Index to FONT record
+ */
+ public function _addFont(Style_Font $font)
+ {
+ $fontHashCode = $font->getHashCode();
+ if(isset($this->_addedFonts[$fontHashCode])){
+ $fontIndex = $this->_addedFonts[$fontHashCode];
+ } else {
+ $countFonts = count($this->_fontWriters);
+ $fontIndex = ($countFonts < 4) ? $countFonts : $countFonts + 1;
+
+ $fontWriter = new Writer_Excel5_Font($font);
+ $fontWriter->setColorIndex($this->_addColor($font->getColor()->getRGB()));
+ $this->_fontWriters[] = $fontWriter;
+
+ $this->_addedFonts[$fontHashCode] = $fontIndex;
+ }
+ return $fontIndex;
+ }
+
+ /**
+ * Alter color palette adding a custom color
+ *
+ * @param string $rgb E.g. 'FF00AA'
+ * @return int Color index
+ */
+ private function _addColor($rgb) {
+ if (!isset($this->_colors[$rgb])) {
+ if (count($this->_colors) < 57) {
+ // then we add a custom color altering the palette
+ $colorIndex = 8 + count($this->_colors);
+ $this->_palette[$colorIndex] =
+ array(
+ hexdec(substr($rgb, 0, 2)),
+ hexdec(substr($rgb, 2, 2)),
+ hexdec(substr($rgb, 4)),
+ 0
+ );
+ $this->_colors[$rgb] = $colorIndex;
+ } else {
+ // no room for more custom colors, just map to black
+ $colorIndex = 0;
+ }
+ } else {
+ // fetch already added custom color
+ $colorIndex = $this->_colors[$rgb];
+ }
+
+ return $colorIndex;
+ }
+
+ /**
+ * Sets the colour palette to the Excel 97+ default.
+ *
+ * @access private
+ */
+ function _setPaletteXl97()
+ {
+ $this->_palette = array(
+ 0x08 => array(0x00, 0x00, 0x00, 0x00),
+ 0x09 => array(0xff, 0xff, 0xff, 0x00),
+ 0x0A => array(0xff, 0x00, 0x00, 0x00),
+ 0x0B => array(0x00, 0xff, 0x00, 0x00),
+ 0x0C => array(0x00, 0x00, 0xff, 0x00),
+ 0x0D => array(0xff, 0xff, 0x00, 0x00),
+ 0x0E => array(0xff, 0x00, 0xff, 0x00),
+ 0x0F => array(0x00, 0xff, 0xff, 0x00),
+ 0x10 => array(0x80, 0x00, 0x00, 0x00),
+ 0x11 => array(0x00, 0x80, 0x00, 0x00),
+ 0x12 => array(0x00, 0x00, 0x80, 0x00),
+ 0x13 => array(0x80, 0x80, 0x00, 0x00),
+ 0x14 => array(0x80, 0x00, 0x80, 0x00),
+ 0x15 => array(0x00, 0x80, 0x80, 0x00),
+ 0x16 => array(0xc0, 0xc0, 0xc0, 0x00),
+ 0x17 => array(0x80, 0x80, 0x80, 0x00),
+ 0x18 => array(0x99, 0x99, 0xff, 0x00),
+ 0x19 => array(0x99, 0x33, 0x66, 0x00),
+ 0x1A => array(0xff, 0xff, 0xcc, 0x00),
+ 0x1B => array(0xcc, 0xff, 0xff, 0x00),
+ 0x1C => array(0x66, 0x00, 0x66, 0x00),
+ 0x1D => array(0xff, 0x80, 0x80, 0x00),
+ 0x1E => array(0x00, 0x66, 0xcc, 0x00),
+ 0x1F => array(0xcc, 0xcc, 0xff, 0x00),
+ 0x20 => array(0x00, 0x00, 0x80, 0x00),
+ 0x21 => array(0xff, 0x00, 0xff, 0x00),
+ 0x22 => array(0xff, 0xff, 0x00, 0x00),
+ 0x23 => array(0x00, 0xff, 0xff, 0x00),
+ 0x24 => array(0x80, 0x00, 0x80, 0x00),
+ 0x25 => array(0x80, 0x00, 0x00, 0x00),
+ 0x26 => array(0x00, 0x80, 0x80, 0x00),
+ 0x27 => array(0x00, 0x00, 0xff, 0x00),
+ 0x28 => array(0x00, 0xcc, 0xff, 0x00),
+ 0x29 => array(0xcc, 0xff, 0xff, 0x00),
+ 0x2A => array(0xcc, 0xff, 0xcc, 0x00),
+ 0x2B => array(0xff, 0xff, 0x99, 0x00),
+ 0x2C => array(0x99, 0xcc, 0xff, 0x00),
+ 0x2D => array(0xff, 0x99, 0xcc, 0x00),
+ 0x2E => array(0xcc, 0x99, 0xff, 0x00),
+ 0x2F => array(0xff, 0xcc, 0x99, 0x00),
+ 0x30 => array(0x33, 0x66, 0xff, 0x00),
+ 0x31 => array(0x33, 0xcc, 0xcc, 0x00),
+ 0x32 => array(0x99, 0xcc, 0x00, 0x00),
+ 0x33 => array(0xff, 0xcc, 0x00, 0x00),
+ 0x34 => array(0xff, 0x99, 0x00, 0x00),
+ 0x35 => array(0xff, 0x66, 0x00, 0x00),
+ 0x36 => array(0x66, 0x66, 0x99, 0x00),
+ 0x37 => array(0x96, 0x96, 0x96, 0x00),
+ 0x38 => array(0x00, 0x33, 0x66, 0x00),
+ 0x39 => array(0x33, 0x99, 0x66, 0x00),
+ 0x3A => array(0x00, 0x33, 0x00, 0x00),
+ 0x3B => array(0x33, 0x33, 0x00, 0x00),
+ 0x3C => array(0x99, 0x33, 0x00, 0x00),
+ 0x3D => array(0x99, 0x33, 0x66, 0x00),
+ 0x3E => array(0x33, 0x33, 0x99, 0x00),
+ 0x3F => array(0x33, 0x33, 0x33, 0x00),
+ );
+ }
+
+ /**
+ * Assemble worksheets into a workbook and send the BIFF data to an OLE
+ * storage.
+ *
+ * @param array $pWorksheetSizes The sizes in bytes of the binary worksheet streams
+ * @return string Binary data for workbook stream
+ */
+ public function writeWorkbook($pWorksheetSizes = null)
+ {
+ $this->_worksheetSizes = $pWorksheetSizes;
+
+ // Calculate the number of selected worksheet tabs and call the finalization
+ // methods for each worksheet
+ $total_worksheets = $this->_phpExcel->getSheetCount();
+
+ // Add part 1 of the Workbook globals, what goes before the SHEET records
+ $this->_storeBof(0x0005);
+ $this->_writeCodepage();
+ $this->_writeWindow1();
+
+ $this->_writeDatemode();
+ $this->_writeAllFonts();
+ $this->_writeAllNumFormats();
+ $this->_writeAllXfs();
+ $this->_writeAllStyles();
+ $this->_writePalette();
+
+ // Prepare part 3 of the workbook global stream, what goes after the SHEET records
+ $part3 = '';
+ if ($this->_country_code != -1) {
+ $part3 .= $this->_writeCountry();
+ }
+ $part3 .= $this->_writeRecalcId();
+
+ $part3 .= $this->_writeSupbookInternal();
+ /* TODO: store external SUPBOOK records and XCT and CRN records
+ in case of external references for BIFF8 */
+ $part3 .= $this->_writeExternsheetBiff8();
+ $part3 .= $this->_writeAllDefinedNamesBiff8();
+ $part3 .= $this->_writeMsoDrawingGroup();
+ $part3 .= $this->_writeSharedStringsTable();
+
+ $part3 .= $this->writeEof();
+
+ // Add part 2 of the Workbook globals, the SHEET records
+ $this->_calcSheetOffsets();
+ for ($i = 0; $i < $total_worksheets; ++$i) {
+ $this->_writeBoundsheet($this->_phpExcel->getSheet($i), $this->_worksheetOffsets[$i]);
+ }
+
+ // Add part 3 of the Workbook globals
+ $this->_data .= $part3;
+
+ return $this->_data;
+ }
+
+ /**
+ * Calculate offsets for Worksheet BOF records.
+ *
+ * @access private
+ */
+ function _calcSheetOffsets()
+ {
+ $boundsheet_length = 10; // fixed length for a BOUNDSHEET record
+
+ // size of Workbook globals part 1 + 3
+ $offset = $this->_datasize;
+
+ // add size of Workbook globals part 2, the length of the SHEET records
+ $total_worksheets = count($this->_phpExcel->getAllSheets());
+ foreach ($this->_phpExcel->getWorksheetIterator() as $sheet) {
+ $offset += $boundsheet_length + strlen(Shared_String::UTF8toBIFF8UnicodeShort($sheet->getTitle()));
+ }
+
+ // add the sizes of each of the Sheet substreams, respectively
+ for ($i = 0; $i < $total_worksheets; ++$i) {
+ $this->_worksheetOffsets[$i] = $offset;
+ $offset += $this->_worksheetSizes[$i];
+ }
+ $this->_biffsize = $offset;
+ }
+
+ /**
+ * Store the Excel FONT records.
+ */
+ private function _writeAllFonts()
+ {
+ foreach ($this->_fontWriters as $fontWriter) {
+ $this->_append($fontWriter->writeFont());
+ }
+ }
+
+ /**
+ * Store user defined numerical formats i.e. FORMAT records
+ */
+ private function _writeAllNumFormats()
+ {
+ foreach ($this->_numberFormats as $numberFormatIndex => $numberFormat) {
+ $this->_writeNumFormat($numberFormat->getFormatCode(), $numberFormatIndex);
+ }
+ }
+
+ /**
+ * Write all XF records.
+ */
+ private function _writeAllXfs()
+ {
+ foreach ($this->_xfWriters as $xfWriter) {
+ $this->_append($xfWriter->writeXf());
+ }
+ }
+
+ /**
+ * Write all STYLE records.
+ */
+ private function _writeAllStyles()
+ {
+ $this->_writeStyle();
+ }
+
+ /**
+ * Write the EXTERNCOUNT and EXTERNSHEET records. These are used as indexes for
+ * the NAME records.
+ */
+ private function _writeExterns()
+ {
+ $countSheets = $this->_phpExcel->getSheetCount();
+ // Create EXTERNCOUNT with number of worksheets
+ $this->_writeExterncount($countSheets);
+
+ // Create EXTERNSHEET for each worksheet
+ for ($i = 0; $i < $countSheets; ++$i) {
+ $this->_writeExternsheet($this->_phpExcel->getSheet($i)->getTitle());
+ }
+ }
+
+ /**
+ * Write the NAME record to define the print area and the repeat rows and cols.
+ */
+ private function _writeNames()
+ {
+ // total number of sheets
+ $total_worksheets = $this->_phpExcel->getSheetCount();
+
+ // Create the print area NAME records
+ for ($i = 0; $i < $total_worksheets; ++$i) {
+ $sheetSetup = $this->_phpExcel->getSheet($i)->getPageSetup();
+ // Write a Name record if the print area has been defined
+ if ($sheetSetup->isPrintAreaSet()) {
+ // Print area
+ $printArea = Cell::splitRange($sheetSetup->getPrintArea());
+ $printArea = $printArea[0];
+ $printArea[0] = Cell::coordinateFromString($printArea[0]);
+ $printArea[1] = Cell::coordinateFromString($printArea[1]);
+
+ $print_rowmin = $printArea[0][1] - 1;
+ $print_rowmax = $printArea[1][1] - 1;
+ $print_colmin = Cell::columnIndexFromString($printArea[0][0]) - 1;
+ $print_colmax = Cell::columnIndexFromString($printArea[1][0]) - 1;
+
+ $this->_writeNameShort(
+ $i, // sheet index
+ 0x06, // NAME type
+ $print_rowmin,
+ $print_rowmax,
+ $print_colmin,
+ $print_colmax
+ );
+ }
+ }
+
+ // Create the print title NAME records
+ for ($i = 0; $i < $total_worksheets; ++$i) {
+ $sheetSetup = $this->_phpExcel->getSheet($i)->getPageSetup();
+
+ // simultaneous repeatColumns repeatRows
+ if ($sheetSetup->isColumnsToRepeatAtLeftSet() && $sheetSetup->isRowsToRepeatAtTopSet()) {
+ $repeat = $sheetSetup->getColumnsToRepeatAtLeft();
+ $colmin = Cell::columnIndexFromString($repeat[0]) - 1;
+ $colmax = Cell::columnIndexFromString($repeat[1]) - 1;
+
+ $repeat = $sheetSetup->getRowsToRepeatAtTop();
+ $rowmin = $repeat[0] - 1;
+ $rowmax = $repeat[1] - 1;
+
+ $this->_writeNameLong(
+ $i, // sheet index
+ 0x07, // NAME type
+ $rowmin,
+ $rowmax,
+ $colmin,
+ $colmax
+ );
+
+ // (exclusive) either repeatColumns or repeatRows
+ } else if ($sheetSetup->isColumnsToRepeatAtLeftSet() || $sheetSetup->isRowsToRepeatAtTopSet()) {
+
+ // Columns to repeat
+ if ($sheetSetup->isColumnsToRepeatAtLeftSet()) {
+ $repeat = $sheetSetup->getColumnsToRepeatAtLeft();
+ $colmin = Cell::columnIndexFromString($repeat[0]) - 1;
+ $colmax = Cell::columnIndexFromString($repeat[1]) - 1;
+ } else {
+ $colmin = 0;
+ $colmax = 255;
+ }
+
+ // Rows to repeat
+ if ($sheetSetup->isRowsToRepeatAtTopSet()) {
+ $repeat = $sheetSetup->getRowsToRepeatAtTop();
+ $rowmin = $repeat[0] - 1;
+ $rowmax = $repeat[1] - 1;
+ } else {
+ $rowmin = 0;
+ $rowmax = 65535;
+ }
+
+ $this->_writeNameShort(
+ $i, // sheet index
+ 0x07, // NAME type
+ $rowmin,
+ $rowmax,
+ $colmin,
+ $colmax
+ );
+ }
+ }
+ }
+
+ /**
+ * Writes all the DEFINEDNAME records (BIFF8).
+ * So far this is only used for repeating rows/columns (print titles) and print areas
+ */
+ private function _writeAllDefinedNamesBiff8()
+ {
+ $chunk = '';
+
+ // Named ranges
+ if (count($this->_phpExcel->getNamedRanges()) > 0) {
+ // Loop named ranges
+ $namedRanges = $this->_phpExcel->getNamedRanges();
+ foreach ($namedRanges as $namedRange) {
+
+ // Create absolute coordinate
+ $range = Cell::splitRange($namedRange->getRange());
+ for ($i = 0; $i < count($range); $i++) {
+ $range[$i][0] = '\'' . str_replace("'", "''", $namedRange->getWorksheet()->getTitle()) . '\'!' . Cell::absoluteCoordinate($range[$i][0]);
+ if (isset($range[$i][1])) {
+ $range[$i][1] = Cell::absoluteCoordinate($range[$i][1]);
+ }
+ }
+ $range = Cell::buildRange($range); // e.g. Sheet1!$A$1:$B$2
+
+ // parse formula
+ try {
+ $error = $this->_parser->parse($range);
+ $formulaData = $this->_parser->toReversePolish();
+
+ // make sure tRef3d is of type tRef3dR (0x3A)
+ if (isset($formulaData{0}) and ($formulaData{0} == "\x7A" or $formulaData{0} == "\x5A")) {
+ $formulaData = "\x3A" . substr($formulaData, 1);
+ }
+
+ if ($namedRange->getLocalOnly()) {
+ // local scope
+ $scope = $this->_phpExcel->getIndex($namedRange->getScope()) + 1;
+ } else {
+ // global scope
+ $scope = 0;
+ }
+ $chunk .= $this->writeData($this->_writeDefinedNameBiff8($namedRange->getName(), $formulaData, $scope, false));
+
+ } catch(Exception $e) {
+ // do nothing
+ }
+ }
+ }
+
+ // total number of sheets
+ $total_worksheets = $this->_phpExcel->getSheetCount();
+
+ // write the print titles (repeating rows, columns), if any
+ for ($i = 0; $i < $total_worksheets; ++$i) {
+ $sheetSetup = $this->_phpExcel->getSheet($i)->getPageSetup();
+ // simultaneous repeatColumns repeatRows
+ if ($sheetSetup->isColumnsToRepeatAtLeftSet() && $sheetSetup->isRowsToRepeatAtTopSet()) {
+ $repeat = $sheetSetup->getColumnsToRepeatAtLeft();
+ $colmin = Cell::columnIndexFromString($repeat[0]) - 1;
+ $colmax = Cell::columnIndexFromString($repeat[1]) - 1;
+
+ $repeat = $sheetSetup->getRowsToRepeatAtTop();
+ $rowmin = $repeat[0] - 1;
+ $rowmax = $repeat[1] - 1;
+
+ // construct formula data manually
+ $formulaData = pack('Cv', 0x29, 0x17); // tMemFunc
+ $formulaData .= pack('Cvvvvv', 0x3B, $i, 0, 65535, $colmin, $colmax); // tArea3d
+ $formulaData .= pack('Cvvvvv', 0x3B, $i, $rowmin, $rowmax, 0, 255); // tArea3d
+ $formulaData .= pack('C', 0x10); // tList
+
+ // store the DEFINEDNAME record
+ $chunk .= $this->writeData($this->_writeDefinedNameBiff8(pack('C', 0x07), $formulaData, $i + 1, true));
+
+ // (exclusive) either repeatColumns or repeatRows
+ } else if ($sheetSetup->isColumnsToRepeatAtLeftSet() || $sheetSetup->isRowsToRepeatAtTopSet()) {
+
+ // Columns to repeat
+ if ($sheetSetup->isColumnsToRepeatAtLeftSet()) {
+ $repeat = $sheetSetup->getColumnsToRepeatAtLeft();
+ $colmin = Cell::columnIndexFromString($repeat[0]) - 1;
+ $colmax = Cell::columnIndexFromString($repeat[1]) - 1;
+ } else {
+ $colmin = 0;
+ $colmax = 255;
+ }
+ // Rows to repeat
+ if ($sheetSetup->isRowsToRepeatAtTopSet()) {
+ $repeat = $sheetSetup->getRowsToRepeatAtTop();
+ $rowmin = $repeat[0] - 1;
+ $rowmax = $repeat[1] - 1;
+ } else {
+ $rowmin = 0;
+ $rowmax = 65535;
+ }
+
+ // construct formula data manually because parser does not recognize absolute 3d cell references
+ $formulaData = pack('Cvvvvv', 0x3B, $i, $rowmin, $rowmax, $colmin, $colmax);
+
+ // store the DEFINEDNAME record
+ $chunk .= $this->writeData($this->_writeDefinedNameBiff8(pack('C', 0x07), $formulaData, $i + 1, true));
+ }
+ }
+
+ // write the print areas, if any
+ for ($i = 0; $i < $total_worksheets; ++$i) {
+ $sheetSetup = $this->_phpExcel->getSheet($i)->getPageSetup();
+ if ($sheetSetup->isPrintAreaSet()) {
+ // Print area, e.g. A3:J6,H1:X20
+ $printArea = Cell::splitRange($sheetSetup->getPrintArea());
+ $countPrintArea = count($printArea);
+
+ $formulaData = '';
+ for ($j = 0; $j < $countPrintArea; ++$j) {
+ $printAreaRect = $printArea[$j]; // e.g. A3:J6
+ $printAreaRect[0] = Cell::coordinateFromString($printAreaRect[0]);
+ $printAreaRect[1] = Cell::coordinateFromString($printAreaRect[1]);
+
+ $print_rowmin = $printAreaRect[0][1] - 1;
+ $print_rowmax = $printAreaRect[1][1] - 1;
+ $print_colmin = Cell::columnIndexFromString($printAreaRect[0][0]) - 1;
+ $print_colmax = Cell::columnIndexFromString($printAreaRect[1][0]) - 1;
+
+ // construct formula data manually because parser does not recognize absolute 3d cell references
+ $formulaData .= pack('Cvvvvv', 0x3B, $i, $print_rowmin, $print_rowmax, $print_colmin, $print_colmax);
+
+ if ($j > 0) {
+ $formulaData .= pack('C', 0x10); // list operator token ','
+ }
+ }
+
+ // store the DEFINEDNAME record
+ $chunk .= $this->writeData($this->_writeDefinedNameBiff8(pack('C', 0x06), $formulaData, $i + 1, true));
+ }
+ }
+
+ // write autofilters, if any
+ for ($i = 0; $i < $total_worksheets; ++$i) {
+ $sheetAutoFilter = $this->_phpExcel->getSheet($i)->getAutoFilter();
+ $autoFilterRange = $sheetAutoFilter->getRange();
+ if(!empty($autoFilterRange)) {
+ $rangeBounds = Cell::rangeBoundaries($autoFilterRange);
+
+ //Autofilter built in name
+ $name = pack('C', 0x0D);
+
+ $chunk .= $this->writeData($this->_writeShortNameBiff8($name, $i + 1, $rangeBounds, true));
+ }
+ }
+
+ return $chunk;
+ }
+
+ /**
+ * Write a DEFINEDNAME record for BIFF8 using explicit binary formula data
+ *
+ * @param string $name The name in UTF-8
+ * @param string $formulaData The binary formula data
+ * @param string $sheetIndex 1-based sheet index the defined name applies to. 0 = global
+ * @param boolean $isBuiltIn Built-in name?
+ * @return string Complete binary record data
+ */
+ private function _writeDefinedNameBiff8($name, $formulaData, $sheetIndex = 0, $isBuiltIn = false)
+ {
+ $record = 0x0018;
+
+ // option flags
+ $options = $isBuiltIn ? 0x20 : 0x00;
+
+ // length of the name, character count
+ $nlen = Shared_String::CountCharacters($name);
+
+ // name with stripped length field
+ $name = substr(Shared_String::UTF8toBIFF8UnicodeLong($name), 2);
+
+ // size of the formula (in bytes)
+ $sz = strlen($formulaData);
+
+ // combine the parts
+ $data = pack('vCCvvvCCCC', $options, 0, $nlen, $sz, 0, $sheetIndex, 0, 0, 0, 0)
+ . $name . $formulaData;
+ $length = strlen($data);
+
+ $header = pack('vv', $record, $length);
+
+ return $header . $data;
+ }
+
+ /**
+ * Write a short NAME record
+ *
+ * @param string $name
+ * @param string $sheetIndex 1-based sheet index the defined name applies to. 0 = global
+ * @param integer[][] $rangeBounds range boundaries
+ * @param boolean $isHidden
+ * @return string Complete binary record data
+ * */
+ private function _writeShortNameBiff8($name, $sheetIndex = 0, $rangeBounds, $isHidden = false){
+ $record = 0x0018;
+
+ // option flags
+ $options = ($isHidden ? 0x21 : 0x00);
+
+ $extra = pack('Cvvvvv',
+ 0x3B,
+ $sheetIndex - 1,
+ $rangeBounds[0][1] - 1,
+ $rangeBounds[1][1] - 1,
+ $rangeBounds[0][0] - 1,
+ $rangeBounds[1][0] - 1);
+
+ // size of the formula (in bytes)
+ $sz = strlen($extra);
+
+ // combine the parts
+ $data = pack('vCCvvvCCCCC', $options, 0, 1, $sz, 0, $sheetIndex, 0, 0, 0, 0, 0)
+ . $name . $extra;
+ $length = strlen($data);
+
+ $header = pack('vv', $record, $length);
+
+ return $header . $data;
+ }
+
+ /**
+ * Stores the CODEPAGE biff record.
+ */
+ private function _writeCodepage()
+ {
+ $record = 0x0042; // Record identifier
+ $length = 0x0002; // Number of bytes to follow
+ $cv = $this->_codepage; // The code page
+
+ $header = pack('vv', $record, $length);
+ $data = pack('v', $cv);
+
+ $this->_append($header . $data);
+ }
+
+ /**
+ * Write Excel BIFF WINDOW1 record.
+ */
+ private function _writeWindow1()
+ {
+ $record = 0x003D; // Record identifier
+ $length = 0x0012; // Number of bytes to follow
+
+ $xWn = 0x0000; // Horizontal position of window
+ $yWn = 0x0000; // Vertical position of window
+ $dxWn = 0x25BC; // Width of window
+ $dyWn = 0x1572; // Height of window
+
+ $grbit = 0x0038; // Option flags
+
+ // not supported by PHPExcel, so there is only one selected sheet, the active
+ $ctabsel = 1; // Number of workbook tabs selected
+
+ $wTabRatio = 0x0258; // Tab to scrollbar ratio
+
+ // not supported by PHPExcel, set to 0
+ $itabFirst = 0; // 1st displayed worksheet
+ $itabCur = $this->_phpExcel->getActiveSheetIndex(); // Active worksheet
+
+ $header = pack("vv", $record, $length);
+ $data = pack("vvvvvvvvv", $xWn, $yWn, $dxWn, $dyWn,
+ $grbit,
+ $itabCur, $itabFirst,
+ $ctabsel, $wTabRatio);
+ $this->_append($header . $data);
+ }
+
+ /**
+ * Writes Excel BIFF BOUNDSHEET record.
+ *
+ * @param PHPExcel\Worksheet $sheet Worksheet name
+ * @param integer $offset Location of worksheet BOF
+ */
+ private function _writeBoundsheet($sheet, $offset)
+ {
+ $sheetname = $sheet->getTitle();
+ $record = 0x0085; // Record identifier
+
+ // sheet state
+ switch ($sheet->getSheetState()) {
+ case Worksheet::SHEETSTATE_VISIBLE: $ss = 0x00; break;
+ case Worksheet::SHEETSTATE_HIDDEN: $ss = 0x01; break;
+ case Worksheet::SHEETSTATE_VERYHIDDEN: $ss = 0x02; break;
+ default: $ss = 0x00; break;
+ }
+
+ // sheet type
+ $st = 0x00;
+
+ $grbit = 0x0000; // Visibility and sheet type
+
+ $data = pack("VCC", $offset, $ss, $st);
+ $data .= Shared_String::UTF8toBIFF8UnicodeShort($sheetname);
+
+ $length = strlen($data);
+ $header = pack("vv", $record, $length);
+ $this->_append($header . $data);
+ }
+
+ /**
+ * Write Internal SUPBOOK record
+ */
+ private function _writeSupbookInternal()
+ {
+ $record = 0x01AE; // Record identifier
+ $length = 0x0004; // Bytes to follow
+
+ $header = pack("vv", $record, $length);
+ $data = pack("vv", $this->_phpExcel->getSheetCount(), 0x0401);
+ return $this->writeData($header . $data);
+ }
+
+ /**
+ * Writes the Excel BIFF EXTERNSHEET record. These references are used by
+ * formulas.
+ *
+ */
+ private function _writeExternsheetBiff8()
+ {
+ $total_references = count($this->_parser->_references);
+ $record = 0x0017; // Record identifier
+ $length = 2 + 6 * $total_references; // Number of bytes to follow
+
+ $supbook_index = 0; // FIXME: only using internal SUPBOOK record
+ $header = pack("vv", $record, $length);
+ $data = pack('v', $total_references);
+ for ($i = 0; $i < $total_references; ++$i) {
+ $data .= $this->_parser->_references[$i];
+ }
+ return $this->writeData($header . $data);
+ }
+
+ /**
+ * Write Excel BIFF STYLE records.
+ */
+ private function _writeStyle()
+ {
+ $record = 0x0293; // Record identifier
+ $length = 0x0004; // Bytes to follow
+
+ $ixfe = 0x8000; // Index to cell style XF
+ $BuiltIn = 0x00; // Built-in style
+ $iLevel = 0xff; // Outline style level
+
+ $header = pack("vv", $record, $length);
+ $data = pack("vCC", $ixfe, $BuiltIn, $iLevel);
+ $this->_append($header . $data);
+ }
+
+ /**
+ * Writes Excel FORMAT record for non "built-in" numerical formats.
+ *
+ * @param string $format Custom format string
+ * @param integer $ifmt Format index code
+ */
+ private function _writeNumFormat($format, $ifmt)
+ {
+ $record = 0x041E; // Record identifier
+
+ $numberFormatString = Shared_String::UTF8toBIFF8UnicodeLong($format);
+ $length = 2 + strlen($numberFormatString); // Number of bytes to follow
+
+
+ $header = pack("vv", $record, $length);
+ $data = pack("v", $ifmt) . $numberFormatString;
+ $this->_append($header . $data);
+ }
+
+ /**
+ * Write DATEMODE record to indicate the date system in use (1904 or 1900).
+ */
+ private function _writeDatemode()
+ {
+ $record = 0x0022; // Record identifier
+ $length = 0x0002; // Bytes to follow
+
+ $f1904 = (Shared_Date::getExcelCalendar() == Shared_Date::CALENDAR_MAC_1904) ?
+ 1 : 0; // Flag for 1904 date system
+
+ $header = pack("vv", $record, $length);
+ $data = pack("v", $f1904);
+ $this->_append($header . $data);
+ }
+
+ /**
+ * Write BIFF record EXTERNCOUNT to indicate the number of external sheet
+ * references in the workbook.
+ *
+ * Excel only stores references to external sheets that are used in NAME.
+ * The workbook NAME record is required to define the print area and the repeat
+ * rows and columns.
+ *
+ * A similar method is used in Worksheet.php for a slightly different purpose.
+ *
+ * @param integer $cxals Number of external references
+ */
+ private function _writeExterncount($cxals)
+ {
+ $record = 0x0016; // Record identifier
+ $length = 0x0002; // Number of bytes to follow
+
+ $header = pack("vv", $record, $length);
+ $data = pack("v", $cxals);
+ $this->_append($header . $data);
+ }
+
+ /**
+ * Writes the Excel BIFF EXTERNSHEET record. These references are used by
+ * formulas. NAME record is required to define the print area and the repeat
+ * rows and columns.
+ *
+ * A similar method is used in Worksheet.php for a slightly different purpose.
+ *
+ * @param string $sheetname Worksheet name
+ */
+ private function _writeExternsheet($sheetname)
+ {
+ $record = 0x0017; // Record identifier
+ $length = 0x02 + strlen($sheetname); // Number of bytes to follow
+
+ $cch = strlen($sheetname); // Length of sheet name
+ $rgch = 0x03; // Filename encoding
+
+ $header = pack("vv", $record, $length);
+ $data = pack("CC", $cch, $rgch);
+ $this->_append($header . $data . $sheetname);
+ }
+
+ /**
+ * Store the NAME record in the short format that is used for storing the print
+ * area, repeat rows only and repeat columns only.
+ *
+ * @param integer $index Sheet index
+ * @param integer $type Built-in name type
+ * @param integer $rowmin Start row
+ * @param integer $rowmax End row
+ * @param integer $colmin Start colum
+ * @param integer $colmax End column
+ */
+ private function _writeNameShort($index, $type, $rowmin, $rowmax, $colmin, $colmax)
+ {
+ $record = 0x0018; // Record identifier
+ $length = 0x0024; // Number of bytes to follow
+
+ $grbit = 0x0020; // Option flags
+ $chKey = 0x00; // Keyboard shortcut
+ $cch = 0x01; // Length of text name
+ $cce = 0x0015; // Length of text definition
+ $ixals = $index + 1; // Sheet index
+ $itab = $ixals; // Equal to ixals
+ $cchCustMenu = 0x00; // Length of cust menu text
+ $cchDescription = 0x00; // Length of description text
+ $cchHelptopic = 0x00; // Length of help topic text
+ $cchStatustext = 0x00; // Length of status bar text
+ $rgch = $type; // Built-in name type
+
+ $unknown03 = 0x3b;
+ $unknown04 = 0xffff-$index;
+ $unknown05 = 0x0000;
+ $unknown06 = 0x0000;
+ $unknown07 = 0x1087;
+ $unknown08 = 0x8005;
+
+ $header = pack("vv", $record, $length);
+ $data = pack("v", $grbit);
+ $data .= pack("C", $chKey);
+ $data .= pack("C", $cch);
+ $data .= pack("v", $cce);
+ $data .= pack("v", $ixals);
+ $data .= pack("v", $itab);
+ $data .= pack("C", $cchCustMenu);
+ $data .= pack("C", $cchDescription);
+ $data .= pack("C", $cchHelptopic);
+ $data .= pack("C", $cchStatustext);
+ $data .= pack("C", $rgch);
+ $data .= pack("C", $unknown03);
+ $data .= pack("v", $unknown04);
+ $data .= pack("v", $unknown05);
+ $data .= pack("v", $unknown06);
+ $data .= pack("v", $unknown07);
+ $data .= pack("v", $unknown08);
+ $data .= pack("v", $index);
+ $data .= pack("v", $index);
+ $data .= pack("v", $rowmin);
+ $data .= pack("v", $rowmax);
+ $data .= pack("C", $colmin);
+ $data .= pack("C", $colmax);
+ $this->_append($header . $data);
+ }
+
+ /**
+ * Store the NAME record in the long format that is used for storing the repeat
+ * rows and columns when both are specified. This shares a lot of code with
+ * _writeNameShort() but we use a separate method to keep the code clean.
+ * Code abstraction for reuse can be carried too far, and I should know. ;-)
+ *
+ * @param integer $index Sheet index
+ * @param integer $type Built-in name type
+ * @param integer $rowmin Start row
+ * @param integer $rowmax End row
+ * @param integer $colmin Start colum
+ * @param integer $colmax End column
+ */
+ private function _writeNameLong($index, $type, $rowmin, $rowmax, $colmin, $colmax)
+ {
+ $record = 0x0018; // Record identifier
+ $length = 0x003d; // Number of bytes to follow
+ $grbit = 0x0020; // Option flags
+ $chKey = 0x00; // Keyboard shortcut
+ $cch = 0x01; // Length of text name
+ $cce = 0x002e; // Length of text definition
+ $ixals = $index + 1; // Sheet index
+ $itab = $ixals; // Equal to ixals
+ $cchCustMenu = 0x00; // Length of cust menu text
+ $cchDescription = 0x00; // Length of description text
+ $cchHelptopic = 0x00; // Length of help topic text
+ $cchStatustext = 0x00; // Length of status bar text
+ $rgch = $type; // Built-in name type
+
+ $unknown01 = 0x29;
+ $unknown02 = 0x002b;
+ $unknown03 = 0x3b;
+ $unknown04 = 0xffff-$index;
+ $unknown05 = 0x0000;
+ $unknown06 = 0x0000;
+ $unknown07 = 0x1087;
+ $unknown08 = 0x8008;
+
+ $header = pack("vv", $record, $length);
+ $data = pack("v", $grbit);
+ $data .= pack("C", $chKey);
+ $data .= pack("C", $cch);
+ $data .= pack("v", $cce);
+ $data .= pack("v", $ixals);
+ $data .= pack("v", $itab);
+ $data .= pack("C", $cchCustMenu);
+ $data .= pack("C", $cchDescription);
+ $data .= pack("C", $cchHelptopic);
+ $data .= pack("C", $cchStatustext);
+ $data .= pack("C", $rgch);
+ $data .= pack("C", $unknown01);
+ $data .= pack("v", $unknown02);
+ // Column definition
+ $data .= pack("C", $unknown03);
+ $data .= pack("v", $unknown04);
+ $data .= pack("v", $unknown05);
+ $data .= pack("v", $unknown06);
+ $data .= pack("v", $unknown07);
+ $data .= pack("v", $unknown08);
+ $data .= pack("v", $index);
+ $data .= pack("v", $index);
+ $data .= pack("v", 0x0000);
+ $data .= pack("v", 0x3fff);
+ $data .= pack("C", $colmin);
+ $data .= pack("C", $colmax);
+ // Row definition
+ $data .= pack("C", $unknown03);
+ $data .= pack("v", $unknown04);
+ $data .= pack("v", $unknown05);
+ $data .= pack("v", $unknown06);
+ $data .= pack("v", $unknown07);
+ $data .= pack("v", $unknown08);
+ $data .= pack("v", $index);
+ $data .= pack("v", $index);
+ $data .= pack("v", $rowmin);
+ $data .= pack("v", $rowmax);
+ $data .= pack("C", 0x00);
+ $data .= pack("C", 0xff);
+ // End of data
+ $data .= pack("C", 0x10);
+ $this->_append($header . $data);
+ }
+
+ /**
+ * Stores the COUNTRY record for localization
+ *
+ * @return string
+ */
+ private function _writeCountry()
+ {
+ $record = 0x008C; // Record identifier
+ $length = 4; // Number of bytes to follow
+
+ $header = pack('vv', $record, $length);
+ /* using the same country code always for simplicity */
+ $data = pack('vv', $this->_country_code, $this->_country_code);
+ //$this->_append($header . $data);
+ return $this->writeData($header . $data);
+ }
+
+ /**
+ * Write the RECALCID record
+ *
+ * @return string
+ */
+ private function _writeRecalcId()
+ {
+ $record = 0x01C1; // Record identifier
+ $length = 8; // Number of bytes to follow
+
+ $header = pack('vv', $record, $length);
+
+ // by inspection of real Excel files, MS Office Excel 2007 writes this
+ $data = pack('VV', 0x000001C1, 0x00001E667);
+
+ return $this->writeData($header . $data);
+ }
+
+ /**
+ * Stores the PALETTE biff record.
+ */
+ private function _writePalette()
+ {
+ $aref = $this->_palette;
+
+ $record = 0x0092; // Record identifier
+ $length = 2 + 4 * count($aref); // Number of bytes to follow
+ $ccv = count($aref); // Number of RGB values to follow
+ $data = ''; // The RGB data
+
+ // Pack the RGB data
+ foreach ($aref as $color) {
+ foreach ($color as $byte) {
+ $data .= pack("C",$byte);
+ }
+ }
+
+ $header = pack("vvv", $record, $length, $ccv);
+ $this->_append($header . $data);
+ }
+
+ /**
+ * Handling of the SST continue blocks is complicated by the need to include an
+ * additional continuation byte depending on whether the string is split between
+ * blocks or whether it starts at the beginning of the block. (There are also
+ * additional complications that will arise later when/if Rich Strings are
+ * supported).
+ *
+ * The Excel documentation says that the SST record should be followed by an
+ * EXTSST record. The EXTSST record is a hash table that is used to optimise
+ * access to SST. However, despite the documentation it doesn't seem to be
+ * required so we will ignore it.
+ *
+ * @return string Binary data
+ */
+ private function _writeSharedStringsTable()
+ {
+ // maximum size of record data (excluding record header)
+ $continue_limit = 8224;
+
+ // initialize array of record data blocks
+ $recordDatas = array();
+
+ // start SST record data block with total number of strings, total number of unique strings
+ $recordData = pack("VV", $this->_str_total, $this->_str_unique);
+
+ // loop through all (unique) strings in shared strings table
+ foreach (array_keys($this->_str_table) as $string) {
+
+ // here $string is a BIFF8 encoded string
+
+ // length = character count
+ $headerinfo = unpack("vlength/Cencoding", $string);
+
+ // currently, this is always 1 = uncompressed
+ $encoding = $headerinfo["encoding"];
+
+ // initialize finished writing current $string
+ $finished = false;
+
+ while ($finished === false) {
+
+ // normally, there will be only one cycle, but if string cannot immediately be written as is
+ // there will be need for more than one cylcle, if string longer than one record data block, there
+ // may be need for even more cycles
+
+ if (strlen($recordData) + strlen($string) <= $continue_limit) {
+ // then we can write the string (or remainder of string) without any problems
+ $recordData .= $string;
+
+ if (strlen($recordData) + strlen($string) == $continue_limit) {
+ // we close the record data block, and initialize a new one
+ $recordDatas[] = $recordData;
+ $recordData = '';
+ }
+
+ // we are finished writing this string
+ $finished = true;
+ } else {
+ // special treatment writing the string (or remainder of the string)
+ // If the string is very long it may need to be written in more than one CONTINUE record.
+
+ // check how many bytes more there is room for in the current record
+ $space_remaining = $continue_limit - strlen($recordData);
+
+ // minimum space needed
+ // uncompressed: 2 byte string length length field + 1 byte option flags + 2 byte character
+ // compressed: 2 byte string length length field + 1 byte option flags + 1 byte character
+ $min_space_needed = ($encoding == 1) ? 5 : 4;
+
+ // We have two cases
+ // 1. space remaining is less than minimum space needed
+ // here we must waste the space remaining and move to next record data block
+ // 2. space remaining is greater than or equal to minimum space needed
+ // here we write as much as we can in the current block, then move to next record data block
+
+ // 1. space remaining is less than minimum space needed
+ if ($space_remaining < $min_space_needed) {
+ // we close the block, store the block data
+ $recordDatas[] = $recordData;
+
+ // and start new record data block where we start writing the string
+ $recordData = '';
+
+ // 2. space remaining is greater than or equal to minimum space needed
+ } else {
+ // initialize effective remaining space, for Unicode strings this may need to be reduced by 1, see below
+ $effective_space_remaining = $space_remaining;
+
+ // for uncompressed strings, sometimes effective space remaining is reduced by 1
+ if ( $encoding == 1 && (strlen($string) - $space_remaining) % 2 == 1 ) {
+ --$effective_space_remaining;
+ }
+
+ // one block fininshed, store the block data
+ $recordData .= substr($string, 0, $effective_space_remaining);
+
+ $string = substr($string, $effective_space_remaining); // for next cycle in while loop
+ $recordDatas[] = $recordData;
+
+ // start new record data block with the repeated option flags
+ $recordData = pack('C', $encoding);
+ }
+ }
+ }
+ }
+
+ // Store the last record data block unless it is empty
+ // if there was no need for any continue records, this will be the for SST record data block itself
+ if (strlen($recordData) > 0) {
+ $recordDatas[] = $recordData;
+ }
+
+ // combine into one chunk with all the blocks SST, CONTINUE,...
+ $chunk = '';
+ foreach ($recordDatas as $i => $recordData) {
+ // first block should have the SST record header, remaing should have CONTINUE header
+ $record = ($i == 0) ? 0x00FC : 0x003C;
+
+ $header = pack("vv", $record, strlen($recordData));
+ $data = $header . $recordData;
+
+ $chunk .= $this->writeData($data);
+ }
+
+ return $chunk;
+ }
+
+ /**
+ * Writes the MSODRAWINGGROUP record if needed. Possibly split using CONTINUE records.
+ */
+ private function _writeMsoDrawingGroup()
+ {
+ // write the Escher stream if necessary
+ if (isset($this->_escher)) {
+ $writer = new Writer_Excel5_Escher($this->_escher);
+ $data = $writer->close();
+
+ $record = 0x00EB;
+ $length = strlen($data);
+ $header = pack("vv", $record, $length);
+
+ return $this->writeData($header . $data);
+
+ } else {
+ return '';
+ }
+ }
+
+ /**
+ * Get Escher object
+ *
+ * @return PHPExcel\Shared_Escher
+ */
+ public function getEscher()
+ {
+ return $this->_escher;
+ }
+
+ /**
+ * Set Escher object
+ *
+ * @param PHPExcel\Shared_Escher $pValue
+ */
+ public function setEscher(Shared_Escher $pValue = null)
+ {
+ $this->_escher = $pValue;
+ }
}
diff --git a/Classes/PHPExcel/Writer/Excel5/Worksheet.php b/Classes/PHPExcel/Writer/Excel5/Worksheet.php
index 7ad827a..420e1ae 100644
--- a/Classes/PHPExcel/Writer/Excel5/Worksheet.php
+++ b/Classes/PHPExcel/Writer/Excel5/Worksheet.php
@@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\Writer_Excel5
* @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##
*/
@@ -72,3612 +72,3612 @@ namespace PHPExcel;
*/
class Writer_Excel5_Worksheet extends Writer_Excel5_BIFFwriter
{
- /**
- * Formula parser
- *
- * @var PHPExcel\Writer_Excel5_Parser
- */
- private $_parser;
-
- /**
- * Maximum number of characters for a string (LABEL record in BIFF5)
- * @var integer
- */
- public $_xls_strmax;
-
- /**
- * Array containing format information for columns
- * @var array
- */
- public $_colinfo;
-
- /**
- * Array containing the selected area for the worksheet
- * @var array
- */
- public $_selection;
-
- /**
- * The active pane for the worksheet
- * @var integer
- */
- public $_active_pane;
-
- /**
- * Whether to use outline.
- * @var integer
- */
- public $_outline_on;
-
- /**
- * Auto outline styles.
- * @var bool
- */
- public $_outline_style;
-
- /**
- * Whether to have outline summary below.
- * @var bool
- */
- public $_outline_below;
-
- /**
- * Whether to have outline summary at the right.
- * @var bool
- */
- public $_outline_right;
-
- /**
- * Reference to the total number of strings in the workbook
- * @var integer
- */
- public $_str_total;
-
- /**
- * Reference to the number of unique strings in the workbook
- * @var integer
- */
- public $_str_unique;
-
- /**
- * Reference to the array containing all the unique strings in the workbook
- * @var array
- */
- public $_str_table;
-
- /**
- * Color cache
- */
- private $_colors;
-
- /**
- * Index of first used row (at least 0)
- * @var int
- */
- private $_firstRowIndex;
-
- /**
- * Index of last used row. (no used rows means -1)
- * @var int
- */
- private $_lastRowIndex;
-
- /**
- * Index of first used column (at least 0)
- * @var int
- */
- private $_firstColumnIndex;
-
- /**
- * Index of last used column (no used columns means -1)
- * @var int
- */
- private $_lastColumnIndex;
-
- /**
- * Sheet object
- * @var PHPExcel\Worksheet
- */
- public $_phpSheet;
-
- /**
- * Count cell style Xfs
- *
- * @var int
- */
- private $_countCellStyleXfs;
-
- /**
- * Escher object corresponding to MSODRAWING
- *
- * @var PHPExcel\Shared_Escher
- */
- private $_escher;
-
- /**
- * Array of font hashes associated to FONT records index
- *
- * @var array
- */
- public $_fntHashIndex;
-
- /**
- * Constructor
- *
- * @param int &$str_total Total number of strings
- * @param int &$str_unique Total number of unique strings
- * @param array &$str_table String Table
- * @param array &$colors Colour Table
- * @param mixed $parser The formula parser created for the Workbook
- * @param boolean $preCalculateFormulas Flag indicating whether formulas should be calculated or just written
- * @param string $phpSheet The worksheet to write
- * @param PHPExcel\Worksheet $phpSheet
- */
- public function __construct(&$str_total, &$str_unique, &$str_table, &$colors,
- $parser, $preCalculateFormulas, $phpSheet)
- {
- // It needs to call its parent's constructor explicitly
- parent::__construct();
-
- // change BIFFwriter limit for CONTINUE records
-// $this->_limit = 8224;
-
-
- $this->_preCalculateFormulas = $preCalculateFormulas;
- $this->_str_total = &$str_total;
- $this->_str_unique = &$str_unique;
- $this->_str_table = &$str_table;
- $this->_colors = &$colors;
- $this->_parser = $parser;
-
- $this->_phpSheet = $phpSheet;
-
- //$this->ext_sheets = array();
- //$this->offset = 0;
- $this->_xls_strmax = 255;
- $this->_colinfo = array();
- $this->_selection = array(0,0,0,0);
- $this->_active_pane = 3;
-
- $this->_print_headers = 0;
-
- $this->_outline_style = 0;
- $this->_outline_below = 1;
- $this->_outline_right = 1;
- $this->_outline_on = 1;
-
- $this->_fntHashIndex = array();
-
- // calculate values for DIMENSIONS record
- $minR = 1;
- $minC = 'A';
-
- $maxR = $this->_phpSheet->getHighestRow();
- $maxC = $this->_phpSheet->getHighestColumn();
-
- // Determine lowest and highest column and row
-// $this->_firstRowIndex = ($minR > 65535) ? 65535 : $minR;
- $this->_lastRowIndex = ($maxR > 65535) ? 65535 : $maxR ;
-
- $this->_firstColumnIndex = Cell::columnIndexFromString($minC);
- $this->_lastColumnIndex = Cell::columnIndexFromString($maxC);
-
-// if ($this->_firstColumnIndex > 255) $this->_firstColumnIndex = 255;
- if ($this->_lastColumnIndex > 255) $this->_lastColumnIndex = 255;
-
- $this->_countCellStyleXfs = count($phpSheet->getParent()->getCellStyleXfCollection());
- }
-
- /**
- * Add data to the beginning of the workbook (note the reverse order)
- * and to the end of the workbook.
- *
- * @access public
- * @see PHPExcel\Writer_Excel5_Workbook::storeWorkbook()
- */
- function close()
- {
- $_phpSheet = $this->_phpSheet;
-
- $num_sheets = $_phpSheet->getParent()->getSheetCount();
-
- // Write BOF record
- $this->_storeBof(0x0010);
-
- // Write PRINTHEADERS
- $this->_writePrintHeaders();
-
- // Write PRINTGRIDLINES
- $this->_writePrintGridlines();
-
- // Write GRIDSET
- $this->_writeGridset();
-
- // Calculate column widths
- $_phpSheet->calculateColumnWidths();
-
- // Column dimensions
- if (($defaultWidth = $_phpSheet->getDefaultColumnDimension()->getWidth()) < 0) {
- $defaultWidth = Shared_Font::getDefaultColumnWidthByFont($_phpSheet->getParent()->getDefaultStyle()->getFont());
- }
-
- $columnDimensions = $_phpSheet->getColumnDimensions();
- $maxCol = $this->_lastColumnIndex -1;
- for ($i = 0; $i <= $maxCol; ++$i) {
- $hidden = 0;
- $level = 0;
- $xfIndex = 15; // there are 15 cell style Xfs
-
- $width = $defaultWidth;
-
- $columnLetter = Cell::stringFromColumnIndex($i);
- if (isset($columnDimensions[$columnLetter])) {
- $columnDimension = $columnDimensions[$columnLetter];
- if ($columnDimension->getWidth() >= 0) {
- $width = $columnDimension->getWidth();
- }
- $hidden = $columnDimension->getVisible() ? 0 : 1;
- $level = $columnDimension->getOutlineLevel();
- $xfIndex = $columnDimension->getXfIndex() + 15; // there are 15 cell style Xfs
- }
-
- // Components of _colinfo:
- // $firstcol first column on the range
- // $lastcol last column on the range
- // $width width to set
- // $xfIndex The optional cell style Xf index to apply to the columns
- // $hidden The optional hidden atribute
- // $level The optional outline level
- $this->_colinfo[] = array($i, $i, $width, $xfIndex, $hidden, $level);
- }
-
- // Write GUTS
- $this->_writeGuts();
-
- // Write DEFAULTROWHEIGHT
- $this->_writeDefaultRowHeight();
-
- // Write WSBOOL
- $this->_writeWsbool();
-
- // Write horizontal and vertical page breaks
- $this->_writeBreaks();
-
- // Write page header
- $this->_writeHeader();
-
- // Write page footer
- $this->_writeFooter();
-
- // Write page horizontal centering
- $this->_writeHcenter();
-
- // Write page vertical centering
- $this->_writeVcenter();
-
- // Write left margin
- $this->_writeMarginLeft();
-
- // Write right margin
- $this->_writeMarginRight();
-
- // Write top margin
- $this->_writeMarginTop();
-
- // Write bottom margin
- $this->_writeMarginBottom();
-
- // Write page setup
- $this->_writeSetup();
-
- // Write sheet protection
- $this->_writeProtect();
-
- // Write SCENPROTECT
- $this->_writeScenProtect();
-
- // Write OBJECTPROTECT
- $this->_writeObjectProtect();
-
- // Write sheet password
- $this->_writePassword();
-
- // Write DEFCOLWIDTH record
- $this->_writeDefcol();
-
- // Write the COLINFO records if they exist
- if (!empty($this->_colinfo)) {
- $colcount = count($this->_colinfo);
- for ($i = 0; $i < $colcount; ++$i) {
- $this->_writeColinfo($this->_colinfo[$i]);
- }
- }
- $autoFilterRange = $_phpSheet->getAutoFilter()->getRange();
- if (!empty($autoFilterRange)) {
- // Write AUTOFILTERINFO
- $this->_writeAutoFilterInfo();
- }
-
- // Write sheet dimensions
- $this->_writeDimensions();
-
- // Row dimensions
- foreach ($_phpSheet->getRowDimensions() as $rowDimension) {
- $xfIndex = $rowDimension->getXfIndex() + 15; // there are 15 cellXfs
- $this->_writeRow( $rowDimension->getRowIndex() - 1, $rowDimension->getRowHeight(), $xfIndex, ($rowDimension->getVisible() ? '0' : '1'), $rowDimension->getOutlineLevel() );
- }
-
- // Write Cells
- foreach ($_phpSheet->getCellCollection() as $cellID) {
- $cell = $_phpSheet->getCell($cellID);
- $row = $cell->getRow() - 1;
- $column = Cell::columnIndexFromString($cell->getColumn()) - 1;
-
- // Don't break Excel!
-// if ($row + 1 > 65536 or $column + 1 > 256) {
- if ($row > 65535 || $column > 255) {
- break;
- }
-
- // Write cell value
- $xfIndex = $cell->getXfIndex() + 15; // there are 15 cell style Xfs
-
- $cVal = $cell->getValue();
- if ($cVal instanceof RichText) {
- // $this->_writeString($row, $column, $cVal->getPlainText(), $xfIndex);
- $arrcRun = array();
- $str_len = Shared_String::CountCharacters($cVal->getPlainText(), 'UTF-8');
- $str_pos = 0;
- $elements = $cVal->getRichTextElements();
- foreach ($elements as $element) {
- // FONT Index
- if ($element instanceof RichText_Run) {
- $str_fontidx = $this->_fntHashIndex[$element->getFont()->getHashCode()];
- }
- else {
- $str_fontidx = 0;
- }
- $arrcRun[] = array('strlen' => $str_pos, 'fontidx' => $str_fontidx);
- // Position FROM
- $str_pos += Shared_String::CountCharacters($element->getText(), 'UTF-8');
- }
- $this->_writeRichTextString($row, $column, $cVal->getPlainText(), $xfIndex, $arrcRun);
- } else {
- switch ($cell->getDatatype()) {
- case Cell_DataType::TYPE_STRING:
- case Cell_DataType::TYPE_NULL:
- if ($cVal === '' || $cVal === null) {
- $this->_writeBlank($row, $column, $xfIndex);
- } else {
- $this->_writeString($row, $column, $cVal, $xfIndex);
- }
- break;
-
- case Cell_DataType::TYPE_NUMERIC:
- $this->_writeNumber($row, $column, $cVal, $xfIndex);
- break;
-
- case Cell_DataType::TYPE_FORMULA:
- $calculatedValue = $this->_preCalculateFormulas ?
- $cell->getCalculatedValue() : null;
- $this->_writeFormula($row, $column, $cVal, $xfIndex, $calculatedValue);
- break;
-
- case Cell_DataType::TYPE_BOOL:
- $this->_writeBoolErr($row, $column, $cVal, 0, $xfIndex);
- break;
-
- case Cell_DataType::TYPE_ERROR:
- $this->_writeBoolErr($row, $column, self::_mapErrorCode($cVal), 1, $xfIndex);
- break;
-
- }
- }
- }
-
- // Append
- $this->_writeMsoDrawing();
-
- // Write WINDOW2 record
- $this->_writeWindow2();
-
- // Write PLV record
- $this->_writePageLayoutView();
-
- // Write ZOOM record
- $this->_writeZoom();
- if ($_phpSheet->getFreezePane()) {
- $this->_writePanes();
- }
-
- // Write SELECTION record
- $this->_writeSelection();
-
- // Write MergedCellsTable Record
- $this->_writeMergedCells();
-
- // Hyperlinks
- foreach ($_phpSheet->getHyperLinkCollection() as $coordinate => $hyperlink) {
- list($column, $row) = Cell::coordinateFromString($coordinate);
-
- $url = $hyperlink->getUrl();
-
- if ( strpos($url, 'sheet://') !== false ) {
- // internal to current workbook
- $url = str_replace('sheet://', 'internal:', $url);
-
- } else if ( preg_match('/^(http:|https:|ftp:|mailto:)/', $url) ) {
- // URL
- // $url = $url;
-
- } else {
- // external (local file)
- $url = 'external:' . $url;
- }
-
- $this->_writeUrl($row - 1, Cell::columnIndexFromString($column) - 1, $url);
- }
-
- $this->_writeDataValidity();
- $this->_writeSheetLayout();
-
- // Write SHEETPROTECTION record
- $this->_writeSheetProtection();
- $this->_writeRangeProtection();
-
- $arrConditionalStyles = $_phpSheet->getConditionalStylesCollection();
- if(!empty($arrConditionalStyles)){
- $arrConditional = array();
- // @todo CFRule & CFHeader
- // Write CFHEADER record
- $this->_writeCFHeader();
- // Write ConditionalFormattingTable records
- foreach ($arrConditionalStyles as $cellCoordinate => $conditionalStyles) {
- foreach ($conditionalStyles as $conditional) {
- if($conditional->getConditionType() == Style_Conditional::CONDITION_EXPRESSION
- || $conditional->getConditionType() == Style_Conditional::CONDITION_CELLIS){
- if(!in_array($conditional->getHashCode(), $arrConditional)){
- $arrConditional[] = $conditional->getHashCode();
- // Write CFRULE record
- $this->_writeCFRule($conditional);
- }
- }
- }
- }
- }
-
- $this->_storeEof();
- }
-
- /**
- * Write a cell range address in BIFF8
- * always fixed range
- * See section 2.5.14 in OpenOffice.org's Documentation of the Microsoft Excel File Format
- *
- * @param string $range E.g. 'A1' or 'A1:B6'
- * @return string Binary data
- */
- private function _writeBIFF8CellRangeAddressFixed($range = 'A1')
- {
- $explodes = explode(':', $range);
-
- // extract first cell, e.g. 'A1'
- $firstCell = $explodes[0];
-
- // extract last cell, e.g. 'B6'
- if (count($explodes) == 1) {
- $lastCell = $firstCell;
- } else {
- $lastCell = $explodes[1];
- }
-
- $firstCellCoordinates = Cell::coordinateFromString($firstCell); // e.g. array(0, 1)
- $lastCellCoordinates = Cell::coordinateFromString($lastCell); // e.g. array(1, 6)
-
- return(pack('vvvv',
- $firstCellCoordinates[1] - 1,
- $lastCellCoordinates[1] - 1,
- Cell::columnIndexFromString($firstCellCoordinates[0]) - 1,
- Cell::columnIndexFromString($lastCellCoordinates[0]) - 1
- ));
- }
-
- /**
- * Retrieves data from memory in one chunk, or from disk in $buffer
- * sized chunks.
- *
- * @return string The data
- */
- function getData()
- {
- $buffer = 4096;
-
- // Return data stored in memory
- if (isset($this->_data)) {
- $tmp = $this->_data;
- unset($this->_data);
- return $tmp;
- }
- // No data to return
- return false;
- }
-
- /**
- * Set the option to print the row and column headers on the printed page.
- *
- * @access public
- * @param integer $print Whether to print the headers or not. Defaults to 1 (print).
- */
- function printRowColHeaders($print = 1)
- {
- $this->_print_headers = $print;
- }
-
- /**
- * This method sets the properties for outlining and grouping. The defaults
- * correspond to Excel's defaults.
- *
- * @param bool $visible
- * @param bool $symbols_below
- * @param bool $symbols_right
- * @param bool $auto_style
- */
- function setOutline($visible = true, $symbols_below = true, $symbols_right = true, $auto_style = false)
- {
- $this->_outline_on = $visible;
- $this->_outline_below = $symbols_below;
- $this->_outline_right = $symbols_right;
- $this->_outline_style = $auto_style;
-
- // Ensure this is a boolean vale for Window2
- if ($this->_outline_on) {
- $this->_outline_on = 1;
- }
- }
-
- /**
- * Write a double to the specified row and column (zero indexed).
- * An integer can be written as a double. Excel will display an
- * integer. $format is optional.
- *
- * Returns 0 : normal termination
- * -2 : row or column out of range
- *
- * @param integer $row Zero indexed row
- * @param integer $col Zero indexed column
- * @param float $num The number to write
- * @param mixed $xfIndex The optional XF format
- * @return integer
- */
- private function _writeNumber($row, $col, $num, $xfIndex)
- {
- $record = 0x0203; // Record identifier
- $length = 0x000E; // Number of bytes to follow
-
- $header = pack("vv", $record, $length);
- $data = pack("vvv", $row, $col, $xfIndex);
- $xl_double = pack("d", $num);
- if (self::getByteOrder()) { // if it's Big Endian
- $xl_double = strrev($xl_double);
- }
-
- $this->_append($header.$data.$xl_double);
- return(0);
- }
-
- /**
- * Write a LABELSST record or a LABEL record. Which one depends on BIFF version
- *
- * @param int $row Row index (0-based)
- * @param int $col Column index (0-based)
- * @param string $str The string
- * @param int $xfIndex Index to XF record
- */
- private function _writeString($row, $col, $str, $xfIndex)
- {
- $this->_writeLabelSst($row, $col, $str, $xfIndex);
- }
-
- /**
- * Write a LABELSST record or a LABEL record. Which one depends on BIFF version
- * It differs from _writeString by the writing of rich text strings.
- * @param int $row Row index (0-based)
- * @param int $col Column index (0-based)
- * @param string $str The string
- * @param mixed $xfIndex The XF format index for the cell
- * @param array $arrcRun Index to Font record and characters beginning
- */
- private function _writeRichTextString($row, $col, $str, $xfIndex, $arrcRun){
- $record = 0x00FD; // Record identifier
- $length = 0x000A; // Bytes to follow
- $str = Shared_String::UTF8toBIFF8UnicodeShort($str, $arrcRun);
-
- /* check if string is already present */
- if (!isset($this->_str_table[$str])) {
- $this->_str_table[$str] = $this->_str_unique++;
- }
- $this->_str_total++;
-
- $header = pack('vv', $record, $length);
- $data = pack('vvvV', $row, $col, $xfIndex, $this->_str_table[$str]);
- $this->_append($header.$data);
- }
-
- /**
- * Write a string to the specified row and column (zero indexed).
- * NOTE: there is an Excel 5 defined limit of 255 characters.
- * $format is optional.
- * Returns 0 : normal termination
- * -2 : row or column out of range
- * -3 : long string truncated to 255 chars
- *
- * @access public
- * @param integer $row Zero indexed row
- * @param integer $col Zero indexed column
- * @param string $str The string to write
- * @param mixed $xfIndex The XF format index for the cell
- * @return integer
- */
- private function _writeLabel($row, $col, $str, $xfIndex)
- {
- $strlen = strlen($str);
- $record = 0x0204; // Record identifier
- $length = 0x0008 + $strlen; // Bytes to follow
-
- $str_error = 0;
-
- if ($strlen > $this->_xls_strmax) { // LABEL must be < 255 chars
- $str = substr($str, 0, $this->_xls_strmax);
- $length = 0x0008 + $this->_xls_strmax;
- $strlen = $this->_xls_strmax;
- $str_error = -3;
- }
-
- $header = pack("vv", $record, $length);
- $data = pack("vvvv", $row, $col, $xfIndex, $strlen);
- $this->_append($header . $data . $str);
- return($str_error);
- }
-
- /**
- * Write a string to the specified row and column (zero indexed).
- * This is the BIFF8 version (no 255 chars limit).
- * $format is optional.
- * Returns 0 : normal termination
- * -2 : row or column out of range
- * -3 : long string truncated to 255 chars
- *
- * @access public
- * @param integer $row Zero indexed row
- * @param integer $col Zero indexed column
- * @param string $str The string to write
- * @param mixed $xfIndex The XF format index for the cell
- * @return integer
- */
- private function _writeLabelSst($row, $col, $str, $xfIndex)
- {
- $record = 0x00FD; // Record identifier
- $length = 0x000A; // Bytes to follow
-
- $str = Shared_String::UTF8toBIFF8UnicodeLong($str);
-
- /* check if string is already present */
- if (!isset($this->_str_table[$str])) {
- $this->_str_table[$str] = $this->_str_unique++;
- }
- $this->_str_total++;
-
- $header = pack('vv', $record, $length);
- $data = pack('vvvV', $row, $col, $xfIndex, $this->_str_table[$str]);
- $this->_append($header.$data);
- }
-
- /**
- * Writes a note associated with the cell given by the row and column.
- * NOTE records don't have a length limit.
- *
- * @param integer $row Zero indexed row
- * @param integer $col Zero indexed column
- * @param string $note The note to write
- */
- private function _writeNote($row, $col, $note)
- {
- $note_length = strlen($note);
- $record = 0x001C; // Record identifier
- $max_length = 2048; // Maximun length for a NOTE record
-
- // Length for this record is no more than 2048 + 6
- $length = 0x0006 + min($note_length, 2048);
- $header = pack("vv", $record, $length);
- $data = pack("vvv", $row, $col, $note_length);
- $this->_append($header . $data . substr($note, 0, 2048));
-
- for ($i = $max_length; $i < $note_length; $i += $max_length) {
- $chunk = substr($note, $i, $max_length);
- $length = 0x0006 + strlen($chunk);
- $header = pack("vv", $record, $length);
- $data = pack("vvv", -1, 0, strlen($chunk));
- $this->_append($header.$data.$chunk);
- }
- return(0);
- }
-
- /**
- * Write a blank cell to the specified row and column (zero indexed).
- * A blank cell is used to specify formatting without adding a string
- * or a number.
- *
- * A blank cell without a format serves no purpose. Therefore, we don't write
- * a BLANK record unless a format is specified.
- *
- * Returns 0 : normal termination (including no format)
- * -1 : insufficient number of arguments
- * -2 : row or column out of range
- *
- * @param integer $row Zero indexed row
- * @param integer $col Zero indexed column
- * @param mixed $xfIndex The XF format index
- */
- function _writeBlank($row, $col, $xfIndex)
- {
- $record = 0x0201; // Record identifier
- $length = 0x0006; // Number of bytes to follow
-
- $header = pack("vv", $record, $length);
- $data = pack("vvv", $row, $col, $xfIndex);
- $this->_append($header . $data);
- return 0;
- }
-
- /**
- * Write a boolean or an error type to the specified row and column (zero indexed)
- *
- * @param int $row Row index (0-based)
- * @param int $col Column index (0-based)
- * @param int $value
- * @param boolean $isError Error or Boolean?
- * @param int $xfIndex
- */
- private function _writeBoolErr($row, $col, $value, $isError, $xfIndex)
- {
- $record = 0x0205;
- $length = 8;
-
- $header = pack("vv", $record, $length);
- $data = pack("vvvCC", $row, $col, $xfIndex, $value, $isError);
- $this->_append($header . $data);
- return 0;
- }
-
- /**
- * Write a formula to the specified row and column (zero indexed).
- * The textual representation of the formula is passed to the parser in
- * Parser.php which returns a packed binary string.
- *
- * Returns 0 : normal termination
- * -1 : formula errors (bad formula)
- * -2 : row or column out of range
- *
- * @param integer $row Zero indexed row
- * @param integer $col Zero indexed column
- * @param string $formula The formula text string
- * @param mixed $xfIndex The XF format index
- * @param mixed $calculatedValue Calculated value
- * @return integer
- */
- private function _writeFormula($row, $col, $formula, $xfIndex, $calculatedValue)
- {
- $record = 0x0006; // Record identifier
-
- // Initialize possible additional value for STRING record that should be written after the FORMULA record?
- $stringValue = null;
-
- // calculated value
- if (isset($calculatedValue)) {
- // Since we can't yet get the data type of the calculated value,
- // we use best effort to determine data type
- if (is_bool($calculatedValue)) {
- // Boolean value
- $num = pack('CCCvCv', 0x01, 0x00, (int)$calculatedValue, 0x00, 0x00, 0xFFFF);
- } elseif (is_int($calculatedValue) || is_float($calculatedValue)) {
- // Numeric value
- $num = pack('d', $calculatedValue);
- } elseif (is_string($calculatedValue)) {
- if (array_key_exists($calculatedValue, Cell_DataType::getErrorCodes())) {
- // Error value
- $num = pack('CCCvCv', 0x02, 0x00, self::_mapErrorCode($calculatedValue), 0x00, 0x00, 0xFFFF);
- } elseif ($calculatedValue === '') {
- // Empty string (and BIFF8)
- $num = pack('CCCvCv', 0x03, 0x00, 0x00, 0x00, 0x00, 0xFFFF);
- } else {
- // Non-empty string value (or empty string BIFF5)
- $stringValue = $calculatedValue;
- $num = pack('CCCvCv', 0x00, 0x00, 0x00, 0x00, 0x00, 0xFFFF);
- }
- } else {
- // We are really not supposed to reach here
- $num = pack('d', 0x00);
- }
- } else {
- $num = pack('d', 0x00);
- }
-
- $grbit = 0x03; // Option flags
- $unknown = 0x0000; // Must be zero
-
- // Strip the '=' or '@' sign at the beginning of the formula string
- if ($formula{0} == '=') {
- $formula = substr($formula,1);
- } else {
- // Error handling
- $this->_writeString($row, $col, 'Unrecognised character for formula');
- return -1;
- }
-
- // Parse the formula using the parser in Parser.php
- try {
- $error = $this->_parser->parse($formula);
- $formula = $this->_parser->toReversePolish();
-
- $formlen = strlen($formula); // Length of the binary string
- $length = 0x16 + $formlen; // Length of the record data
-
- $header = pack("vv", $record, $length);
-
- $data = pack("vvv", $row, $col, $xfIndex)
- . $num
- . pack("vVv", $grbit, $unknown, $formlen);
- $this->_append($header . $data . $formula);
-
- // Append also a STRING record if necessary
- if ($stringValue !== null) {
- $this->_writeStringRecord($stringValue);
- }
-
- return 0;
-
- } catch (Exception $e) {
- // do nothing
- }
-
- }
-
- /**
- * Write a STRING record. This
- *
- * @param string $stringValue
- */
- private function _writeStringRecord($stringValue)
- {
- $record = 0x0207; // Record identifier
- $data = Shared_String::UTF8toBIFF8UnicodeLong($stringValue);
-
- $length = strlen($data);
- $header = pack('vv', $record, $length);
-
- $this->_append($header . $data);
- }
-
- /**
- * Write a hyperlink.
- * This is comprised of two elements: the visible label and
- * the invisible link. The visible label is the same as the link unless an
- * alternative string is specified. The label is written using the
- * _writeString() method. Therefore the 255 characters string limit applies.
- * $string and $format are optional.
- *
- * The hyperlink can be to a http, ftp, mail, internal sheet (not yet), or external
- * directory url.
- *
- * Returns 0 : normal termination
- * -2 : row or column out of range
- * -3 : long string truncated to 255 chars
- *
- * @param integer $row Row
- * @param integer $col Column
- * @param string $url URL string
- * @return integer
- */
- private function _writeUrl($row, $col, $url)
- {
- // Add start row and col to arg list
- return($this->_writeUrlRange($row, $col, $row, $col, $url));
- }
-
- /**
- * This is the more general form of _writeUrl(). It allows a hyperlink to be
- * written to a range of cells. This function also decides the type of hyperlink
- * to be written. These are either, Web (http, ftp, mailto), Internal
- * (Sheet1!A1) or external ('c:\temp\foo.xls#Sheet1!A1').
- *
- * @access private
- * @see _writeUrl()
- * @param integer $row1 Start row
- * @param integer $col1 Start column
- * @param integer $row2 End row
- * @param integer $col2 End column
- * @param string $url URL string
- * @return integer
- */
- function _writeUrlRange($row1, $col1, $row2, $col2, $url)
- {
- // Check for internal/external sheet links or default to web link
- if (preg_match('[^internal:]', $url)) {
- return($this->_writeUrlInternal($row1, $col1, $row2, $col2, $url));
- }
- if (preg_match('[^external:]', $url)) {
- return($this->_writeUrlExternal($row1, $col1, $row2, $col2, $url));
- }
- return($this->_writeUrlWeb($row1, $col1, $row2, $col2, $url));
- }
-
- /**
- * Used to write http, ftp and mailto hyperlinks.
- * The link type ($options) is 0x03 is the same as absolute dir ref without
- * sheet. However it is differentiated by the $unknown2 data stream.
- *
- * @access private
- * @see _writeUrl()
- * @param integer $row1 Start row
- * @param integer $col1 Start column
- * @param integer $row2 End row
- * @param integer $col2 End column
- * @param string $url URL string
- * @return integer
- */
- function _writeUrlWeb($row1, $col1, $row2, $col2, $url)
- {
- $record = 0x01B8; // Record identifier
- $length = 0x00000; // Bytes to follow
-
- // Pack the undocumented parts of the hyperlink stream
- $unknown1 = pack("H*", "D0C9EA79F9BACE118C8200AA004BA90B02000000");
- $unknown2 = pack("H*", "E0C9EA79F9BACE118C8200AA004BA90B");
-
- // Pack the option flags
- $options = pack("V", 0x03);
-
- // Convert URL to a null terminated wchar string
- $url = join("\0", preg_split("''", $url, -1, PREG_SPLIT_NO_EMPTY));
- $url = $url . "\0\0\0";
-
- // Pack the length of the URL
- $url_len = pack("V", strlen($url));
-
- // Calculate the data length
- $length = 0x34 + strlen($url);
-
- // Pack the header data
- $header = pack("vv", $record, $length);
- $data = pack("vvvv", $row1, $row2, $col1, $col2);
-
- // Write the packed data
- $this->_append($header . $data .
- $unknown1 . $options .
- $unknown2 . $url_len . $url);
- return 0;
- }
-
- /**
- * Used to write internal reference hyperlinks such as "Sheet1!A1".
- *
- * @access private
- * @see _writeUrl()
- * @param integer $row1 Start row
- * @param integer $col1 Start column
- * @param integer $row2 End row
- * @param integer $col2 End column
- * @param string $url URL string
- * @return integer
- */
- function _writeUrlInternal($row1, $col1, $row2, $col2, $url)
- {
- $record = 0x01B8; // Record identifier
- $length = 0x00000; // Bytes to follow
-
- // Strip URL type
- $url = preg_replace('/^internal:/', '', $url);
-
- // Pack the undocumented parts of the hyperlink stream
- $unknown1 = pack("H*", "D0C9EA79F9BACE118C8200AA004BA90B02000000");
-
- // Pack the option flags
- $options = pack("V", 0x08);
-
- // Convert the URL type and to a null terminated wchar string
- $url .= "\0";
-
- // character count
- $url_len = Shared_String::CountCharacters($url);
- $url_len = pack('V', $url_len);
-
- $url = Shared_String::ConvertEncoding($url, 'UTF-16LE', 'UTF-8');
-
- // Calculate the data length
- $length = 0x24 + strlen($url);
-
- // Pack the header data
- $header = pack("vv", $record, $length);
- $data = pack("vvvv", $row1, $row2, $col1, $col2);
-
- // Write the packed data
- $this->_append($header . $data .
- $unknown1 . $options .
- $url_len . $url);
- return 0;
- }
-
- /**
- * Write links to external directory names such as 'c:\foo.xls',
- * c:\foo.xls#Sheet1!A1', '../../foo.xls'. and '../../foo.xls#Sheet1!A1'.
- *
- * Note: Excel writes some relative links with the $dir_long string. We ignore
- * these cases for the sake of simpler code.
- *
- * @access private
- * @see _writeUrl()
- * @param integer $row1 Start row
- * @param integer $col1 Start column
- * @param integer $row2 End row
- * @param integer $col2 End column
- * @param string $url URL string
- * @return integer
- */
- function _writeUrlExternal($row1, $col1, $row2, $col2, $url)
- {
- // Network drives are different. We will handle them separately
- // MS/Novell network drives and shares start with \\
- if (preg_match('[^external:\\\\]', $url)) {
- return; //($this->_writeUrlExternal_net($row1, $col1, $row2, $col2, $url, $str, $format));
- }
-
- $record = 0x01B8; // Record identifier
- $length = 0x00000; // Bytes to follow
-
- // Strip URL type and change Unix dir separator to Dos style (if needed)
- //
- $url = preg_replace('/^external:/', '', $url);
- $url = preg_replace('/\//', "\\", $url);
-
- // Determine if the link is relative or absolute:
- // relative if link contains no dir separator, "somefile.xls"
- // relative if link starts with up-dir, "..\..\somefile.xls"
- // otherwise, absolute
-
- $absolute = 0x00; // relative path
- if ( preg_match('/^[A-Z]:/', $url) ) {
- $absolute = 0x02; // absolute path on Windows, e.g. C:\...
- }
- $link_type = 0x01 | $absolute;
-
- // Determine if the link contains a sheet reference and change some of the
- // parameters accordingly.
- // Split the dir name and sheet name (if it exists)
- $dir_long = $url;
- if (preg_match("/\#/", $url)) {
- $link_type |= 0x08;
- }
-
-
- // Pack the link type
- $link_type = pack("V", $link_type);
-
- // Calculate the up-level dir count e.g.. (..\..\..\ == 3)
- $up_count = preg_match_all("/\.\.\\\/", $dir_long, $useless);
- $up_count = pack("v", $up_count);
-
- // Store the short dos dir name (null terminated)
- $dir_short = preg_replace("/\.\.\\\/", '', $dir_long) . "\0";
-
- // Store the long dir name as a wchar string (non-null terminated)
- $dir_long = $dir_long . "\0";
-
- // Pack the lengths of the dir strings
- $dir_short_len = pack("V", strlen($dir_short) );
- $dir_long_len = pack("V", strlen($dir_long) );
- $stream_len = pack("V", 0);//strlen($dir_long) + 0x06);
-
- // Pack the undocumented parts of the hyperlink stream
- $unknown1 = pack("H*",'D0C9EA79F9BACE118C8200AA004BA90B02000000' );
- $unknown2 = pack("H*",'0303000000000000C000000000000046' );
- $unknown3 = pack("H*",'FFFFADDE000000000000000000000000000000000000000');
- $unknown4 = pack("v", 0x03 );
-
- // Pack the main data stream
- $data = pack("vvvv", $row1, $row2, $col1, $col2) .
- $unknown1 .
- $link_type .
- $unknown2 .
- $up_count .
- $dir_short_len.
- $dir_short .
- $unknown3 .
- $stream_len ;/*.
- $dir_long_len .
- $unknown4 .
- $dir_long .
- $sheet_len .
- $sheet ;*/
-
- // Pack the header data
- $length = strlen($data);
- $header = pack("vv", $record, $length);
-
- // Write the packed data
- $this->_append($header. $data);
- return 0;
- }
-
- /**
- * This method is used to set the height and format for a row.
- *
- * @param integer $row The row to set
- * @param integer $height Height we are giving to the row.
- * Use null to set XF without setting height
- * @param integer $xfIndex The optional cell style Xf index to apply to the columns
- * @param bool $hidden The optional hidden attribute
- * @param integer $level The optional outline level for row, in range [0,7]
- */
- private function _writeRow($row, $height, $xfIndex, $hidden = false, $level = 0)
- {
- $record = 0x0208; // Record identifier
- $length = 0x0010; // Number of bytes to follow
-
- $colMic = 0x0000; // First defined column
- $colMac = 0x0000; // Last defined column
- $irwMac = 0x0000; // Used by Excel to optimise loading
- $reserved = 0x0000; // Reserved
- $grbit = 0x0000; // Option flags
- $ixfe = $xfIndex;
-
- if ( $height < 0 ){
- $height = null;
- }
-
- // Use _writeRow($row, null, $XF) to set XF format without setting height
- if ($height != null) {
- $miyRw = $height * 20; // row height
- } else {
- $miyRw = 0xff; // default row height is 256
- }
-
- // Set the options flags. fUnsynced is used to show that the font and row
- // heights are not compatible. This is usually the case for WriteExcel.
- // The collapsed flag 0x10 doesn't seem to be used to indicate that a row
- // is collapsed. Instead it is used to indicate that the previous row is
- // collapsed. The zero height flag, 0x20, is used to collapse a row.
-
- $grbit |= $level;
- if ($hidden) {
- $grbit |= 0x0020;
- }
- if ($height !== null) {
- $grbit |= 0x0040; // fUnsynced
- }
- if ($xfIndex !== 0xF) {
- $grbit |= 0x0080;
- }
- $grbit |= 0x0100;
-
- $header = pack("vv", $record, $length);
- $data = pack("vvvvvvvv", $row, $colMic, $colMac, $miyRw,
- $irwMac,$reserved, $grbit, $ixfe);
- $this->_append($header.$data);
- }
-
- /**
- * Writes Excel DIMENSIONS to define the area in which there is data.
- */
- private function _writeDimensions()
- {
- $record = 0x0200; // Record identifier
-
- $length = 0x000E;
- $data = pack('VVvvv'
- , $this->_firstRowIndex
- , $this->_lastRowIndex + 1
- , $this->_firstColumnIndex
- , $this->_lastColumnIndex + 1
- , 0x0000 // reserved
- );
-
- $header = pack("vv", $record, $length);
- $this->_append($header.$data);
- }
-
- /**
- * Write BIFF record Window2.
- */
- private function _writeWindow2()
- {
- $record = 0x023E; // Record identifier
- $length = 0x0012;
-
- $grbit = 0x00B6; // Option flags
- $rwTop = 0x0000; // Top row visible in window
- $colLeft = 0x0000; // Leftmost column visible in window
-
-
- // The options flags that comprise $grbit
- $fDspFmla = 0; // 0 - bit
- $fDspGrid = $this->_phpSheet->getShowGridlines() ? 1 : 0; // 1
- $fDspRwCol = $this->_phpSheet->getShowRowColHeaders() ? 1 : 0; // 2
- $fFrozen = $this->_phpSheet->getFreezePane() ? 1 : 0; // 3
- $fDspZeros = 1; // 4
- $fDefaultHdr = 1; // 5
- $fArabic = $this->_phpSheet->getRightToLeft() ? 1 : 0; // 6
- $fDspGuts = $this->_outline_on; // 7
- $fFrozenNoSplit = 0; // 0 - bit
- // no support in PHPExcel for selected sheet, therefore sheet is only selected if it is the active sheet
- $fSelected = ($this->_phpSheet === $this->_phpSheet->getParent()->getActiveSheet()) ? 1 : 0;
- $fPaged = 1; // 2
- $fPageBreakPreview = $this->_phpSheet->getSheetView()->getView() === Worksheet_SheetView::SHEETVIEW_PAGE_BREAK_PREVIEW;
-
- $grbit = $fDspFmla;
- $grbit |= $fDspGrid << 1;
- $grbit |= $fDspRwCol << 2;
- $grbit |= $fFrozen << 3;
- $grbit |= $fDspZeros << 4;
- $grbit |= $fDefaultHdr << 5;
- $grbit |= $fArabic << 6;
- $grbit |= $fDspGuts << 7;
- $grbit |= $fFrozenNoSplit << 8;
- $grbit |= $fSelected << 9;
- $grbit |= $fPaged << 10;
- $grbit |= $fPageBreakPreview << 11;
-
- $header = pack("vv", $record, $length);
- $data = pack("vvv", $grbit, $rwTop, $colLeft);
-
- // FIXME !!!
- $rgbHdr = 0x0040; // Row/column heading and gridline color index
- $zoom_factor_page_break = ($fPageBreakPreview? $this->_phpSheet->getSheetView()->getZoomScale() : 0x0000);
- $zoom_factor_normal = $this->_phpSheet->getSheetView()->getZoomScaleNormal();
-
- $data .= pack("vvvvV", $rgbHdr, 0x0000, $zoom_factor_page_break, $zoom_factor_normal, 0x00000000);
-
- $this->_append($header.$data);
- }
-
- /**
- * Write BIFF record DEFAULTROWHEIGHT.
- */
- private function _writeDefaultRowHeight()
- {
- $defaultRowHeight = $this->_phpSheet->getDefaultRowDimension()->getRowHeight();
-
- if ($defaultRowHeight < 0) {
- return;
- }
-
- // convert to twips
- $defaultRowHeight = (int) 20 * $defaultRowHeight;
-
- $record = 0x0225; // Record identifier
- $length = 0x0004; // Number of bytes to follow
-
- $header = pack("vv", $record, $length);
- $data = pack("vv", 1, $defaultRowHeight);
- $this->_append($header . $data);
- }
-
- /**
- * Write BIFF record DEFCOLWIDTH if COLINFO records are in use.
- */
- private function _writeDefcol()
- {
- $defaultColWidth = 8;
-
- $record = 0x0055; // Record identifier
- $length = 0x0002; // Number of bytes to follow
-
- $header = pack("vv", $record, $length);
- $data = pack("v", $defaultColWidth);
- $this->_append($header . $data);
- }
-
- /**
- * Write BIFF record COLINFO to define column widths
- *
- * Note: The SDK says the record length is 0x0B but Excel writes a 0x0C
- * length record.
- *
- * @param array $col_array This is the only parameter received and is composed of the following:
- * 0 => First formatted column,
- * 1 => Last formatted column,
- * 2 => Col width (8.43 is Excel default),
- * 3 => The optional XF format of the column,
- * 4 => Option flags.
- * 5 => Optional outline level
- */
- private function _writeColinfo($col_array)
- {
- if (isset($col_array[0])) {
- $colFirst = $col_array[0];
- }
- if (isset($col_array[1])) {
- $colLast = $col_array[1];
- }
- if (isset($col_array[2])) {
- $coldx = $col_array[2];
- } else {
- $coldx = 8.43;
- }
- if (isset($col_array[3])) {
- $xfIndex = $col_array[3];
- } else {
- $xfIndex = 15;
- }
- if (isset($col_array[4])) {
- $grbit = $col_array[4];
- } else {
- $grbit = 0;
- }
- if (isset($col_array[5])) {
- $level = $col_array[5];
- } else {
- $level = 0;
- }
- $record = 0x007D; // Record identifier
- $length = 0x000C; // Number of bytes to follow
-
- $coldx *= 256; // Convert to units of 1/256 of a char
-
- $ixfe = $xfIndex;
- $reserved = 0x0000; // Reserved
-
- $level = max(0, min($level, 7));
- $grbit |= $level << 8;
-
- $header = pack("vv", $record, $length);
- $data = pack("vvvvvv", $colFirst, $colLast, $coldx,
- $ixfe, $grbit, $reserved);
- $this->_append($header.$data);
- }
-
- /**
- * Write BIFF record SELECTION.
- */
- private function _writeSelection()
- {
- // look up the selected cell range
- $selectedCells = $this->_phpSheet->getSelectedCells();
- $selectedCells = Cell::splitRange($this->_phpSheet->getSelectedCells());
- $selectedCells = $selectedCells[0];
- if (count($selectedCells) == 2) {
- list($first, $last) = $selectedCells;
- } else {
- $first = $selectedCells[0];
- $last = $selectedCells[0];
- }
-
- list($colFirst, $rwFirst) = Cell::coordinateFromString($first);
- $colFirst = Cell::columnIndexFromString($colFirst) - 1; // base 0 column index
- --$rwFirst; // base 0 row index
-
- list($colLast, $rwLast) = Cell::coordinateFromString($last);
- $colLast = Cell::columnIndexFromString($colLast) - 1; // base 0 column index
- --$rwLast; // base 0 row index
-
- // make sure we are not out of bounds
- $colFirst = min($colFirst, 255);
- $colLast = min($colLast, 255);
-
- $rwFirst = min($rwFirst, 65535);
- $rwLast = min($rwLast, 65535);
-
- $record = 0x001D; // Record identifier
- $length = 0x000F; // Number of bytes to follow
-
- $pnn = $this->_active_pane; // Pane position
- $rwAct = $rwFirst; // Active row
- $colAct = $colFirst; // Active column
- $irefAct = 0; // Active cell ref
- $cref = 1; // Number of refs
-
- if (!isset($rwLast)) {
- $rwLast = $rwFirst; // Last row in reference
- }
- if (!isset($colLast)) {
- $colLast = $colFirst; // Last col in reference
- }
-
- // Swap last row/col for first row/col as necessary
- if ($rwFirst > $rwLast) {
- list($rwFirst, $rwLast) = array($rwLast, $rwFirst);
- }
-
- if ($colFirst > $colLast) {
- list($colFirst, $colLast) = array($colLast, $colFirst);
- }
-
- $header = pack("vv", $record, $length);
- $data = pack("CvvvvvvCC", $pnn, $rwAct, $colAct,
- $irefAct, $cref,
- $rwFirst, $rwLast,
- $colFirst, $colLast);
- $this->_append($header . $data);
- }
-
- /**
- * Store the MERGEDCELLS records for all ranges of merged cells
- */
- private function _writeMergedCells()
- {
- $mergeCells = $this->_phpSheet->getMergeCells();
- $countMergeCells = count($mergeCells);
-
- if ($countMergeCells == 0) {
- return;
- }
-
- // maximum allowed number of merged cells per record
- $maxCountMergeCellsPerRecord = 1027;
-
- // record identifier
- $record = 0x00E5;
-
- // counter for total number of merged cells treated so far by the writer
- $i = 0;
-
- // counter for number of merged cells written in record currently being written
- $j = 0;
-
- // initialize record data
- $recordData = '';
-
- // loop through the merged cells
- foreach ($mergeCells as $mergeCell) {
- ++$i;
- ++$j;
-
- // extract the row and column indexes
- $range = Cell::splitRange($mergeCell);
- list($first, $last) = $range[0];
- list($firstColumn, $firstRow) = Cell::coordinateFromString($first);
- list($lastColumn, $lastRow) = Cell::coordinateFromString($last);
-
- $recordData .= pack('vvvv', $firstRow - 1, $lastRow - 1, Cell::columnIndexFromString($firstColumn) - 1, Cell::columnIndexFromString($lastColumn) - 1);
-
- // flush record if we have reached limit for number of merged cells, or reached final merged cell
- if ($j == $maxCountMergeCellsPerRecord or $i == $countMergeCells) {
- $recordData = pack('v', $j) . $recordData;
- $length = strlen($recordData);
- $header = pack('vv', $record, $length);
- $this->_append($header . $recordData);
-
- // initialize for next record, if any
- $recordData = '';
- $j = 0;
- }
- }
- }
-
- /**
- * Write SHEETLAYOUT record
- */
- private function _writeSheetLayout()
- {
- if (!$this->_phpSheet->isTabColorSet()) {
- return;
- }
-
- $recordData = pack(
- 'vvVVVvv'
- , 0x0862
- , 0x0000 // unused
- , 0x00000000 // unused
- , 0x00000000 // unused
- , 0x00000014 // size of record data
- , $this->_colors[$this->_phpSheet->getTabColor()->getRGB()] // color index
- , 0x0000 // unused
- );
-
- $length = strlen($recordData);
-
- $record = 0x0862; // Record identifier
- $header = pack('vv', $record, $length);
- $this->_append($header . $recordData);
- }
-
- /**
- * Write SHEETPROTECTION
- */
- private function _writeSheetProtection()
- {
- // record identifier
- $record = 0x0867;
-
- // prepare options
- $options = (int) !$this->_phpSheet->getProtection()->getObjects()
- | (int) !$this->_phpSheet->getProtection()->getScenarios() << 1
- | (int) !$this->_phpSheet->getProtection()->getFormatCells() << 2
- | (int) !$this->_phpSheet->getProtection()->getFormatColumns() << 3
- | (int) !$this->_phpSheet->getProtection()->getFormatRows() << 4
- | (int) !$this->_phpSheet->getProtection()->getInsertColumns() << 5
- | (int) !$this->_phpSheet->getProtection()->getInsertRows() << 6
- | (int) !$this->_phpSheet->getProtection()->getInsertHyperlinks() << 7
- | (int) !$this->_phpSheet->getProtection()->getDeleteColumns() << 8
- | (int) !$this->_phpSheet->getProtection()->getDeleteRows() << 9
- | (int) !$this->_phpSheet->getProtection()->getSelectLockedCells() << 10
- | (int) !$this->_phpSheet->getProtection()->getSort() << 11
- | (int) !$this->_phpSheet->getProtection()->getAutoFilter() << 12
- | (int) !$this->_phpSheet->getProtection()->getPivotTables() << 13
- | (int) !$this->_phpSheet->getProtection()->getSelectUnlockedCells() << 14 ;
-
- // record data
- $recordData = pack(
- 'vVVCVVvv'
- , 0x0867 // repeated record identifier
- , 0x0000 // not used
- , 0x0000 // not used
- , 0x00 // not used
- , 0x01000200 // unknown data
- , 0xFFFFFFFF // unknown data
- , $options // options
- , 0x0000 // not used
- );
-
- $length = strlen($recordData);
- $header = pack('vv', $record, $length);
-
- $this->_append($header . $recordData);
- }
-
- /**
- * Write BIFF record RANGEPROTECTION
- *
- * Openoffice.org's Documentaion of the Microsoft Excel File Format uses term RANGEPROTECTION for these records
- * Microsoft Office Excel 97-2007 Binary File Format Specification uses term FEAT for these records
- */
- private function _writeRangeProtection()
- {
- foreach ($this->_phpSheet->getProtectedCells() as $range => $password) {
- // number of ranges, e.g. 'A1:B3 C20:D25'
- $cellRanges = explode(' ', $range);
- $cref = count($cellRanges);
-
- $recordData = pack(
- 'vvVVvCVvVv',
- 0x0868,
- 0x00,
- 0x0000,
- 0x0000,
- 0x02,
- 0x0,
- 0x0000,
- $cref,
- 0x0000,
- 0x00
- );
-
- foreach ($cellRanges as $cellRange) {
- $recordData .= $this->_writeBIFF8CellRangeAddressFixed($cellRange);
- }
-
- // the rgbFeat structure
- $recordData .= pack(
- 'VV',
- 0x0000,
- hexdec($password)
- );
-
- $recordData .= Shared_String::UTF8toBIFF8UnicodeLong('p' . md5($recordData));
-
- $length = strlen($recordData);
-
- $record = 0x0868; // Record identifier
- $header = pack("vv", $record, $length);
- $this->_append($header . $recordData);
- }
- }
-
- /**
- * Write BIFF record EXTERNCOUNT to indicate the number of external sheet
- * references in a worksheet.
- *
- * Excel only stores references to external sheets that are used in formulas.
- * For simplicity we store references to all the sheets in the workbook
- * regardless of whether they are used or not. This reduces the overall
- * complexity and eliminates the need for a two way dialogue between the formula
- * parser the worksheet objects.
- *
- * @param integer $count The number of external sheet references in this worksheet
- */
- private function _writeExterncount($count)
- {
- $record = 0x0016; // Record identifier
- $length = 0x0002; // Number of bytes to follow
-
- $header = pack("vv", $record, $length);
- $data = pack("v", $count);
- $this->_append($header . $data);
- }
-
- /**
- * Writes the Excel BIFF EXTERNSHEET record. These references are used by
- * formulas. A formula references a sheet name via an index. Since we store a
- * reference to all of the external worksheets the EXTERNSHEET index is the same
- * as the worksheet index.
- *
- * @param string $sheetname The name of a external worksheet
- */
- private function _writeExternsheet($sheetname)
- {
- $record = 0x0017; // Record identifier
-
- // References to the current sheet are encoded differently to references to
- // external sheets.
- //
- if ($this->_phpSheet->getTitle() == $sheetname) {
- $sheetname = '';
- $length = 0x02; // The following 2 bytes
- $cch = 1; // The following byte
- $rgch = 0x02; // Self reference
- } else {
- $length = 0x02 + strlen($sheetname);
- $cch = strlen($sheetname);
- $rgch = 0x03; // Reference to a sheet in the current workbook
- }
-
- $header = pack("vv", $record, $length);
- $data = pack("CC", $cch, $rgch);
- $this->_append($header . $data . $sheetname);
- }
-
- /**
- * Writes the Excel BIFF PANE record.
- * The panes can either be frozen or thawed (unfrozen).
- * Frozen panes are specified in terms of an integer number of rows and columns.
- * Thawed panes are specified in terms of Excel's units for rows and columns.
- */
- private function _writePanes()
- {
- $panes = array();
- if ($freezePane = $this->_phpSheet->getFreezePane()) {
- list($column, $row) = Cell::coordinateFromString($freezePane);
- $panes[0] = $row - 1;
- $panes[1] = Cell::columnIndexFromString($column) - 1;
- } else {
- // thaw panes
- return;
- }
-
- $y = isset($panes[0]) ? $panes[0] : null;
- $x = isset($panes[1]) ? $panes[1] : null;
- $rwTop = isset($panes[2]) ? $panes[2] : null;
- $colLeft = isset($panes[3]) ? $panes[3] : null;
- if (count($panes) > 4) { // if Active pane was received
- $pnnAct = $panes[4];
- } else {
- $pnnAct = null;
- }
- $record = 0x0041; // Record identifier
- $length = 0x000A; // Number of bytes to follow
-
- // Code specific to frozen or thawed panes.
- if ($this->_phpSheet->getFreezePane()) {
- // Set default values for $rwTop and $colLeft
- if (!isset($rwTop)) {
- $rwTop = $y;
- }
- if (!isset($colLeft)) {
- $colLeft = $x;
- }
- } else {
- // Set default values for $rwTop and $colLeft
- if (!isset($rwTop)) {
- $rwTop = 0;
- }
- if (!isset($colLeft)) {
- $colLeft = 0;
- }
-
- // Convert Excel's row and column units to the internal units.
- // The default row height is 12.75
- // The default column width is 8.43
- // The following slope and intersection values were interpolated.
- //
- $y = 20*$y + 255;
- $x = 113.879*$x + 390;
- }
-
-
- // Determine which pane should be active. There is also the undocumented
- // option to override this should it be necessary: may be removed later.
- //
- if (!isset($pnnAct)) {
- if ($x != 0 && $y != 0) {
- $pnnAct = 0; // Bottom right
- }
- if ($x != 0 && $y == 0) {
- $pnnAct = 1; // Top right
- }
- if ($x == 0 && $y != 0) {
- $pnnAct = 2; // Bottom left
- }
- if ($x == 0 && $y == 0) {
- $pnnAct = 3; // Top left
- }
- }
-
- $this->_active_pane = $pnnAct; // Used in _writeSelection
-
- $header = pack("vv", $record, $length);
- $data = pack("vvvvv", $x, $y, $rwTop, $colLeft, $pnnAct);
- $this->_append($header . $data);
- }
-
- /**
- * Store the page setup SETUP BIFF record.
- */
- private function _writeSetup()
- {
- $record = 0x00A1; // Record identifier
- $length = 0x0022; // Number of bytes to follow
-
- $iPaperSize = $this->_phpSheet->getPageSetup()->getPaperSize(); // Paper size
-
- $iScale = $this->_phpSheet->getPageSetup()->getScale() ?
- $this->_phpSheet->getPageSetup()->getScale() : 100; // Print scaling factor
-
- $iPageStart = 0x01; // Starting page number
- $iFitWidth = (int) $this->_phpSheet->getPageSetup()->getFitToWidth(); // Fit to number of pages wide
- $iFitHeight = (int) $this->_phpSheet->getPageSetup()->getFitToHeight(); // Fit to number of pages high
- $grbit = 0x00; // Option flags
- $iRes = 0x0258; // Print resolution
- $iVRes = 0x0258; // Vertical print resolution
-
- $numHdr = $this->_phpSheet->getPageMargins()->getHeader(); // Header Margin
-
- $numFtr = $this->_phpSheet->getPageMargins()->getFooter(); // Footer Margin
- $iCopies = 0x01; // Number of copies
-
- $fLeftToRight = 0x0; // Print over then down
-
- // Page orientation
- $fLandscape = ($this->_phpSheet->getPageSetup()->getOrientation() == Worksheet_PageSetup::ORIENTATION_LANDSCAPE) ?
- 0x0 : 0x1;
-
- $fNoPls = 0x0; // Setup not read from printer
- $fNoColor = 0x0; // Print black and white
- $fDraft = 0x0; // Print draft quality
- $fNotes = 0x0; // Print notes
- $fNoOrient = 0x0; // Orientation not set
- $fUsePage = 0x0; // Use custom starting page
-
- $grbit = $fLeftToRight;
- $grbit |= $fLandscape << 1;
- $grbit |= $fNoPls << 2;
- $grbit |= $fNoColor << 3;
- $grbit |= $fDraft << 4;
- $grbit |= $fNotes << 5;
- $grbit |= $fNoOrient << 6;
- $grbit |= $fUsePage << 7;
-
- $numHdr = pack("d", $numHdr);
- $numFtr = pack("d", $numFtr);
- if (self::getByteOrder()) { // if it's Big Endian
- $numHdr = strrev($numHdr);
- $numFtr = strrev($numFtr);
- }
-
- $header = pack("vv", $record, $length);
- $data1 = pack("vvvvvvvv", $iPaperSize,
- $iScale,
- $iPageStart,
- $iFitWidth,
- $iFitHeight,
- $grbit,
- $iRes,
- $iVRes);
- $data2 = $numHdr.$numFtr;
- $data3 = pack("v", $iCopies);
- $this->_append($header . $data1 . $data2 . $data3);
- }
-
- /**
- * Store the header caption BIFF record.
- */
- private function _writeHeader()
- {
- $record = 0x0014; // Record identifier
-
- /* removing for now
- // need to fix character count (multibyte!)
- if (strlen($this->_phpSheet->getHeaderFooter()->getOddHeader()) <= 255) {
- $str = $this->_phpSheet->getHeaderFooter()->getOddHeader(); // header string
- } else {
- $str = '';
- }
- */
-
- $recordData = Shared_String::UTF8toBIFF8UnicodeLong($this->_phpSheet->getHeaderFooter()->getOddHeader());
- $length = strlen($recordData);
-
- $header = pack("vv", $record, $length);
-
- $this->_append($header . $recordData);
- }
-
- /**
- * Store the footer caption BIFF record.
- */
- private function _writeFooter()
- {
- $record = 0x0015; // Record identifier
-
- /* removing for now
- // need to fix character count (multibyte!)
- if (strlen($this->_phpSheet->getHeaderFooter()->getOddFooter()) <= 255) {
- $str = $this->_phpSheet->getHeaderFooter()->getOddFooter();
- } else {
- $str = '';
- }
- */
-
- $recordData = Shared_String::UTF8toBIFF8UnicodeLong($this->_phpSheet->getHeaderFooter()->getOddFooter());
- $length = strlen($recordData);
-
- $header = pack("vv", $record, $length);
-
- $this->_append($header . $recordData);
- }
-
- /**
- * Store the horizontal centering HCENTER BIFF record.
- *
- * @access private
- */
- private function _writeHcenter()
- {
- $record = 0x0083; // Record identifier
- $length = 0x0002; // Bytes to follow
-
- $fHCenter = $this->_phpSheet->getPageSetup()->getHorizontalCentered() ? 1 : 0; // Horizontal centering
-
- $header = pack("vv", $record, $length);
- $data = pack("v", $fHCenter);
-
- $this->_append($header.$data);
- }
-
- /**
- * Store the vertical centering VCENTER BIFF record.
- */
- private function _writeVcenter()
- {
- $record = 0x0084; // Record identifier
- $length = 0x0002; // Bytes to follow
-
- $fVCenter = $this->_phpSheet->getPageSetup()->getVerticalCentered() ? 1 : 0; // Horizontal centering
-
- $header = pack("vv", $record, $length);
- $data = pack("v", $fVCenter);
- $this->_append($header . $data);
- }
-
- /**
- * Store the LEFTMARGIN BIFF record.
- */
- private function _writeMarginLeft()
- {
- $record = 0x0026; // Record identifier
- $length = 0x0008; // Bytes to follow
-
- $margin = $this->_phpSheet->getPageMargins()->getLeft(); // Margin in inches
-
- $header = pack("vv", $record, $length);
- $data = pack("d", $margin);
- if (self::getByteOrder()) { // if it's Big Endian
- $data = strrev($data);
- }
-
- $this->_append($header . $data);
- }
-
- /**
- * Store the RIGHTMARGIN BIFF record.
- */
- private function _writeMarginRight()
- {
- $record = 0x0027; // Record identifier
- $length = 0x0008; // Bytes to follow
-
- $margin = $this->_phpSheet->getPageMargins()->getRight(); // Margin in inches
-
- $header = pack("vv", $record, $length);
- $data = pack("d", $margin);
- if (self::getByteOrder()) { // if it's Big Endian
- $data = strrev($data);
- }
-
- $this->_append($header . $data);
- }
-
- /**
- * Store the TOPMARGIN BIFF record.
- */
- private function _writeMarginTop()
- {
- $record = 0x0028; // Record identifier
- $length = 0x0008; // Bytes to follow
-
- $margin = $this->_phpSheet->getPageMargins()->getTop(); // Margin in inches
-
- $header = pack("vv", $record, $length);
- $data = pack("d", $margin);
- if (self::getByteOrder()) { // if it's Big Endian
- $data = strrev($data);
- }
-
- $this->_append($header . $data);
- }
-
- /**
- * Store the BOTTOMMARGIN BIFF record.
- */
- private function _writeMarginBottom()
- {
- $record = 0x0029; // Record identifier
- $length = 0x0008; // Bytes to follow
-
- $margin = $this->_phpSheet->getPageMargins()->getBottom(); // Margin in inches
-
- $header = pack("vv", $record, $length);
- $data = pack("d", $margin);
- if (self::getByteOrder()) { // if it's Big Endian
- $data = strrev($data);
- }
-
- $this->_append($header . $data);
- }
-
- /**
- * Write the PRINTHEADERS BIFF record.
- */
- private function _writePrintHeaders()
- {
- $record = 0x002a; // Record identifier
- $length = 0x0002; // Bytes to follow
-
- $fPrintRwCol = $this->_print_headers; // Boolean flag
-
- $header = pack("vv", $record, $length);
- $data = pack("v", $fPrintRwCol);
- $this->_append($header . $data);
- }
-
- /**
- * Write the PRINTGRIDLINES BIFF record. Must be used in conjunction with the
- * GRIDSET record.
- */
- private function _writePrintGridlines()
- {
- $record = 0x002b; // Record identifier
- $length = 0x0002; // Bytes to follow
-
- $fPrintGrid = $this->_phpSheet->getPrintGridlines() ? 1 : 0; // Boolean flag
-
- $header = pack("vv", $record, $length);
- $data = pack("v", $fPrintGrid);
- $this->_append($header . $data);
- }
-
- /**
- * Write the GRIDSET BIFF record. Must be used in conjunction with the
- * PRINTGRIDLINES record.
- */
- private function _writeGridset()
- {
- $record = 0x0082; // Record identifier
- $length = 0x0002; // Bytes to follow
-
- $fGridSet = !$this->_phpSheet->getPrintGridlines(); // Boolean flag
-
- $header = pack("vv", $record, $length);
- $data = pack("v", $fGridSet);
- $this->_append($header . $data);
- }
-
- /**
- * Write the AUTOFILTERINFO BIFF record. This is used to configure the number of autofilter select used in the sheet.
- */
- private function _writeAutoFilterInfo(){
- $record = 0x009D; // Record identifier
- $length = 0x0002; // Bytes to follow
-
- $rangeBounds = Cell::rangeBoundaries($this->_phpSheet->getAutoFilter()->getRange());
- $iNumFilters = 1 + $rangeBounds[1][0] - $rangeBounds[0][0];
-
- $header = pack("vv", $record, $length);
- $data = pack("v", $iNumFilters);
- $this->_append($header . $data);
- }
-
- /**
- * Write the GUTS BIFF record. This is used to configure the gutter margins
- * where Excel outline symbols are displayed. The visibility of the gutters is
- * controlled by a flag in WSBOOL.
- *
- * @see _writeWsbool()
- */
- private function _writeGuts()
- {
- $record = 0x0080; // Record identifier
- $length = 0x0008; // Bytes to follow
-
- $dxRwGut = 0x0000; // Size of row gutter
- $dxColGut = 0x0000; // Size of col gutter
-
- // determine maximum row outline level
- $maxRowOutlineLevel = 0;
- foreach ($this->_phpSheet->getRowDimensions() as $rowDimension) {
- $maxRowOutlineLevel = max($maxRowOutlineLevel, $rowDimension->getOutlineLevel());
- }
-
- $col_level = 0;
-
- // Calculate the maximum column outline level. The equivalent calculation
- // for the row outline level is carried out in _writeRow().
- $colcount = count($this->_colinfo);
- for ($i = 0; $i < $colcount; ++$i) {
- $col_level = max($this->_colinfo[$i][5], $col_level);
- }
-
- // Set the limits for the outline levels (0 <= x <= 7).
- $col_level = max(0, min($col_level, 7));
-
- // The displayed level is one greater than the max outline levels
- if ($maxRowOutlineLevel) {
- ++$maxRowOutlineLevel;
- }
- if ($col_level) {
- ++$col_level;
- }
-
- $header = pack("vv", $record, $length);
- $data = pack("vvvv", $dxRwGut, $dxColGut, $maxRowOutlineLevel, $col_level);
-
- $this->_append($header.$data);
- }
-
- /**
- * Write the WSBOOL BIFF record, mainly for fit-to-page. Used in conjunction
- * with the SETUP record.
- */
- private function _writeWsbool()
- {
- $record = 0x0081; // Record identifier
- $length = 0x0002; // Bytes to follow
- $grbit = 0x0000;
-
- // The only option that is of interest is the flag for fit to page. So we
- // set all the options in one go.
- //
- // Set the option flags
- $grbit |= 0x0001; // Auto page breaks visible
- if ($this->_outline_style) {
- $grbit |= 0x0020; // Auto outline styles
- }
- if ($this->_phpSheet->getShowSummaryBelow()) {
- $grbit |= 0x0040; // Outline summary below
- }
- if ($this->_phpSheet->getShowSummaryRight()) {
- $grbit |= 0x0080; // Outline summary right
- }
- if ($this->_phpSheet->getPageSetup()->getFitToPage()) {
- $grbit |= 0x0100; // Page setup fit to page
- }
- if ($this->_outline_on) {
- $grbit |= 0x0400; // Outline symbols displayed
- }
-
- $header = pack("vv", $record, $length);
- $data = pack("v", $grbit);
- $this->_append($header . $data);
- }
-
- /**
- * Write the HORIZONTALPAGEBREAKS and VERTICALPAGEBREAKS BIFF records.
- */
- private function _writeBreaks()
- {
- // initialize
- $vbreaks = array();
- $hbreaks = array();
-
- foreach ($this->_phpSheet->getBreaks() as $cell => $breakType) {
- // Fetch coordinates
- $coordinates = Cell::coordinateFromString($cell);
-
- // Decide what to do by the type of break
- switch ($breakType) {
- case Worksheet::BREAK_COLUMN:
- // Add to list of vertical breaks
- $vbreaks[] = Cell::columnIndexFromString($coordinates[0]) - 1;
- break;
-
- case Worksheet::BREAK_ROW:
- // Add to list of horizontal breaks
- $hbreaks[] = $coordinates[1];
- break;
-
- case Worksheet::BREAK_NONE:
- default:
- // Nothing to do
- break;
- }
- }
-
- //horizontal page breaks
- if (!empty($hbreaks)) {
-
- // Sort and filter array of page breaks
- sort($hbreaks, SORT_NUMERIC);
- if ($hbreaks[0] == 0) { // don't use first break if it's 0
- array_shift($hbreaks);
- }
-
- $record = 0x001b; // Record identifier
- $cbrk = count($hbreaks); // Number of page breaks
- $length = 2 + 6 * $cbrk; // Bytes to follow
-
- $header = pack("vv", $record, $length);
- $data = pack("v", $cbrk);
-
- // Append each page break
- foreach ($hbreaks as $hbreak) {
- $data .= pack("vvv", $hbreak, 0x0000, 0x00ff);
- }
-
- $this->_append($header . $data);
- }
-
- // vertical page breaks
- if (!empty($vbreaks)) {
-
- // 1000 vertical pagebreaks appears to be an internal Excel 5 limit.
- // It is slightly higher in Excel 97/200, approx. 1026
- $vbreaks = array_slice($vbreaks, 0, 1000);
-
- // Sort and filter array of page breaks
- sort($vbreaks, SORT_NUMERIC);
- if ($vbreaks[0] == 0) { // don't use first break if it's 0
- array_shift($vbreaks);
- }
-
- $record = 0x001a; // Record identifier
- $cbrk = count($vbreaks); // Number of page breaks
- $length = 2 + 6 * $cbrk; // Bytes to follow
-
- $header = pack("vv", $record, $length);
- $data = pack("v", $cbrk);
-
- // Append each page break
- foreach ($vbreaks as $vbreak) {
- $data .= pack("vvv", $vbreak, 0x0000, 0xffff);
- }
-
- $this->_append($header . $data);
- }
- }
-
- /**
- * Set the Biff PROTECT record to indicate that the worksheet is protected.
- */
- private function _writeProtect()
- {
- // Exit unless sheet protection has been specified
- if (!$this->_phpSheet->getProtection()->getSheet()) {
- return;
- }
-
- $record = 0x0012; // Record identifier
- $length = 0x0002; // Bytes to follow
-
- $fLock = 1; // Worksheet is protected
-
- $header = pack("vv", $record, $length);
- $data = pack("v", $fLock);
-
- $this->_append($header.$data);
- }
-
- /**
- * Write SCENPROTECT
- */
- private function _writeScenProtect()
- {
- // Exit if sheet protection is not active
- if (!$this->_phpSheet->getProtection()->getSheet()) {
- return;
- }
-
- // Exit if scenarios are not protected
- if (!$this->_phpSheet->getProtection()->getScenarios()) {
- return;
- }
-
- $record = 0x00DD; // Record identifier
- $length = 0x0002; // Bytes to follow
-
- $header = pack('vv', $record, $length);
- $data = pack('v', 1);
-
- $this->_append($header . $data);
- }
-
- /**
- * Write OBJECTPROTECT
- */
- private function _writeObjectProtect()
- {
- // Exit if sheet protection is not active
- if (!$this->_phpSheet->getProtection()->getSheet()) {
- return;
- }
-
- // Exit if objects are not protected
- if (!$this->_phpSheet->getProtection()->getObjects()) {
- return;
- }
-
- $record = 0x0063; // Record identifier
- $length = 0x0002; // Bytes to follow
-
- $header = pack('vv', $record, $length);
- $data = pack('v', 1);
-
- $this->_append($header . $data);
- }
-
- /**
- * Write the worksheet PASSWORD record.
- */
- private function _writePassword()
- {
- // Exit unless sheet protection and password have been specified
- if (!$this->_phpSheet->getProtection()->getSheet() || !$this->_phpSheet->getProtection()->getPassword()) {
- return;
- }
-
- $record = 0x0013; // Record identifier
- $length = 0x0002; // Bytes to follow
-
- $wPassword = hexdec($this->_phpSheet->getProtection()->getPassword()); // Encoded password
-
- $header = pack("vv", $record, $length);
- $data = pack("v", $wPassword);
-
- $this->_append($header . $data);
- }
-
- /**
- * Insert a 24bit bitmap image in a worksheet.
- *
- * @access public
- * @param integer $row The row we are going to insert the bitmap into
- * @param integer $col The column we are going to insert the bitmap into
- * @param mixed $bitmap The bitmap filename or GD-image resource
- * @param integer $x The horizontal position (offset) of the image inside the cell.
- * @param integer $y The vertical position (offset) of the image inside the cell.
- * @param float $scale_x The horizontal scale
- * @param float $scale_y The vertical scale
- */
- function insertBitmap($row, $col, $bitmap, $x = 0, $y = 0, $scale_x = 1, $scale_y = 1)
- {
- $bitmap_array = (is_resource($bitmap) ? $this->_processBitmapGd($bitmap) : $this->_processBitmap($bitmap));
- list($width, $height, $size, $data) = $bitmap_array; //$this->_processBitmap($bitmap);
-
- // Scale the frame of the image.
- $width *= $scale_x;
- $height *= $scale_y;
-
- // Calculate the vertices of the image and write the OBJ record
- $this->_positionImage($col, $row, $x, $y, $width, $height);
-
- // Write the IMDATA record to store the bitmap data
- $record = 0x007f;
- $length = 8 + $size;
- $cf = 0x09;
- $env = 0x01;
- $lcb = $size;
-
- $header = pack("vvvvV", $record, $length, $cf, $env, $lcb);
- $this->_append($header.$data);
- }
-
- /**
- * 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
- * The SDK incorrectly states that the height should be expressed as a
- * percentage of 1024.
- *
- * @access private
- * @param integer $col_start Col containing upper left corner of object
- * @param integer $row_start Row containing top left corner of object
- * @param integer $x1 Distance to left side of object
- * @param integer $y1 Distance to top of object
- * @param integer $width Width of image frame
- * @param integer $height Height of image frame
- */
- function _positionImage($col_start, $row_start, $x1, $y1, $width, $height)
- {
- // 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 >= Shared_Excel5::sizeCol($this->_phpSheet, Cell::stringFromColumnIndex($col_start))) {
- $x1 = 0;
- }
- if ($y1 >= Shared_Excel5::sizeRow($this->_phpSheet, $row_start + 1)) {
- $y1 = 0;
- }
-
- $width = $width + $x1 -1;
- $height = $height + $y1 -1;
-
- // Subtract the underlying cell widths to find the end cell of the image
- while ($width >= Shared_Excel5::sizeCol($this->_phpSheet, Cell::stringFromColumnIndex($col_end))) {
- $width -= Shared_Excel5::sizeCol($this->_phpSheet, Cell::stringFromColumnIndex($col_end));
- ++$col_end;
- }
-
- // Subtract the underlying cell heights to find the end cell of the image
- while ($height >= Shared_Excel5::sizeRow($this->_phpSheet, $row_end + 1)) {
- $height -= Shared_Excel5::sizeRow($this->_phpSheet, $row_end + 1);
- ++$row_end;
- }
-
- // Bitmap isn't allowed to start or finish in a hidden cell, i.e. a cell
- // with zero eight or width.
- //
- if (Shared_Excel5::sizeCol($this->_phpSheet, Cell::stringFromColumnIndex($col_start)) == 0) {
- return;
- }
- if (Shared_Excel5::sizeCol($this->_phpSheet, Cell::stringFromColumnIndex($col_end)) == 0) {
- return;
- }
- if (Shared_Excel5::sizeRow($this->_phpSheet, $row_start + 1) == 0) {
- return;
- }
- if (Shared_Excel5::sizeRow($this->_phpSheet, $row_end + 1) == 0) {
- return;
- }
-
- // Convert the pixel values to the percentage value expected by Excel
- $x1 = $x1 / Shared_Excel5::sizeCol($this->_phpSheet, Cell::stringFromColumnIndex($col_start)) * 1024;
- $y1 = $y1 / Shared_Excel5::sizeRow($this->_phpSheet, $row_start + 1) * 256;
- $x2 = $width / Shared_Excel5::sizeCol($this->_phpSheet, Cell::stringFromColumnIndex($col_end)) * 1024; // Distance to right side of object
- $y2 = $height / Shared_Excel5::sizeRow($this->_phpSheet, $row_end + 1) * 256; // Distance to bottom of object
-
- $this->_writeObjPicture($col_start, $x1,
- $row_start, $y1,
- $col_end, $x2,
- $row_end, $y2);
- }
-
- /**
- * Store the OBJ record that precedes an IMDATA record. This could be generalise
- * to support other Excel objects.
- *
- * @param integer $colL Column containing upper left corner of object
- * @param integer $dxL Distance from left side of cell
- * @param integer $rwT Row containing top left corner of object
- * @param integer $dyT Distance from top of cell
- * @param integer $colR Column containing lower right corner of object
- * @param integer $dxR Distance from right of cell
- * @param integer $rwB Row containing bottom right corner of object
- * @param integer $dyB Distance from bottom of cell
- */
- private function _writeObjPicture($colL,$dxL,$rwT,$dyT,$colR,$dxR,$rwB,$dyB)
- {
- $record = 0x005d; // Record identifier
- $length = 0x003c; // Bytes to follow
-
- $cObj = 0x0001; // Count of objects in file (set to 1)
- $OT = 0x0008; // Object type. 8 = Picture
- $id = 0x0001; // Object ID
- $grbit = 0x0614; // Option flags
-
- $cbMacro = 0x0000; // Length of FMLA structure
- $Reserved1 = 0x0000; // Reserved
- $Reserved2 = 0x0000; // Reserved
-
- $icvBack = 0x09; // Background colour
- $icvFore = 0x09; // Foreground colour
- $fls = 0x00; // Fill pattern
- $fAuto = 0x00; // Automatic fill
- $icv = 0x08; // Line colour
- $lns = 0xff; // Line style
- $lnw = 0x01; // Line weight
- $fAutoB = 0x00; // Automatic border
- $frs = 0x0000; // Frame style
- $cf = 0x0009; // Image format, 9 = bitmap
- $Reserved3 = 0x0000; // Reserved
- $cbPictFmla = 0x0000; // Length of FMLA structure
- $Reserved4 = 0x0000; // Reserved
- $grbit2 = 0x0001; // Option flags
- $Reserved5 = 0x0000; // Reserved
-
-
- $header = pack("vv", $record, $length);
- $data = pack("V", $cObj);
- $data .= pack("v", $OT);
- $data .= pack("v", $id);
- $data .= pack("v", $grbit);
- $data .= pack("v", $colL);
- $data .= pack("v", $dxL);
- $data .= pack("v", $rwT);
- $data .= pack("v", $dyT);
- $data .= pack("v", $colR);
- $data .= pack("v", $dxR);
- $data .= pack("v", $rwB);
- $data .= pack("v", $dyB);
- $data .= pack("v", $cbMacro);
- $data .= pack("V", $Reserved1);
- $data .= pack("v", $Reserved2);
- $data .= pack("C", $icvBack);
- $data .= pack("C", $icvFore);
- $data .= pack("C", $fls);
- $data .= pack("C", $fAuto);
- $data .= pack("C", $icv);
- $data .= pack("C", $lns);
- $data .= pack("C", $lnw);
- $data .= pack("C", $fAutoB);
- $data .= pack("v", $frs);
- $data .= pack("V", $cf);
- $data .= pack("v", $Reserved3);
- $data .= pack("v", $cbPictFmla);
- $data .= pack("v", $Reserved4);
- $data .= pack("v", $grbit2);
- $data .= pack("V", $Reserved5);
-
- $this->_append($header . $data);
- }
-
- /**
- * Convert a GD-image into the internal format.
- *
- * @access private
- * @param resource $image The image to process
- * @return array Array with data and properties of the bitmap
- */
- function _processBitmapGd($image) {
- $width = imagesx($image);
- $height = imagesy($image);
-
- $data = pack("Vvvvv", 0x000c, $width, $height, 0x01, 0x18);
- for ($j=$height; $j--; ) {
- for ($i=0; $i < $width; ++$i) {
- $color = imagecolorsforindex($image, imagecolorat($image, $i, $j));
- foreach (array("red", "green", "blue") as $key) {
- $color[$key] = $color[$key] + round((255 - $color[$key]) * $color["alpha"] / 127);
- }
- $data .= chr($color["blue"]) . chr($color["green"]) . chr($color["red"]);
- }
- if (3*$width % 4) {
- $data .= str_repeat("\x00", 4 - 3*$width % 4);
- }
- }
-
- return array($width, $height, strlen($data), $data);
- }
-
- /**
- * Convert a 24 bit bitmap into the modified internal format used by Windows.
- * This is described in BITMAPCOREHEADER and BITMAPCOREINFO structures in the
- * MSDN library.
- *
- * @access private
- * @param string $bitmap The bitmap to process
- * @return array Array with data and properties of the bitmap
- */
- function _processBitmap($bitmap)
- {
- // Open file.
- $bmp_fd = @fopen($bitmap,"rb");
- if (!$bmp_fd) {
- throw new Writer_Exception("Couldn't import $bitmap");
- }
-
- // Slurp the file into a string.
- $data = fread($bmp_fd, filesize($bitmap));
-
- // Check that the file is big enough to be a bitmap.
- if (strlen($data) <= 0x36) {
- throw new Writer_Exception("$bitmap doesn't contain enough data.\n");
- }
-
- // The first 2 bytes are used to identify the bitmap.
- $identity = unpack("A2ident", $data);
- if ($identity['ident'] != "BM") {
- throw new Writer_Exception("$bitmap doesn't appear to be a valid bitmap image.\n");
- }
-
- // Remove bitmap data: ID.
- $data = substr($data, 2);
-
- // Read and remove the bitmap size. This is more reliable than reading
- // the data size at offset 0x22.
- //
- $size_array = unpack("Vsa", substr($data, 0, 4));
- $size = $size_array['sa'];
- $data = substr($data, 4);
- $size -= 0x36; // Subtract size of bitmap header.
- $size += 0x0C; // Add size of BIFF header.
-
- // Remove bitmap data: reserved, offset, header length.
- $data = substr($data, 12);
-
- // Read and remove the bitmap width and height. Verify the sizes.
- $width_and_height = unpack("V2", substr($data, 0, 8));
- $width = $width_and_height[1];
- $height = $width_and_height[2];
- $data = substr($data, 8);
- if ($width > 0xFFFF) {
- throw new Writer_Exception("$bitmap: largest image width supported is 65k.\n");
- }
- if ($height > 0xFFFF) {
- throw new Writer_Exception("$bitmap: largest image height supported is 65k.\n");
- }
-
- // Read and remove the bitmap planes and bpp data. Verify them.
- $planes_and_bitcount = unpack("v2", substr($data, 0, 4));
- $data = substr($data, 4);
- if ($planes_and_bitcount[2] != 24) { // Bitcount
- throw new Writer_Exception("$bitmap isn't a 24bit true color bitmap.\n");
- }
- if ($planes_and_bitcount[1] != 1) {
- throw new Writer_Exception("$bitmap: only 1 plane supported in bitmap image.\n");
- }
-
- // Read and remove the bitmap compression. Verify compression.
- $compression = unpack("Vcomp", substr($data, 0, 4));
- $data = substr($data, 4);
-
- //$compression = 0;
- if ($compression['comp'] != 0) {
- throw new Writer_Exception("$bitmap: compression not supported in bitmap image.\n");
- }
-
- // Remove bitmap data: data size, hres, vres, colours, imp. colours.
- $data = substr($data, 20);
-
- // Add the BITMAPCOREHEADER data
- $header = pack("Vvvvv", 0x000c, $width, $height, 0x01, 0x18);
- $data = $header . $data;
-
- return (array($width, $height, $size, $data));
- }
-
- /**
- * Store the window zoom factor. This should be a reduced fraction but for
- * simplicity we will store all fractions with a numerator of 100.
- */
- private function _writeZoom()
- {
- // If scale is 100 we don't need to write a record
- if ($this->_phpSheet->getSheetView()->getZoomScale() == 100) {
- return;
- }
-
- $record = 0x00A0; // Record identifier
- $length = 0x0004; // Bytes to follow
-
- $header = pack("vv", $record, $length);
- $data = pack("vv", $this->_phpSheet->getSheetView()->getZoomScale(), 100);
- $this->_append($header . $data);
- }
-
- /**
- * Get Escher object
- *
- * @return PHPExcel\Shared_Escher
- */
- public function getEscher()
- {
- return $this->_escher;
- }
-
- /**
- * Set Escher object
- *
- * @param PHPExcel\Shared_Escher $pValue
- */
- public function setEscher(Shared_Escher $pValue = null)
- {
- $this->_escher = $pValue;
- }
-
- /**
- * Write MSODRAWING record
- */
- private function _writeMsoDrawing()
- {
- // write the Escher stream if necessary
- if (isset($this->_escher)) {
- $writer = new Writer_Excel5_Escher($this->_escher);
- $data = $writer->close();
- $spOffsets = $writer->getSpOffsets();
- $spTypes = $writer->getSpTypes();
- // write the neccesary MSODRAWING, OBJ records
-
- // split the Escher stream
- $spOffsets[0] = 0;
- $nm = count($spOffsets) - 1; // number of shapes excluding first shape
- for ($i = 1; $i <= $nm; ++$i) {
- // MSODRAWING record
- $record = 0x00EC; // Record identifier
-
- // chunk of Escher stream for one shape
- $dataChunk = substr($data, $spOffsets[$i -1], $spOffsets[$i] - $spOffsets[$i - 1]);
-
- $length = strlen($dataChunk);
- $header = pack("vv", $record, $length);
-
- $this->_append($header . $dataChunk);
-
- // OBJ record
- $record = 0x005D; // record identifier
- $objData = '';
-
- // ftCmo
- if($spTypes[$i] == 0x00C9){
- // Add ftCmo (common object data) subobject
- $objData .=
- pack('vvvvvVVV'
- , 0x0015 // 0x0015 = ftCmo
- , 0x0012 // length of ftCmo data
- , 0x0014 // object type, 0x0014 = filter
- , $i // object id number, Excel seems to use 1-based index, local for the sheet
- , 0x2101 // option flags, 0x2001 is what OpenOffice.org uses
- , 0 // reserved
- , 0 // reserved
- , 0 // reserved
- );
-
- // Add ftSbs Scroll bar subobject
- $objData .= pack('vv', 0x00C, 0x0014);
- $objData .= pack('H*', '0000000000000000640001000A00000010000100');
- // Add ftLbsData (List box data) subobject
- $objData .= pack('vv', 0x0013, 0x1FEE);
- $objData .= pack('H*', '00000000010001030000020008005700');
- }
- else {
- // Add ftCmo (common object data) subobject
- $objData .=
- pack('vvvvvVVV'
- , 0x0015 // 0x0015 = ftCmo
- , 0x0012 // length of ftCmo data
- , 0x0008 // object type, 0x0008 = picture
- , $i // object id number, Excel seems to use 1-based index, local for the sheet
- , 0x6011 // option flags, 0x6011 is what OpenOffice.org uses
- , 0 // reserved
- , 0 // reserved
- , 0 // reserved
- );
- }
-
- // ftEnd
- $objData .=
- pack('vv'
- , 0x0000 // 0x0000 = ftEnd
- , 0x0000 // length of ftEnd data
- );
-
- $length = strlen($objData);
- $header = pack('vv', $record, $length);
- $this->_append($header . $objData);
- }
- }
- }
-
- /**
- * Store the DATAVALIDATIONS and DATAVALIDATION records.
- */
- private function _writeDataValidity()
- {
- // Datavalidation collection
- $dataValidationCollection = $this->_phpSheet->getDataValidationCollection();
-
- // Write data validations?
- if (!empty($dataValidationCollection)) {
-
- // DATAVALIDATIONS record
- $record = 0x01B2; // Record identifier
- $length = 0x0012; // Bytes to follow
-
- $grbit = 0x0000; // Prompt box at cell, no cached validity data at DV records
- $horPos = 0x00000000; // Horizontal position of prompt box, if fixed position
- $verPos = 0x00000000; // Vertical position of prompt box, if fixed position
- $objId = 0xFFFFFFFF; // Object identifier of drop down arrow object, or -1 if not visible
-
- $header = pack('vv', $record, $length);
- $data = pack('vVVVV', $grbit, $horPos, $verPos, $objId,
- count($dataValidationCollection));
- $this->_append($header.$data);
-
- // DATAVALIDATION records
- $record = 0x01BE; // Record identifier
-
- foreach ($dataValidationCollection as $cellCoordinate => $dataValidation) {
- // initialize record data
- $data = '';
-
- // options
- $options = 0x00000000;
-
- // data type
- $type = $dataValidation->getType();
- switch ($type) {
- case Cell_DataValidation::TYPE_NONE: $type = 0x00; break;
- case Cell_DataValidation::TYPE_WHOLE: $type = 0x01; break;
- case Cell_DataValidation::TYPE_DECIMAL: $type = 0x02; break;
- case Cell_DataValidation::TYPE_LIST: $type = 0x03; break;
- case Cell_DataValidation::TYPE_DATE: $type = 0x04; break;
- case Cell_DataValidation::TYPE_TIME: $type = 0x05; break;
- case Cell_DataValidation::TYPE_TEXTLENGTH: $type = 0x06; break;
- case Cell_DataValidation::TYPE_CUSTOM: $type = 0x07; break;
- }
- $options |= $type << 0;
-
- // error style
- $errorStyle = $dataValidation->getType();
- switch ($errorStyle) {
- case Cell_DataValidation::STYLE_STOP: $errorStyle = 0x00; break;
- case Cell_DataValidation::STYLE_WARNING: $errorStyle = 0x01; break;
- case Cell_DataValidation::STYLE_INFORMATION: $errorStyle = 0x02; break;
- }
- $options |= $errorStyle << 4;
-
- // explicit formula?
- if ($type == 0x03 && preg_match('/^\".*\"$/', $dataValidation->getFormula1())) {
- $options |= 0x01 << 7;
- }
-
- // empty cells allowed
- $options |= $dataValidation->getAllowBlank() << 8;
-
- // show drop down
- $options |= (!$dataValidation->getShowDropDown()) << 9;
-
- // show input message
- $options |= $dataValidation->getShowInputMessage() << 18;
-
- // show error message
- $options |= $dataValidation->getShowErrorMessage() << 19;
-
- // condition operator
- $operator = $dataValidation->getOperator();
- switch ($operator) {
- case Cell_DataValidation::OPERATOR_BETWEEN: $operator = 0x00 ; break;
- case Cell_DataValidation::OPERATOR_NOTBETWEEN: $operator = 0x01 ; break;
- case Cell_DataValidation::OPERATOR_EQUAL: $operator = 0x02 ; break;
- case Cell_DataValidation::OPERATOR_NOTEQUAL: $operator = 0x03 ; break;
- case Cell_DataValidation::OPERATOR_GREATERTHAN: $operator = 0x04 ; break;
- case Cell_DataValidation::OPERATOR_LESSTHAN: $operator = 0x05 ; break;
- case Cell_DataValidation::OPERATOR_GREATERTHANOREQUAL: $operator = 0x06; break;
- case Cell_DataValidation::OPERATOR_LESSTHANOREQUAL: $operator = 0x07 ; break;
- }
- $options |= $operator << 20;
-
- $data = pack('V', $options);
-
- // prompt title
- $promptTitle = $dataValidation->getPromptTitle() !== '' ?
- $dataValidation->getPromptTitle() : chr(0);
- $data .= Shared_String::UTF8toBIFF8UnicodeLong($promptTitle);
-
- // error title
- $errorTitle = $dataValidation->getErrorTitle() !== '' ?
- $dataValidation->getErrorTitle() : chr(0);
- $data .= Shared_String::UTF8toBIFF8UnicodeLong($errorTitle);
-
- // prompt text
- $prompt = $dataValidation->getPrompt() !== '' ?
- $dataValidation->getPrompt() : chr(0);
- $data .= Shared_String::UTF8toBIFF8UnicodeLong($prompt);
-
- // error text
- $error = $dataValidation->getError() !== '' ?
- $dataValidation->getError() : chr(0);
- $data .= Shared_String::UTF8toBIFF8UnicodeLong($error);
-
- // formula 1
- try {
- $formula1 = $dataValidation->getFormula1();
- if ($type == 0x03) { // list type
- $formula1 = str_replace(',', chr(0), $formula1);
- }
- $this->_parser->parse($formula1);
- $formula1 = $this->_parser->toReversePolish();
- $sz1 = strlen($formula1);
-
- } catch(Exception $e) {
- $sz1 = 0;
- $formula1 = '';
- }
- $data .= pack('vv', $sz1, 0x0000);
- $data .= $formula1;
-
- // formula 2
- try {
- $formula2 = $dataValidation->getFormula2();
- if ($formula2 === '') {
- throw new Writer_Exception('No formula2');
- }
- $this->_parser->parse($formula2);
- $formula2 = $this->_parser->toReversePolish();
- $sz2 = strlen($formula2);
-
- } catch(Exception $e) {
- $sz2 = 0;
- $formula2 = '';
- }
- $data .= pack('vv', $sz2, 0x0000);
- $data .= $formula2;
-
- // cell range address list
- $data .= pack('v', 0x0001);
- $data .= $this->_writeBIFF8CellRangeAddressFixed($cellCoordinate);
-
- $length = strlen($data);
- $header = pack("vv", $record, $length);
-
- $this->_append($header . $data);
- }
- }
- }
-
- /**
- * Map Error code
- *
- * @param string $errorCode
- * @return int
- */
- private static function _mapErrorCode($errorCode) {
- switch ($errorCode) {
- case '#NULL!': return 0x00;
- case '#DIV/0!': return 0x07;
- case '#VALUE!': return 0x0F;
- case '#REF!': return 0x17;
- case '#NAME?': return 0x1D;
- case '#NUM!': return 0x24;
- case '#N/A': return 0x2A;
- }
-
- return 0;
- }
-
- /**
- * Write PLV Record
- */
- private function _writePageLayoutView(){
- $record = 0x088B; // Record identifier
- $length = 0x0010; // Bytes to follow
-
- $rt = 0x088B; // 2
- $grbitFrt = 0x0000; // 2
- $reserved = 0x0000000000000000; // 8
- $wScalvePLV = $this->_phpSheet->getSheetView()->getZoomScale(); // 2
-
- // The options flags that comprise $grbit
- if($this->_phpSheet->getSheetView()->getView() == Worksheet_SheetView::SHEETVIEW_PAGE_LAYOUT){
- $fPageLayoutView = 1;
- } else {
- $fPageLayoutView = 0;
- }
- $fRulerVisible = 0;
- $fWhitespaceHidden = 0;
-
- $grbit = $fPageLayoutView; // 2
- $grbit |= $fRulerVisible << 1;
- $grbit |= $fWhitespaceHidden << 3;
-
- $header = pack("vv", $record, $length);
- $data = pack("vvVVvv", $rt, $grbitFrt, 0x00000000, 0x00000000, $wScalvePLV, $grbit);
- $this->_append($header . $data);
- }
-
- /**
- * Write CFRule Record
- * @param PHPExcel\Style_Conditional $conditional
- */
- private function _writeCFRule(Style_Conditional $conditional){
- $record = 0x01B1; // Record identifier
-
- // $type : Type of the CF
- // $operatorType : Comparison operator
- if($conditional->getConditionType() == Style_Conditional::CONDITION_EXPRESSION){
- $type = 0x02;
- $operatorType = 0x00;
- } else if($conditional->getConditionType() == Style_Conditional::CONDITION_CELLIS){
- $type = 0x01;
-
- switch ($conditional->getOperatorType()){
- case Style_Conditional::OPERATOR_NONE:
- $operatorType = 0x00;
- break;
- case Style_Conditional::OPERATOR_EQUAL:
- $operatorType = 0x03;
- break;
- case Style_Conditional::OPERATOR_GREATERTHAN:
- $operatorType = 0x05;
- break;
- case Style_Conditional::OPERATOR_GREATERTHANOREQUAL:
- $operatorType = 0x07;
- break;
- case Style_Conditional::OPERATOR_LESSTHAN:
- $operatorType = 0x06;
- break;
- case Style_Conditional::OPERATOR_LESSTHANOREQUAL:
- $operatorType = 0x08;
- break;
- case Style_Conditional::OPERATOR_NOTEQUAL:
- $operatorType = 0x04;
- break;
- case Style_Conditional::OPERATOR_BETWEEN:
- $operatorType = 0x01;
- break;
- // not OPERATOR_NOTBETWEEN 0x02
- }
- }
-
- // $szValue1 : size of the formula data for first value or formula
- // $szValue2 : size of the formula data for second value or formula
- $arrConditions = $conditional->getConditions();
- $numConditions = sizeof($arrConditions);
- if($numConditions == 1){
- $szValue1 = ($arrConditions[0] <= 65535 ? 3 : 0x0000);
- $szValue2 = 0x0000;
- $operand1 = pack('Cv', 0x1E, $arrConditions[0]);
- $operand2 = null;
- } else if($numConditions == 2 && ($conditional->getOperatorType() == Style_Conditional::OPERATOR_BETWEEN)){
- $szValue1 = ($arrConditions[0] <= 65535 ? 3 : 0x0000);
- $szValue2 = ($arrConditions[1] <= 65535 ? 3 : 0x0000);
- $operand1 = pack('Cv', 0x1E, $arrConditions[0]);
- $operand2 = pack('Cv', 0x1E, $arrConditions[1]);
- } else {
- $szValue1 = 0x0000;
- $szValue2 = 0x0000;
- $operand1 = null;
- $operand2 = null;
- }
-
- // $flags : Option flags
- // Alignment
- $bAlignHz = ($conditional->getStyle()->getAlignment()->getHorizontal() == null ? 1 : 0);
- $bAlignVt = ($conditional->getStyle()->getAlignment()->getVertical() == null ? 1 : 0);
- $bAlignWrapTx = ($conditional->getStyle()->getAlignment()->getWrapText() == false ? 1 : 0);
- $bTxRotation = ($conditional->getStyle()->getAlignment()->getTextRotation() == null ? 1 : 0);
- $bIndent = ($conditional->getStyle()->getAlignment()->getIndent() == 0 ? 1 : 0);
- $bShrinkToFit = ($conditional->getStyle()->getAlignment()->getShrinkToFit() == false ? 1 : 0);
- if($bAlignHz == 0 || $bAlignVt == 0 || $bAlignWrapTx == 0 || $bTxRotation == 0 || $bIndent == 0 || $bShrinkToFit == 0){
- $bFormatAlign = 1;
- } else {
- $bFormatAlign = 0;
- }
- // Protection
- $bProtLocked = ($conditional->getStyle()->getProtection()->getLocked() == null ? 1 : 0);
- $bProtHidden = ($conditional->getStyle()->getProtection()->getHidden() == null ? 1 : 0);
- if($bProtLocked == 0 || $bProtHidden == 0){
- $bFormatProt = 1;
- } else {
- $bFormatProt = 0;
- }
- // Border
- $bBorderLeft = ($conditional->getStyle()->getBorders()->getLeft()->getColor()->getARGB() == Style_Color::COLOR_BLACK
- && $conditional->getStyle()->getBorders()->getLeft()->getBorderStyle() == Style_Border::BORDER_NONE ? 1 : 0);
- $bBorderRight = ($conditional->getStyle()->getBorders()->getRight()->getColor()->getARGB() == Style_Color::COLOR_BLACK
- && $conditional->getStyle()->getBorders()->getRight()->getBorderStyle() == Style_Border::BORDER_NONE ? 1 : 0);
- $bBorderTop = ($conditional->getStyle()->getBorders()->getTop()->getColor()->getARGB() == Style_Color::COLOR_BLACK
- && $conditional->getStyle()->getBorders()->getTop()->getBorderStyle() == Style_Border::BORDER_NONE ? 1 : 0);
- $bBorderBottom = ($conditional->getStyle()->getBorders()->getBottom()->getColor()->getARGB() == Style_Color::COLOR_BLACK
- && $conditional->getStyle()->getBorders()->getBottom()->getBorderStyle() == Style_Border::BORDER_NONE ? 1 : 0);
- if($bBorderLeft == 0 || $bBorderRight == 0 || $bBorderTop == 0 || $bBorderBottom == 0){
- $bFormatBorder = 1;
- } else {
- $bFormatBorder = 0;
- }
- // Pattern
- $bFillStyle = ($conditional->getStyle()->getFill()->getFillType() == null ? 0 : 1);
- $bFillColor = ($conditional->getStyle()->getFill()->getStartColor()->getARGB() == null ? 0 : 1);
- $bFillColorBg = ($conditional->getStyle()->getFill()->getEndColor()->getARGB() == null ? 0 : 1);
- if($bFillStyle == 0 || $bFillColor == 0 || $bFillColorBg == 0){
- $bFormatFill = 1;
- } else {
- $bFormatFill = 0;
- }
- // Font
- if($conditional->getStyle()->getFont()->getName() != null
- || $conditional->getStyle()->getFont()->getSize() != null
- || $conditional->getStyle()->getFont()->getBold() != null
- || $conditional->getStyle()->getFont()->getItalic() != null
- || $conditional->getStyle()->getFont()->getSuperScript() != null
- || $conditional->getStyle()->getFont()->getSubScript() != null
- || $conditional->getStyle()->getFont()->getUnderline() != null
- || $conditional->getStyle()->getFont()->getStrikethrough() != null
- || $conditional->getStyle()->getFont()->getColor()->getARGB() != null){
- $bFormatFont = 1;
- } else {
- $bFormatFont = 0;
- }
- // Alignment
- $flags = 0;
- $flags |= (1 == $bAlignHz ? 0x00000001 : 0);
- $flags |= (1 == $bAlignVt ? 0x00000002 : 0);
- $flags |= (1 == $bAlignWrapTx ? 0x00000004 : 0);
- $flags |= (1 == $bTxRotation ? 0x00000008 : 0);
- // Justify last line flag
- $flags |= (1 == 1 ? 0x00000010 : 0);
- $flags |= (1 == $bIndent ? 0x00000020 : 0);
- $flags |= (1 == $bShrinkToFit ? 0x00000040 : 0);
- // Default
- $flags |= (1 == 1 ? 0x00000080 : 0);
- // Protection
- $flags |= (1 == $bProtLocked ? 0x00000100 : 0);
- $flags |= (1 == $bProtHidden ? 0x00000200 : 0);
- // Border
- $flags |= (1 == $bBorderLeft ? 0x00000400 : 0);
- $flags |= (1 == $bBorderRight ? 0x00000800 : 0);
- $flags |= (1 == $bBorderTop ? 0x00001000 : 0);
- $flags |= (1 == $bBorderBottom ? 0x00002000 : 0);
- $flags |= (1 == 1 ? 0x00004000 : 0); // Top left to Bottom right border
- $flags |= (1 == 1 ? 0x00008000 : 0); // Bottom left to Top right border
- // Pattern
- $flags |= (1 == $bFillStyle ? 0x00010000 : 0);
- $flags |= (1 == $bFillColor ? 0x00020000 : 0);
- $flags |= (1 == $bFillColorBg ? 0x00040000 : 0);
- $flags |= (1 == 1 ? 0x00380000 : 0);
- // Font
- $flags |= (1 == $bFormatFont ? 0x04000000 : 0);
- // Alignment :
- $flags |= (1 == $bFormatAlign ? 0x08000000 : 0);
- // Border
- $flags |= (1 == $bFormatBorder ? 0x10000000 : 0);
- // Pattern
- $flags |= (1 == $bFormatFill ? 0x20000000 : 0);
- // Protection
- $flags |= (1 == $bFormatProt ? 0x40000000 : 0);
- // Text direction
- $flags |= (1 == 0 ? 0x80000000 : 0);
-
- // Data Blocks
- if($bFormatFont == 1){
- // Font Name
- if($conditional->getStyle()->getFont()->getName() == null){
- $dataBlockFont = pack('VVVVVVVV', 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000);
- $dataBlockFont .= pack('VVVVVVVV', 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000);
- } else {
- $dataBlockFont = Shared_String::UTF8toBIFF8UnicodeLong($conditional->getStyle()->getFont()->getName());
- }
- // Font Size
- if($conditional->getStyle()->getFont()->getSize() == null){
- $dataBlockFont .= pack('V', 20 * 11);
- } else {
- $dataBlockFont .= pack('V', 20 * $conditional->getStyle()->getFont()->getSize());
- }
- // Font Options
- $dataBlockFont .= pack('V', 0);
- // Font weight
- if($conditional->getStyle()->getFont()->getBold() == true){
- $dataBlockFont .= pack('v', 0x02BC);
- } else {
- $dataBlockFont .= pack('v', 0x0190);
- }
- // Escapement type
- if($conditional->getStyle()->getFont()->getSubScript() == true){
- $dataBlockFont .= pack('v', 0x02);
- $fontEscapement = 0;
- } else if($conditional->getStyle()->getFont()->getSuperScript() == true){
- $dataBlockFont .= pack('v', 0x01);
- $fontEscapement = 0;
- } else {
- $dataBlockFont .= pack('v', 0x00);
- $fontEscapement = 1;
- }
- // Underline type
- switch ($conditional->getStyle()->getFont()->getUnderline()){
- case Style_Font::UNDERLINE_NONE : $dataBlockFont .= pack('C', 0x00); $fontUnderline = 0; break;
- case Style_Font::UNDERLINE_DOUBLE : $dataBlockFont .= pack('C', 0x02); $fontUnderline = 0; break;
- case Style_Font::UNDERLINE_DOUBLEACCOUNTING : $dataBlockFont .= pack('C', 0x22); $fontUnderline = 0; break;
- case Style_Font::UNDERLINE_SINGLE : $dataBlockFont .= pack('C', 0x01); $fontUnderline = 0; break;
- case Style_Font::UNDERLINE_SINGLEACCOUNTING : $dataBlockFont .= pack('C', 0x21); $fontUnderline = 0; break;
- default : $dataBlockFont .= pack('C', 0x00); $fontUnderline = 1; break;
- }
- // Not used (3)
- $dataBlockFont .= pack('vC', 0x0000, 0x00);
- // Font color index
- switch ($conditional->getStyle()->getFont()->getColor()->getRGB()) {
- case '000000': $colorIdx = 0x08; break;
- case 'FFFFFF': $colorIdx = 0x09; break;
- case 'FF0000': $colorIdx = 0x0A; break;
- case '00FF00': $colorIdx = 0x0B; break;
- case '0000FF': $colorIdx = 0x0C; break;
- case 'FFFF00': $colorIdx = 0x0D; break;
- case 'FF00FF': $colorIdx = 0x0E; break;
- case '00FFFF': $colorIdx = 0x0F; break;
- case '800000': $colorIdx = 0x10; break;
- case '008000': $colorIdx = 0x11; break;
- case '000080': $colorIdx = 0x12; break;
- case '808000': $colorIdx = 0x13; break;
- case '800080': $colorIdx = 0x14; break;
- case '008080': $colorIdx = 0x15; break;
- case 'C0C0C0': $colorIdx = 0x16; break;
- case '808080': $colorIdx = 0x17; break;
- case '9999FF': $colorIdx = 0x18; break;
- case '993366': $colorIdx = 0x19; break;
- case 'FFFFCC': $colorIdx = 0x1A; break;
- case 'CCFFFF': $colorIdx = 0x1B; break;
- case '660066': $colorIdx = 0x1C; break;
- case 'FF8080': $colorIdx = 0x1D; break;
- case '0066CC': $colorIdx = 0x1E; break;
- case 'CCCCFF': $colorIdx = 0x1F; break;
- case '000080': $colorIdx = 0x20; break;
- case 'FF00FF': $colorIdx = 0x21; break;
- case 'FFFF00': $colorIdx = 0x22; break;
- case '00FFFF': $colorIdx = 0x23; break;
- case '800080': $colorIdx = 0x24; break;
- case '800000': $colorIdx = 0x25; break;
- case '008080': $colorIdx = 0x26; break;
- case '0000FF': $colorIdx = 0x27; break;
- case '00CCFF': $colorIdx = 0x28; break;
- case 'CCFFFF': $colorIdx = 0x29; break;
- case 'CCFFCC': $colorIdx = 0x2A; break;
- case 'FFFF99': $colorIdx = 0x2B; break;
- case '99CCFF': $colorIdx = 0x2C; break;
- case 'FF99CC': $colorIdx = 0x2D; break;
- case 'CC99FF': $colorIdx = 0x2E; break;
- case 'FFCC99': $colorIdx = 0x2F; break;
- case '3366FF': $colorIdx = 0x30; break;
- case '33CCCC': $colorIdx = 0x31; break;
- case '99CC00': $colorIdx = 0x32; break;
- case 'FFCC00': $colorIdx = 0x33; break;
- case 'FF9900': $colorIdx = 0x34; break;
- case 'FF6600': $colorIdx = 0x35; break;
- case '666699': $colorIdx = 0x36; break;
- case '969696': $colorIdx = 0x37; break;
- case '003366': $colorIdx = 0x38; break;
- case '339966': $colorIdx = 0x39; break;
- case '003300': $colorIdx = 0x3A; break;
- case '333300': $colorIdx = 0x3B; break;
- case '993300': $colorIdx = 0x3C; break;
- case '993366': $colorIdx = 0x3D; break;
- case '333399': $colorIdx = 0x3E; break;
- case '333333': $colorIdx = 0x3F; break;
- default: $colorIdx = 0x00; break;
- }
- $dataBlockFont .= pack('V', $colorIdx);
- // Not used (4)
- $dataBlockFont .= pack('V', 0x00000000);
- // Options flags for modified font attributes
- $optionsFlags = 0;
- $optionsFlagsBold = ($conditional->getStyle()->getFont()->getBold() == null ? 1 : 0);
- $optionsFlags |= (1 == $optionsFlagsBold ? 0x00000002 : 0);
- $optionsFlags |= (1 == 1 ? 0x00000008 : 0);
- $optionsFlags |= (1 == 1 ? 0x00000010 : 0);
- $optionsFlags |= (1 == 0 ? 0x00000020 : 0);
- $optionsFlags |= (1 == 1 ? 0x00000080 : 0);
- $dataBlockFont .= pack('V', $optionsFlags);
- // Escapement type
- $dataBlockFont .= pack('V', $fontEscapement);
- // Underline type
- $dataBlockFont .= pack('V', $fontUnderline);
- // Always
- $dataBlockFont .= pack('V', 0x00000000);
- // Always
- $dataBlockFont .= pack('V', 0x00000000);
- // Not used (8)
- $dataBlockFont .= pack('VV', 0x00000000, 0x00000000);
- // Always
- $dataBlockFont .= pack('v', 0x0001);
- }
- if($bFormatAlign == 1){
- $blockAlign = 0;
- // Alignment and text break
- switch ($conditional->getStyle()->getAlignment()->getHorizontal()){
- case Style_Alignment::HORIZONTAL_GENERAL : $blockAlign = 0; break;
- case Style_Alignment::HORIZONTAL_LEFT : $blockAlign = 1; break;
- case Style_Alignment::HORIZONTAL_RIGHT : $blockAlign = 3; break;
- case Style_Alignment::HORIZONTAL_CENTER : $blockAlign = 2; break;
- case Style_Alignment::HORIZONTAL_CENTER_CONTINUOUS : $blockAlign = 6; break;
- case Style_Alignment::HORIZONTAL_JUSTIFY : $blockAlign = 5; break;
- }
- if($conditional->getStyle()->getAlignment()->getWrapText() == true){
- $blockAlign |= 1 << 3;
- } else {
- $blockAlign |= 0 << 3;
- }
- switch ($conditional->getStyle()->getAlignment()->getVertical()){
- case Style_Alignment::VERTICAL_BOTTOM : $blockAlign = 2 << 4; break;
- case Style_Alignment::VERTICAL_TOP : $blockAlign = 0 << 4; break;
- case Style_Alignment::VERTICAL_CENTER : $blockAlign = 1 << 4; break;
- case Style_Alignment::VERTICAL_JUSTIFY : $blockAlign = 3 << 4; break;
- }
- $blockAlign |= 0 << 7;
-
- // Text rotation angle
- $blockRotation = $conditional->getStyle()->getAlignment()->getTextRotation();
-
- // Indentation
- $blockIndent = $conditional->getStyle()->getAlignment()->getIndent();
- if($conditional->getStyle()->getAlignment()->getShrinkToFit() == true){
- $blockIndent |= 1 << 4;
- } else {
- $blockIndent |= 0 << 4;
- }
- $blockIndent |= 0 << 6;
-
- // Relative indentation
- $blockIndentRelative = 255;
-
- $dataBlockAlign = pack('CCvvv', $blockAlign, $blockRotation, $blockIndent, $blockIndentRelative, 0x0000);
- }
- if($bFormatBorder == 1){
- $blockLineStyle = 0;
- switch ($conditional->getStyle()->getBorders()->getLeft()->getBorderStyle()){
- case Style_Border::BORDER_NONE : $blockLineStyle |= 0x00; break;
- case Style_Border::BORDER_THIN : $blockLineStyle |= 0x01; break;
- case Style_Border::BORDER_MEDIUM : $blockLineStyle |= 0x02; break;
- case Style_Border::BORDER_DASHED : $blockLineStyle |= 0x03; break;
- case Style_Border::BORDER_DOTTED : $blockLineStyle |= 0x04; break;
- case Style_Border::BORDER_THICK : $blockLineStyle |= 0x05; break;
- case Style_Border::BORDER_DOUBLE : $blockLineStyle |= 0x06; break;
- case Style_Border::BORDER_HAIR : $blockLineStyle |= 0x07; break;
- case Style_Border::BORDER_MEDIUMDASHED : $blockLineStyle |= 0x08; break;
- case Style_Border::BORDER_DASHDOT : $blockLineStyle |= 0x09; break;
- case Style_Border::BORDER_MEDIUMDASHDOT : $blockLineStyle |= 0x0A; break;
- case Style_Border::BORDER_DASHDOTDOT : $blockLineStyle |= 0x0B; break;
- case Style_Border::BORDER_MEDIUMDASHDOTDOT : $blockLineStyle |= 0x0C; break;
- case Style_Border::BORDER_SLANTDASHDOT : $blockLineStyle |= 0x0D; break;
- }
- switch ($conditional->getStyle()->getBorders()->getRight()->getBorderStyle()){
- case Style_Border::BORDER_NONE : $blockLineStyle |= 0x00 << 4; break;
- case Style_Border::BORDER_THIN : $blockLineStyle |= 0x01 << 4; break;
- case Style_Border::BORDER_MEDIUM : $blockLineStyle |= 0x02 << 4; break;
- case Style_Border::BORDER_DASHED : $blockLineStyle |= 0x03 << 4; break;
- case Style_Border::BORDER_DOTTED : $blockLineStyle |= 0x04 << 4; break;
- case Style_Border::BORDER_THICK : $blockLineStyle |= 0x05 << 4; break;
- case Style_Border::BORDER_DOUBLE : $blockLineStyle |= 0x06 << 4; break;
- case Style_Border::BORDER_HAIR : $blockLineStyle |= 0x07 << 4; break;
- case Style_Border::BORDER_MEDIUMDASHED : $blockLineStyle |= 0x08 << 4; break;
- case Style_Border::BORDER_DASHDOT : $blockLineStyle |= 0x09 << 4; break;
- case Style_Border::BORDER_MEDIUMDASHDOT : $blockLineStyle |= 0x0A << 4; break;
- case Style_Border::BORDER_DASHDOTDOT : $blockLineStyle |= 0x0B << 4; break;
- case Style_Border::BORDER_MEDIUMDASHDOTDOT : $blockLineStyle |= 0x0C << 4; break;
- case Style_Border::BORDER_SLANTDASHDOT : $blockLineStyle |= 0x0D << 4; break;
- }
- switch ($conditional->getStyle()->getBorders()->getTop()->getBorderStyle()){
- case Style_Border::BORDER_NONE : $blockLineStyle |= 0x00 << 8; break;
- case Style_Border::BORDER_THIN : $blockLineStyle |= 0x01 << 8; break;
- case Style_Border::BORDER_MEDIUM : $blockLineStyle |= 0x02 << 8; break;
- case Style_Border::BORDER_DASHED : $blockLineStyle |= 0x03 << 8; break;
- case Style_Border::BORDER_DOTTED : $blockLineStyle |= 0x04 << 8; break;
- case Style_Border::BORDER_THICK : $blockLineStyle |= 0x05 << 8; break;
- case Style_Border::BORDER_DOUBLE : $blockLineStyle |= 0x06 << 8; break;
- case Style_Border::BORDER_HAIR : $blockLineStyle |= 0x07 << 8; break;
- case Style_Border::BORDER_MEDIUMDASHED : $blockLineStyle |= 0x08 << 8; break;
- case Style_Border::BORDER_DASHDOT : $blockLineStyle |= 0x09 << 8; break;
- case Style_Border::BORDER_MEDIUMDASHDOT : $blockLineStyle |= 0x0A << 8; break;
- case Style_Border::BORDER_DASHDOTDOT : $blockLineStyle |= 0x0B << 8; break;
- case Style_Border::BORDER_MEDIUMDASHDOTDOT : $blockLineStyle |= 0x0C << 8; break;
- case Style_Border::BORDER_SLANTDASHDOT : $blockLineStyle |= 0x0D << 8; break;
- }
- switch ($conditional->getStyle()->getBorders()->getBottom()->getBorderStyle()){
- case Style_Border::BORDER_NONE : $blockLineStyle |= 0x00 << 12; break;
- case Style_Border::BORDER_THIN : $blockLineStyle |= 0x01 << 12; break;
- case Style_Border::BORDER_MEDIUM : $blockLineStyle |= 0x02 << 12; break;
- case Style_Border::BORDER_DASHED : $blockLineStyle |= 0x03 << 12; break;
- case Style_Border::BORDER_DOTTED : $blockLineStyle |= 0x04 << 12; break;
- case Style_Border::BORDER_THICK : $blockLineStyle |= 0x05 << 12; break;
- case Style_Border::BORDER_DOUBLE : $blockLineStyle |= 0x06 << 12; break;
- case Style_Border::BORDER_HAIR : $blockLineStyle |= 0x07 << 12; break;
- case Style_Border::BORDER_MEDIUMDASHED : $blockLineStyle |= 0x08 << 12; break;
- case Style_Border::BORDER_DASHDOT : $blockLineStyle |= 0x09 << 12; break;
- case Style_Border::BORDER_MEDIUMDASHDOT : $blockLineStyle |= 0x0A << 12; break;
- case Style_Border::BORDER_DASHDOTDOT : $blockLineStyle |= 0x0B << 12; break;
- case Style_Border::BORDER_MEDIUMDASHDOTDOT : $blockLineStyle |= 0x0C << 12; break;
- case Style_Border::BORDER_SLANTDASHDOT : $blockLineStyle |= 0x0D << 12; break;
- }
- //@todo _writeCFRule() => $blockLineStyle => Index Color for left line
- //@todo _writeCFRule() => $blockLineStyle => Index Color for right line
- //@todo _writeCFRule() => $blockLineStyle => Top-left to bottom-right on/off
- //@todo _writeCFRule() => $blockLineStyle => Bottom-left to top-right on/off
- $blockColor = 0;
- //@todo _writeCFRule() => $blockColor => Index Color for top line
- //@todo _writeCFRule() => $blockColor => Index Color for bottom line
- //@todo _writeCFRule() => $blockColor => Index Color for diagonal line
- switch ($conditional->getStyle()->getBorders()->getDiagonal()->getBorderStyle()){
- case Style_Border::BORDER_NONE : $blockColor |= 0x00 << 21; break;
- case Style_Border::BORDER_THIN : $blockColor |= 0x01 << 21; break;
- case Style_Border::BORDER_MEDIUM : $blockColor |= 0x02 << 21; break;
- case Style_Border::BORDER_DASHED : $blockColor |= 0x03 << 21; break;
- case Style_Border::BORDER_DOTTED : $blockColor |= 0x04 << 21; break;
- case Style_Border::BORDER_THICK : $blockColor |= 0x05 << 21; break;
- case Style_Border::BORDER_DOUBLE : $blockColor |= 0x06 << 21; break;
- case Style_Border::BORDER_HAIR : $blockColor |= 0x07 << 21; break;
- case Style_Border::BORDER_MEDIUMDASHED : $blockColor |= 0x08 << 21; break;
- case Style_Border::BORDER_DASHDOT : $blockColor |= 0x09 << 21; break;
- case Style_Border::BORDER_MEDIUMDASHDOT : $blockColor |= 0x0A << 21; break;
- case Style_Border::BORDER_DASHDOTDOT : $blockColor |= 0x0B << 21; break;
- case Style_Border::BORDER_MEDIUMDASHDOTDOT : $blockColor |= 0x0C << 21; break;
- case Style_Border::BORDER_SLANTDASHDOT : $blockColor |= 0x0D << 21; break;
- }
- $dataBlockBorder = pack('vv', $blockLineStyle, $blockColor);
- }
- if($bFormatFill == 1){
- // Fill Patern Style
- $blockFillPatternStyle = 0;
- switch ($conditional->getStyle()->getFill()->getFillType()){
- case Style_Fill::FILL_NONE : $blockFillPatternStyle = 0x00; break;
- case Style_Fill::FILL_SOLID : $blockFillPatternStyle = 0x01; break;
- case Style_Fill::FILL_PATTERN_MEDIUMGRAY : $blockFillPatternStyle = 0x02; break;
- case Style_Fill::FILL_PATTERN_DARKGRAY : $blockFillPatternStyle = 0x03; break;
- case Style_Fill::FILL_PATTERN_LIGHTGRAY : $blockFillPatternStyle = 0x04; break;
- case Style_Fill::FILL_PATTERN_DARKHORIZONTAL : $blockFillPatternStyle = 0x05; break;
- case Style_Fill::FILL_PATTERN_DARKVERTICAL : $blockFillPatternStyle = 0x06; break;
- case Style_Fill::FILL_PATTERN_DARKDOWN : $blockFillPatternStyle = 0x07; break;
- case Style_Fill::FILL_PATTERN_DARKUP : $blockFillPatternStyle = 0x08; break;
- case Style_Fill::FILL_PATTERN_DARKGRID : $blockFillPatternStyle = 0x09; break;
- case Style_Fill::FILL_PATTERN_DARKTRELLIS : $blockFillPatternStyle = 0x0A; break;
- case Style_Fill::FILL_PATTERN_LIGHTHORIZONTAL : $blockFillPatternStyle = 0x0B; break;
- case Style_Fill::FILL_PATTERN_LIGHTVERTICAL : $blockFillPatternStyle = 0x0C; break;
- case Style_Fill::FILL_PATTERN_LIGHTDOWN : $blockFillPatternStyle = 0x0D; break;
- case Style_Fill::FILL_PATTERN_LIGHTUP : $blockFillPatternStyle = 0x0E; break;
- case Style_Fill::FILL_PATTERN_LIGHTGRID : $blockFillPatternStyle = 0x0F; break;
- case Style_Fill::FILL_PATTERN_LIGHTTRELLIS : $blockFillPatternStyle = 0x10; break;
- case Style_Fill::FILL_PATTERN_GRAY125 : $blockFillPatternStyle = 0x11; break;
- case Style_Fill::FILL_PATTERN_GRAY0625 : $blockFillPatternStyle = 0x12; break;
- case Style_Fill::FILL_GRADIENT_LINEAR : $blockFillPatternStyle = 0x00; break; // does not exist in BIFF8
- case Style_Fill::FILL_GRADIENT_PATH : $blockFillPatternStyle = 0x00; break; // does not exist in BIFF8
- default : $blockFillPatternStyle = 0x00; break;
- }
- // Color
- switch ($conditional->getStyle()->getFill()->getStartColor()->getRGB()) {
- case '000000': $colorIdxBg = 0x08; break;
- case 'FFFFFF': $colorIdxBg = 0x09; break;
- case 'FF0000': $colorIdxBg = 0x0A; break;
- case '00FF00': $colorIdxBg = 0x0B; break;
- case '0000FF': $colorIdxBg = 0x0C; break;
- case 'FFFF00': $colorIdxBg = 0x0D; break;
- case 'FF00FF': $colorIdxBg = 0x0E; break;
- case '00FFFF': $colorIdxBg = 0x0F; break;
- case '800000': $colorIdxBg = 0x10; break;
- case '008000': $colorIdxBg = 0x11; break;
- case '000080': $colorIdxBg = 0x12; break;
- case '808000': $colorIdxBg = 0x13; break;
- case '800080': $colorIdxBg = 0x14; break;
- case '008080': $colorIdxBg = 0x15; break;
- case 'C0C0C0': $colorIdxBg = 0x16; break;
- case '808080': $colorIdxBg = 0x17; break;
- case '9999FF': $colorIdxBg = 0x18; break;
- case '993366': $colorIdxBg = 0x19; break;
- case 'FFFFCC': $colorIdxBg = 0x1A; break;
- case 'CCFFFF': $colorIdxBg = 0x1B; break;
- case '660066': $colorIdxBg = 0x1C; break;
- case 'FF8080': $colorIdxBg = 0x1D; break;
- case '0066CC': $colorIdxBg = 0x1E; break;
- case 'CCCCFF': $colorIdxBg = 0x1F; break;
- case '000080': $colorIdxBg = 0x20; break;
- case 'FF00FF': $colorIdxBg = 0x21; break;
- case 'FFFF00': $colorIdxBg = 0x22; break;
- case '00FFFF': $colorIdxBg = 0x23; break;
- case '800080': $colorIdxBg = 0x24; break;
- case '800000': $colorIdxBg = 0x25; break;
- case '008080': $colorIdxBg = 0x26; break;
- case '0000FF': $colorIdxBg = 0x27; break;
- case '00CCFF': $colorIdxBg = 0x28; break;
- case 'CCFFFF': $colorIdxBg = 0x29; break;
- case 'CCFFCC': $colorIdxBg = 0x2A; break;
- case 'FFFF99': $colorIdxBg = 0x2B; break;
- case '99CCFF': $colorIdxBg = 0x2C; break;
- case 'FF99CC': $colorIdxBg = 0x2D; break;
- case 'CC99FF': $colorIdxBg = 0x2E; break;
- case 'FFCC99': $colorIdxBg = 0x2F; break;
- case '3366FF': $colorIdxBg = 0x30; break;
- case '33CCCC': $colorIdxBg = 0x31; break;
- case '99CC00': $colorIdxBg = 0x32; break;
- case 'FFCC00': $colorIdxBg = 0x33; break;
- case 'FF9900': $colorIdxBg = 0x34; break;
- case 'FF6600': $colorIdxBg = 0x35; break;
- case '666699': $colorIdxBg = 0x36; break;
- case '969696': $colorIdxBg = 0x37; break;
- case '003366': $colorIdxBg = 0x38; break;
- case '339966': $colorIdxBg = 0x39; break;
- case '003300': $colorIdxBg = 0x3A; break;
- case '333300': $colorIdxBg = 0x3B; break;
- case '993300': $colorIdxBg = 0x3C; break;
- case '993366': $colorIdxBg = 0x3D; break;
- case '333399': $colorIdxBg = 0x3E; break;
- case '333333': $colorIdxBg = 0x3F; break;
- default: $colorIdxBg = 0x41; break;
- }
- // Fg Color
- switch ($conditional->getStyle()->getFill()->getEndColor()->getRGB()) {
- case '000000': $colorIdxFg = 0x08; break;
- case 'FFFFFF': $colorIdxFg = 0x09; break;
- case 'FF0000': $colorIdxFg = 0x0A; break;
- case '00FF00': $colorIdxFg = 0x0B; break;
- case '0000FF': $colorIdxFg = 0x0C; break;
- case 'FFFF00': $colorIdxFg = 0x0D; break;
- case 'FF00FF': $colorIdxFg = 0x0E; break;
- case '00FFFF': $colorIdxFg = 0x0F; break;
- case '800000': $colorIdxFg = 0x10; break;
- case '008000': $colorIdxFg = 0x11; break;
- case '000080': $colorIdxFg = 0x12; break;
- case '808000': $colorIdxFg = 0x13; break;
- case '800080': $colorIdxFg = 0x14; break;
- case '008080': $colorIdxFg = 0x15; break;
- case 'C0C0C0': $colorIdxFg = 0x16; break;
- case '808080': $colorIdxFg = 0x17; break;
- case '9999FF': $colorIdxFg = 0x18; break;
- case '993366': $colorIdxFg = 0x19; break;
- case 'FFFFCC': $colorIdxFg = 0x1A; break;
- case 'CCFFFF': $colorIdxFg = 0x1B; break;
- case '660066': $colorIdxFg = 0x1C; break;
- case 'FF8080': $colorIdxFg = 0x1D; break;
- case '0066CC': $colorIdxFg = 0x1E; break;
- case 'CCCCFF': $colorIdxFg = 0x1F; break;
- case '000080': $colorIdxFg = 0x20; break;
- case 'FF00FF': $colorIdxFg = 0x21; break;
- case 'FFFF00': $colorIdxFg = 0x22; break;
- case '00FFFF': $colorIdxFg = 0x23; break;
- case '800080': $colorIdxFg = 0x24; break;
- case '800000': $colorIdxFg = 0x25; break;
- case '008080': $colorIdxFg = 0x26; break;
- case '0000FF': $colorIdxFg = 0x27; break;
- case '00CCFF': $colorIdxFg = 0x28; break;
- case 'CCFFFF': $colorIdxFg = 0x29; break;
- case 'CCFFCC': $colorIdxFg = 0x2A; break;
- case 'FFFF99': $colorIdxFg = 0x2B; break;
- case '99CCFF': $colorIdxFg = 0x2C; break;
- case 'FF99CC': $colorIdxFg = 0x2D; break;
- case 'CC99FF': $colorIdxFg = 0x2E; break;
- case 'FFCC99': $colorIdxFg = 0x2F; break;
- case '3366FF': $colorIdxFg = 0x30; break;
- case '33CCCC': $colorIdxFg = 0x31; break;
- case '99CC00': $colorIdxFg = 0x32; break;
- case 'FFCC00': $colorIdxFg = 0x33; break;
- case 'FF9900': $colorIdxFg = 0x34; break;
- case 'FF6600': $colorIdxFg = 0x35; break;
- case '666699': $colorIdxFg = 0x36; break;
- case '969696': $colorIdxFg = 0x37; break;
- case '003366': $colorIdxFg = 0x38; break;
- case '339966': $colorIdxFg = 0x39; break;
- case '003300': $colorIdxFg = 0x3A; break;
- case '333300': $colorIdxFg = 0x3B; break;
- case '993300': $colorIdxFg = 0x3C; break;
- case '993366': $colorIdxFg = 0x3D; break;
- case '333399': $colorIdxFg = 0x3E; break;
- case '333333': $colorIdxFg = 0x3F; break;
- default: $colorIdxFg = 0x40; break;
- }
- $dataBlockFill = pack('v', $blockFillPatternStyle);
- $dataBlockFill .= pack('v', $colorIdxFg | ($colorIdxBg << 7));
- }
- if($bFormatProt == 1){
- $dataBlockProtection = 0;
- if($conditional->getStyle()->getProtection()->getLocked() == Style_Protection::PROTECTION_PROTECTED){
- $dataBlockProtection = 1;
- }
- if($conditional->getStyle()->getProtection()->getHidden() == Style_Protection::PROTECTION_PROTECTED){
- $dataBlockProtection = 1 << 1;
- }
- }
-
- $data = pack('CCvvVv', $type, $operatorType, $szValue1, $szValue2, $flags, 0x0000);
- if($bFormatFont == 1){ // Block Formatting : OK
- $data .= $dataBlockFont;
- }
- if($bFormatAlign == 1){
- $data .= $dataBlockAlign;
- }
- if($bFormatBorder == 1){
- $data .= $dataBlockBorder;
- }
- if($bFormatFill == 1){ // Block Formatting : OK
- $data .= $dataBlockFill;
- }
- if($bFormatProt == 1){
- $data .= $dataBlockProtection;
- }
- if(!is_null($operand1)){
- $data .= $operand1;
- }
- if(!is_null($operand2)){
- $data .= $operand2;
- }
- $header = pack('vv', $record, strlen($data));
- $this->_append($header . $data);
- }
-
- /**
- * Write CFHeader record
- */
- private function _writeCFHeader(){
- $record = 0x01B0; // Record identifier
- $length = 0x0016; // Bytes to follow
-
- $numColumnMin = null;
- $numColumnMax = null;
- $numRowMin = null;
- $numRowMax = null;
- $arrConditional = array();
- foreach ($this->_phpSheet->getConditionalStylesCollection() as $cellCoordinate => $conditionalStyles) {
- foreach ($conditionalStyles as $conditional) {
- if($conditional->getConditionType() == Style_Conditional::CONDITION_EXPRESSION
- || $conditional->getConditionType() == Style_Conditional::CONDITION_CELLIS){
- if(!in_array($conditional->getHashCode(), $arrConditional)){
- $arrConditional[] = $conditional->getHashCode();
- }
- // Cells
- $arrCoord = Cell::coordinateFromString($cellCoordinate);
- if(!is_numeric($arrCoord[0])){
- $arrCoord[0] = Cell::columnIndexFromString($arrCoord[0]);
- }
- if(is_null($numColumnMin) || ($numColumnMin > $arrCoord[0])){
- $numColumnMin = $arrCoord[0];
- }
- if(is_null($numColumnMax) || ($numColumnMax < $arrCoord[0])){
- $numColumnMax = $arrCoord[0];
- }
- if(is_null($numRowMin) || ($numRowMin > $arrCoord[1])){
- $numRowMin = $arrCoord[1];
- }
- if(is_null($numRowMax) || ($numRowMax < $arrCoord[1])){
- $numRowMax = $arrCoord[1];
- }
- }
- }
- }
- $needRedraw = 1;
- $cellRange = pack('vvvv', $numRowMin-1, $numRowMax-1, $numColumnMin-1, $numColumnMax-1);
-
- $header = pack('vv', $record, $length);
- $data = pack('vv', count($arrConditional), $needRedraw);
- $data .= $cellRange;
- $data .= pack('v', 0x0001);
- $data .= $cellRange;
- $this->_append($header . $data);
- }
+ /**
+ * Formula parser
+ *
+ * @var PHPExcel\Writer_Excel5_Parser
+ */
+ private $_parser;
+
+ /**
+ * Maximum number of characters for a string (LABEL record in BIFF5)
+ * @var integer
+ */
+ public $_xls_strmax;
+
+ /**
+ * Array containing format information for columns
+ * @var array
+ */
+ public $_colinfo;
+
+ /**
+ * Array containing the selected area for the worksheet
+ * @var array
+ */
+ public $_selection;
+
+ /**
+ * The active pane for the worksheet
+ * @var integer
+ */
+ public $_active_pane;
+
+ /**
+ * Whether to use outline.
+ * @var integer
+ */
+ public $_outline_on;
+
+ /**
+ * Auto outline styles.
+ * @var bool
+ */
+ public $_outline_style;
+
+ /**
+ * Whether to have outline summary below.
+ * @var bool
+ */
+ public $_outline_below;
+
+ /**
+ * Whether to have outline summary at the right.
+ * @var bool
+ */
+ public $_outline_right;
+
+ /**
+ * Reference to the total number of strings in the workbook
+ * @var integer
+ */
+ public $_str_total;
+
+ /**
+ * Reference to the number of unique strings in the workbook
+ * @var integer
+ */
+ public $_str_unique;
+
+ /**
+ * Reference to the array containing all the unique strings in the workbook
+ * @var array
+ */
+ public $_str_table;
+
+ /**
+ * Color cache
+ */
+ private $_colors;
+
+ /**
+ * Index of first used row (at least 0)
+ * @var int
+ */
+ private $_firstRowIndex;
+
+ /**
+ * Index of last used row. (no used rows means -1)
+ * @var int
+ */
+ private $_lastRowIndex;
+
+ /**
+ * Index of first used column (at least 0)
+ * @var int
+ */
+ private $_firstColumnIndex;
+
+ /**
+ * Index of last used column (no used columns means -1)
+ * @var int
+ */
+ private $_lastColumnIndex;
+
+ /**
+ * Sheet object
+ * @var PHPExcel\Worksheet
+ */
+ public $_phpSheet;
+
+ /**
+ * Count cell style Xfs
+ *
+ * @var int
+ */
+ private $_countCellStyleXfs;
+
+ /**
+ * Escher object corresponding to MSODRAWING
+ *
+ * @var PHPExcel\Shared_Escher
+ */
+ private $_escher;
+
+ /**
+ * Array of font hashes associated to FONT records index
+ *
+ * @var array
+ */
+ public $_fntHashIndex;
+
+ /**
+ * Constructor
+ *
+ * @param int &$str_total Total number of strings
+ * @param int &$str_unique Total number of unique strings
+ * @param array &$str_table String Table
+ * @param array &$colors Colour Table
+ * @param mixed $parser The formula parser created for the Workbook
+ * @param boolean $preCalculateFormulas Flag indicating whether formulas should be calculated or just written
+ * @param string $phpSheet The worksheet to write
+ * @param PHPExcel\Worksheet $phpSheet
+ */
+ public function __construct(&$str_total, &$str_unique, &$str_table, &$colors,
+ $parser, $preCalculateFormulas, $phpSheet)
+ {
+ // It needs to call its parent's constructor explicitly
+ parent::__construct();
+
+ // change BIFFwriter limit for CONTINUE records
+// $this->_limit = 8224;
+
+
+ $this->_preCalculateFormulas = $preCalculateFormulas;
+ $this->_str_total = &$str_total;
+ $this->_str_unique = &$str_unique;
+ $this->_str_table = &$str_table;
+ $this->_colors = &$colors;
+ $this->_parser = $parser;
+
+ $this->_phpSheet = $phpSheet;
+
+ //$this->ext_sheets = array();
+ //$this->offset = 0;
+ $this->_xls_strmax = 255;
+ $this->_colinfo = array();
+ $this->_selection = array(0,0,0,0);
+ $this->_active_pane = 3;
+
+ $this->_print_headers = 0;
+
+ $this->_outline_style = 0;
+ $this->_outline_below = 1;
+ $this->_outline_right = 1;
+ $this->_outline_on = 1;
+
+ $this->_fntHashIndex = array();
+
+ // calculate values for DIMENSIONS record
+ $minR = 1;
+ $minC = 'A';
+
+ $maxR = $this->_phpSheet->getHighestRow();
+ $maxC = $this->_phpSheet->getHighestColumn();
+
+ // Determine lowest and highest column and row
+// $this->_firstRowIndex = ($minR > 65535) ? 65535 : $minR;
+ $this->_lastRowIndex = ($maxR > 65535) ? 65535 : $maxR ;
+
+ $this->_firstColumnIndex = Cell::columnIndexFromString($minC);
+ $this->_lastColumnIndex = Cell::columnIndexFromString($maxC);
+
+// if ($this->_firstColumnIndex > 255) $this->_firstColumnIndex = 255;
+ if ($this->_lastColumnIndex > 255) $this->_lastColumnIndex = 255;
+
+ $this->_countCellStyleXfs = count($phpSheet->getParent()->getCellStyleXfCollection());
+ }
+
+ /**
+ * Add data to the beginning of the workbook (note the reverse order)
+ * and to the end of the workbook.
+ *
+ * @access public
+ * @see PHPExcel\Writer_Excel5_Workbook::storeWorkbook()
+ */
+ function close()
+ {
+ $_phpSheet = $this->_phpSheet;
+
+ $num_sheets = $_phpSheet->getParent()->getSheetCount();
+
+ // Write BOF record
+ $this->_storeBof(0x0010);
+
+ // Write PRINTHEADERS
+ $this->_writePrintHeaders();
+
+ // Write PRINTGRIDLINES
+ $this->_writePrintGridlines();
+
+ // Write GRIDSET
+ $this->_writeGridset();
+
+ // Calculate column widths
+ $_phpSheet->calculateColumnWidths();
+
+ // Column dimensions
+ if (($defaultWidth = $_phpSheet->getDefaultColumnDimension()->getWidth()) < 0) {
+ $defaultWidth = Shared_Font::getDefaultColumnWidthByFont($_phpSheet->getParent()->getDefaultStyle()->getFont());
+ }
+
+ $columnDimensions = $_phpSheet->getColumnDimensions();
+ $maxCol = $this->_lastColumnIndex -1;
+ for ($i = 0; $i <= $maxCol; ++$i) {
+ $hidden = 0;
+ $level = 0;
+ $xfIndex = 15; // there are 15 cell style Xfs
+
+ $width = $defaultWidth;
+
+ $columnLetter = Cell::stringFromColumnIndex($i);
+ if (isset($columnDimensions[$columnLetter])) {
+ $columnDimension = $columnDimensions[$columnLetter];
+ if ($columnDimension->getWidth() >= 0) {
+ $width = $columnDimension->getWidth();
+ }
+ $hidden = $columnDimension->getVisible() ? 0 : 1;
+ $level = $columnDimension->getOutlineLevel();
+ $xfIndex = $columnDimension->getXfIndex() + 15; // there are 15 cell style Xfs
+ }
+
+ // Components of _colinfo:
+ // $firstcol first column on the range
+ // $lastcol last column on the range
+ // $width width to set
+ // $xfIndex The optional cell style Xf index to apply to the columns
+ // $hidden The optional hidden atribute
+ // $level The optional outline level
+ $this->_colinfo[] = array($i, $i, $width, $xfIndex, $hidden, $level);
+ }
+
+ // Write GUTS
+ $this->_writeGuts();
+
+ // Write DEFAULTROWHEIGHT
+ $this->_writeDefaultRowHeight();
+
+ // Write WSBOOL
+ $this->_writeWsbool();
+
+ // Write horizontal and vertical page breaks
+ $this->_writeBreaks();
+
+ // Write page header
+ $this->_writeHeader();
+
+ // Write page footer
+ $this->_writeFooter();
+
+ // Write page horizontal centering
+ $this->_writeHcenter();
+
+ // Write page vertical centering
+ $this->_writeVcenter();
+
+ // Write left margin
+ $this->_writeMarginLeft();
+
+ // Write right margin
+ $this->_writeMarginRight();
+
+ // Write top margin
+ $this->_writeMarginTop();
+
+ // Write bottom margin
+ $this->_writeMarginBottom();
+
+ // Write page setup
+ $this->_writeSetup();
+
+ // Write sheet protection
+ $this->_writeProtect();
+
+ // Write SCENPROTECT
+ $this->_writeScenProtect();
+
+ // Write OBJECTPROTECT
+ $this->_writeObjectProtect();
+
+ // Write sheet password
+ $this->_writePassword();
+
+ // Write DEFCOLWIDTH record
+ $this->_writeDefcol();
+
+ // Write the COLINFO records if they exist
+ if (!empty($this->_colinfo)) {
+ $colcount = count($this->_colinfo);
+ for ($i = 0; $i < $colcount; ++$i) {
+ $this->_writeColinfo($this->_colinfo[$i]);
+ }
+ }
+ $autoFilterRange = $_phpSheet->getAutoFilter()->getRange();
+ if (!empty($autoFilterRange)) {
+ // Write AUTOFILTERINFO
+ $this->_writeAutoFilterInfo();
+ }
+
+ // Write sheet dimensions
+ $this->_writeDimensions();
+
+ // Row dimensions
+ foreach ($_phpSheet->getRowDimensions() as $rowDimension) {
+ $xfIndex = $rowDimension->getXfIndex() + 15; // there are 15 cellXfs
+ $this->_writeRow( $rowDimension->getRowIndex() - 1, $rowDimension->getRowHeight(), $xfIndex, ($rowDimension->getVisible() ? '0' : '1'), $rowDimension->getOutlineLevel() );
+ }
+
+ // Write Cells
+ foreach ($_phpSheet->getCellCollection() as $cellID) {
+ $cell = $_phpSheet->getCell($cellID);
+ $row = $cell->getRow() - 1;
+ $column = Cell::columnIndexFromString($cell->getColumn()) - 1;
+
+ // Don't break Excel!
+// if ($row + 1 > 65536 or $column + 1 > 256) {
+ if ($row > 65535 || $column > 255) {
+ break;
+ }
+
+ // Write cell value
+ $xfIndex = $cell->getXfIndex() + 15; // there are 15 cell style Xfs
+
+ $cVal = $cell->getValue();
+ if ($cVal instanceof RichText) {
+ // $this->_writeString($row, $column, $cVal->getPlainText(), $xfIndex);
+ $arrcRun = array();
+ $str_len = Shared_String::CountCharacters($cVal->getPlainText(), 'UTF-8');
+ $str_pos = 0;
+ $elements = $cVal->getRichTextElements();
+ foreach ($elements as $element) {
+ // FONT Index
+ if ($element instanceof RichText_Run) {
+ $str_fontidx = $this->_fntHashIndex[$element->getFont()->getHashCode()];
+ }
+ else {
+ $str_fontidx = 0;
+ }
+ $arrcRun[] = array('strlen' => $str_pos, 'fontidx' => $str_fontidx);
+ // Position FROM
+ $str_pos += Shared_String::CountCharacters($element->getText(), 'UTF-8');
+ }
+ $this->_writeRichTextString($row, $column, $cVal->getPlainText(), $xfIndex, $arrcRun);
+ } else {
+ switch ($cell->getDatatype()) {
+ case Cell_DataType::TYPE_STRING:
+ case Cell_DataType::TYPE_NULL:
+ if ($cVal === '' || $cVal === null) {
+ $this->_writeBlank($row, $column, $xfIndex);
+ } else {
+ $this->_writeString($row, $column, $cVal, $xfIndex);
+ }
+ break;
+
+ case Cell_DataType::TYPE_NUMERIC:
+ $this->_writeNumber($row, $column, $cVal, $xfIndex);
+ break;
+
+ case Cell_DataType::TYPE_FORMULA:
+ $calculatedValue = $this->_preCalculateFormulas ?
+ $cell->getCalculatedValue() : null;
+ $this->_writeFormula($row, $column, $cVal, $xfIndex, $calculatedValue);
+ break;
+
+ case Cell_DataType::TYPE_BOOL:
+ $this->_writeBoolErr($row, $column, $cVal, 0, $xfIndex);
+ break;
+
+ case Cell_DataType::TYPE_ERROR:
+ $this->_writeBoolErr($row, $column, self::_mapErrorCode($cVal), 1, $xfIndex);
+ break;
+
+ }
+ }
+ }
+
+ // Append
+ $this->_writeMsoDrawing();
+
+ // Write WINDOW2 record
+ $this->_writeWindow2();
+
+ // Write PLV record
+ $this->_writePageLayoutView();
+
+ // Write ZOOM record
+ $this->_writeZoom();
+ if ($_phpSheet->getFreezePane()) {
+ $this->_writePanes();
+ }
+
+ // Write SELECTION record
+ $this->_writeSelection();
+
+ // Write MergedCellsTable Record
+ $this->_writeMergedCells();
+
+ // Hyperlinks
+ foreach ($_phpSheet->getHyperLinkCollection() as $coordinate => $hyperlink) {
+ list($column, $row) = Cell::coordinateFromString($coordinate);
+
+ $url = $hyperlink->getUrl();
+
+ if ( strpos($url, 'sheet://') !== false ) {
+ // internal to current workbook
+ $url = str_replace('sheet://', 'internal:', $url);
+
+ } else if ( preg_match('/^(http:|https:|ftp:|mailto:)/', $url) ) {
+ // URL
+ // $url = $url;
+
+ } else {
+ // external (local file)
+ $url = 'external:' . $url;
+ }
+
+ $this->_writeUrl($row - 1, Cell::columnIndexFromString($column) - 1, $url);
+ }
+
+ $this->_writeDataValidity();
+ $this->_writeSheetLayout();
+
+ // Write SHEETPROTECTION record
+ $this->_writeSheetProtection();
+ $this->_writeRangeProtection();
+
+ $arrConditionalStyles = $_phpSheet->getConditionalStylesCollection();
+ if(!empty($arrConditionalStyles)){
+ $arrConditional = array();
+ // @todo CFRule & CFHeader
+ // Write CFHEADER record
+ $this->_writeCFHeader();
+ // Write ConditionalFormattingTable records
+ foreach ($arrConditionalStyles as $cellCoordinate => $conditionalStyles) {
+ foreach ($conditionalStyles as $conditional) {
+ if($conditional->getConditionType() == Style_Conditional::CONDITION_EXPRESSION
+ || $conditional->getConditionType() == Style_Conditional::CONDITION_CELLIS){
+ if(!in_array($conditional->getHashCode(), $arrConditional)){
+ $arrConditional[] = $conditional->getHashCode();
+ // Write CFRULE record
+ $this->_writeCFRule($conditional);
+ }
+ }
+ }
+ }
+ }
+
+ $this->_storeEof();
+ }
+
+ /**
+ * Write a cell range address in BIFF8
+ * always fixed range
+ * See section 2.5.14 in OpenOffice.org's Documentation of the Microsoft Excel File Format
+ *
+ * @param string $range E.g. 'A1' or 'A1:B6'
+ * @return string Binary data
+ */
+ private function _writeBIFF8CellRangeAddressFixed($range = 'A1')
+ {
+ $explodes = explode(':', $range);
+
+ // extract first cell, e.g. 'A1'
+ $firstCell = $explodes[0];
+
+ // extract last cell, e.g. 'B6'
+ if (count($explodes) == 1) {
+ $lastCell = $firstCell;
+ } else {
+ $lastCell = $explodes[1];
+ }
+
+ $firstCellCoordinates = Cell::coordinateFromString($firstCell); // e.g. array(0, 1)
+ $lastCellCoordinates = Cell::coordinateFromString($lastCell); // e.g. array(1, 6)
+
+ return(pack('vvvv',
+ $firstCellCoordinates[1] - 1,
+ $lastCellCoordinates[1] - 1,
+ Cell::columnIndexFromString($firstCellCoordinates[0]) - 1,
+ Cell::columnIndexFromString($lastCellCoordinates[0]) - 1
+ ));
+ }
+
+ /**
+ * Retrieves data from memory in one chunk, or from disk in $buffer
+ * sized chunks.
+ *
+ * @return string The data
+ */
+ function getData()
+ {
+ $buffer = 4096;
+
+ // Return data stored in memory
+ if (isset($this->_data)) {
+ $tmp = $this->_data;
+ unset($this->_data);
+ return $tmp;
+ }
+ // No data to return
+ return false;
+ }
+
+ /**
+ * Set the option to print the row and column headers on the printed page.
+ *
+ * @access public
+ * @param integer $print Whether to print the headers or not. Defaults to 1 (print).
+ */
+ function printRowColHeaders($print = 1)
+ {
+ $this->_print_headers = $print;
+ }
+
+ /**
+ * This method sets the properties for outlining and grouping. The defaults
+ * correspond to Excel's defaults.
+ *
+ * @param bool $visible
+ * @param bool $symbols_below
+ * @param bool $symbols_right
+ * @param bool $auto_style
+ */
+ function setOutline($visible = true, $symbols_below = true, $symbols_right = true, $auto_style = false)
+ {
+ $this->_outline_on = $visible;
+ $this->_outline_below = $symbols_below;
+ $this->_outline_right = $symbols_right;
+ $this->_outline_style = $auto_style;
+
+ // Ensure this is a boolean vale for Window2
+ if ($this->_outline_on) {
+ $this->_outline_on = 1;
+ }
+ }
+
+ /**
+ * Write a double to the specified row and column (zero indexed).
+ * An integer can be written as a double. Excel will display an
+ * integer. $format is optional.
+ *
+ * Returns 0 : normal termination
+ * -2 : row or column out of range
+ *
+ * @param integer $row Zero indexed row
+ * @param integer $col Zero indexed column
+ * @param float $num The number to write
+ * @param mixed $xfIndex The optional XF format
+ * @return integer
+ */
+ private function _writeNumber($row, $col, $num, $xfIndex)
+ {
+ $record = 0x0203; // Record identifier
+ $length = 0x000E; // Number of bytes to follow
+
+ $header = pack("vv", $record, $length);
+ $data = pack("vvv", $row, $col, $xfIndex);
+ $xl_double = pack("d", $num);
+ if (self::getByteOrder()) { // if it's Big Endian
+ $xl_double = strrev($xl_double);
+ }
+
+ $this->_append($header.$data.$xl_double);
+ return(0);
+ }
+
+ /**
+ * Write a LABELSST record or a LABEL record. Which one depends on BIFF version
+ *
+ * @param int $row Row index (0-based)
+ * @param int $col Column index (0-based)
+ * @param string $str The string
+ * @param int $xfIndex Index to XF record
+ */
+ private function _writeString($row, $col, $str, $xfIndex)
+ {
+ $this->_writeLabelSst($row, $col, $str, $xfIndex);
+ }
+
+ /**
+ * Write a LABELSST record or a LABEL record. Which one depends on BIFF version
+ * It differs from _writeString by the writing of rich text strings.
+ * @param int $row Row index (0-based)
+ * @param int $col Column index (0-based)
+ * @param string $str The string
+ * @param mixed $xfIndex The XF format index for the cell
+ * @param array $arrcRun Index to Font record and characters beginning
+ */
+ private function _writeRichTextString($row, $col, $str, $xfIndex, $arrcRun){
+ $record = 0x00FD; // Record identifier
+ $length = 0x000A; // Bytes to follow
+ $str = Shared_String::UTF8toBIFF8UnicodeShort($str, $arrcRun);
+
+ /* check if string is already present */
+ if (!isset($this->_str_table[$str])) {
+ $this->_str_table[$str] = $this->_str_unique++;
+ }
+ $this->_str_total++;
+
+ $header = pack('vv', $record, $length);
+ $data = pack('vvvV', $row, $col, $xfIndex, $this->_str_table[$str]);
+ $this->_append($header.$data);
+ }
+
+ /**
+ * Write a string to the specified row and column (zero indexed).
+ * NOTE: there is an Excel 5 defined limit of 255 characters.
+ * $format is optional.
+ * Returns 0 : normal termination
+ * -2 : row or column out of range
+ * -3 : long string truncated to 255 chars
+ *
+ * @access public
+ * @param integer $row Zero indexed row
+ * @param integer $col Zero indexed column
+ * @param string $str The string to write
+ * @param mixed $xfIndex The XF format index for the cell
+ * @return integer
+ */
+ private function _writeLabel($row, $col, $str, $xfIndex)
+ {
+ $strlen = strlen($str);
+ $record = 0x0204; // Record identifier
+ $length = 0x0008 + $strlen; // Bytes to follow
+
+ $str_error = 0;
+
+ if ($strlen > $this->_xls_strmax) { // LABEL must be < 255 chars
+ $str = substr($str, 0, $this->_xls_strmax);
+ $length = 0x0008 + $this->_xls_strmax;
+ $strlen = $this->_xls_strmax;
+ $str_error = -3;
+ }
+
+ $header = pack("vv", $record, $length);
+ $data = pack("vvvv", $row, $col, $xfIndex, $strlen);
+ $this->_append($header . $data . $str);
+ return($str_error);
+ }
+
+ /**
+ * Write a string to the specified row and column (zero indexed).
+ * This is the BIFF8 version (no 255 chars limit).
+ * $format is optional.
+ * Returns 0 : normal termination
+ * -2 : row or column out of range
+ * -3 : long string truncated to 255 chars
+ *
+ * @access public
+ * @param integer $row Zero indexed row
+ * @param integer $col Zero indexed column
+ * @param string $str The string to write
+ * @param mixed $xfIndex The XF format index for the cell
+ * @return integer
+ */
+ private function _writeLabelSst($row, $col, $str, $xfIndex)
+ {
+ $record = 0x00FD; // Record identifier
+ $length = 0x000A; // Bytes to follow
+
+ $str = Shared_String::UTF8toBIFF8UnicodeLong($str);
+
+ /* check if string is already present */
+ if (!isset($this->_str_table[$str])) {
+ $this->_str_table[$str] = $this->_str_unique++;
+ }
+ $this->_str_total++;
+
+ $header = pack('vv', $record, $length);
+ $data = pack('vvvV', $row, $col, $xfIndex, $this->_str_table[$str]);
+ $this->_append($header.$data);
+ }
+
+ /**
+ * Writes a note associated with the cell given by the row and column.
+ * NOTE records don't have a length limit.
+ *
+ * @param integer $row Zero indexed row
+ * @param integer $col Zero indexed column
+ * @param string $note The note to write
+ */
+ private function _writeNote($row, $col, $note)
+ {
+ $note_length = strlen($note);
+ $record = 0x001C; // Record identifier
+ $max_length = 2048; // Maximun length for a NOTE record
+
+ // Length for this record is no more than 2048 + 6
+ $length = 0x0006 + min($note_length, 2048);
+ $header = pack("vv", $record, $length);
+ $data = pack("vvv", $row, $col, $note_length);
+ $this->_append($header . $data . substr($note, 0, 2048));
+
+ for ($i = $max_length; $i < $note_length; $i += $max_length) {
+ $chunk = substr($note, $i, $max_length);
+ $length = 0x0006 + strlen($chunk);
+ $header = pack("vv", $record, $length);
+ $data = pack("vvv", -1, 0, strlen($chunk));
+ $this->_append($header.$data.$chunk);
+ }
+ return(0);
+ }
+
+ /**
+ * Write a blank cell to the specified row and column (zero indexed).
+ * A blank cell is used to specify formatting without adding a string
+ * or a number.
+ *
+ * A blank cell without a format serves no purpose. Therefore, we don't write
+ * a BLANK record unless a format is specified.
+ *
+ * Returns 0 : normal termination (including no format)
+ * -1 : insufficient number of arguments
+ * -2 : row or column out of range
+ *
+ * @param integer $row Zero indexed row
+ * @param integer $col Zero indexed column
+ * @param mixed $xfIndex The XF format index
+ */
+ function _writeBlank($row, $col, $xfIndex)
+ {
+ $record = 0x0201; // Record identifier
+ $length = 0x0006; // Number of bytes to follow
+
+ $header = pack("vv", $record, $length);
+ $data = pack("vvv", $row, $col, $xfIndex);
+ $this->_append($header . $data);
+ return 0;
+ }
+
+ /**
+ * Write a boolean or an error type to the specified row and column (zero indexed)
+ *
+ * @param int $row Row index (0-based)
+ * @param int $col Column index (0-based)
+ * @param int $value
+ * @param boolean $isError Error or Boolean?
+ * @param int $xfIndex
+ */
+ private function _writeBoolErr($row, $col, $value, $isError, $xfIndex)
+ {
+ $record = 0x0205;
+ $length = 8;
+
+ $header = pack("vv", $record, $length);
+ $data = pack("vvvCC", $row, $col, $xfIndex, $value, $isError);
+ $this->_append($header . $data);
+ return 0;
+ }
+
+ /**
+ * Write a formula to the specified row and column (zero indexed).
+ * The textual representation of the formula is passed to the parser in
+ * Parser.php which returns a packed binary string.
+ *
+ * Returns 0 : normal termination
+ * -1 : formula errors (bad formula)
+ * -2 : row or column out of range
+ *
+ * @param integer $row Zero indexed row
+ * @param integer $col Zero indexed column
+ * @param string $formula The formula text string
+ * @param mixed $xfIndex The XF format index
+ * @param mixed $calculatedValue Calculated value
+ * @return integer
+ */
+ private function _writeFormula($row, $col, $formula, $xfIndex, $calculatedValue)
+ {
+ $record = 0x0006; // Record identifier
+
+ // Initialize possible additional value for STRING record that should be written after the FORMULA record?
+ $stringValue = null;
+
+ // calculated value
+ if (isset($calculatedValue)) {
+ // Since we can't yet get the data type of the calculated value,
+ // we use best effort to determine data type
+ if (is_bool($calculatedValue)) {
+ // Boolean value
+ $num = pack('CCCvCv', 0x01, 0x00, (int)$calculatedValue, 0x00, 0x00, 0xFFFF);
+ } elseif (is_int($calculatedValue) || is_float($calculatedValue)) {
+ // Numeric value
+ $num = pack('d', $calculatedValue);
+ } elseif (is_string($calculatedValue)) {
+ if (array_key_exists($calculatedValue, Cell_DataType::getErrorCodes())) {
+ // Error value
+ $num = pack('CCCvCv', 0x02, 0x00, self::_mapErrorCode($calculatedValue), 0x00, 0x00, 0xFFFF);
+ } elseif ($calculatedValue === '') {
+ // Empty string (and BIFF8)
+ $num = pack('CCCvCv', 0x03, 0x00, 0x00, 0x00, 0x00, 0xFFFF);
+ } else {
+ // Non-empty string value (or empty string BIFF5)
+ $stringValue = $calculatedValue;
+ $num = pack('CCCvCv', 0x00, 0x00, 0x00, 0x00, 0x00, 0xFFFF);
+ }
+ } else {
+ // We are really not supposed to reach here
+ $num = pack('d', 0x00);
+ }
+ } else {
+ $num = pack('d', 0x00);
+ }
+
+ $grbit = 0x03; // Option flags
+ $unknown = 0x0000; // Must be zero
+
+ // Strip the '=' or '@' sign at the beginning of the formula string
+ if ($formula{0} == '=') {
+ $formula = substr($formula,1);
+ } else {
+ // Error handling
+ $this->_writeString($row, $col, 'Unrecognised character for formula');
+ return -1;
+ }
+
+ // Parse the formula using the parser in Parser.php
+ try {
+ $error = $this->_parser->parse($formula);
+ $formula = $this->_parser->toReversePolish();
+
+ $formlen = strlen($formula); // Length of the binary string
+ $length = 0x16 + $formlen; // Length of the record data
+
+ $header = pack("vv", $record, $length);
+
+ $data = pack("vvv", $row, $col, $xfIndex)
+ . $num
+ . pack("vVv", $grbit, $unknown, $formlen);
+ $this->_append($header . $data . $formula);
+
+ // Append also a STRING record if necessary
+ if ($stringValue !== null) {
+ $this->_writeStringRecord($stringValue);
+ }
+
+ return 0;
+
+ } catch (Exception $e) {
+ // do nothing
+ }
+
+ }
+
+ /**
+ * Write a STRING record. This
+ *
+ * @param string $stringValue
+ */
+ private function _writeStringRecord($stringValue)
+ {
+ $record = 0x0207; // Record identifier
+ $data = Shared_String::UTF8toBIFF8UnicodeLong($stringValue);
+
+ $length = strlen($data);
+ $header = pack('vv', $record, $length);
+
+ $this->_append($header . $data);
+ }
+
+ /**
+ * Write a hyperlink.
+ * This is comprised of two elements: the visible label and
+ * the invisible link. The visible label is the same as the link unless an
+ * alternative string is specified. The label is written using the
+ * _writeString() method. Therefore the 255 characters string limit applies.
+ * $string and $format are optional.
+ *
+ * The hyperlink can be to a http, ftp, mail, internal sheet (not yet), or external
+ * directory url.
+ *
+ * Returns 0 : normal termination
+ * -2 : row or column out of range
+ * -3 : long string truncated to 255 chars
+ *
+ * @param integer $row Row
+ * @param integer $col Column
+ * @param string $url URL string
+ * @return integer
+ */
+ private function _writeUrl($row, $col, $url)
+ {
+ // Add start row and col to arg list
+ return($this->_writeUrlRange($row, $col, $row, $col, $url));
+ }
+
+ /**
+ * This is the more general form of _writeUrl(). It allows a hyperlink to be
+ * written to a range of cells. This function also decides the type of hyperlink
+ * to be written. These are either, Web (http, ftp, mailto), Internal
+ * (Sheet1!A1) or external ('c:\temp\foo.xls#Sheet1!A1').
+ *
+ * @access private
+ * @see _writeUrl()
+ * @param integer $row1 Start row
+ * @param integer $col1 Start column
+ * @param integer $row2 End row
+ * @param integer $col2 End column
+ * @param string $url URL string
+ * @return integer
+ */
+ function _writeUrlRange($row1, $col1, $row2, $col2, $url)
+ {
+ // Check for internal/external sheet links or default to web link
+ if (preg_match('[^internal:]', $url)) {
+ return($this->_writeUrlInternal($row1, $col1, $row2, $col2, $url));
+ }
+ if (preg_match('[^external:]', $url)) {
+ return($this->_writeUrlExternal($row1, $col1, $row2, $col2, $url));
+ }
+ return($this->_writeUrlWeb($row1, $col1, $row2, $col2, $url));
+ }
+
+ /**
+ * Used to write http, ftp and mailto hyperlinks.
+ * The link type ($options) is 0x03 is the same as absolute dir ref without
+ * sheet. However it is differentiated by the $unknown2 data stream.
+ *
+ * @access private
+ * @see _writeUrl()
+ * @param integer $row1 Start row
+ * @param integer $col1 Start column
+ * @param integer $row2 End row
+ * @param integer $col2 End column
+ * @param string $url URL string
+ * @return integer
+ */
+ function _writeUrlWeb($row1, $col1, $row2, $col2, $url)
+ {
+ $record = 0x01B8; // Record identifier
+ $length = 0x00000; // Bytes to follow
+
+ // Pack the undocumented parts of the hyperlink stream
+ $unknown1 = pack("H*", "D0C9EA79F9BACE118C8200AA004BA90B02000000");
+ $unknown2 = pack("H*", "E0C9EA79F9BACE118C8200AA004BA90B");
+
+ // Pack the option flags
+ $options = pack("V", 0x03);
+
+ // Convert URL to a null terminated wchar string
+ $url = join("\0", preg_split("''", $url, -1, PREG_SPLIT_NO_EMPTY));
+ $url = $url . "\0\0\0";
+
+ // Pack the length of the URL
+ $url_len = pack("V", strlen($url));
+
+ // Calculate the data length
+ $length = 0x34 + strlen($url);
+
+ // Pack the header data
+ $header = pack("vv", $record, $length);
+ $data = pack("vvvv", $row1, $row2, $col1, $col2);
+
+ // Write the packed data
+ $this->_append($header . $data .
+ $unknown1 . $options .
+ $unknown2 . $url_len . $url);
+ return 0;
+ }
+
+ /**
+ * Used to write internal reference hyperlinks such as "Sheet1!A1".
+ *
+ * @access private
+ * @see _writeUrl()
+ * @param integer $row1 Start row
+ * @param integer $col1 Start column
+ * @param integer $row2 End row
+ * @param integer $col2 End column
+ * @param string $url URL string
+ * @return integer
+ */
+ function _writeUrlInternal($row1, $col1, $row2, $col2, $url)
+ {
+ $record = 0x01B8; // Record identifier
+ $length = 0x00000; // Bytes to follow
+
+ // Strip URL type
+ $url = preg_replace('/^internal:/', '', $url);
+
+ // Pack the undocumented parts of the hyperlink stream
+ $unknown1 = pack("H*", "D0C9EA79F9BACE118C8200AA004BA90B02000000");
+
+ // Pack the option flags
+ $options = pack("V", 0x08);
+
+ // Convert the URL type and to a null terminated wchar string
+ $url .= "\0";
+
+ // character count
+ $url_len = Shared_String::CountCharacters($url);
+ $url_len = pack('V', $url_len);
+
+ $url = Shared_String::ConvertEncoding($url, 'UTF-16LE', 'UTF-8');
+
+ // Calculate the data length
+ $length = 0x24 + strlen($url);
+
+ // Pack the header data
+ $header = pack("vv", $record, $length);
+ $data = pack("vvvv", $row1, $row2, $col1, $col2);
+
+ // Write the packed data
+ $this->_append($header . $data .
+ $unknown1 . $options .
+ $url_len . $url);
+ return 0;
+ }
+
+ /**
+ * Write links to external directory names such as 'c:\foo.xls',
+ * c:\foo.xls#Sheet1!A1', '../../foo.xls'. and '../../foo.xls#Sheet1!A1'.
+ *
+ * Note: Excel writes some relative links with the $dir_long string. We ignore
+ * these cases for the sake of simpler code.
+ *
+ * @access private
+ * @see _writeUrl()
+ * @param integer $row1 Start row
+ * @param integer $col1 Start column
+ * @param integer $row2 End row
+ * @param integer $col2 End column
+ * @param string $url URL string
+ * @return integer
+ */
+ function _writeUrlExternal($row1, $col1, $row2, $col2, $url)
+ {
+ // Network drives are different. We will handle them separately
+ // MS/Novell network drives and shares start with \\
+ if (preg_match('[^external:\\\\]', $url)) {
+ return; //($this->_writeUrlExternal_net($row1, $col1, $row2, $col2, $url, $str, $format));
+ }
+
+ $record = 0x01B8; // Record identifier
+ $length = 0x00000; // Bytes to follow
+
+ // Strip URL type and change Unix dir separator to Dos style (if needed)
+ //
+ $url = preg_replace('/^external:/', '', $url);
+ $url = preg_replace('/\//', "\\", $url);
+
+ // Determine if the link is relative or absolute:
+ // relative if link contains no dir separator, "somefile.xls"
+ // relative if link starts with up-dir, "..\..\somefile.xls"
+ // otherwise, absolute
+
+ $absolute = 0x00; // relative path
+ if ( preg_match('/^[A-Z]:/', $url) ) {
+ $absolute = 0x02; // absolute path on Windows, e.g. C:\...
+ }
+ $link_type = 0x01 | $absolute;
+
+ // Determine if the link contains a sheet reference and change some of the
+ // parameters accordingly.
+ // Split the dir name and sheet name (if it exists)
+ $dir_long = $url;
+ if (preg_match("/\#/", $url)) {
+ $link_type |= 0x08;
+ }
+
+
+ // Pack the link type
+ $link_type = pack("V", $link_type);
+
+ // Calculate the up-level dir count e.g.. (..\..\..\ == 3)
+ $up_count = preg_match_all("/\.\.\\\/", $dir_long, $useless);
+ $up_count = pack("v", $up_count);
+
+ // Store the short dos dir name (null terminated)
+ $dir_short = preg_replace("/\.\.\\\/", '', $dir_long) . "\0";
+
+ // Store the long dir name as a wchar string (non-null terminated)
+ $dir_long = $dir_long . "\0";
+
+ // Pack the lengths of the dir strings
+ $dir_short_len = pack("V", strlen($dir_short) );
+ $dir_long_len = pack("V", strlen($dir_long) );
+ $stream_len = pack("V", 0);//strlen($dir_long) + 0x06);
+
+ // Pack the undocumented parts of the hyperlink stream
+ $unknown1 = pack("H*",'D0C9EA79F9BACE118C8200AA004BA90B02000000' );
+ $unknown2 = pack("H*",'0303000000000000C000000000000046' );
+ $unknown3 = pack("H*",'FFFFADDE000000000000000000000000000000000000000');
+ $unknown4 = pack("v", 0x03 );
+
+ // Pack the main data stream
+ $data = pack("vvvv", $row1, $row2, $col1, $col2) .
+ $unknown1 .
+ $link_type .
+ $unknown2 .
+ $up_count .
+ $dir_short_len.
+ $dir_short .
+ $unknown3 .
+ $stream_len ;/*.
+ $dir_long_len .
+ $unknown4 .
+ $dir_long .
+ $sheet_len .
+ $sheet ;*/
+
+ // Pack the header data
+ $length = strlen($data);
+ $header = pack("vv", $record, $length);
+
+ // Write the packed data
+ $this->_append($header. $data);
+ return 0;
+ }
+
+ /**
+ * This method is used to set the height and format for a row.
+ *
+ * @param integer $row The row to set
+ * @param integer $height Height we are giving to the row.
+ * Use null to set XF without setting height
+ * @param integer $xfIndex The optional cell style Xf index to apply to the columns
+ * @param bool $hidden The optional hidden attribute
+ * @param integer $level The optional outline level for row, in range [0,7]
+ */
+ private function _writeRow($row, $height, $xfIndex, $hidden = false, $level = 0)
+ {
+ $record = 0x0208; // Record identifier
+ $length = 0x0010; // Number of bytes to follow
+
+ $colMic = 0x0000; // First defined column
+ $colMac = 0x0000; // Last defined column
+ $irwMac = 0x0000; // Used by Excel to optimise loading
+ $reserved = 0x0000; // Reserved
+ $grbit = 0x0000; // Option flags
+ $ixfe = $xfIndex;
+
+ if ( $height < 0 ){
+ $height = null;
+ }
+
+ // Use _writeRow($row, null, $XF) to set XF format without setting height
+ if ($height != null) {
+ $miyRw = $height * 20; // row height
+ } else {
+ $miyRw = 0xff; // default row height is 256
+ }
+
+ // Set the options flags. fUnsynced is used to show that the font and row
+ // heights are not compatible. This is usually the case for WriteExcel.
+ // The collapsed flag 0x10 doesn't seem to be used to indicate that a row
+ // is collapsed. Instead it is used to indicate that the previous row is
+ // collapsed. The zero height flag, 0x20, is used to collapse a row.
+
+ $grbit |= $level;
+ if ($hidden) {
+ $grbit |= 0x0020;
+ }
+ if ($height !== null) {
+ $grbit |= 0x0040; // fUnsynced
+ }
+ if ($xfIndex !== 0xF) {
+ $grbit |= 0x0080;
+ }
+ $grbit |= 0x0100;
+
+ $header = pack("vv", $record, $length);
+ $data = pack("vvvvvvvv", $row, $colMic, $colMac, $miyRw,
+ $irwMac,$reserved, $grbit, $ixfe);
+ $this->_append($header.$data);
+ }
+
+ /**
+ * Writes Excel DIMENSIONS to define the area in which there is data.
+ */
+ private function _writeDimensions()
+ {
+ $record = 0x0200; // Record identifier
+
+ $length = 0x000E;
+ $data = pack('VVvvv'
+ , $this->_firstRowIndex
+ , $this->_lastRowIndex + 1
+ , $this->_firstColumnIndex
+ , $this->_lastColumnIndex + 1
+ , 0x0000 // reserved
+ );
+
+ $header = pack("vv", $record, $length);
+ $this->_append($header.$data);
+ }
+
+ /**
+ * Write BIFF record Window2.
+ */
+ private function _writeWindow2()
+ {
+ $record = 0x023E; // Record identifier
+ $length = 0x0012;
+
+ $grbit = 0x00B6; // Option flags
+ $rwTop = 0x0000; // Top row visible in window
+ $colLeft = 0x0000; // Leftmost column visible in window
+
+
+ // The options flags that comprise $grbit
+ $fDspFmla = 0; // 0 - bit
+ $fDspGrid = $this->_phpSheet->getShowGridlines() ? 1 : 0; // 1
+ $fDspRwCol = $this->_phpSheet->getShowRowColHeaders() ? 1 : 0; // 2
+ $fFrozen = $this->_phpSheet->getFreezePane() ? 1 : 0; // 3
+ $fDspZeros = 1; // 4
+ $fDefaultHdr = 1; // 5
+ $fArabic = $this->_phpSheet->getRightToLeft() ? 1 : 0; // 6
+ $fDspGuts = $this->_outline_on; // 7
+ $fFrozenNoSplit = 0; // 0 - bit
+ // no support in PHPExcel for selected sheet, therefore sheet is only selected if it is the active sheet
+ $fSelected = ($this->_phpSheet === $this->_phpSheet->getParent()->getActiveSheet()) ? 1 : 0;
+ $fPaged = 1; // 2
+ $fPageBreakPreview = $this->_phpSheet->getSheetView()->getView() === Worksheet_SheetView::SHEETVIEW_PAGE_BREAK_PREVIEW;
+
+ $grbit = $fDspFmla;
+ $grbit |= $fDspGrid << 1;
+ $grbit |= $fDspRwCol << 2;
+ $grbit |= $fFrozen << 3;
+ $grbit |= $fDspZeros << 4;
+ $grbit |= $fDefaultHdr << 5;
+ $grbit |= $fArabic << 6;
+ $grbit |= $fDspGuts << 7;
+ $grbit |= $fFrozenNoSplit << 8;
+ $grbit |= $fSelected << 9;
+ $grbit |= $fPaged << 10;
+ $grbit |= $fPageBreakPreview << 11;
+
+ $header = pack("vv", $record, $length);
+ $data = pack("vvv", $grbit, $rwTop, $colLeft);
+
+ // FIXME !!!
+ $rgbHdr = 0x0040; // Row/column heading and gridline color index
+ $zoom_factor_page_break = ($fPageBreakPreview? $this->_phpSheet->getSheetView()->getZoomScale() : 0x0000);
+ $zoom_factor_normal = $this->_phpSheet->getSheetView()->getZoomScaleNormal();
+
+ $data .= pack("vvvvV", $rgbHdr, 0x0000, $zoom_factor_page_break, $zoom_factor_normal, 0x00000000);
+
+ $this->_append($header.$data);
+ }
+
+ /**
+ * Write BIFF record DEFAULTROWHEIGHT.
+ */
+ private function _writeDefaultRowHeight()
+ {
+ $defaultRowHeight = $this->_phpSheet->getDefaultRowDimension()->getRowHeight();
+
+ if ($defaultRowHeight < 0) {
+ return;
+ }
+
+ // convert to twips
+ $defaultRowHeight = (int) 20 * $defaultRowHeight;
+
+ $record = 0x0225; // Record identifier
+ $length = 0x0004; // Number of bytes to follow
+
+ $header = pack("vv", $record, $length);
+ $data = pack("vv", 1, $defaultRowHeight);
+ $this->_append($header . $data);
+ }
+
+ /**
+ * Write BIFF record DEFCOLWIDTH if COLINFO records are in use.
+ */
+ private function _writeDefcol()
+ {
+ $defaultColWidth = 8;
+
+ $record = 0x0055; // Record identifier
+ $length = 0x0002; // Number of bytes to follow
+
+ $header = pack("vv", $record, $length);
+ $data = pack("v", $defaultColWidth);
+ $this->_append($header . $data);
+ }
+
+ /**
+ * Write BIFF record COLINFO to define column widths
+ *
+ * Note: The SDK says the record length is 0x0B but Excel writes a 0x0C
+ * length record.
+ *
+ * @param array $col_array This is the only parameter received and is composed of the following:
+ * 0 => First formatted column,
+ * 1 => Last formatted column,
+ * 2 => Col width (8.43 is Excel default),
+ * 3 => The optional XF format of the column,
+ * 4 => Option flags.
+ * 5 => Optional outline level
+ */
+ private function _writeColinfo($col_array)
+ {
+ if (isset($col_array[0])) {
+ $colFirst = $col_array[0];
+ }
+ if (isset($col_array[1])) {
+ $colLast = $col_array[1];
+ }
+ if (isset($col_array[2])) {
+ $coldx = $col_array[2];
+ } else {
+ $coldx = 8.43;
+ }
+ if (isset($col_array[3])) {
+ $xfIndex = $col_array[3];
+ } else {
+ $xfIndex = 15;
+ }
+ if (isset($col_array[4])) {
+ $grbit = $col_array[4];
+ } else {
+ $grbit = 0;
+ }
+ if (isset($col_array[5])) {
+ $level = $col_array[5];
+ } else {
+ $level = 0;
+ }
+ $record = 0x007D; // Record identifier
+ $length = 0x000C; // Number of bytes to follow
+
+ $coldx *= 256; // Convert to units of 1/256 of a char
+
+ $ixfe = $xfIndex;
+ $reserved = 0x0000; // Reserved
+
+ $level = max(0, min($level, 7));
+ $grbit |= $level << 8;
+
+ $header = pack("vv", $record, $length);
+ $data = pack("vvvvvv", $colFirst, $colLast, $coldx,
+ $ixfe, $grbit, $reserved);
+ $this->_append($header.$data);
+ }
+
+ /**
+ * Write BIFF record SELECTION.
+ */
+ private function _writeSelection()
+ {
+ // look up the selected cell range
+ $selectedCells = $this->_phpSheet->getSelectedCells();
+ $selectedCells = Cell::splitRange($this->_phpSheet->getSelectedCells());
+ $selectedCells = $selectedCells[0];
+ if (count($selectedCells) == 2) {
+ list($first, $last) = $selectedCells;
+ } else {
+ $first = $selectedCells[0];
+ $last = $selectedCells[0];
+ }
+
+ list($colFirst, $rwFirst) = Cell::coordinateFromString($first);
+ $colFirst = Cell::columnIndexFromString($colFirst) - 1; // base 0 column index
+ --$rwFirst; // base 0 row index
+
+ list($colLast, $rwLast) = Cell::coordinateFromString($last);
+ $colLast = Cell::columnIndexFromString($colLast) - 1; // base 0 column index
+ --$rwLast; // base 0 row index
+
+ // make sure we are not out of bounds
+ $colFirst = min($colFirst, 255);
+ $colLast = min($colLast, 255);
+
+ $rwFirst = min($rwFirst, 65535);
+ $rwLast = min($rwLast, 65535);
+
+ $record = 0x001D; // Record identifier
+ $length = 0x000F; // Number of bytes to follow
+
+ $pnn = $this->_active_pane; // Pane position
+ $rwAct = $rwFirst; // Active row
+ $colAct = $colFirst; // Active column
+ $irefAct = 0; // Active cell ref
+ $cref = 1; // Number of refs
+
+ if (!isset($rwLast)) {
+ $rwLast = $rwFirst; // Last row in reference
+ }
+ if (!isset($colLast)) {
+ $colLast = $colFirst; // Last col in reference
+ }
+
+ // Swap last row/col for first row/col as necessary
+ if ($rwFirst > $rwLast) {
+ list($rwFirst, $rwLast) = array($rwLast, $rwFirst);
+ }
+
+ if ($colFirst > $colLast) {
+ list($colFirst, $colLast) = array($colLast, $colFirst);
+ }
+
+ $header = pack("vv", $record, $length);
+ $data = pack("CvvvvvvCC", $pnn, $rwAct, $colAct,
+ $irefAct, $cref,
+ $rwFirst, $rwLast,
+ $colFirst, $colLast);
+ $this->_append($header . $data);
+ }
+
+ /**
+ * Store the MERGEDCELLS records for all ranges of merged cells
+ */
+ private function _writeMergedCells()
+ {
+ $mergeCells = $this->_phpSheet->getMergeCells();
+ $countMergeCells = count($mergeCells);
+
+ if ($countMergeCells == 0) {
+ return;
+ }
+
+ // maximum allowed number of merged cells per record
+ $maxCountMergeCellsPerRecord = 1027;
+
+ // record identifier
+ $record = 0x00E5;
+
+ // counter for total number of merged cells treated so far by the writer
+ $i = 0;
+
+ // counter for number of merged cells written in record currently being written
+ $j = 0;
+
+ // initialize record data
+ $recordData = '';
+
+ // loop through the merged cells
+ foreach ($mergeCells as $mergeCell) {
+ ++$i;
+ ++$j;
+
+ // extract the row and column indexes
+ $range = Cell::splitRange($mergeCell);
+ list($first, $last) = $range[0];
+ list($firstColumn, $firstRow) = Cell::coordinateFromString($first);
+ list($lastColumn, $lastRow) = Cell::coordinateFromString($last);
+
+ $recordData .= pack('vvvv', $firstRow - 1, $lastRow - 1, Cell::columnIndexFromString($firstColumn) - 1, Cell::columnIndexFromString($lastColumn) - 1);
+
+ // flush record if we have reached limit for number of merged cells, or reached final merged cell
+ if ($j == $maxCountMergeCellsPerRecord or $i == $countMergeCells) {
+ $recordData = pack('v', $j) . $recordData;
+ $length = strlen($recordData);
+ $header = pack('vv', $record, $length);
+ $this->_append($header . $recordData);
+
+ // initialize for next record, if any
+ $recordData = '';
+ $j = 0;
+ }
+ }
+ }
+
+ /**
+ * Write SHEETLAYOUT record
+ */
+ private function _writeSheetLayout()
+ {
+ if (!$this->_phpSheet->isTabColorSet()) {
+ return;
+ }
+
+ $recordData = pack(
+ 'vvVVVvv'
+ , 0x0862
+ , 0x0000 // unused
+ , 0x00000000 // unused
+ , 0x00000000 // unused
+ , 0x00000014 // size of record data
+ , $this->_colors[$this->_phpSheet->getTabColor()->getRGB()] // color index
+ , 0x0000 // unused
+ );
+
+ $length = strlen($recordData);
+
+ $record = 0x0862; // Record identifier
+ $header = pack('vv', $record, $length);
+ $this->_append($header . $recordData);
+ }
+
+ /**
+ * Write SHEETPROTECTION
+ */
+ private function _writeSheetProtection()
+ {
+ // record identifier
+ $record = 0x0867;
+
+ // prepare options
+ $options = (int) !$this->_phpSheet->getProtection()->getObjects()
+ | (int) !$this->_phpSheet->getProtection()->getScenarios() << 1
+ | (int) !$this->_phpSheet->getProtection()->getFormatCells() << 2
+ | (int) !$this->_phpSheet->getProtection()->getFormatColumns() << 3
+ | (int) !$this->_phpSheet->getProtection()->getFormatRows() << 4
+ | (int) !$this->_phpSheet->getProtection()->getInsertColumns() << 5
+ | (int) !$this->_phpSheet->getProtection()->getInsertRows() << 6
+ | (int) !$this->_phpSheet->getProtection()->getInsertHyperlinks() << 7
+ | (int) !$this->_phpSheet->getProtection()->getDeleteColumns() << 8
+ | (int) !$this->_phpSheet->getProtection()->getDeleteRows() << 9
+ | (int) !$this->_phpSheet->getProtection()->getSelectLockedCells() << 10
+ | (int) !$this->_phpSheet->getProtection()->getSort() << 11
+ | (int) !$this->_phpSheet->getProtection()->getAutoFilter() << 12
+ | (int) !$this->_phpSheet->getProtection()->getPivotTables() << 13
+ | (int) !$this->_phpSheet->getProtection()->getSelectUnlockedCells() << 14 ;
+
+ // record data
+ $recordData = pack(
+ 'vVVCVVvv'
+ , 0x0867 // repeated record identifier
+ , 0x0000 // not used
+ , 0x0000 // not used
+ , 0x00 // not used
+ , 0x01000200 // unknown data
+ , 0xFFFFFFFF // unknown data
+ , $options // options
+ , 0x0000 // not used
+ );
+
+ $length = strlen($recordData);
+ $header = pack('vv', $record, $length);
+
+ $this->_append($header . $recordData);
+ }
+
+ /**
+ * Write BIFF record RANGEPROTECTION
+ *
+ * Openoffice.org's Documentaion of the Microsoft Excel File Format uses term RANGEPROTECTION for these records
+ * Microsoft Office Excel 97-2007 Binary File Format Specification uses term FEAT for these records
+ */
+ private function _writeRangeProtection()
+ {
+ foreach ($this->_phpSheet->getProtectedCells() as $range => $password) {
+ // number of ranges, e.g. 'A1:B3 C20:D25'
+ $cellRanges = explode(' ', $range);
+ $cref = count($cellRanges);
+
+ $recordData = pack(
+ 'vvVVvCVvVv',
+ 0x0868,
+ 0x00,
+ 0x0000,
+ 0x0000,
+ 0x02,
+ 0x0,
+ 0x0000,
+ $cref,
+ 0x0000,
+ 0x00
+ );
+
+ foreach ($cellRanges as $cellRange) {
+ $recordData .= $this->_writeBIFF8CellRangeAddressFixed($cellRange);
+ }
+
+ // the rgbFeat structure
+ $recordData .= pack(
+ 'VV',
+ 0x0000,
+ hexdec($password)
+ );
+
+ $recordData .= Shared_String::UTF8toBIFF8UnicodeLong('p' . md5($recordData));
+
+ $length = strlen($recordData);
+
+ $record = 0x0868; // Record identifier
+ $header = pack("vv", $record, $length);
+ $this->_append($header . $recordData);
+ }
+ }
+
+ /**
+ * Write BIFF record EXTERNCOUNT to indicate the number of external sheet
+ * references in a worksheet.
+ *
+ * Excel only stores references to external sheets that are used in formulas.
+ * For simplicity we store references to all the sheets in the workbook
+ * regardless of whether they are used or not. This reduces the overall
+ * complexity and eliminates the need for a two way dialogue between the formula
+ * parser the worksheet objects.
+ *
+ * @param integer $count The number of external sheet references in this worksheet
+ */
+ private function _writeExterncount($count)
+ {
+ $record = 0x0016; // Record identifier
+ $length = 0x0002; // Number of bytes to follow
+
+ $header = pack("vv", $record, $length);
+ $data = pack("v", $count);
+ $this->_append($header . $data);
+ }
+
+ /**
+ * Writes the Excel BIFF EXTERNSHEET record. These references are used by
+ * formulas. A formula references a sheet name via an index. Since we store a
+ * reference to all of the external worksheets the EXTERNSHEET index is the same
+ * as the worksheet index.
+ *
+ * @param string $sheetname The name of a external worksheet
+ */
+ private function _writeExternsheet($sheetname)
+ {
+ $record = 0x0017; // Record identifier
+
+ // References to the current sheet are encoded differently to references to
+ // external sheets.
+ //
+ if ($this->_phpSheet->getTitle() == $sheetname) {
+ $sheetname = '';
+ $length = 0x02; // The following 2 bytes
+ $cch = 1; // The following byte
+ $rgch = 0x02; // Self reference
+ } else {
+ $length = 0x02 + strlen($sheetname);
+ $cch = strlen($sheetname);
+ $rgch = 0x03; // Reference to a sheet in the current workbook
+ }
+
+ $header = pack("vv", $record, $length);
+ $data = pack("CC", $cch, $rgch);
+ $this->_append($header . $data . $sheetname);
+ }
+
+ /**
+ * Writes the Excel BIFF PANE record.
+ * The panes can either be frozen or thawed (unfrozen).
+ * Frozen panes are specified in terms of an integer number of rows and columns.
+ * Thawed panes are specified in terms of Excel's units for rows and columns.
+ */
+ private function _writePanes()
+ {
+ $panes = array();
+ if ($freezePane = $this->_phpSheet->getFreezePane()) {
+ list($column, $row) = Cell::coordinateFromString($freezePane);
+ $panes[0] = $row - 1;
+ $panes[1] = Cell::columnIndexFromString($column) - 1;
+ } else {
+ // thaw panes
+ return;
+ }
+
+ $y = isset($panes[0]) ? $panes[0] : null;
+ $x = isset($panes[1]) ? $panes[1] : null;
+ $rwTop = isset($panes[2]) ? $panes[2] : null;
+ $colLeft = isset($panes[3]) ? $panes[3] : null;
+ if (count($panes) > 4) { // if Active pane was received
+ $pnnAct = $panes[4];
+ } else {
+ $pnnAct = null;
+ }
+ $record = 0x0041; // Record identifier
+ $length = 0x000A; // Number of bytes to follow
+
+ // Code specific to frozen or thawed panes.
+ if ($this->_phpSheet->getFreezePane()) {
+ // Set default values for $rwTop and $colLeft
+ if (!isset($rwTop)) {
+ $rwTop = $y;
+ }
+ if (!isset($colLeft)) {
+ $colLeft = $x;
+ }
+ } else {
+ // Set default values for $rwTop and $colLeft
+ if (!isset($rwTop)) {
+ $rwTop = 0;
+ }
+ if (!isset($colLeft)) {
+ $colLeft = 0;
+ }
+
+ // Convert Excel's row and column units to the internal units.
+ // The default row height is 12.75
+ // The default column width is 8.43
+ // The following slope and intersection values were interpolated.
+ //
+ $y = 20*$y + 255;
+ $x = 113.879*$x + 390;
+ }
+
+
+ // Determine which pane should be active. There is also the undocumented
+ // option to override this should it be necessary: may be removed later.
+ //
+ if (!isset($pnnAct)) {
+ if ($x != 0 && $y != 0) {
+ $pnnAct = 0; // Bottom right
+ }
+ if ($x != 0 && $y == 0) {
+ $pnnAct = 1; // Top right
+ }
+ if ($x == 0 && $y != 0) {
+ $pnnAct = 2; // Bottom left
+ }
+ if ($x == 0 && $y == 0) {
+ $pnnAct = 3; // Top left
+ }
+ }
+
+ $this->_active_pane = $pnnAct; // Used in _writeSelection
+
+ $header = pack("vv", $record, $length);
+ $data = pack("vvvvv", $x, $y, $rwTop, $colLeft, $pnnAct);
+ $this->_append($header . $data);
+ }
+
+ /**
+ * Store the page setup SETUP BIFF record.
+ */
+ private function _writeSetup()
+ {
+ $record = 0x00A1; // Record identifier
+ $length = 0x0022; // Number of bytes to follow
+
+ $iPaperSize = $this->_phpSheet->getPageSetup()->getPaperSize(); // Paper size
+
+ $iScale = $this->_phpSheet->getPageSetup()->getScale() ?
+ $this->_phpSheet->getPageSetup()->getScale() : 100; // Print scaling factor
+
+ $iPageStart = 0x01; // Starting page number
+ $iFitWidth = (int) $this->_phpSheet->getPageSetup()->getFitToWidth(); // Fit to number of pages wide
+ $iFitHeight = (int) $this->_phpSheet->getPageSetup()->getFitToHeight(); // Fit to number of pages high
+ $grbit = 0x00; // Option flags
+ $iRes = 0x0258; // Print resolution
+ $iVRes = 0x0258; // Vertical print resolution
+
+ $numHdr = $this->_phpSheet->getPageMargins()->getHeader(); // Header Margin
+
+ $numFtr = $this->_phpSheet->getPageMargins()->getFooter(); // Footer Margin
+ $iCopies = 0x01; // Number of copies
+
+ $fLeftToRight = 0x0; // Print over then down
+
+ // Page orientation
+ $fLandscape = ($this->_phpSheet->getPageSetup()->getOrientation() == Worksheet_PageSetup::ORIENTATION_LANDSCAPE) ?
+ 0x0 : 0x1;
+
+ $fNoPls = 0x0; // Setup not read from printer
+ $fNoColor = 0x0; // Print black and white
+ $fDraft = 0x0; // Print draft quality
+ $fNotes = 0x0; // Print notes
+ $fNoOrient = 0x0; // Orientation not set
+ $fUsePage = 0x0; // Use custom starting page
+
+ $grbit = $fLeftToRight;
+ $grbit |= $fLandscape << 1;
+ $grbit |= $fNoPls << 2;
+ $grbit |= $fNoColor << 3;
+ $grbit |= $fDraft << 4;
+ $grbit |= $fNotes << 5;
+ $grbit |= $fNoOrient << 6;
+ $grbit |= $fUsePage << 7;
+
+ $numHdr = pack("d", $numHdr);
+ $numFtr = pack("d", $numFtr);
+ if (self::getByteOrder()) { // if it's Big Endian
+ $numHdr = strrev($numHdr);
+ $numFtr = strrev($numFtr);
+ }
+
+ $header = pack("vv", $record, $length);
+ $data1 = pack("vvvvvvvv", $iPaperSize,
+ $iScale,
+ $iPageStart,
+ $iFitWidth,
+ $iFitHeight,
+ $grbit,
+ $iRes,
+ $iVRes);
+ $data2 = $numHdr.$numFtr;
+ $data3 = pack("v", $iCopies);
+ $this->_append($header . $data1 . $data2 . $data3);
+ }
+
+ /**
+ * Store the header caption BIFF record.
+ */
+ private function _writeHeader()
+ {
+ $record = 0x0014; // Record identifier
+
+ /* removing for now
+ // need to fix character count (multibyte!)
+ if (strlen($this->_phpSheet->getHeaderFooter()->getOddHeader()) <= 255) {
+ $str = $this->_phpSheet->getHeaderFooter()->getOddHeader(); // header string
+ } else {
+ $str = '';
+ }
+ */
+
+ $recordData = Shared_String::UTF8toBIFF8UnicodeLong($this->_phpSheet->getHeaderFooter()->getOddHeader());
+ $length = strlen($recordData);
+
+ $header = pack("vv", $record, $length);
+
+ $this->_append($header . $recordData);
+ }
+
+ /**
+ * Store the footer caption BIFF record.
+ */
+ private function _writeFooter()
+ {
+ $record = 0x0015; // Record identifier
+
+ /* removing for now
+ // need to fix character count (multibyte!)
+ if (strlen($this->_phpSheet->getHeaderFooter()->getOddFooter()) <= 255) {
+ $str = $this->_phpSheet->getHeaderFooter()->getOddFooter();
+ } else {
+ $str = '';
+ }
+ */
+
+ $recordData = Shared_String::UTF8toBIFF8UnicodeLong($this->_phpSheet->getHeaderFooter()->getOddFooter());
+ $length = strlen($recordData);
+
+ $header = pack("vv", $record, $length);
+
+ $this->_append($header . $recordData);
+ }
+
+ /**
+ * Store the horizontal centering HCENTER BIFF record.
+ *
+ * @access private
+ */
+ private function _writeHcenter()
+ {
+ $record = 0x0083; // Record identifier
+ $length = 0x0002; // Bytes to follow
+
+ $fHCenter = $this->_phpSheet->getPageSetup()->getHorizontalCentered() ? 1 : 0; // Horizontal centering
+
+ $header = pack("vv", $record, $length);
+ $data = pack("v", $fHCenter);
+
+ $this->_append($header.$data);
+ }
+
+ /**
+ * Store the vertical centering VCENTER BIFF record.
+ */
+ private function _writeVcenter()
+ {
+ $record = 0x0084; // Record identifier
+ $length = 0x0002; // Bytes to follow
+
+ $fVCenter = $this->_phpSheet->getPageSetup()->getVerticalCentered() ? 1 : 0; // Horizontal centering
+
+ $header = pack("vv", $record, $length);
+ $data = pack("v", $fVCenter);
+ $this->_append($header . $data);
+ }
+
+ /**
+ * Store the LEFTMARGIN BIFF record.
+ */
+ private function _writeMarginLeft()
+ {
+ $record = 0x0026; // Record identifier
+ $length = 0x0008; // Bytes to follow
+
+ $margin = $this->_phpSheet->getPageMargins()->getLeft(); // Margin in inches
+
+ $header = pack("vv", $record, $length);
+ $data = pack("d", $margin);
+ if (self::getByteOrder()) { // if it's Big Endian
+ $data = strrev($data);
+ }
+
+ $this->_append($header . $data);
+ }
+
+ /**
+ * Store the RIGHTMARGIN BIFF record.
+ */
+ private function _writeMarginRight()
+ {
+ $record = 0x0027; // Record identifier
+ $length = 0x0008; // Bytes to follow
+
+ $margin = $this->_phpSheet->getPageMargins()->getRight(); // Margin in inches
+
+ $header = pack("vv", $record, $length);
+ $data = pack("d", $margin);
+ if (self::getByteOrder()) { // if it's Big Endian
+ $data = strrev($data);
+ }
+
+ $this->_append($header . $data);
+ }
+
+ /**
+ * Store the TOPMARGIN BIFF record.
+ */
+ private function _writeMarginTop()
+ {
+ $record = 0x0028; // Record identifier
+ $length = 0x0008; // Bytes to follow
+
+ $margin = $this->_phpSheet->getPageMargins()->getTop(); // Margin in inches
+
+ $header = pack("vv", $record, $length);
+ $data = pack("d", $margin);
+ if (self::getByteOrder()) { // if it's Big Endian
+ $data = strrev($data);
+ }
+
+ $this->_append($header . $data);
+ }
+
+ /**
+ * Store the BOTTOMMARGIN BIFF record.
+ */
+ private function _writeMarginBottom()
+ {
+ $record = 0x0029; // Record identifier
+ $length = 0x0008; // Bytes to follow
+
+ $margin = $this->_phpSheet->getPageMargins()->getBottom(); // Margin in inches
+
+ $header = pack("vv", $record, $length);
+ $data = pack("d", $margin);
+ if (self::getByteOrder()) { // if it's Big Endian
+ $data = strrev($data);
+ }
+
+ $this->_append($header . $data);
+ }
+
+ /**
+ * Write the PRINTHEADERS BIFF record.
+ */
+ private function _writePrintHeaders()
+ {
+ $record = 0x002a; // Record identifier
+ $length = 0x0002; // Bytes to follow
+
+ $fPrintRwCol = $this->_print_headers; // Boolean flag
+
+ $header = pack("vv", $record, $length);
+ $data = pack("v", $fPrintRwCol);
+ $this->_append($header . $data);
+ }
+
+ /**
+ * Write the PRINTGRIDLINES BIFF record. Must be used in conjunction with the
+ * GRIDSET record.
+ */
+ private function _writePrintGridlines()
+ {
+ $record = 0x002b; // Record identifier
+ $length = 0x0002; // Bytes to follow
+
+ $fPrintGrid = $this->_phpSheet->getPrintGridlines() ? 1 : 0; // Boolean flag
+
+ $header = pack("vv", $record, $length);
+ $data = pack("v", $fPrintGrid);
+ $this->_append($header . $data);
+ }
+
+ /**
+ * Write the GRIDSET BIFF record. Must be used in conjunction with the
+ * PRINTGRIDLINES record.
+ */
+ private function _writeGridset()
+ {
+ $record = 0x0082; // Record identifier
+ $length = 0x0002; // Bytes to follow
+
+ $fGridSet = !$this->_phpSheet->getPrintGridlines(); // Boolean flag
+
+ $header = pack("vv", $record, $length);
+ $data = pack("v", $fGridSet);
+ $this->_append($header . $data);
+ }
+
+ /**
+ * Write the AUTOFILTERINFO BIFF record. This is used to configure the number of autofilter select used in the sheet.
+ */
+ private function _writeAutoFilterInfo(){
+ $record = 0x009D; // Record identifier
+ $length = 0x0002; // Bytes to follow
+
+ $rangeBounds = Cell::rangeBoundaries($this->_phpSheet->getAutoFilter()->getRange());
+ $iNumFilters = 1 + $rangeBounds[1][0] - $rangeBounds[0][0];
+
+ $header = pack("vv", $record, $length);
+ $data = pack("v", $iNumFilters);
+ $this->_append($header . $data);
+ }
+
+ /**
+ * Write the GUTS BIFF record. This is used to configure the gutter margins
+ * where Excel outline symbols are displayed. The visibility of the gutters is
+ * controlled by a flag in WSBOOL.
+ *
+ * @see _writeWsbool()
+ */
+ private function _writeGuts()
+ {
+ $record = 0x0080; // Record identifier
+ $length = 0x0008; // Bytes to follow
+
+ $dxRwGut = 0x0000; // Size of row gutter
+ $dxColGut = 0x0000; // Size of col gutter
+
+ // determine maximum row outline level
+ $maxRowOutlineLevel = 0;
+ foreach ($this->_phpSheet->getRowDimensions() as $rowDimension) {
+ $maxRowOutlineLevel = max($maxRowOutlineLevel, $rowDimension->getOutlineLevel());
+ }
+
+ $col_level = 0;
+
+ // Calculate the maximum column outline level. The equivalent calculation
+ // for the row outline level is carried out in _writeRow().
+ $colcount = count($this->_colinfo);
+ for ($i = 0; $i < $colcount; ++$i) {
+ $col_level = max($this->_colinfo[$i][5], $col_level);
+ }
+
+ // Set the limits for the outline levels (0 <= x <= 7).
+ $col_level = max(0, min($col_level, 7));
+
+ // The displayed level is one greater than the max outline levels
+ if ($maxRowOutlineLevel) {
+ ++$maxRowOutlineLevel;
+ }
+ if ($col_level) {
+ ++$col_level;
+ }
+
+ $header = pack("vv", $record, $length);
+ $data = pack("vvvv", $dxRwGut, $dxColGut, $maxRowOutlineLevel, $col_level);
+
+ $this->_append($header.$data);
+ }
+
+ /**
+ * Write the WSBOOL BIFF record, mainly for fit-to-page. Used in conjunction
+ * with the SETUP record.
+ */
+ private function _writeWsbool()
+ {
+ $record = 0x0081; // Record identifier
+ $length = 0x0002; // Bytes to follow
+ $grbit = 0x0000;
+
+ // The only option that is of interest is the flag for fit to page. So we
+ // set all the options in one go.
+ //
+ // Set the option flags
+ $grbit |= 0x0001; // Auto page breaks visible
+ if ($this->_outline_style) {
+ $grbit |= 0x0020; // Auto outline styles
+ }
+ if ($this->_phpSheet->getShowSummaryBelow()) {
+ $grbit |= 0x0040; // Outline summary below
+ }
+ if ($this->_phpSheet->getShowSummaryRight()) {
+ $grbit |= 0x0080; // Outline summary right
+ }
+ if ($this->_phpSheet->getPageSetup()->getFitToPage()) {
+ $grbit |= 0x0100; // Page setup fit to page
+ }
+ if ($this->_outline_on) {
+ $grbit |= 0x0400; // Outline symbols displayed
+ }
+
+ $header = pack("vv", $record, $length);
+ $data = pack("v", $grbit);
+ $this->_append($header . $data);
+ }
+
+ /**
+ * Write the HORIZONTALPAGEBREAKS and VERTICALPAGEBREAKS BIFF records.
+ */
+ private function _writeBreaks()
+ {
+ // initialize
+ $vbreaks = array();
+ $hbreaks = array();
+
+ foreach ($this->_phpSheet->getBreaks() as $cell => $breakType) {
+ // Fetch coordinates
+ $coordinates = Cell::coordinateFromString($cell);
+
+ // Decide what to do by the type of break
+ switch ($breakType) {
+ case Worksheet::BREAK_COLUMN:
+ // Add to list of vertical breaks
+ $vbreaks[] = Cell::columnIndexFromString($coordinates[0]) - 1;
+ break;
+
+ case Worksheet::BREAK_ROW:
+ // Add to list of horizontal breaks
+ $hbreaks[] = $coordinates[1];
+ break;
+
+ case Worksheet::BREAK_NONE:
+ default:
+ // Nothing to do
+ break;
+ }
+ }
+
+ //horizontal page breaks
+ if (!empty($hbreaks)) {
+
+ // Sort and filter array of page breaks
+ sort($hbreaks, SORT_NUMERIC);
+ if ($hbreaks[0] == 0) { // don't use first break if it's 0
+ array_shift($hbreaks);
+ }
+
+ $record = 0x001b; // Record identifier
+ $cbrk = count($hbreaks); // Number of page breaks
+ $length = 2 + 6 * $cbrk; // Bytes to follow
+
+ $header = pack("vv", $record, $length);
+ $data = pack("v", $cbrk);
+
+ // Append each page break
+ foreach ($hbreaks as $hbreak) {
+ $data .= pack("vvv", $hbreak, 0x0000, 0x00ff);
+ }
+
+ $this->_append($header . $data);
+ }
+
+ // vertical page breaks
+ if (!empty($vbreaks)) {
+
+ // 1000 vertical pagebreaks appears to be an internal Excel 5 limit.
+ // It is slightly higher in Excel 97/200, approx. 1026
+ $vbreaks = array_slice($vbreaks, 0, 1000);
+
+ // Sort and filter array of page breaks
+ sort($vbreaks, SORT_NUMERIC);
+ if ($vbreaks[0] == 0) { // don't use first break if it's 0
+ array_shift($vbreaks);
+ }
+
+ $record = 0x001a; // Record identifier
+ $cbrk = count($vbreaks); // Number of page breaks
+ $length = 2 + 6 * $cbrk; // Bytes to follow
+
+ $header = pack("vv", $record, $length);
+ $data = pack("v", $cbrk);
+
+ // Append each page break
+ foreach ($vbreaks as $vbreak) {
+ $data .= pack("vvv", $vbreak, 0x0000, 0xffff);
+ }
+
+ $this->_append($header . $data);
+ }
+ }
+
+ /**
+ * Set the Biff PROTECT record to indicate that the worksheet is protected.
+ */
+ private function _writeProtect()
+ {
+ // Exit unless sheet protection has been specified
+ if (!$this->_phpSheet->getProtection()->getSheet()) {
+ return;
+ }
+
+ $record = 0x0012; // Record identifier
+ $length = 0x0002; // Bytes to follow
+
+ $fLock = 1; // Worksheet is protected
+
+ $header = pack("vv", $record, $length);
+ $data = pack("v", $fLock);
+
+ $this->_append($header.$data);
+ }
+
+ /**
+ * Write SCENPROTECT
+ */
+ private function _writeScenProtect()
+ {
+ // Exit if sheet protection is not active
+ if (!$this->_phpSheet->getProtection()->getSheet()) {
+ return;
+ }
+
+ // Exit if scenarios are not protected
+ if (!$this->_phpSheet->getProtection()->getScenarios()) {
+ return;
+ }
+
+ $record = 0x00DD; // Record identifier
+ $length = 0x0002; // Bytes to follow
+
+ $header = pack('vv', $record, $length);
+ $data = pack('v', 1);
+
+ $this->_append($header . $data);
+ }
+
+ /**
+ * Write OBJECTPROTECT
+ */
+ private function _writeObjectProtect()
+ {
+ // Exit if sheet protection is not active
+ if (!$this->_phpSheet->getProtection()->getSheet()) {
+ return;
+ }
+
+ // Exit if objects are not protected
+ if (!$this->_phpSheet->getProtection()->getObjects()) {
+ return;
+ }
+
+ $record = 0x0063; // Record identifier
+ $length = 0x0002; // Bytes to follow
+
+ $header = pack('vv', $record, $length);
+ $data = pack('v', 1);
+
+ $this->_append($header . $data);
+ }
+
+ /**
+ * Write the worksheet PASSWORD record.
+ */
+ private function _writePassword()
+ {
+ // Exit unless sheet protection and password have been specified
+ if (!$this->_phpSheet->getProtection()->getSheet() || !$this->_phpSheet->getProtection()->getPassword()) {
+ return;
+ }
+
+ $record = 0x0013; // Record identifier
+ $length = 0x0002; // Bytes to follow
+
+ $wPassword = hexdec($this->_phpSheet->getProtection()->getPassword()); // Encoded password
+
+ $header = pack("vv", $record, $length);
+ $data = pack("v", $wPassword);
+
+ $this->_append($header . $data);
+ }
+
+ /**
+ * Insert a 24bit bitmap image in a worksheet.
+ *
+ * @access public
+ * @param integer $row The row we are going to insert the bitmap into
+ * @param integer $col The column we are going to insert the bitmap into
+ * @param mixed $bitmap The bitmap filename or GD-image resource
+ * @param integer $x The horizontal position (offset) of the image inside the cell.
+ * @param integer $y The vertical position (offset) of the image inside the cell.
+ * @param float $scale_x The horizontal scale
+ * @param float $scale_y The vertical scale
+ */
+ function insertBitmap($row, $col, $bitmap, $x = 0, $y = 0, $scale_x = 1, $scale_y = 1)
+ {
+ $bitmap_array = (is_resource($bitmap) ? $this->_processBitmapGd($bitmap) : $this->_processBitmap($bitmap));
+ list($width, $height, $size, $data) = $bitmap_array; //$this->_processBitmap($bitmap);
+
+ // Scale the frame of the image.
+ $width *= $scale_x;
+ $height *= $scale_y;
+
+ // Calculate the vertices of the image and write the OBJ record
+ $this->_positionImage($col, $row, $x, $y, $width, $height);
+
+ // Write the IMDATA record to store the bitmap data
+ $record = 0x007f;
+ $length = 8 + $size;
+ $cf = 0x09;
+ $env = 0x01;
+ $lcb = $size;
+
+ $header = pack("vvvvV", $record, $length, $cf, $env, $lcb);
+ $this->_append($header.$data);
+ }
+
+ /**
+ * 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
+ * The SDK incorrectly states that the height should be expressed as a
+ * percentage of 1024.
+ *
+ * @access private
+ * @param integer $col_start Col containing upper left corner of object
+ * @param integer $row_start Row containing top left corner of object
+ * @param integer $x1 Distance to left side of object
+ * @param integer $y1 Distance to top of object
+ * @param integer $width Width of image frame
+ * @param integer $height Height of image frame
+ */
+ function _positionImage($col_start, $row_start, $x1, $y1, $width, $height)
+ {
+ // 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 >= Shared_Excel5::sizeCol($this->_phpSheet, Cell::stringFromColumnIndex($col_start))) {
+ $x1 = 0;
+ }
+ if ($y1 >= Shared_Excel5::sizeRow($this->_phpSheet, $row_start + 1)) {
+ $y1 = 0;
+ }
+
+ $width = $width + $x1 -1;
+ $height = $height + $y1 -1;
+
+ // Subtract the underlying cell widths to find the end cell of the image
+ while ($width >= Shared_Excel5::sizeCol($this->_phpSheet, Cell::stringFromColumnIndex($col_end))) {
+ $width -= Shared_Excel5::sizeCol($this->_phpSheet, Cell::stringFromColumnIndex($col_end));
+ ++$col_end;
+ }
+
+ // Subtract the underlying cell heights to find the end cell of the image
+ while ($height >= Shared_Excel5::sizeRow($this->_phpSheet, $row_end + 1)) {
+ $height -= Shared_Excel5::sizeRow($this->_phpSheet, $row_end + 1);
+ ++$row_end;
+ }
+
+ // Bitmap isn't allowed to start or finish in a hidden cell, i.e. a cell
+ // with zero eight or width.
+ //
+ if (Shared_Excel5::sizeCol($this->_phpSheet, Cell::stringFromColumnIndex($col_start)) == 0) {
+ return;
+ }
+ if (Shared_Excel5::sizeCol($this->_phpSheet, Cell::stringFromColumnIndex($col_end)) == 0) {
+ return;
+ }
+ if (Shared_Excel5::sizeRow($this->_phpSheet, $row_start + 1) == 0) {
+ return;
+ }
+ if (Shared_Excel5::sizeRow($this->_phpSheet, $row_end + 1) == 0) {
+ return;
+ }
+
+ // Convert the pixel values to the percentage value expected by Excel
+ $x1 = $x1 / Shared_Excel5::sizeCol($this->_phpSheet, Cell::stringFromColumnIndex($col_start)) * 1024;
+ $y1 = $y1 / Shared_Excel5::sizeRow($this->_phpSheet, $row_start + 1) * 256;
+ $x2 = $width / Shared_Excel5::sizeCol($this->_phpSheet, Cell::stringFromColumnIndex($col_end)) * 1024; // Distance to right side of object
+ $y2 = $height / Shared_Excel5::sizeRow($this->_phpSheet, $row_end + 1) * 256; // Distance to bottom of object
+
+ $this->_writeObjPicture($col_start, $x1,
+ $row_start, $y1,
+ $col_end, $x2,
+ $row_end, $y2);
+ }
+
+ /**
+ * Store the OBJ record that precedes an IMDATA record. This could be generalise
+ * to support other Excel objects.
+ *
+ * @param integer $colL Column containing upper left corner of object
+ * @param integer $dxL Distance from left side of cell
+ * @param integer $rwT Row containing top left corner of object
+ * @param integer $dyT Distance from top of cell
+ * @param integer $colR Column containing lower right corner of object
+ * @param integer $dxR Distance from right of cell
+ * @param integer $rwB Row containing bottom right corner of object
+ * @param integer $dyB Distance from bottom of cell
+ */
+ private function _writeObjPicture($colL,$dxL,$rwT,$dyT,$colR,$dxR,$rwB,$dyB)
+ {
+ $record = 0x005d; // Record identifier
+ $length = 0x003c; // Bytes to follow
+
+ $cObj = 0x0001; // Count of objects in file (set to 1)
+ $OT = 0x0008; // Object type. 8 = Picture
+ $id = 0x0001; // Object ID
+ $grbit = 0x0614; // Option flags
+
+ $cbMacro = 0x0000; // Length of FMLA structure
+ $Reserved1 = 0x0000; // Reserved
+ $Reserved2 = 0x0000; // Reserved
+
+ $icvBack = 0x09; // Background colour
+ $icvFore = 0x09; // Foreground colour
+ $fls = 0x00; // Fill pattern
+ $fAuto = 0x00; // Automatic fill
+ $icv = 0x08; // Line colour
+ $lns = 0xff; // Line style
+ $lnw = 0x01; // Line weight
+ $fAutoB = 0x00; // Automatic border
+ $frs = 0x0000; // Frame style
+ $cf = 0x0009; // Image format, 9 = bitmap
+ $Reserved3 = 0x0000; // Reserved
+ $cbPictFmla = 0x0000; // Length of FMLA structure
+ $Reserved4 = 0x0000; // Reserved
+ $grbit2 = 0x0001; // Option flags
+ $Reserved5 = 0x0000; // Reserved
+
+
+ $header = pack("vv", $record, $length);
+ $data = pack("V", $cObj);
+ $data .= pack("v", $OT);
+ $data .= pack("v", $id);
+ $data .= pack("v", $grbit);
+ $data .= pack("v", $colL);
+ $data .= pack("v", $dxL);
+ $data .= pack("v", $rwT);
+ $data .= pack("v", $dyT);
+ $data .= pack("v", $colR);
+ $data .= pack("v", $dxR);
+ $data .= pack("v", $rwB);
+ $data .= pack("v", $dyB);
+ $data .= pack("v", $cbMacro);
+ $data .= pack("V", $Reserved1);
+ $data .= pack("v", $Reserved2);
+ $data .= pack("C", $icvBack);
+ $data .= pack("C", $icvFore);
+ $data .= pack("C", $fls);
+ $data .= pack("C", $fAuto);
+ $data .= pack("C", $icv);
+ $data .= pack("C", $lns);
+ $data .= pack("C", $lnw);
+ $data .= pack("C", $fAutoB);
+ $data .= pack("v", $frs);
+ $data .= pack("V", $cf);
+ $data .= pack("v", $Reserved3);
+ $data .= pack("v", $cbPictFmla);
+ $data .= pack("v", $Reserved4);
+ $data .= pack("v", $grbit2);
+ $data .= pack("V", $Reserved5);
+
+ $this->_append($header . $data);
+ }
+
+ /**
+ * Convert a GD-image into the internal format.
+ *
+ * @access private
+ * @param resource $image The image to process
+ * @return array Array with data and properties of the bitmap
+ */
+ function _processBitmapGd($image) {
+ $width = imagesx($image);
+ $height = imagesy($image);
+
+ $data = pack("Vvvvv", 0x000c, $width, $height, 0x01, 0x18);
+ for ($j=$height; $j--; ) {
+ for ($i=0; $i < $width; ++$i) {
+ $color = imagecolorsforindex($image, imagecolorat($image, $i, $j));
+ foreach (array("red", "green", "blue") as $key) {
+ $color[$key] = $color[$key] + round((255 - $color[$key]) * $color["alpha"] / 127);
+ }
+ $data .= chr($color["blue"]) . chr($color["green"]) . chr($color["red"]);
+ }
+ if (3*$width % 4) {
+ $data .= str_repeat("\x00", 4 - 3*$width % 4);
+ }
+ }
+
+ return array($width, $height, strlen($data), $data);
+ }
+
+ /**
+ * Convert a 24 bit bitmap into the modified internal format used by Windows.
+ * This is described in BITMAPCOREHEADER and BITMAPCOREINFO structures in the
+ * MSDN library.
+ *
+ * @access private
+ * @param string $bitmap The bitmap to process
+ * @return array Array with data and properties of the bitmap
+ */
+ function _processBitmap($bitmap)
+ {
+ // Open file.
+ $bmp_fd = @fopen($bitmap,"rb");
+ if (!$bmp_fd) {
+ throw new Writer_Exception("Couldn't import $bitmap");
+ }
+
+ // Slurp the file into a string.
+ $data = fread($bmp_fd, filesize($bitmap));
+
+ // Check that the file is big enough to be a bitmap.
+ if (strlen($data) <= 0x36) {
+ throw new Writer_Exception("$bitmap doesn't contain enough data.\n");
+ }
+
+ // The first 2 bytes are used to identify the bitmap.
+ $identity = unpack("A2ident", $data);
+ if ($identity['ident'] != "BM") {
+ throw new Writer_Exception("$bitmap doesn't appear to be a valid bitmap image.\n");
+ }
+
+ // Remove bitmap data: ID.
+ $data = substr($data, 2);
+
+ // Read and remove the bitmap size. This is more reliable than reading
+ // the data size at offset 0x22.
+ //
+ $size_array = unpack("Vsa", substr($data, 0, 4));
+ $size = $size_array['sa'];
+ $data = substr($data, 4);
+ $size -= 0x36; // Subtract size of bitmap header.
+ $size += 0x0C; // Add size of BIFF header.
+
+ // Remove bitmap data: reserved, offset, header length.
+ $data = substr($data, 12);
+
+ // Read and remove the bitmap width and height. Verify the sizes.
+ $width_and_height = unpack("V2", substr($data, 0, 8));
+ $width = $width_and_height[1];
+ $height = $width_and_height[2];
+ $data = substr($data, 8);
+ if ($width > 0xFFFF) {
+ throw new Writer_Exception("$bitmap: largest image width supported is 65k.\n");
+ }
+ if ($height > 0xFFFF) {
+ throw new Writer_Exception("$bitmap: largest image height supported is 65k.\n");
+ }
+
+ // Read and remove the bitmap planes and bpp data. Verify them.
+ $planes_and_bitcount = unpack("v2", substr($data, 0, 4));
+ $data = substr($data, 4);
+ if ($planes_and_bitcount[2] != 24) { // Bitcount
+ throw new Writer_Exception("$bitmap isn't a 24bit true color bitmap.\n");
+ }
+ if ($planes_and_bitcount[1] != 1) {
+ throw new Writer_Exception("$bitmap: only 1 plane supported in bitmap image.\n");
+ }
+
+ // Read and remove the bitmap compression. Verify compression.
+ $compression = unpack("Vcomp", substr($data, 0, 4));
+ $data = substr($data, 4);
+
+ //$compression = 0;
+ if ($compression['comp'] != 0) {
+ throw new Writer_Exception("$bitmap: compression not supported in bitmap image.\n");
+ }
+
+ // Remove bitmap data: data size, hres, vres, colours, imp. colours.
+ $data = substr($data, 20);
+
+ // Add the BITMAPCOREHEADER data
+ $header = pack("Vvvvv", 0x000c, $width, $height, 0x01, 0x18);
+ $data = $header . $data;
+
+ return (array($width, $height, $size, $data));
+ }
+
+ /**
+ * Store the window zoom factor. This should be a reduced fraction but for
+ * simplicity we will store all fractions with a numerator of 100.
+ */
+ private function _writeZoom()
+ {
+ // If scale is 100 we don't need to write a record
+ if ($this->_phpSheet->getSheetView()->getZoomScale() == 100) {
+ return;
+ }
+
+ $record = 0x00A0; // Record identifier
+ $length = 0x0004; // Bytes to follow
+
+ $header = pack("vv", $record, $length);
+ $data = pack("vv", $this->_phpSheet->getSheetView()->getZoomScale(), 100);
+ $this->_append($header . $data);
+ }
+
+ /**
+ * Get Escher object
+ *
+ * @return PHPExcel\Shared_Escher
+ */
+ public function getEscher()
+ {
+ return $this->_escher;
+ }
+
+ /**
+ * Set Escher object
+ *
+ * @param PHPExcel\Shared_Escher $pValue
+ */
+ public function setEscher(Shared_Escher $pValue = null)
+ {
+ $this->_escher = $pValue;
+ }
+
+ /**
+ * Write MSODRAWING record
+ */
+ private function _writeMsoDrawing()
+ {
+ // write the Escher stream if necessary
+ if (isset($this->_escher)) {
+ $writer = new Writer_Excel5_Escher($this->_escher);
+ $data = $writer->close();
+ $spOffsets = $writer->getSpOffsets();
+ $spTypes = $writer->getSpTypes();
+ // write the neccesary MSODRAWING, OBJ records
+
+ // split the Escher stream
+ $spOffsets[0] = 0;
+ $nm = count($spOffsets) - 1; // number of shapes excluding first shape
+ for ($i = 1; $i <= $nm; ++$i) {
+ // MSODRAWING record
+ $record = 0x00EC; // Record identifier
+
+ // chunk of Escher stream for one shape
+ $dataChunk = substr($data, $spOffsets[$i -1], $spOffsets[$i] - $spOffsets[$i - 1]);
+
+ $length = strlen($dataChunk);
+ $header = pack("vv", $record, $length);
+
+ $this->_append($header . $dataChunk);
+
+ // OBJ record
+ $record = 0x005D; // record identifier
+ $objData = '';
+
+ // ftCmo
+ if($spTypes[$i] == 0x00C9){
+ // Add ftCmo (common object data) subobject
+ $objData .=
+ pack('vvvvvVVV'
+ , 0x0015 // 0x0015 = ftCmo
+ , 0x0012 // length of ftCmo data
+ , 0x0014 // object type, 0x0014 = filter
+ , $i // object id number, Excel seems to use 1-based index, local for the sheet
+ , 0x2101 // option flags, 0x2001 is what OpenOffice.org uses
+ , 0 // reserved
+ , 0 // reserved
+ , 0 // reserved
+ );
+
+ // Add ftSbs Scroll bar subobject
+ $objData .= pack('vv', 0x00C, 0x0014);
+ $objData .= pack('H*', '0000000000000000640001000A00000010000100');
+ // Add ftLbsData (List box data) subobject
+ $objData .= pack('vv', 0x0013, 0x1FEE);
+ $objData .= pack('H*', '00000000010001030000020008005700');
+ }
+ else {
+ // Add ftCmo (common object data) subobject
+ $objData .=
+ pack('vvvvvVVV'
+ , 0x0015 // 0x0015 = ftCmo
+ , 0x0012 // length of ftCmo data
+ , 0x0008 // object type, 0x0008 = picture
+ , $i // object id number, Excel seems to use 1-based index, local for the sheet
+ , 0x6011 // option flags, 0x6011 is what OpenOffice.org uses
+ , 0 // reserved
+ , 0 // reserved
+ , 0 // reserved
+ );
+ }
+
+ // ftEnd
+ $objData .=
+ pack('vv'
+ , 0x0000 // 0x0000 = ftEnd
+ , 0x0000 // length of ftEnd data
+ );
+
+ $length = strlen($objData);
+ $header = pack('vv', $record, $length);
+ $this->_append($header . $objData);
+ }
+ }
+ }
+
+ /**
+ * Store the DATAVALIDATIONS and DATAVALIDATION records.
+ */
+ private function _writeDataValidity()
+ {
+ // Datavalidation collection
+ $dataValidationCollection = $this->_phpSheet->getDataValidationCollection();
+
+ // Write data validations?
+ if (!empty($dataValidationCollection)) {
+
+ // DATAVALIDATIONS record
+ $record = 0x01B2; // Record identifier
+ $length = 0x0012; // Bytes to follow
+
+ $grbit = 0x0000; // Prompt box at cell, no cached validity data at DV records
+ $horPos = 0x00000000; // Horizontal position of prompt box, if fixed position
+ $verPos = 0x00000000; // Vertical position of prompt box, if fixed position
+ $objId = 0xFFFFFFFF; // Object identifier of drop down arrow object, or -1 if not visible
+
+ $header = pack('vv', $record, $length);
+ $data = pack('vVVVV', $grbit, $horPos, $verPos, $objId,
+ count($dataValidationCollection));
+ $this->_append($header.$data);
+
+ // DATAVALIDATION records
+ $record = 0x01BE; // Record identifier
+
+ foreach ($dataValidationCollection as $cellCoordinate => $dataValidation) {
+ // initialize record data
+ $data = '';
+
+ // options
+ $options = 0x00000000;
+
+ // data type
+ $type = $dataValidation->getType();
+ switch ($type) {
+ case Cell_DataValidation::TYPE_NONE: $type = 0x00; break;
+ case Cell_DataValidation::TYPE_WHOLE: $type = 0x01; break;
+ case Cell_DataValidation::TYPE_DECIMAL: $type = 0x02; break;
+ case Cell_DataValidation::TYPE_LIST: $type = 0x03; break;
+ case Cell_DataValidation::TYPE_DATE: $type = 0x04; break;
+ case Cell_DataValidation::TYPE_TIME: $type = 0x05; break;
+ case Cell_DataValidation::TYPE_TEXTLENGTH: $type = 0x06; break;
+ case Cell_DataValidation::TYPE_CUSTOM: $type = 0x07; break;
+ }
+ $options |= $type << 0;
+
+ // error style
+ $errorStyle = $dataValidation->getType();
+ switch ($errorStyle) {
+ case Cell_DataValidation::STYLE_STOP: $errorStyle = 0x00; break;
+ case Cell_DataValidation::STYLE_WARNING: $errorStyle = 0x01; break;
+ case Cell_DataValidation::STYLE_INFORMATION: $errorStyle = 0x02; break;
+ }
+ $options |= $errorStyle << 4;
+
+ // explicit formula?
+ if ($type == 0x03 && preg_match('/^\".*\"$/', $dataValidation->getFormula1())) {
+ $options |= 0x01 << 7;
+ }
+
+ // empty cells allowed
+ $options |= $dataValidation->getAllowBlank() << 8;
+
+ // show drop down
+ $options |= (!$dataValidation->getShowDropDown()) << 9;
+
+ // show input message
+ $options |= $dataValidation->getShowInputMessage() << 18;
+
+ // show error message
+ $options |= $dataValidation->getShowErrorMessage() << 19;
+
+ // condition operator
+ $operator = $dataValidation->getOperator();
+ switch ($operator) {
+ case Cell_DataValidation::OPERATOR_BETWEEN: $operator = 0x00 ; break;
+ case Cell_DataValidation::OPERATOR_NOTBETWEEN: $operator = 0x01 ; break;
+ case Cell_DataValidation::OPERATOR_EQUAL: $operator = 0x02 ; break;
+ case Cell_DataValidation::OPERATOR_NOTEQUAL: $operator = 0x03 ; break;
+ case Cell_DataValidation::OPERATOR_GREATERTHAN: $operator = 0x04 ; break;
+ case Cell_DataValidation::OPERATOR_LESSTHAN: $operator = 0x05 ; break;
+ case Cell_DataValidation::OPERATOR_GREATERTHANOREQUAL: $operator = 0x06; break;
+ case Cell_DataValidation::OPERATOR_LESSTHANOREQUAL: $operator = 0x07 ; break;
+ }
+ $options |= $operator << 20;
+
+ $data = pack('V', $options);
+
+ // prompt title
+ $promptTitle = $dataValidation->getPromptTitle() !== '' ?
+ $dataValidation->getPromptTitle() : chr(0);
+ $data .= Shared_String::UTF8toBIFF8UnicodeLong($promptTitle);
+
+ // error title
+ $errorTitle = $dataValidation->getErrorTitle() !== '' ?
+ $dataValidation->getErrorTitle() : chr(0);
+ $data .= Shared_String::UTF8toBIFF8UnicodeLong($errorTitle);
+
+ // prompt text
+ $prompt = $dataValidation->getPrompt() !== '' ?
+ $dataValidation->getPrompt() : chr(0);
+ $data .= Shared_String::UTF8toBIFF8UnicodeLong($prompt);
+
+ // error text
+ $error = $dataValidation->getError() !== '' ?
+ $dataValidation->getError() : chr(0);
+ $data .= Shared_String::UTF8toBIFF8UnicodeLong($error);
+
+ // formula 1
+ try {
+ $formula1 = $dataValidation->getFormula1();
+ if ($type == 0x03) { // list type
+ $formula1 = str_replace(',', chr(0), $formula1);
+ }
+ $this->_parser->parse($formula1);
+ $formula1 = $this->_parser->toReversePolish();
+ $sz1 = strlen($formula1);
+
+ } catch(Exception $e) {
+ $sz1 = 0;
+ $formula1 = '';
+ }
+ $data .= pack('vv', $sz1, 0x0000);
+ $data .= $formula1;
+
+ // formula 2
+ try {
+ $formula2 = $dataValidation->getFormula2();
+ if ($formula2 === '') {
+ throw new Writer_Exception('No formula2');
+ }
+ $this->_parser->parse($formula2);
+ $formula2 = $this->_parser->toReversePolish();
+ $sz2 = strlen($formula2);
+
+ } catch(Exception $e) {
+ $sz2 = 0;
+ $formula2 = '';
+ }
+ $data .= pack('vv', $sz2, 0x0000);
+ $data .= $formula2;
+
+ // cell range address list
+ $data .= pack('v', 0x0001);
+ $data .= $this->_writeBIFF8CellRangeAddressFixed($cellCoordinate);
+
+ $length = strlen($data);
+ $header = pack("vv", $record, $length);
+
+ $this->_append($header . $data);
+ }
+ }
+ }
+
+ /**
+ * Map Error code
+ *
+ * @param string $errorCode
+ * @return int
+ */
+ private static function _mapErrorCode($errorCode) {
+ switch ($errorCode) {
+ case '#NULL!': return 0x00;
+ case '#DIV/0!': return 0x07;
+ case '#VALUE!': return 0x0F;
+ case '#REF!': return 0x17;
+ case '#NAME?': return 0x1D;
+ case '#NUM!': return 0x24;
+ case '#N/A': return 0x2A;
+ }
+
+ return 0;
+ }
+
+ /**
+ * Write PLV Record
+ */
+ private function _writePageLayoutView(){
+ $record = 0x088B; // Record identifier
+ $length = 0x0010; // Bytes to follow
+
+ $rt = 0x088B; // 2
+ $grbitFrt = 0x0000; // 2
+ $reserved = 0x0000000000000000; // 8
+ $wScalvePLV = $this->_phpSheet->getSheetView()->getZoomScale(); // 2
+
+ // The options flags that comprise $grbit
+ if($this->_phpSheet->getSheetView()->getView() == Worksheet_SheetView::SHEETVIEW_PAGE_LAYOUT){
+ $fPageLayoutView = 1;
+ } else {
+ $fPageLayoutView = 0;
+ }
+ $fRulerVisible = 0;
+ $fWhitespaceHidden = 0;
+
+ $grbit = $fPageLayoutView; // 2
+ $grbit |= $fRulerVisible << 1;
+ $grbit |= $fWhitespaceHidden << 3;
+
+ $header = pack("vv", $record, $length);
+ $data = pack("vvVVvv", $rt, $grbitFrt, 0x00000000, 0x00000000, $wScalvePLV, $grbit);
+ $this->_append($header . $data);
+ }
+
+ /**
+ * Write CFRule Record
+ * @param PHPExcel\Style_Conditional $conditional
+ */
+ private function _writeCFRule(Style_Conditional $conditional){
+ $record = 0x01B1; // Record identifier
+
+ // $type : Type of the CF
+ // $operatorType : Comparison operator
+ if($conditional->getConditionType() == Style_Conditional::CONDITION_EXPRESSION){
+ $type = 0x02;
+ $operatorType = 0x00;
+ } else if($conditional->getConditionType() == Style_Conditional::CONDITION_CELLIS){
+ $type = 0x01;
+
+ switch ($conditional->getOperatorType()){
+ case Style_Conditional::OPERATOR_NONE:
+ $operatorType = 0x00;
+ break;
+ case Style_Conditional::OPERATOR_EQUAL:
+ $operatorType = 0x03;
+ break;
+ case Style_Conditional::OPERATOR_GREATERTHAN:
+ $operatorType = 0x05;
+ break;
+ case Style_Conditional::OPERATOR_GREATERTHANOREQUAL:
+ $operatorType = 0x07;
+ break;
+ case Style_Conditional::OPERATOR_LESSTHAN:
+ $operatorType = 0x06;
+ break;
+ case Style_Conditional::OPERATOR_LESSTHANOREQUAL:
+ $operatorType = 0x08;
+ break;
+ case Style_Conditional::OPERATOR_NOTEQUAL:
+ $operatorType = 0x04;
+ break;
+ case Style_Conditional::OPERATOR_BETWEEN:
+ $operatorType = 0x01;
+ break;
+ // not OPERATOR_NOTBETWEEN 0x02
+ }
+ }
+
+ // $szValue1 : size of the formula data for first value or formula
+ // $szValue2 : size of the formula data for second value or formula
+ $arrConditions = $conditional->getConditions();
+ $numConditions = sizeof($arrConditions);
+ if($numConditions == 1){
+ $szValue1 = ($arrConditions[0] <= 65535 ? 3 : 0x0000);
+ $szValue2 = 0x0000;
+ $operand1 = pack('Cv', 0x1E, $arrConditions[0]);
+ $operand2 = null;
+ } else if($numConditions == 2 && ($conditional->getOperatorType() == Style_Conditional::OPERATOR_BETWEEN)){
+ $szValue1 = ($arrConditions[0] <= 65535 ? 3 : 0x0000);
+ $szValue2 = ($arrConditions[1] <= 65535 ? 3 : 0x0000);
+ $operand1 = pack('Cv', 0x1E, $arrConditions[0]);
+ $operand2 = pack('Cv', 0x1E, $arrConditions[1]);
+ } else {
+ $szValue1 = 0x0000;
+ $szValue2 = 0x0000;
+ $operand1 = null;
+ $operand2 = null;
+ }
+
+ // $flags : Option flags
+ // Alignment
+ $bAlignHz = ($conditional->getStyle()->getAlignment()->getHorizontal() == null ? 1 : 0);
+ $bAlignVt = ($conditional->getStyle()->getAlignment()->getVertical() == null ? 1 : 0);
+ $bAlignWrapTx = ($conditional->getStyle()->getAlignment()->getWrapText() == false ? 1 : 0);
+ $bTxRotation = ($conditional->getStyle()->getAlignment()->getTextRotation() == null ? 1 : 0);
+ $bIndent = ($conditional->getStyle()->getAlignment()->getIndent() == 0 ? 1 : 0);
+ $bShrinkToFit = ($conditional->getStyle()->getAlignment()->getShrinkToFit() == false ? 1 : 0);
+ if($bAlignHz == 0 || $bAlignVt == 0 || $bAlignWrapTx == 0 || $bTxRotation == 0 || $bIndent == 0 || $bShrinkToFit == 0){
+ $bFormatAlign = 1;
+ } else {
+ $bFormatAlign = 0;
+ }
+ // Protection
+ $bProtLocked = ($conditional->getStyle()->getProtection()->getLocked() == null ? 1 : 0);
+ $bProtHidden = ($conditional->getStyle()->getProtection()->getHidden() == null ? 1 : 0);
+ if($bProtLocked == 0 || $bProtHidden == 0){
+ $bFormatProt = 1;
+ } else {
+ $bFormatProt = 0;
+ }
+ // Border
+ $bBorderLeft = ($conditional->getStyle()->getBorders()->getLeft()->getColor()->getARGB() == Style_Color::COLOR_BLACK
+ && $conditional->getStyle()->getBorders()->getLeft()->getBorderStyle() == Style_Border::BORDER_NONE ? 1 : 0);
+ $bBorderRight = ($conditional->getStyle()->getBorders()->getRight()->getColor()->getARGB() == Style_Color::COLOR_BLACK
+ && $conditional->getStyle()->getBorders()->getRight()->getBorderStyle() == Style_Border::BORDER_NONE ? 1 : 0);
+ $bBorderTop = ($conditional->getStyle()->getBorders()->getTop()->getColor()->getARGB() == Style_Color::COLOR_BLACK
+ && $conditional->getStyle()->getBorders()->getTop()->getBorderStyle() == Style_Border::BORDER_NONE ? 1 : 0);
+ $bBorderBottom = ($conditional->getStyle()->getBorders()->getBottom()->getColor()->getARGB() == Style_Color::COLOR_BLACK
+ && $conditional->getStyle()->getBorders()->getBottom()->getBorderStyle() == Style_Border::BORDER_NONE ? 1 : 0);
+ if($bBorderLeft == 0 || $bBorderRight == 0 || $bBorderTop == 0 || $bBorderBottom == 0){
+ $bFormatBorder = 1;
+ } else {
+ $bFormatBorder = 0;
+ }
+ // Pattern
+ $bFillStyle = ($conditional->getStyle()->getFill()->getFillType() == null ? 0 : 1);
+ $bFillColor = ($conditional->getStyle()->getFill()->getStartColor()->getARGB() == null ? 0 : 1);
+ $bFillColorBg = ($conditional->getStyle()->getFill()->getEndColor()->getARGB() == null ? 0 : 1);
+ if($bFillStyle == 0 || $bFillColor == 0 || $bFillColorBg == 0){
+ $bFormatFill = 1;
+ } else {
+ $bFormatFill = 0;
+ }
+ // Font
+ if($conditional->getStyle()->getFont()->getName() != null
+ || $conditional->getStyle()->getFont()->getSize() != null
+ || $conditional->getStyle()->getFont()->getBold() != null
+ || $conditional->getStyle()->getFont()->getItalic() != null
+ || $conditional->getStyle()->getFont()->getSuperScript() != null
+ || $conditional->getStyle()->getFont()->getSubScript() != null
+ || $conditional->getStyle()->getFont()->getUnderline() != null
+ || $conditional->getStyle()->getFont()->getStrikethrough() != null
+ || $conditional->getStyle()->getFont()->getColor()->getARGB() != null){
+ $bFormatFont = 1;
+ } else {
+ $bFormatFont = 0;
+ }
+ // Alignment
+ $flags = 0;
+ $flags |= (1 == $bAlignHz ? 0x00000001 : 0);
+ $flags |= (1 == $bAlignVt ? 0x00000002 : 0);
+ $flags |= (1 == $bAlignWrapTx ? 0x00000004 : 0);
+ $flags |= (1 == $bTxRotation ? 0x00000008 : 0);
+ // Justify last line flag
+ $flags |= (1 == 1 ? 0x00000010 : 0);
+ $flags |= (1 == $bIndent ? 0x00000020 : 0);
+ $flags |= (1 == $bShrinkToFit ? 0x00000040 : 0);
+ // Default
+ $flags |= (1 == 1 ? 0x00000080 : 0);
+ // Protection
+ $flags |= (1 == $bProtLocked ? 0x00000100 : 0);
+ $flags |= (1 == $bProtHidden ? 0x00000200 : 0);
+ // Border
+ $flags |= (1 == $bBorderLeft ? 0x00000400 : 0);
+ $flags |= (1 == $bBorderRight ? 0x00000800 : 0);
+ $flags |= (1 == $bBorderTop ? 0x00001000 : 0);
+ $flags |= (1 == $bBorderBottom ? 0x00002000 : 0);
+ $flags |= (1 == 1 ? 0x00004000 : 0); // Top left to Bottom right border
+ $flags |= (1 == 1 ? 0x00008000 : 0); // Bottom left to Top right border
+ // Pattern
+ $flags |= (1 == $bFillStyle ? 0x00010000 : 0);
+ $flags |= (1 == $bFillColor ? 0x00020000 : 0);
+ $flags |= (1 == $bFillColorBg ? 0x00040000 : 0);
+ $flags |= (1 == 1 ? 0x00380000 : 0);
+ // Font
+ $flags |= (1 == $bFormatFont ? 0x04000000 : 0);
+ // Alignment :
+ $flags |= (1 == $bFormatAlign ? 0x08000000 : 0);
+ // Border
+ $flags |= (1 == $bFormatBorder ? 0x10000000 : 0);
+ // Pattern
+ $flags |= (1 == $bFormatFill ? 0x20000000 : 0);
+ // Protection
+ $flags |= (1 == $bFormatProt ? 0x40000000 : 0);
+ // Text direction
+ $flags |= (1 == 0 ? 0x80000000 : 0);
+
+ // Data Blocks
+ if($bFormatFont == 1){
+ // Font Name
+ if($conditional->getStyle()->getFont()->getName() == null){
+ $dataBlockFont = pack('VVVVVVVV', 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000);
+ $dataBlockFont .= pack('VVVVVVVV', 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000);
+ } else {
+ $dataBlockFont = Shared_String::UTF8toBIFF8UnicodeLong($conditional->getStyle()->getFont()->getName());
+ }
+ // Font Size
+ if($conditional->getStyle()->getFont()->getSize() == null){
+ $dataBlockFont .= pack('V', 20 * 11);
+ } else {
+ $dataBlockFont .= pack('V', 20 * $conditional->getStyle()->getFont()->getSize());
+ }
+ // Font Options
+ $dataBlockFont .= pack('V', 0);
+ // Font weight
+ if($conditional->getStyle()->getFont()->getBold() == true){
+ $dataBlockFont .= pack('v', 0x02BC);
+ } else {
+ $dataBlockFont .= pack('v', 0x0190);
+ }
+ // Escapement type
+ if($conditional->getStyle()->getFont()->getSubScript() == true){
+ $dataBlockFont .= pack('v', 0x02);
+ $fontEscapement = 0;
+ } else if($conditional->getStyle()->getFont()->getSuperScript() == true){
+ $dataBlockFont .= pack('v', 0x01);
+ $fontEscapement = 0;
+ } else {
+ $dataBlockFont .= pack('v', 0x00);
+ $fontEscapement = 1;
+ }
+ // Underline type
+ switch ($conditional->getStyle()->getFont()->getUnderline()){
+ case Style_Font::UNDERLINE_NONE : $dataBlockFont .= pack('C', 0x00); $fontUnderline = 0; break;
+ case Style_Font::UNDERLINE_DOUBLE : $dataBlockFont .= pack('C', 0x02); $fontUnderline = 0; break;
+ case Style_Font::UNDERLINE_DOUBLEACCOUNTING : $dataBlockFont .= pack('C', 0x22); $fontUnderline = 0; break;
+ case Style_Font::UNDERLINE_SINGLE : $dataBlockFont .= pack('C', 0x01); $fontUnderline = 0; break;
+ case Style_Font::UNDERLINE_SINGLEACCOUNTING : $dataBlockFont .= pack('C', 0x21); $fontUnderline = 0; break;
+ default : $dataBlockFont .= pack('C', 0x00); $fontUnderline = 1; break;
+ }
+ // Not used (3)
+ $dataBlockFont .= pack('vC', 0x0000, 0x00);
+ // Font color index
+ switch ($conditional->getStyle()->getFont()->getColor()->getRGB()) {
+ case '000000': $colorIdx = 0x08; break;
+ case 'FFFFFF': $colorIdx = 0x09; break;
+ case 'FF0000': $colorIdx = 0x0A; break;
+ case '00FF00': $colorIdx = 0x0B; break;
+ case '0000FF': $colorIdx = 0x0C; break;
+ case 'FFFF00': $colorIdx = 0x0D; break;
+ case 'FF00FF': $colorIdx = 0x0E; break;
+ case '00FFFF': $colorIdx = 0x0F; break;
+ case '800000': $colorIdx = 0x10; break;
+ case '008000': $colorIdx = 0x11; break;
+ case '000080': $colorIdx = 0x12; break;
+ case '808000': $colorIdx = 0x13; break;
+ case '800080': $colorIdx = 0x14; break;
+ case '008080': $colorIdx = 0x15; break;
+ case 'C0C0C0': $colorIdx = 0x16; break;
+ case '808080': $colorIdx = 0x17; break;
+ case '9999FF': $colorIdx = 0x18; break;
+ case '993366': $colorIdx = 0x19; break;
+ case 'FFFFCC': $colorIdx = 0x1A; break;
+ case 'CCFFFF': $colorIdx = 0x1B; break;
+ case '660066': $colorIdx = 0x1C; break;
+ case 'FF8080': $colorIdx = 0x1D; break;
+ case '0066CC': $colorIdx = 0x1E; break;
+ case 'CCCCFF': $colorIdx = 0x1F; break;
+ case '000080': $colorIdx = 0x20; break;
+ case 'FF00FF': $colorIdx = 0x21; break;
+ case 'FFFF00': $colorIdx = 0x22; break;
+ case '00FFFF': $colorIdx = 0x23; break;
+ case '800080': $colorIdx = 0x24; break;
+ case '800000': $colorIdx = 0x25; break;
+ case '008080': $colorIdx = 0x26; break;
+ case '0000FF': $colorIdx = 0x27; break;
+ case '00CCFF': $colorIdx = 0x28; break;
+ case 'CCFFFF': $colorIdx = 0x29; break;
+ case 'CCFFCC': $colorIdx = 0x2A; break;
+ case 'FFFF99': $colorIdx = 0x2B; break;
+ case '99CCFF': $colorIdx = 0x2C; break;
+ case 'FF99CC': $colorIdx = 0x2D; break;
+ case 'CC99FF': $colorIdx = 0x2E; break;
+ case 'FFCC99': $colorIdx = 0x2F; break;
+ case '3366FF': $colorIdx = 0x30; break;
+ case '33CCCC': $colorIdx = 0x31; break;
+ case '99CC00': $colorIdx = 0x32; break;
+ case 'FFCC00': $colorIdx = 0x33; break;
+ case 'FF9900': $colorIdx = 0x34; break;
+ case 'FF6600': $colorIdx = 0x35; break;
+ case '666699': $colorIdx = 0x36; break;
+ case '969696': $colorIdx = 0x37; break;
+ case '003366': $colorIdx = 0x38; break;
+ case '339966': $colorIdx = 0x39; break;
+ case '003300': $colorIdx = 0x3A; break;
+ case '333300': $colorIdx = 0x3B; break;
+ case '993300': $colorIdx = 0x3C; break;
+ case '993366': $colorIdx = 0x3D; break;
+ case '333399': $colorIdx = 0x3E; break;
+ case '333333': $colorIdx = 0x3F; break;
+ default: $colorIdx = 0x00; break;
+ }
+ $dataBlockFont .= pack('V', $colorIdx);
+ // Not used (4)
+ $dataBlockFont .= pack('V', 0x00000000);
+ // Options flags for modified font attributes
+ $optionsFlags = 0;
+ $optionsFlagsBold = ($conditional->getStyle()->getFont()->getBold() == null ? 1 : 0);
+ $optionsFlags |= (1 == $optionsFlagsBold ? 0x00000002 : 0);
+ $optionsFlags |= (1 == 1 ? 0x00000008 : 0);
+ $optionsFlags |= (1 == 1 ? 0x00000010 : 0);
+ $optionsFlags |= (1 == 0 ? 0x00000020 : 0);
+ $optionsFlags |= (1 == 1 ? 0x00000080 : 0);
+ $dataBlockFont .= pack('V', $optionsFlags);
+ // Escapement type
+ $dataBlockFont .= pack('V', $fontEscapement);
+ // Underline type
+ $dataBlockFont .= pack('V', $fontUnderline);
+ // Always
+ $dataBlockFont .= pack('V', 0x00000000);
+ // Always
+ $dataBlockFont .= pack('V', 0x00000000);
+ // Not used (8)
+ $dataBlockFont .= pack('VV', 0x00000000, 0x00000000);
+ // Always
+ $dataBlockFont .= pack('v', 0x0001);
+ }
+ if($bFormatAlign == 1){
+ $blockAlign = 0;
+ // Alignment and text break
+ switch ($conditional->getStyle()->getAlignment()->getHorizontal()){
+ case Style_Alignment::HORIZONTAL_GENERAL : $blockAlign = 0; break;
+ case Style_Alignment::HORIZONTAL_LEFT : $blockAlign = 1; break;
+ case Style_Alignment::HORIZONTAL_RIGHT : $blockAlign = 3; break;
+ case Style_Alignment::HORIZONTAL_CENTER : $blockAlign = 2; break;
+ case Style_Alignment::HORIZONTAL_CENTER_CONTINUOUS : $blockAlign = 6; break;
+ case Style_Alignment::HORIZONTAL_JUSTIFY : $blockAlign = 5; break;
+ }
+ if($conditional->getStyle()->getAlignment()->getWrapText() == true){
+ $blockAlign |= 1 << 3;
+ } else {
+ $blockAlign |= 0 << 3;
+ }
+ switch ($conditional->getStyle()->getAlignment()->getVertical()){
+ case Style_Alignment::VERTICAL_BOTTOM : $blockAlign = 2 << 4; break;
+ case Style_Alignment::VERTICAL_TOP : $blockAlign = 0 << 4; break;
+ case Style_Alignment::VERTICAL_CENTER : $blockAlign = 1 << 4; break;
+ case Style_Alignment::VERTICAL_JUSTIFY : $blockAlign = 3 << 4; break;
+ }
+ $blockAlign |= 0 << 7;
+
+ // Text rotation angle
+ $blockRotation = $conditional->getStyle()->getAlignment()->getTextRotation();
+
+ // Indentation
+ $blockIndent = $conditional->getStyle()->getAlignment()->getIndent();
+ if($conditional->getStyle()->getAlignment()->getShrinkToFit() == true){
+ $blockIndent |= 1 << 4;
+ } else {
+ $blockIndent |= 0 << 4;
+ }
+ $blockIndent |= 0 << 6;
+
+ // Relative indentation
+ $blockIndentRelative = 255;
+
+ $dataBlockAlign = pack('CCvvv', $blockAlign, $blockRotation, $blockIndent, $blockIndentRelative, 0x0000);
+ }
+ if($bFormatBorder == 1){
+ $blockLineStyle = 0;
+ switch ($conditional->getStyle()->getBorders()->getLeft()->getBorderStyle()){
+ case Style_Border::BORDER_NONE : $blockLineStyle |= 0x00; break;
+ case Style_Border::BORDER_THIN : $blockLineStyle |= 0x01; break;
+ case Style_Border::BORDER_MEDIUM : $blockLineStyle |= 0x02; break;
+ case Style_Border::BORDER_DASHED : $blockLineStyle |= 0x03; break;
+ case Style_Border::BORDER_DOTTED : $blockLineStyle |= 0x04; break;
+ case Style_Border::BORDER_THICK : $blockLineStyle |= 0x05; break;
+ case Style_Border::BORDER_DOUBLE : $blockLineStyle |= 0x06; break;
+ case Style_Border::BORDER_HAIR : $blockLineStyle |= 0x07; break;
+ case Style_Border::BORDER_MEDIUMDASHED : $blockLineStyle |= 0x08; break;
+ case Style_Border::BORDER_DASHDOT : $blockLineStyle |= 0x09; break;
+ case Style_Border::BORDER_MEDIUMDASHDOT : $blockLineStyle |= 0x0A; break;
+ case Style_Border::BORDER_DASHDOTDOT : $blockLineStyle |= 0x0B; break;
+ case Style_Border::BORDER_MEDIUMDASHDOTDOT : $blockLineStyle |= 0x0C; break;
+ case Style_Border::BORDER_SLANTDASHDOT : $blockLineStyle |= 0x0D; break;
+ }
+ switch ($conditional->getStyle()->getBorders()->getRight()->getBorderStyle()){
+ case Style_Border::BORDER_NONE : $blockLineStyle |= 0x00 << 4; break;
+ case Style_Border::BORDER_THIN : $blockLineStyle |= 0x01 << 4; break;
+ case Style_Border::BORDER_MEDIUM : $blockLineStyle |= 0x02 << 4; break;
+ case Style_Border::BORDER_DASHED : $blockLineStyle |= 0x03 << 4; break;
+ case Style_Border::BORDER_DOTTED : $blockLineStyle |= 0x04 << 4; break;
+ case Style_Border::BORDER_THICK : $blockLineStyle |= 0x05 << 4; break;
+ case Style_Border::BORDER_DOUBLE : $blockLineStyle |= 0x06 << 4; break;
+ case Style_Border::BORDER_HAIR : $blockLineStyle |= 0x07 << 4; break;
+ case Style_Border::BORDER_MEDIUMDASHED : $blockLineStyle |= 0x08 << 4; break;
+ case Style_Border::BORDER_DASHDOT : $blockLineStyle |= 0x09 << 4; break;
+ case Style_Border::BORDER_MEDIUMDASHDOT : $blockLineStyle |= 0x0A << 4; break;
+ case Style_Border::BORDER_DASHDOTDOT : $blockLineStyle |= 0x0B << 4; break;
+ case Style_Border::BORDER_MEDIUMDASHDOTDOT : $blockLineStyle |= 0x0C << 4; break;
+ case Style_Border::BORDER_SLANTDASHDOT : $blockLineStyle |= 0x0D << 4; break;
+ }
+ switch ($conditional->getStyle()->getBorders()->getTop()->getBorderStyle()){
+ case Style_Border::BORDER_NONE : $blockLineStyle |= 0x00 << 8; break;
+ case Style_Border::BORDER_THIN : $blockLineStyle |= 0x01 << 8; break;
+ case Style_Border::BORDER_MEDIUM : $blockLineStyle |= 0x02 << 8; break;
+ case Style_Border::BORDER_DASHED : $blockLineStyle |= 0x03 << 8; break;
+ case Style_Border::BORDER_DOTTED : $blockLineStyle |= 0x04 << 8; break;
+ case Style_Border::BORDER_THICK : $blockLineStyle |= 0x05 << 8; break;
+ case Style_Border::BORDER_DOUBLE : $blockLineStyle |= 0x06 << 8; break;
+ case Style_Border::BORDER_HAIR : $blockLineStyle |= 0x07 << 8; break;
+ case Style_Border::BORDER_MEDIUMDASHED : $blockLineStyle |= 0x08 << 8; break;
+ case Style_Border::BORDER_DASHDOT : $blockLineStyle |= 0x09 << 8; break;
+ case Style_Border::BORDER_MEDIUMDASHDOT : $blockLineStyle |= 0x0A << 8; break;
+ case Style_Border::BORDER_DASHDOTDOT : $blockLineStyle |= 0x0B << 8; break;
+ case Style_Border::BORDER_MEDIUMDASHDOTDOT : $blockLineStyle |= 0x0C << 8; break;
+ case Style_Border::BORDER_SLANTDASHDOT : $blockLineStyle |= 0x0D << 8; break;
+ }
+ switch ($conditional->getStyle()->getBorders()->getBottom()->getBorderStyle()){
+ case Style_Border::BORDER_NONE : $blockLineStyle |= 0x00 << 12; break;
+ case Style_Border::BORDER_THIN : $blockLineStyle |= 0x01 << 12; break;
+ case Style_Border::BORDER_MEDIUM : $blockLineStyle |= 0x02 << 12; break;
+ case Style_Border::BORDER_DASHED : $blockLineStyle |= 0x03 << 12; break;
+ case Style_Border::BORDER_DOTTED : $blockLineStyle |= 0x04 << 12; break;
+ case Style_Border::BORDER_THICK : $blockLineStyle |= 0x05 << 12; break;
+ case Style_Border::BORDER_DOUBLE : $blockLineStyle |= 0x06 << 12; break;
+ case Style_Border::BORDER_HAIR : $blockLineStyle |= 0x07 << 12; break;
+ case Style_Border::BORDER_MEDIUMDASHED : $blockLineStyle |= 0x08 << 12; break;
+ case Style_Border::BORDER_DASHDOT : $blockLineStyle |= 0x09 << 12; break;
+ case Style_Border::BORDER_MEDIUMDASHDOT : $blockLineStyle |= 0x0A << 12; break;
+ case Style_Border::BORDER_DASHDOTDOT : $blockLineStyle |= 0x0B << 12; break;
+ case Style_Border::BORDER_MEDIUMDASHDOTDOT : $blockLineStyle |= 0x0C << 12; break;
+ case Style_Border::BORDER_SLANTDASHDOT : $blockLineStyle |= 0x0D << 12; break;
+ }
+ //@todo _writeCFRule() => $blockLineStyle => Index Color for left line
+ //@todo _writeCFRule() => $blockLineStyle => Index Color for right line
+ //@todo _writeCFRule() => $blockLineStyle => Top-left to bottom-right on/off
+ //@todo _writeCFRule() => $blockLineStyle => Bottom-left to top-right on/off
+ $blockColor = 0;
+ //@todo _writeCFRule() => $blockColor => Index Color for top line
+ //@todo _writeCFRule() => $blockColor => Index Color for bottom line
+ //@todo _writeCFRule() => $blockColor => Index Color for diagonal line
+ switch ($conditional->getStyle()->getBorders()->getDiagonal()->getBorderStyle()){
+ case Style_Border::BORDER_NONE : $blockColor |= 0x00 << 21; break;
+ case Style_Border::BORDER_THIN : $blockColor |= 0x01 << 21; break;
+ case Style_Border::BORDER_MEDIUM : $blockColor |= 0x02 << 21; break;
+ case Style_Border::BORDER_DASHED : $blockColor |= 0x03 << 21; break;
+ case Style_Border::BORDER_DOTTED : $blockColor |= 0x04 << 21; break;
+ case Style_Border::BORDER_THICK : $blockColor |= 0x05 << 21; break;
+ case Style_Border::BORDER_DOUBLE : $blockColor |= 0x06 << 21; break;
+ case Style_Border::BORDER_HAIR : $blockColor |= 0x07 << 21; break;
+ case Style_Border::BORDER_MEDIUMDASHED : $blockColor |= 0x08 << 21; break;
+ case Style_Border::BORDER_DASHDOT : $blockColor |= 0x09 << 21; break;
+ case Style_Border::BORDER_MEDIUMDASHDOT : $blockColor |= 0x0A << 21; break;
+ case Style_Border::BORDER_DASHDOTDOT : $blockColor |= 0x0B << 21; break;
+ case Style_Border::BORDER_MEDIUMDASHDOTDOT : $blockColor |= 0x0C << 21; break;
+ case Style_Border::BORDER_SLANTDASHDOT : $blockColor |= 0x0D << 21; break;
+ }
+ $dataBlockBorder = pack('vv', $blockLineStyle, $blockColor);
+ }
+ if($bFormatFill == 1){
+ // Fill Patern Style
+ $blockFillPatternStyle = 0;
+ switch ($conditional->getStyle()->getFill()->getFillType()){
+ case Style_Fill::FILL_NONE : $blockFillPatternStyle = 0x00; break;
+ case Style_Fill::FILL_SOLID : $blockFillPatternStyle = 0x01; break;
+ case Style_Fill::FILL_PATTERN_MEDIUMGRAY : $blockFillPatternStyle = 0x02; break;
+ case Style_Fill::FILL_PATTERN_DARKGRAY : $blockFillPatternStyle = 0x03; break;
+ case Style_Fill::FILL_PATTERN_LIGHTGRAY : $blockFillPatternStyle = 0x04; break;
+ case Style_Fill::FILL_PATTERN_DARKHORIZONTAL : $blockFillPatternStyle = 0x05; break;
+ case Style_Fill::FILL_PATTERN_DARKVERTICAL : $blockFillPatternStyle = 0x06; break;
+ case Style_Fill::FILL_PATTERN_DARKDOWN : $blockFillPatternStyle = 0x07; break;
+ case Style_Fill::FILL_PATTERN_DARKUP : $blockFillPatternStyle = 0x08; break;
+ case Style_Fill::FILL_PATTERN_DARKGRID : $blockFillPatternStyle = 0x09; break;
+ case Style_Fill::FILL_PATTERN_DARKTRELLIS : $blockFillPatternStyle = 0x0A; break;
+ case Style_Fill::FILL_PATTERN_LIGHTHORIZONTAL : $blockFillPatternStyle = 0x0B; break;
+ case Style_Fill::FILL_PATTERN_LIGHTVERTICAL : $blockFillPatternStyle = 0x0C; break;
+ case Style_Fill::FILL_PATTERN_LIGHTDOWN : $blockFillPatternStyle = 0x0D; break;
+ case Style_Fill::FILL_PATTERN_LIGHTUP : $blockFillPatternStyle = 0x0E; break;
+ case Style_Fill::FILL_PATTERN_LIGHTGRID : $blockFillPatternStyle = 0x0F; break;
+ case Style_Fill::FILL_PATTERN_LIGHTTRELLIS : $blockFillPatternStyle = 0x10; break;
+ case Style_Fill::FILL_PATTERN_GRAY125 : $blockFillPatternStyle = 0x11; break;
+ case Style_Fill::FILL_PATTERN_GRAY0625 : $blockFillPatternStyle = 0x12; break;
+ case Style_Fill::FILL_GRADIENT_LINEAR : $blockFillPatternStyle = 0x00; break; // does not exist in BIFF8
+ case Style_Fill::FILL_GRADIENT_PATH : $blockFillPatternStyle = 0x00; break; // does not exist in BIFF8
+ default : $blockFillPatternStyle = 0x00; break;
+ }
+ // Color
+ switch ($conditional->getStyle()->getFill()->getStartColor()->getRGB()) {
+ case '000000': $colorIdxBg = 0x08; break;
+ case 'FFFFFF': $colorIdxBg = 0x09; break;
+ case 'FF0000': $colorIdxBg = 0x0A; break;
+ case '00FF00': $colorIdxBg = 0x0B; break;
+ case '0000FF': $colorIdxBg = 0x0C; break;
+ case 'FFFF00': $colorIdxBg = 0x0D; break;
+ case 'FF00FF': $colorIdxBg = 0x0E; break;
+ case '00FFFF': $colorIdxBg = 0x0F; break;
+ case '800000': $colorIdxBg = 0x10; break;
+ case '008000': $colorIdxBg = 0x11; break;
+ case '000080': $colorIdxBg = 0x12; break;
+ case '808000': $colorIdxBg = 0x13; break;
+ case '800080': $colorIdxBg = 0x14; break;
+ case '008080': $colorIdxBg = 0x15; break;
+ case 'C0C0C0': $colorIdxBg = 0x16; break;
+ case '808080': $colorIdxBg = 0x17; break;
+ case '9999FF': $colorIdxBg = 0x18; break;
+ case '993366': $colorIdxBg = 0x19; break;
+ case 'FFFFCC': $colorIdxBg = 0x1A; break;
+ case 'CCFFFF': $colorIdxBg = 0x1B; break;
+ case '660066': $colorIdxBg = 0x1C; break;
+ case 'FF8080': $colorIdxBg = 0x1D; break;
+ case '0066CC': $colorIdxBg = 0x1E; break;
+ case 'CCCCFF': $colorIdxBg = 0x1F; break;
+ case '000080': $colorIdxBg = 0x20; break;
+ case 'FF00FF': $colorIdxBg = 0x21; break;
+ case 'FFFF00': $colorIdxBg = 0x22; break;
+ case '00FFFF': $colorIdxBg = 0x23; break;
+ case '800080': $colorIdxBg = 0x24; break;
+ case '800000': $colorIdxBg = 0x25; break;
+ case '008080': $colorIdxBg = 0x26; break;
+ case '0000FF': $colorIdxBg = 0x27; break;
+ case '00CCFF': $colorIdxBg = 0x28; break;
+ case 'CCFFFF': $colorIdxBg = 0x29; break;
+ case 'CCFFCC': $colorIdxBg = 0x2A; break;
+ case 'FFFF99': $colorIdxBg = 0x2B; break;
+ case '99CCFF': $colorIdxBg = 0x2C; break;
+ case 'FF99CC': $colorIdxBg = 0x2D; break;
+ case 'CC99FF': $colorIdxBg = 0x2E; break;
+ case 'FFCC99': $colorIdxBg = 0x2F; break;
+ case '3366FF': $colorIdxBg = 0x30; break;
+ case '33CCCC': $colorIdxBg = 0x31; break;
+ case '99CC00': $colorIdxBg = 0x32; break;
+ case 'FFCC00': $colorIdxBg = 0x33; break;
+ case 'FF9900': $colorIdxBg = 0x34; break;
+ case 'FF6600': $colorIdxBg = 0x35; break;
+ case '666699': $colorIdxBg = 0x36; break;
+ case '969696': $colorIdxBg = 0x37; break;
+ case '003366': $colorIdxBg = 0x38; break;
+ case '339966': $colorIdxBg = 0x39; break;
+ case '003300': $colorIdxBg = 0x3A; break;
+ case '333300': $colorIdxBg = 0x3B; break;
+ case '993300': $colorIdxBg = 0x3C; break;
+ case '993366': $colorIdxBg = 0x3D; break;
+ case '333399': $colorIdxBg = 0x3E; break;
+ case '333333': $colorIdxBg = 0x3F; break;
+ default: $colorIdxBg = 0x41; break;
+ }
+ // Fg Color
+ switch ($conditional->getStyle()->getFill()->getEndColor()->getRGB()) {
+ case '000000': $colorIdxFg = 0x08; break;
+ case 'FFFFFF': $colorIdxFg = 0x09; break;
+ case 'FF0000': $colorIdxFg = 0x0A; break;
+ case '00FF00': $colorIdxFg = 0x0B; break;
+ case '0000FF': $colorIdxFg = 0x0C; break;
+ case 'FFFF00': $colorIdxFg = 0x0D; break;
+ case 'FF00FF': $colorIdxFg = 0x0E; break;
+ case '00FFFF': $colorIdxFg = 0x0F; break;
+ case '800000': $colorIdxFg = 0x10; break;
+ case '008000': $colorIdxFg = 0x11; break;
+ case '000080': $colorIdxFg = 0x12; break;
+ case '808000': $colorIdxFg = 0x13; break;
+ case '800080': $colorIdxFg = 0x14; break;
+ case '008080': $colorIdxFg = 0x15; break;
+ case 'C0C0C0': $colorIdxFg = 0x16; break;
+ case '808080': $colorIdxFg = 0x17; break;
+ case '9999FF': $colorIdxFg = 0x18; break;
+ case '993366': $colorIdxFg = 0x19; break;
+ case 'FFFFCC': $colorIdxFg = 0x1A; break;
+ case 'CCFFFF': $colorIdxFg = 0x1B; break;
+ case '660066': $colorIdxFg = 0x1C; break;
+ case 'FF8080': $colorIdxFg = 0x1D; break;
+ case '0066CC': $colorIdxFg = 0x1E; break;
+ case 'CCCCFF': $colorIdxFg = 0x1F; break;
+ case '000080': $colorIdxFg = 0x20; break;
+ case 'FF00FF': $colorIdxFg = 0x21; break;
+ case 'FFFF00': $colorIdxFg = 0x22; break;
+ case '00FFFF': $colorIdxFg = 0x23; break;
+ case '800080': $colorIdxFg = 0x24; break;
+ case '800000': $colorIdxFg = 0x25; break;
+ case '008080': $colorIdxFg = 0x26; break;
+ case '0000FF': $colorIdxFg = 0x27; break;
+ case '00CCFF': $colorIdxFg = 0x28; break;
+ case 'CCFFFF': $colorIdxFg = 0x29; break;
+ case 'CCFFCC': $colorIdxFg = 0x2A; break;
+ case 'FFFF99': $colorIdxFg = 0x2B; break;
+ case '99CCFF': $colorIdxFg = 0x2C; break;
+ case 'FF99CC': $colorIdxFg = 0x2D; break;
+ case 'CC99FF': $colorIdxFg = 0x2E; break;
+ case 'FFCC99': $colorIdxFg = 0x2F; break;
+ case '3366FF': $colorIdxFg = 0x30; break;
+ case '33CCCC': $colorIdxFg = 0x31; break;
+ case '99CC00': $colorIdxFg = 0x32; break;
+ case 'FFCC00': $colorIdxFg = 0x33; break;
+ case 'FF9900': $colorIdxFg = 0x34; break;
+ case 'FF6600': $colorIdxFg = 0x35; break;
+ case '666699': $colorIdxFg = 0x36; break;
+ case '969696': $colorIdxFg = 0x37; break;
+ case '003366': $colorIdxFg = 0x38; break;
+ case '339966': $colorIdxFg = 0x39; break;
+ case '003300': $colorIdxFg = 0x3A; break;
+ case '333300': $colorIdxFg = 0x3B; break;
+ case '993300': $colorIdxFg = 0x3C; break;
+ case '993366': $colorIdxFg = 0x3D; break;
+ case '333399': $colorIdxFg = 0x3E; break;
+ case '333333': $colorIdxFg = 0x3F; break;
+ default: $colorIdxFg = 0x40; break;
+ }
+ $dataBlockFill = pack('v', $blockFillPatternStyle);
+ $dataBlockFill .= pack('v', $colorIdxFg | ($colorIdxBg << 7));
+ }
+ if($bFormatProt == 1){
+ $dataBlockProtection = 0;
+ if($conditional->getStyle()->getProtection()->getLocked() == Style_Protection::PROTECTION_PROTECTED){
+ $dataBlockProtection = 1;
+ }
+ if($conditional->getStyle()->getProtection()->getHidden() == Style_Protection::PROTECTION_PROTECTED){
+ $dataBlockProtection = 1 << 1;
+ }
+ }
+
+ $data = pack('CCvvVv', $type, $operatorType, $szValue1, $szValue2, $flags, 0x0000);
+ if($bFormatFont == 1){ // Block Formatting : OK
+ $data .= $dataBlockFont;
+ }
+ if($bFormatAlign == 1){
+ $data .= $dataBlockAlign;
+ }
+ if($bFormatBorder == 1){
+ $data .= $dataBlockBorder;
+ }
+ if($bFormatFill == 1){ // Block Formatting : OK
+ $data .= $dataBlockFill;
+ }
+ if($bFormatProt == 1){
+ $data .= $dataBlockProtection;
+ }
+ if(!is_null($operand1)){
+ $data .= $operand1;
+ }
+ if(!is_null($operand2)){
+ $data .= $operand2;
+ }
+ $header = pack('vv', $record, strlen($data));
+ $this->_append($header . $data);
+ }
+
+ /**
+ * Write CFHeader record
+ */
+ private function _writeCFHeader(){
+ $record = 0x01B0; // Record identifier
+ $length = 0x0016; // Bytes to follow
+
+ $numColumnMin = null;
+ $numColumnMax = null;
+ $numRowMin = null;
+ $numRowMax = null;
+ $arrConditional = array();
+ foreach ($this->_phpSheet->getConditionalStylesCollection() as $cellCoordinate => $conditionalStyles) {
+ foreach ($conditionalStyles as $conditional) {
+ if($conditional->getConditionType() == Style_Conditional::CONDITION_EXPRESSION
+ || $conditional->getConditionType() == Style_Conditional::CONDITION_CELLIS){
+ if(!in_array($conditional->getHashCode(), $arrConditional)){
+ $arrConditional[] = $conditional->getHashCode();
+ }
+ // Cells
+ $arrCoord = Cell::coordinateFromString($cellCoordinate);
+ if(!is_numeric($arrCoord[0])){
+ $arrCoord[0] = Cell::columnIndexFromString($arrCoord[0]);
+ }
+ if(is_null($numColumnMin) || ($numColumnMin > $arrCoord[0])){
+ $numColumnMin = $arrCoord[0];
+ }
+ if(is_null($numColumnMax) || ($numColumnMax < $arrCoord[0])){
+ $numColumnMax = $arrCoord[0];
+ }
+ if(is_null($numRowMin) || ($numRowMin > $arrCoord[1])){
+ $numRowMin = $arrCoord[1];
+ }
+ if(is_null($numRowMax) || ($numRowMax < $arrCoord[1])){
+ $numRowMax = $arrCoord[1];
+ }
+ }
+ }
+ }
+ $needRedraw = 1;
+ $cellRange = pack('vvvv', $numRowMin-1, $numRowMax-1, $numColumnMin-1, $numColumnMax-1);
+
+ $header = pack('vv', $record, $length);
+ $data = pack('vv', count($arrConditional), $needRedraw);
+ $data .= $cellRange;
+ $data .= pack('v', 0x0001);
+ $data .= $cellRange;
+ $this->_append($header . $data);
+ }
}
\ No newline at end of file
diff --git a/Classes/PHPExcel/Writer/Excel5/Xf.php b/Classes/PHPExcel/Writer/Excel5/Xf.php
index 4a1bdfa..6f00327 100644
--- a/Classes/PHPExcel/Writer/Excel5/Xf.php
+++ b/Classes/PHPExcel/Writer/Excel5/Xf.php
@@ -21,7 +21,7 @@
* @category PHPExcel
* @package PHPExcel\Writer_Excel5
* @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##
*/
@@ -73,476 +73,476 @@ namespace PHPExcel;
class Writer_Excel5_Xf
{
/**
- * Style XF or a cell XF ?
- *
- * @var boolean
- */
- private $_isStyleXf;
+ * Style XF or a cell XF ?
+ *
+ * @var boolean
+ */
+ private $_isStyleXf;
- /**
- * Index to the FONT record. Index 4 does not exist
- * @var integer
- */
- private $_fontIndex;
+ /**
+ * Index to the FONT record. Index 4 does not exist
+ * @var integer
+ */
+ private $_fontIndex;
- /**
- * An index (2 bytes) to a FORMAT record (number format).
- * @var integer
- */
- public $_numberFormatIndex;
+ /**
+ * An index (2 bytes) to a FORMAT record (number format).
+ * @var integer
+ */
+ public $_numberFormatIndex;
- /**
- * 1 bit, apparently not used.
- * @var integer
- */
- public $_text_justlast;
+ /**
+ * 1 bit, apparently not used.
+ * @var integer
+ */
+ public $_text_justlast;
- /**
- * The cell's foreground color.
- * @var integer
- */
- public $_fg_color;
+ /**
+ * The cell's foreground color.
+ * @var integer
+ */
+ public $_fg_color;
- /**
- * The cell's background color.
- * @var integer
- */
- public $_bg_color;
+ /**
+ * The cell's background color.
+ * @var integer
+ */
+ public $_bg_color;
- /**
- * Color of the bottom border of the cell.
- * @var integer
- */
- public $_bottom_color;
+ /**
+ * Color of the bottom border of the cell.
+ * @var integer
+ */
+ public $_bottom_color;
- /**
- * Color of the top border of the cell.
- * @var integer
- */
- public $_top_color;
+ /**
+ * Color of the top border of the cell.
+ * @var integer
+ */
+ public $_top_color;
- /**
- * Color of the left border of the cell.
- * @var integer
- */
- public $_left_color;
+ /**
+ * Color of the left border of the cell.
+ * @var integer
+ */
+ public $_left_color;
- /**
- * Color of the right border of the cell.
- * @var integer
- */
- public $_right_color;
+ /**
+ * Color of the right border of the cell.
+ * @var integer
+ */
+ public $_right_color;
- /**
- * Constructor
- *
- * @access public
- * @param PHPExcel\Style The XF format
- */
- public function __construct(Style $style = null)
- {
- $this->_isStyleXf = false;
- $this->_fontIndex = 0;
+ /**
+ * Constructor
+ *
+ * @access public
+ * @param PHPExcel\Style The XF format
+ */
+ public function __construct(Style $style = null)
+ {
+ $this->_isStyleXf = false;
+ $this->_fontIndex = 0;
- $this->_numberFormatIndex = 0;
+ $this->_numberFormatIndex = 0;
- $this->_text_justlast = 0;
+ $this->_text_justlast = 0;
- $this->_fg_color = 0x40;
- $this->_bg_color = 0x41;
+ $this->_fg_color = 0x40;
+ $this->_bg_color = 0x41;
- $this->_diag = 0;
+ $this->_diag = 0;
- $this->_bottom_color = 0x40;
- $this->_top_color = 0x40;
- $this->_left_color = 0x40;
- $this->_right_color = 0x40;
- $this->_diag_color = 0x40;
- $this->_style = $style;
+ $this->_bottom_color = 0x40;
+ $this->_top_color = 0x40;
+ $this->_left_color = 0x40;
+ $this->_right_color = 0x40;
+ $this->_diag_color = 0x40;
+ $this->_style = $style;
- }
+ }
- /**
- * Generate an Excel BIFF XF record (style or cell).
- *
- * @return string The XF record
- */
- function writeXf()
- {
- // Set the type of the XF record and some of the attributes.
- if ($this->_isStyleXf) {
- $style = 0xFFF5;
- } else {
- $style = self::_mapLocked($this->_style->getProtection()->getLocked());
- $style |= self::_mapHidden($this->_style->getProtection()->getHidden()) << 1;
- }
+ /**
+ * Generate an Excel BIFF XF record (style or cell).
+ *
+ * @return string The XF record
+ */
+ function writeXf()
+ {
+ // Set the type of the XF record and some of the attributes.
+ if ($this->_isStyleXf) {
+ $style = 0xFFF5;
+ } else {
+ $style = self::_mapLocked($this->_style->getProtection()->getLocked());
+ $style |= self::_mapHidden($this->_style->getProtection()->getHidden()) << 1;
+ }
- // Flags to indicate if attributes have been set.
- $atr_num = ($this->_numberFormatIndex != 0)?1:0;
- $atr_fnt = ($this->_fontIndex != 0)?1:0;
- $atr_alc = ((int) $this->_style->getAlignment()->getWrapText())?1:0;
- $atr_bdr = (self::_mapBorderStyle($this->_style->getBorders()->getBottom()->getBorderStyle()) ||
- self::_mapBorderStyle($this->_style->getBorders()->getTop()->getBorderStyle()) ||
- self::_mapBorderStyle($this->_style->getBorders()->getLeft()->getBorderStyle()) ||
- self::_mapBorderStyle($this->_style->getBorders()->getRight()->getBorderStyle()))?1:0;
- $atr_pat = (($this->_fg_color != 0x40) ||
- ($this->_bg_color != 0x41) ||
- self::_mapFillType($this->_style->getFill()->getFillType()))?1:0;
- $atr_prot = self::_mapLocked($this->_style->getProtection()->getLocked())
- | self::_mapHidden($this->_style->getProtection()->getHidden());
+ // Flags to indicate if attributes have been set.
+ $atr_num = ($this->_numberFormatIndex != 0)?1:0;
+ $atr_fnt = ($this->_fontIndex != 0)?1:0;
+ $atr_alc = ((int) $this->_style->getAlignment()->getWrapText())?1:0;
+ $atr_bdr = (self::_mapBorderStyle($this->_style->getBorders()->getBottom()->getBorderStyle()) ||
+ self::_mapBorderStyle($this->_style->getBorders()->getTop()->getBorderStyle()) ||
+ self::_mapBorderStyle($this->_style->getBorders()->getLeft()->getBorderStyle()) ||
+ self::_mapBorderStyle($this->_style->getBorders()->getRight()->getBorderStyle()))?1:0;
+ $atr_pat = (($this->_fg_color != 0x40) ||
+ ($this->_bg_color != 0x41) ||
+ self::_mapFillType($this->_style->getFill()->getFillType()))?1:0;
+ $atr_prot = self::_mapLocked($this->_style->getProtection()->getLocked())
+ | self::_mapHidden($this->_style->getProtection()->getHidden());
- // Zero the default border colour if the border has not been set.
- if (self::_mapBorderStyle($this->_style->getBorders()->getBottom()->getBorderStyle()) == 0) {
- $this->_bottom_color = 0;
- }
- if (self::_mapBorderStyle($this->_style->getBorders()->getTop()->getBorderStyle()) == 0) {
- $this->_top_color = 0;
- }
- if (self::_mapBorderStyle($this->_style->getBorders()->getRight()->getBorderStyle()) == 0) {
- $this->_right_color = 0;
- }
- if (self::_mapBorderStyle($this->_style->getBorders()->getLeft()->getBorderStyle()) == 0) {
- $this->_left_color = 0;
- }
- if (self::_mapBorderStyle($this->_style->getBorders()->getDiagonal()->getBorderStyle()) == 0) {
- $this->_diag_color = 0;
- }
+ // Zero the default border colour if the border has not been set.
+ if (self::_mapBorderStyle($this->_style->getBorders()->getBottom()->getBorderStyle()) == 0) {
+ $this->_bottom_color = 0;
+ }
+ if (self::_mapBorderStyle($this->_style->getBorders()->getTop()->getBorderStyle()) == 0) {
+ $this->_top_color = 0;
+ }
+ if (self::_mapBorderStyle($this->_style->getBorders()->getRight()->getBorderStyle()) == 0) {
+ $this->_right_color = 0;
+ }
+ if (self::_mapBorderStyle($this->_style->getBorders()->getLeft()->getBorderStyle()) == 0) {
+ $this->_left_color = 0;
+ }
+ if (self::_mapBorderStyle($this->_style->getBorders()->getDiagonal()->getBorderStyle()) == 0) {
+ $this->_diag_color = 0;
+ }
- $record = 0x00E0; // Record identifier
- $length = 0x0014; // Number of bytes to follow
+ $record = 0x00E0; // Record identifier
+ $length = 0x0014; // Number of bytes to follow
- $ifnt = $this->_fontIndex; // Index to FONT record
- $ifmt = $this->_numberFormatIndex; // Index to FORMAT record
+ $ifnt = $this->_fontIndex; // Index to FONT record
+ $ifmt = $this->_numberFormatIndex; // Index to FORMAT record
- $align = $this->_mapHAlign($this->_style->getAlignment()->getHorizontal()); // Alignment
- $align |= (int) $this->_style->getAlignment()->getWrapText() << 3;
- $align |= self::_mapVAlign($this->_style->getAlignment()->getVertical()) << 4;
- $align |= $this->_text_justlast << 7;
+ $align = $this->_mapHAlign($this->_style->getAlignment()->getHorizontal()); // Alignment
+ $align |= (int) $this->_style->getAlignment()->getWrapText() << 3;
+ $align |= self::_mapVAlign($this->_style->getAlignment()->getVertical()) << 4;
+ $align |= $this->_text_justlast << 7;
- $used_attrib = $atr_num << 2;
- $used_attrib |= $atr_fnt << 3;
- $used_attrib |= $atr_alc << 4;
- $used_attrib |= $atr_bdr << 5;
- $used_attrib |= $atr_pat << 6;
- $used_attrib |= $atr_prot << 7;
+ $used_attrib = $atr_num << 2;
+ $used_attrib |= $atr_fnt << 3;
+ $used_attrib |= $atr_alc << 4;
+ $used_attrib |= $atr_bdr << 5;
+ $used_attrib |= $atr_pat << 6;
+ $used_attrib |= $atr_prot << 7;
- $icv = $this->_fg_color; // fg and bg pattern colors
- $icv |= $this->_bg_color << 7;
+ $icv = $this->_fg_color; // fg and bg pattern colors
+ $icv |= $this->_bg_color << 7;
- $border1 = self::_mapBorderStyle($this->_style->getBorders()->getLeft()->getBorderStyle()); // Border line style and color
- $border1 |= self::_mapBorderStyle($this->_style->getBorders()->getRight()->getBorderStyle()) << 4;
- $border1 |= self::_mapBorderStyle($this->_style->getBorders()->getTop()->getBorderStyle()) << 8;
- $border1 |= self::_mapBorderStyle($this->_style->getBorders()->getBottom()->getBorderStyle()) << 12;
- $border1 |= $this->_left_color << 16;
- $border1 |= $this->_right_color << 23;
+ $border1 = self::_mapBorderStyle($this->_style->getBorders()->getLeft()->getBorderStyle()); // Border line style and color
+ $border1 |= self::_mapBorderStyle($this->_style->getBorders()->getRight()->getBorderStyle()) << 4;
+ $border1 |= self::_mapBorderStyle($this->_style->getBorders()->getTop()->getBorderStyle()) << 8;
+ $border1 |= self::_mapBorderStyle($this->_style->getBorders()->getBottom()->getBorderStyle()) << 12;
+ $border1 |= $this->_left_color << 16;
+ $border1 |= $this->_right_color << 23;
- $diagonalDirection = $this->_style->getBorders()->getDiagonalDirection();
- $diag_tl_to_rb = $diagonalDirection == Style_Borders::DIAGONAL_BOTH
- || $diagonalDirection == Style_Borders::DIAGONAL_DOWN;
- $diag_tr_to_lb = $diagonalDirection == Style_Borders::DIAGONAL_BOTH
- || $diagonalDirection == Style_Borders::DIAGONAL_UP;
- $border1 |= $diag_tl_to_rb << 30;
- $border1 |= $diag_tr_to_lb << 31;
+ $diagonalDirection = $this->_style->getBorders()->getDiagonalDirection();
+ $diag_tl_to_rb = $diagonalDirection == Style_Borders::DIAGONAL_BOTH
+ || $diagonalDirection == Style_Borders::DIAGONAL_DOWN;
+ $diag_tr_to_lb = $diagonalDirection == Style_Borders::DIAGONAL_BOTH
+ || $diagonalDirection == Style_Borders::DIAGONAL_UP;
+ $border1 |= $diag_tl_to_rb << 30;
+ $border1 |= $diag_tr_to_lb << 31;
- $border2 = $this->_top_color; // Border color
- $border2 |= $this->_bottom_color << 7;
- $border2 |= $this->_diag_color << 14;
- $border2 |= self::_mapBorderStyle($this->_style->getBorders()->getDiagonal()->getBorderStyle()) << 21;
- $border2 |= self::_mapFillType($this->_style->getFill()->getFillType()) << 26;
+ $border2 = $this->_top_color; // Border color
+ $border2 |= $this->_bottom_color << 7;
+ $border2 |= $this->_diag_color << 14;
+ $border2 |= self::_mapBorderStyle($this->_style->getBorders()->getDiagonal()->getBorderStyle()) << 21;
+ $border2 |= self::_mapFillType($this->_style->getFill()->getFillType()) << 26;
- $header = pack("vv", $record, $length);
+ $header = pack("vv", $record, $length);
- //BIFF8 options: identation, shrinkToFit and text direction
- $biff8_options = $this->_style->getAlignment()->getIndent();
- $biff8_options |= (int) $this->_style->getAlignment()->getShrinkToFit() << 4;
+ //BIFF8 options: identation, shrinkToFit and text direction
+ $biff8_options = $this->_style->getAlignment()->getIndent();
+ $biff8_options |= (int) $this->_style->getAlignment()->getShrinkToFit() << 4;
- $data = pack("vvvC", $ifnt, $ifmt, $style, $align);
- $data .= pack("CCC"
- , self::_mapTextRotation($this->_style->getAlignment()->getTextRotation())
- , $biff8_options
- , $used_attrib
- );
- $data .= pack("VVv", $border1, $border2, $icv);
+ $data = pack("vvvC", $ifnt, $ifmt, $style, $align);
+ $data .= pack("CCC"
+ , self::_mapTextRotation($this->_style->getAlignment()->getTextRotation())
+ , $biff8_options
+ , $used_attrib
+ );
+ $data .= pack("VVv", $border1, $border2, $icv);
- return($header . $data);
- }
+ return($header . $data);
+ }
- /**
- * Is this a style XF ?
- *
- * @param boolean $value
- */
- public function setIsStyleXf($value)
- {
- $this->_isStyleXf = $value;
- }
+ /**
+ * Is this a style XF ?
+ *
+ * @param boolean $value
+ */
+ public function setIsStyleXf($value)
+ {
+ $this->_isStyleXf = $value;
+ }
- /**
- * Sets the cell's bottom border color
- *
- * @access public
- * @param int $colorIndex Color index
- */
- function setBottomColor($colorIndex)
- {
- $this->_bottom_color = $colorIndex;
- }
+ /**
+ * Sets the cell's bottom border color
+ *
+ * @access public
+ * @param int $colorIndex Color index
+ */
+ function setBottomColor($colorIndex)
+ {
+ $this->_bottom_color = $colorIndex;
+ }
- /**
- * Sets the cell's top border color
- *
- * @access public
- * @param int $colorIndex Color index
- */
- function setTopColor($colorIndex)
- {
- $this->_top_color = $colorIndex;
- }
+ /**
+ * Sets the cell's top border color
+ *
+ * @access public
+ * @param int $colorIndex Color index
+ */
+ function setTopColor($colorIndex)
+ {
+ $this->_top_color = $colorIndex;
+ }
- /**
- * Sets the cell's left border color
- *
- * @access public
- * @param int $colorIndex Color index
- */
- function setLeftColor($colorIndex)
- {
- $this->_left_color = $colorIndex;
- }
+ /**
+ * Sets the cell's left border color
+ *
+ * @access public
+ * @param int $colorIndex Color index
+ */
+ function setLeftColor($colorIndex)
+ {
+ $this->_left_color = $colorIndex;
+ }
- /**
- * Sets the cell's right border color
- *
- * @access public
- * @param int $colorIndex Color index
- */
- function setRightColor($colorIndex)
- {
- $this->_right_color = $colorIndex;
- }
+ /**
+ * Sets the cell's right border color
+ *
+ * @access public
+ * @param int $colorIndex Color index
+ */
+ function setRightColor($colorIndex)
+ {
+ $this->_right_color = $colorIndex;
+ }
- /**
- * Sets the cell's diagonal border color
- *
- * @access public
- * @param int $colorIndex Color index
- */
- function setDiagColor($colorIndex)
- {
- $this->_diag_color = $colorIndex;
- }
+ /**
+ * Sets the cell's diagonal border color
+ *
+ * @access public
+ * @param int $colorIndex Color index
+ */
+ function setDiagColor($colorIndex)
+ {
+ $this->_diag_color = $colorIndex;
+ }
- /**
- * Sets the cell's foreground color
- *
- * @access public
- * @param int $colorIndex Color index
- */
- function setFgColor($colorIndex)
- {
- $this->_fg_color = $colorIndex;
- }
+ /**
+ * Sets the cell's foreground color
+ *
+ * @access public
+ * @param int $colorIndex Color index
+ */
+ function setFgColor($colorIndex)
+ {
+ $this->_fg_color = $colorIndex;
+ }
- /**
- * Sets the cell's background color
- *
- * @access public
- * @param int $colorIndex Color index
- */
- function setBgColor($colorIndex)
- {
- $this->_bg_color = $colorIndex;
- }
+ /**
+ * Sets the cell's background color
+ *
+ * @access public
+ * @param int $colorIndex Color index
+ */
+ function setBgColor($colorIndex)
+ {
+ $this->_bg_color = $colorIndex;
+ }
- /**
- * Sets the index to the number format record
- * It can be date, time, currency, etc...
- *
- * @access public
- * @param integer $numberFormatIndex Index to format record
- */
- function setNumberFormatIndex($numberFormatIndex)
- {
- $this->_numberFormatIndex = $numberFormatIndex;
- }
+ /**
+ * Sets the index to the number format record
+ * It can be date, time, currency, etc...
+ *
+ * @access public
+ * @param integer $numberFormatIndex Index to format record
+ */
+ function setNumberFormatIndex($numberFormatIndex)
+ {
+ $this->_numberFormatIndex = $numberFormatIndex;
+ }
- /**
- * Set the font index.
- *
- * @param int $value Font index, note that value 4 does not exist
- */
- public function setFontIndex($value)
- {
- $this->_fontIndex = $value;
- }
+ /**
+ * Set the font index.
+ *
+ * @param int $value Font index, note that value 4 does not exist
+ */
+ public function setFontIndex($value)
+ {
+ $this->_fontIndex = $value;
+ }
- /**
- * Map of BIFF2-BIFF8 codes for border styles
- * @static array of int
- *
- */
- private static $_mapBorderStyle = array ( Style_Border::BORDER_NONE => 0x00,
- Style_Border::BORDER_THIN => 0x01,
- Style_Border::BORDER_MEDIUM => 0x02,
- Style_Border::BORDER_DASHED => 0x03,
- Style_Border::BORDER_DOTTED => 0x04,
- Style_Border::BORDER_THICK => 0x05,
- Style_Border::BORDER_DOUBLE => 0x06,
- Style_Border::BORDER_HAIR => 0x07,
- Style_Border::BORDER_MEDIUMDASHED => 0x08,
- Style_Border::BORDER_DASHDOT => 0x09,
- Style_Border::BORDER_MEDIUMDASHDOT => 0x0A,
- Style_Border::BORDER_DASHDOTDOT => 0x0B,
- Style_Border::BORDER_MEDIUMDASHDOTDOT => 0x0C,
- Style_Border::BORDER_SLANTDASHDOT => 0x0D,
- );
+ /**
+ * Map of BIFF2-BIFF8 codes for border styles
+ * @static array of int
+ *
+ */
+ private static $_mapBorderStyle = array ( Style_Border::BORDER_NONE => 0x00,
+ Style_Border::BORDER_THIN => 0x01,
+ Style_Border::BORDER_MEDIUM => 0x02,
+ Style_Border::BORDER_DASHED => 0x03,
+ Style_Border::BORDER_DOTTED => 0x04,
+ Style_Border::BORDER_THICK => 0x05,
+ Style_Border::BORDER_DOUBLE => 0x06,
+ Style_Border::BORDER_HAIR => 0x07,
+ Style_Border::BORDER_MEDIUMDASHED => 0x08,
+ Style_Border::BORDER_DASHDOT => 0x09,
+ Style_Border::BORDER_MEDIUMDASHDOT => 0x0A,
+ Style_Border::BORDER_DASHDOTDOT => 0x0B,
+ Style_Border::BORDER_MEDIUMDASHDOTDOT => 0x0C,
+ Style_Border::BORDER_SLANTDASHDOT => 0x0D,
+ );
- /**
- * Map border style
- *
- * @param string $borderStyle
- * @return int
- */
- private static function _mapBorderStyle($borderStyle) {
- if (isset(self::$_mapBorderStyle[$borderStyle]))
- return self::$_mapBorderStyle[$borderStyle];
- return 0x00;
- }
+ /**
+ * Map border style
+ *
+ * @param string $borderStyle
+ * @return int
+ */
+ private static function _mapBorderStyle($borderStyle) {
+ if (isset(self::$_mapBorderStyle[$borderStyle]))
+ return self::$_mapBorderStyle[$borderStyle];
+ return 0x00;
+ }
- /**
- * Map of BIFF2-BIFF8 codes for fill types
- * @static array of int
- *
- */
- private static $_mapFillType = array( Style_Fill::FILL_NONE => 0x00,
- Style_Fill::FILL_SOLID => 0x01,
- Style_Fill::FILL_PATTERN_MEDIUMGRAY => 0x02,
- Style_Fill::FILL_PATTERN_DARKGRAY => 0x03,
- Style_Fill::FILL_PATTERN_LIGHTGRAY => 0x04,
- Style_Fill::FILL_PATTERN_DARKHORIZONTAL => 0x05,
- Style_Fill::FILL_PATTERN_DARKVERTICAL => 0x06,
- Style_Fill::FILL_PATTERN_DARKDOWN => 0x07,
- Style_Fill::FILL_PATTERN_DARKUP => 0x08,
- Style_Fill::FILL_PATTERN_DARKGRID => 0x09,
- Style_Fill::FILL_PATTERN_DARKTRELLIS => 0x0A,
- Style_Fill::FILL_PATTERN_LIGHTHORIZONTAL => 0x0B,
- Style_Fill::FILL_PATTERN_LIGHTVERTICAL => 0x0C,
- Style_Fill::FILL_PATTERN_LIGHTDOWN => 0x0D,
- Style_Fill::FILL_PATTERN_LIGHTUP => 0x0E,
- Style_Fill::FILL_PATTERN_LIGHTGRID => 0x0F,
- Style_Fill::FILL_PATTERN_LIGHTTRELLIS => 0x10,
- Style_Fill::FILL_PATTERN_GRAY125 => 0x11,
- Style_Fill::FILL_PATTERN_GRAY0625 => 0x12,
- Style_Fill::FILL_GRADIENT_LINEAR => 0x00, // does not exist in BIFF8
- Style_Fill::FILL_GRADIENT_PATH => 0x00, // does not exist in BIFF8
- );
- /**
- * Map fill type
- *
- * @param string $fillType
- * @return int
- */
- private static function _mapFillType($fillType) {
- if (isset(self::$_mapFillType[$fillType]))
- return self::$_mapFillType[$fillType];
- return 0x00;
- }
+ /**
+ * Map of BIFF2-BIFF8 codes for fill types
+ * @static array of int
+ *
+ */
+ private static $_mapFillType = array( Style_Fill::FILL_NONE => 0x00,
+ Style_Fill::FILL_SOLID => 0x01,
+ Style_Fill::FILL_PATTERN_MEDIUMGRAY => 0x02,
+ Style_Fill::FILL_PATTERN_DARKGRAY => 0x03,
+ Style_Fill::FILL_PATTERN_LIGHTGRAY => 0x04,
+ Style_Fill::FILL_PATTERN_DARKHORIZONTAL => 0x05,
+ Style_Fill::FILL_PATTERN_DARKVERTICAL => 0x06,
+ Style_Fill::FILL_PATTERN_DARKDOWN => 0x07,
+ Style_Fill::FILL_PATTERN_DARKUP => 0x08,
+ Style_Fill::FILL_PATTERN_DARKGRID => 0x09,
+ Style_Fill::FILL_PATTERN_DARKTRELLIS => 0x0A,
+ Style_Fill::FILL_PATTERN_LIGHTHORIZONTAL => 0x0B,
+ Style_Fill::FILL_PATTERN_LIGHTVERTICAL => 0x0C,
+ Style_Fill::FILL_PATTERN_LIGHTDOWN => 0x0D,
+ Style_Fill::FILL_PATTERN_LIGHTUP => 0x0E,
+ Style_Fill::FILL_PATTERN_LIGHTGRID => 0x0F,
+ Style_Fill::FILL_PATTERN_LIGHTTRELLIS => 0x10,
+ Style_Fill::FILL_PATTERN_GRAY125 => 0x11,
+ Style_Fill::FILL_PATTERN_GRAY0625 => 0x12,
+ Style_Fill::FILL_GRADIENT_LINEAR => 0x00, // does not exist in BIFF8
+ Style_Fill::FILL_GRADIENT_PATH => 0x00, // does not exist in BIFF8
+ );
+ /**
+ * Map fill type
+ *
+ * @param string $fillType
+ * @return int
+ */
+ private static function _mapFillType($fillType) {
+ if (isset(self::$_mapFillType[$fillType]))
+ return self::$_mapFillType[$fillType];
+ return 0x00;
+ }
- /**
- * Map of BIFF2-BIFF8 codes for horizontal alignment
- * @static array of int
- *
- */
- private static $_mapHAlign = array( Style_Alignment::HORIZONTAL_GENERAL => 0,
- Style_Alignment::HORIZONTAL_LEFT => 1,
- Style_Alignment::HORIZONTAL_CENTER => 2,
- Style_Alignment::HORIZONTAL_RIGHT => 3,
- Style_Alignment::HORIZONTAL_JUSTIFY => 5,
- Style_Alignment::HORIZONTAL_CENTER_CONTINUOUS => 6,
- );
- /**
- * Map to BIFF2-BIFF8 codes for horizontal alignment
- *
- * @param string $hAlign
- * @return int
- */
- private function _mapHAlign($hAlign)
- {
- if (isset(self::$_mapHAlign[$hAlign]))
- return self::$_mapHAlign[$hAlign];
- return 0;
- }
+ /**
+ * Map of BIFF2-BIFF8 codes for horizontal alignment
+ * @static array of int
+ *
+ */
+ private static $_mapHAlign = array( Style_Alignment::HORIZONTAL_GENERAL => 0,
+ Style_Alignment::HORIZONTAL_LEFT => 1,
+ Style_Alignment::HORIZONTAL_CENTER => 2,
+ Style_Alignment::HORIZONTAL_RIGHT => 3,
+ Style_Alignment::HORIZONTAL_JUSTIFY => 5,
+ Style_Alignment::HORIZONTAL_CENTER_CONTINUOUS => 6,
+ );
+ /**
+ * Map to BIFF2-BIFF8 codes for horizontal alignment
+ *
+ * @param string $hAlign
+ * @return int
+ */
+ private function _mapHAlign($hAlign)
+ {
+ if (isset(self::$_mapHAlign[$hAlign]))
+ return self::$_mapHAlign[$hAlign];
+ return 0;
+ }
- /**
- * Map of BIFF2-BIFF8 codes for vertical alignment
- * @static array of int
- *
- */
- private static $_mapVAlign = array( Style_Alignment::VERTICAL_TOP => 0,
- Style_Alignment::VERTICAL_CENTER => 1,
- Style_Alignment::VERTICAL_BOTTOM => 2,
- Style_Alignment::VERTICAL_JUSTIFY => 3,
- );
- /**
- * Map to BIFF2-BIFF8 codes for vertical alignment
- *
- * @param string $vAlign
- * @return int
- */
- private static function _mapVAlign($vAlign) {
- if (isset(self::$_mapVAlign[$vAlign]))
- return self::$_mapVAlign[$vAlign];
- return 2;
- }
+ /**
+ * Map of BIFF2-BIFF8 codes for vertical alignment
+ * @static array of int
+ *
+ */
+ private static $_mapVAlign = array( Style_Alignment::VERTICAL_TOP => 0,
+ Style_Alignment::VERTICAL_CENTER => 1,
+ Style_Alignment::VERTICAL_BOTTOM => 2,
+ Style_Alignment::VERTICAL_JUSTIFY => 3,
+ );
+ /**
+ * Map to BIFF2-BIFF8 codes for vertical alignment
+ *
+ * @param string $vAlign
+ * @return int
+ */
+ private static function _mapVAlign($vAlign) {
+ if (isset(self::$_mapVAlign[$vAlign]))
+ return self::$_mapVAlign[$vAlign];
+ return 2;
+ }
- /**
- * Map to BIFF8 codes for text rotation angle
- *
- * @param int $textRotation
- * @return int
- */
- private static function _mapTextRotation($textRotation) {
- if ($textRotation >= 0) {
- return $textRotation;
- }
- if ($textRotation == -165) {
- return 255;
- }
- if ($textRotation < 0) {
- return 90 - $textRotation;
- }
- }
+ /**
+ * Map to BIFF8 codes for text rotation angle
+ *
+ * @param int $textRotation
+ * @return int
+ */
+ private static function _mapTextRotation($textRotation) {
+ if ($textRotation >= 0) {
+ return $textRotation;
+ }
+ if ($textRotation == -165) {
+ return 255;
+ }
+ if ($textRotation < 0) {
+ return 90 - $textRotation;
+ }
+ }
- /**
- * Map locked
- *
- * @param string
- * @return int
- */
- private static function _mapLocked($locked) {
- switch ($locked) {
- case Style_Protection::PROTECTION_INHERIT: return 1;
- case Style_Protection::PROTECTION_PROTECTED: return 1;
- case Style_Protection::PROTECTION_UNPROTECTED: return 0;
- default: return 1;
- }
- }
+ /**
+ * Map locked
+ *
+ * @param string
+ * @return int
+ */
+ private static function _mapLocked($locked) {
+ switch ($locked) {
+ case Style_Protection::PROTECTION_INHERIT: return 1;
+ case Style_Protection::PROTECTION_PROTECTED: return 1;
+ case Style_Protection::PROTECTION_UNPROTECTED: return 0;
+ default: return 1;
+ }
+ }
- /**
- * Map hidden
- *
- * @param string
- * @return int
- */
- private static function _mapHidden($hidden) {
- switch ($hidden) {
- case Style_Protection::PROTECTION_INHERIT: return 0;
- case Style_Protection::PROTECTION_PROTECTED: return 1;
- case Style_Protection::PROTECTION_UNPROTECTED: return 0;
- default: return 0;
- }
- }
+ /**
+ * Map hidden
+ *
+ * @param string
+ * @return int
+ */
+ private static function _mapHidden($hidden) {
+ switch ($hidden) {
+ case Style_Protection::PROTECTION_INHERIT: return 0;
+ case Style_Protection::PROTECTION_PROTECTED: return 1;
+ case Style_Protection::PROTECTION_UNPROTECTED: return 0;
+ default: return 0;
+ }
+ }
}
diff --git a/Classes/PHPExcel/Writer/Exception.php b/Classes/PHPExcel/Writer/Exception.php
index d0e0adf..47dfd28 100644
--- a/Classes/PHPExcel/Writer/Exception.php
+++ b/Classes/PHPExcel/Writer/Exception.php
@@ -21,8 +21,8 @@
* @category PHPExcel
* @package PHPExcel\Writer
* @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 Writer_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;
+ }
}
diff --git a/Classes/PHPExcel/Writer/HTML.php b/Classes/PHPExcel/Writer/HTML.php
index 55a8591..52f4a57 100644
--- a/Classes/PHPExcel/Writer/HTML.php
+++ b/Classes/PHPExcel/Writer/HTML.php
@@ -19,10 +19,10 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category PHPExcel
- * @package PHPExcel\Writer_HTML
+ * @package PHPExcel\Writer_HTML
* @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,1499 +32,1498 @@ namespace PHPExcel;
* PHPExcel\Writer_HTML
*
* @category PHPExcel
- * @package PHPExcel\Writer_HTML
+ * @package PHPExcel\Writer_HTML
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
*/
class Writer_HTML extends Writer_Abstract implements Writer_IWriter {
- /**
- * PHPExcel object
- *
- * @var PHPExcel
- */
- protected $_phpExcel;
-
- /**
- * Sheet index to write
- *
- * @var int
- */
- private $_sheetIndex = 0;
-
- /**
- * Images root
- *
- * @var string
- */
- private $_imagesRoot = '.';
-
- /**
- * embed images, or link to images
- *
- * @var boolean
- */
- private $_embedImages = FALSE;
-
- /**
- * Use inline CSS?
- *
- * @var boolean
- */
- private $_useInlineCss = false;
-
- /**
- * Array of CSS styles
- *
- * @var array
- */
- private $_cssStyles = null;
-
- /**
- * Array of column widths in points
- *
- * @var array
- */
- private $_columnWidths = null;
-
- /**
- * Default font
- *
- * @var PHPExcel\Style_Font
- */
- private $_defaultFont;
-
- /**
- * Flag whether spans have been calculated
- *
- * @var boolean
- */
- private $_spansAreCalculated = false;
-
- /**
- * Excel cells that should not be written as HTML cells
- *
- * @var array
- */
- private $_isSpannedCell = array();
-
- /**
- * Excel cells that are upper-left corner in a cell merge
- *
- * @var array
- */
- private $_isBaseCell = array();
-
- /**
- * Excel rows that should not be written as HTML rows
- *
- * @var array
- */
- private $_isSpannedRow = array();
-
- /**
- * Is the current writer creating PDF?
- *
- * @var boolean
- */
- protected $_isPdf = false;
-
- /**
- * Generate the Navigation block
- *
- * @var boolean
- */
- private $_generateSheetNavigationBlock = true;
-
- /**
- * Create a new PHPExcel\Writer_HTML
- *
- * @param PHPExcel\Workbook $phpExcel PHPExcel object
- */
- public function __construct(Workbook $phpExcel) {
- $this->_phpExcel = $phpExcel;
- $this->_defaultFont = $this->_phpExcel->getDefaultStyle()->getFont();
- }
-
- /**
- * Save PHPExcel to file
- *
- * @param string $pFilename
- * @throws PHPExcel\Writer_Exception
- */
- public function save($pFilename = null) {
- // garbage collect
- $this->_phpExcel->garbageCollect();
-
- $saveDebugLog = Calculation::getInstance($this->_phpExcel)->getDebugLog()->getWriteDebugLog();
- Calculation::getInstance($this->_phpExcel)->getDebugLog()->setWriteDebugLog(FALSE);
- $saveArrayReturnType = Calculation::getArrayReturnType();
- Calculation::setArrayReturnType(Calculation::RETURN_ARRAY_AS_VALUE);
-
- // Build CSS
- $this->buildCSS(!$this->_useInlineCss);
-
- // Open file
- $fileHandle = fopen($pFilename, 'wb+');
- if ($fileHandle === false) {
- throw new Writer_Exception("Could not open file $pFilename for writing.");
- }
-
- // Write headers
- fwrite($fileHandle, $this->generateHTMLHeader(!$this->_useInlineCss));
-
- // Write navigation (tabs)
- if ((!$this->_isPdf) && ($this->_generateSheetNavigationBlock)) {
- fwrite($fileHandle, $this->generateNavigation());
- }
-
- // Write data
- fwrite($fileHandle, $this->generateSheetData());
-
- // Write footer
- fwrite($fileHandle, $this->generateHTMLFooter());
-
- // Close file
- fclose($fileHandle);
-
- Calculation::setArrayReturnType($saveArrayReturnType);
- Calculation::getInstance($this->_phpExcel)->getDebugLog()->setWriteDebugLog($saveDebugLog);
- }
-
- /**
- * Map VAlign
- *
- * @param string $vAlign Vertical alignment
- * @return string
- */
- private function _mapVAlign($vAlign) {
- switch ($vAlign) {
- case Style_Alignment::VERTICAL_BOTTOM: return 'bottom';
- case Style_Alignment::VERTICAL_TOP: return 'top';
- case Style_Alignment::VERTICAL_CENTER:
- case Style_Alignment::VERTICAL_JUSTIFY: return 'middle';
- default: return 'baseline';
- }
- }
-
- /**
- * Map HAlign
- *
- * @param string $hAlign Horizontal alignment
- * @return string|false
- */
- private function _mapHAlign($hAlign) {
- switch ($hAlign) {
- case Style_Alignment::HORIZONTAL_GENERAL: return false;
- case Style_Alignment::HORIZONTAL_LEFT: return 'left';
- case Style_Alignment::HORIZONTAL_RIGHT: return 'right';
- case Style_Alignment::HORIZONTAL_CENTER:
- case Style_Alignment::HORIZONTAL_CENTER_CONTINUOUS: return 'center';
- case Style_Alignment::HORIZONTAL_JUSTIFY: return 'justify';
- default: return false;
- }
- }
-
- /**
- * Map border style
- *
- * @param int $borderStyle Sheet index
- * @return string
- */
- private function _mapBorderStyle($borderStyle) {
- switch ($borderStyle) {
- case Style_Border::BORDER_NONE: return 'none';
- case Style_Border::BORDER_DASHDOT: return '1px dashed';
- case Style_Border::BORDER_DASHDOTDOT: return '1px dotted';
- case Style_Border::BORDER_DASHED: return '1px dashed';
- case Style_Border::BORDER_DOTTED: return '1px dotted';
- case Style_Border::BORDER_DOUBLE: return '3px double';
- case Style_Border::BORDER_HAIR: return '1px solid';
- case Style_Border::BORDER_MEDIUM: return '2px solid';
- case Style_Border::BORDER_MEDIUMDASHDOT: return '2px dashed';
- case Style_Border::BORDER_MEDIUMDASHDOTDOT: return '2px dotted';
- case Style_Border::BORDER_MEDIUMDASHED: return '2px dashed';
- case Style_Border::BORDER_SLANTDASHDOT: return '2px dashed';
- case Style_Border::BORDER_THICK: return '3px solid';
- case Style_Border::BORDER_THIN: return '1px solid';
- default: return '1px solid'; // map others to thin
- }
- }
-
- /**
- * Get sheet index
- *
- * @return int
- */
- public function getSheetIndex() {
- return $this->_sheetIndex;
- }
-
- /**
- * Set sheet index
- *
- * @param int $pValue Sheet index
- * @return PHPExcel\Writer_HTML
- */
- public function setSheetIndex($pValue = 0) {
- $this->_sheetIndex = $pValue;
- return $this;
- }
-
- /**
- * Get sheet index
- *
- * @return boolean
- */
- public function getGenerateSheetNavigationBlock() {
- return $this->_generateSheetNavigationBlock;
- }
-
- /**
- * Set sheet index
- *
- * @param boolean $pValue Flag indicating whether the sheet navigation block should be generated or not
- * @return PHPExcel\Writer_HTML
- */
- public function setGenerateSheetNavigationBlock($pValue = true) {
- $this->_generateSheetNavigationBlock = (bool) $pValue;
- return $this;
- }
-
- /**
- * Write all sheets (resets sheetIndex to NULL)
- */
- public function writeAllSheets() {
- $this->_sheetIndex = null;
- return $this;
- }
-
- /**
- * Generate HTML header
- *
- * @param boolean $pIncludeStyles Include styles?
- * @return string
- * @throws PHPExcel\Writer_Exception
- */
- public function generateHTMLHeader($pIncludeStyles = false) {
- // PHPExcel object known?
- if (is_null($this->_phpExcel)) {
- throw new Writer_Exception('Internal PHPExcel object not set to an instance of an object.');
- }
-
- // Construct HTML
- $properties = $this->_phpExcel->getProperties();
- $html = '' . PHP_EOL;
- $html .= '' . PHP_EOL;
- $html .= '' . PHP_EOL;
- $html .= ' ' . PHP_EOL;
- $html .= ' ' . PHP_EOL;
- if ($properties->getTitle() > '')
- $html .= ' ';
- for ($col = 'A'; $col != $colMax; ++$col) {
- $html .= ' ';
- }
- return $html;
- }
-
-
- /**
- * Generate image tag in cell
- *
- * @param PHPExcel\Worksheet $pSheet PHPExcel Worksheet
- * @param string $coordinates Cell coordinates
- * @return string
- * @throws PHPExcel\Writer_Exception
- */
- private function _writeImageInCell(Worksheet $pSheet, $coordinates) {
- // Construct HTML
- $html = '';
-
- // Write images
- foreach ($pSheet->getDrawingCollection() as $drawing) {
- if ($drawing instanceof Worksheet_Drawing) {
- if ($drawing->getCoordinates() == $coordinates) {
- $filename = $drawing->getPath();
-
- // Strip off eventual '.'
- if (substr($filename, 0, 1) == '.') {
- $filename = substr($filename, 1);
- }
-
- // Prepend images root
- $filename = $this->getImagesRoot() . $filename;
-
- // Strip off eventual '.'
- if (substr($filename, 0, 1) == '.' && substr($filename, 0, 2) != './') {
- $filename = substr($filename, 1);
- }
-
- // Convert UTF8 data to PCDATA
- $filename = htmlspecialchars($filename);
-
- $html .= PHP_EOL;
- if ((!$this->_embedImages) || ($this->_isPdf)) {
- $imageData = $filename;
- } else {
- $imageDetails = getimagesize($filename);
- if ($fp = fopen($filename,"rb", 0)) {
- $picture = fread($fp,filesize($filename));
- fclose($fp);
- // base64 encode the binary data, then break it
- // into chunks according to RFC 2045 semantics
- $base64 = chunk_split(base64_encode($picture));
- $imageData = 'data:'.$imageDetails['mime'].';base64,' . $base64;
- } else {
- $imageData = $filename;
- }
- }
-
- $html .= '';
- $html .= $this->_writeImageInCell($pSheet, $col.$row);
- if ($this->_includeCharts) {
- $html .= $this->_writeChartInCell($pSheet, $col.$row);
- }
- $html .= ' ';
- }
- ++$row;
- $html .= '' . PHP_EOL;
- } else {
- $style = isset($this->_cssStyles['table']) ?
- $this->_assembleCSS($this->_cssStyles['table']) : '';
-
- if ($this->_isPdf && $pSheet->getShowGridLines()) {
- $html .= '
' . PHP_EOL;
- } else {
- $html .= '
- $html .= $this->_generateTableFooter();
-
- // insert page break
- $html .= '';
-
- // open table again: ' . PHP_EOL;
- }
- }
-
- // Write
' . PHP_EOL;
-
- // Return
- return $html;
- }
-
- /**
- * Generate row
- *
- * @param PHPExcel\Worksheet $pSheet Worksheet
- * @param array $pValues Array containing cells in a row
- * @param int $pRow Row number (0-based)
- * @return string
- * @throws PHPExcel\Writer_Exception
- */
- private function _generateRow(Worksheet $pSheet, $pValues = null, $pRow = 0) {
- if (is_array($pValues)) {
- // Construct HTML
- $html = '';
-
- // Sheet index
- $sheetIndex = $pSheet->getParent()->getIndex($pSheet);
-
- // DomPDF and breaks
- if ($this->_isPdf && count($pSheet->getBreaks()) > 0) {
- $breaks = $pSheet->getBreaks();
-
- // check if a break is needed before this row
- if (isset($breaks['A' . $pRow])) {
- // close table: +
' . PHP_EOL;
- } else {
- $style = isset($this->_cssStyles['table.sheet' . $sheetIndex . ' tr.row' . $pRow])
- ? $this->_assembleCSS($this->_cssStyles['table.sheet' . $sheetIndex . ' tr.row' . $pRow]) : '';
-
- $html .= ' ' . PHP_EOL;
- }
-
- // Write cells
- $colNum = 0;
- foreach ($pValues as $cell) {
- $coordinate = Cell::stringFromColumnIndex($colNum) . ($pRow + 1);
-
- if (!$this->_useInlineCss) {
- $cssClass = '';
- $cssClass = 'column' . $colNum;
- } else {
- $cssClass = array();
- if (isset($this->_cssStyles['table.sheet' . $sheetIndex . ' td.column' . $colNum])) {
- $this->_cssStyles['table.sheet' . $sheetIndex . ' td.column' . $colNum];
- }
- }
- $colSpan = 1;
- $rowSpan = 1;
-
- // initialize
- $cellData = ' ';
-
- // PHPExcel Cell
- if ($cell instanceof Cell) {
- $cellData = '';
- if (is_null($cell->getParent())) {
- $cell->attach($pSheet);
- }
- // Value
- if ($cell->getValue() instanceof RichText) {
- // Loop through rich text elements
- $elements = $cell->getValue()->getRichTextElements();
- foreach ($elements as $element) {
- // Rich text start?
- if ($element instanceof RichText_Run) {
- $cellData .= '';
-
- if ($element->getFont()->getSuperScript()) {
- $cellData .= '';
- } else if ($element->getFont()->getSubScript()) {
- $cellData .= '';
- }
- }
-
- // Convert UTF8 data to PCDATA
- $cellText = $element->getText();
- $cellData .= htmlspecialchars($cellText);
-
- if ($element instanceof RichText_Run) {
- if ($element->getFont()->getSuperScript()) {
- $cellData .= '';
- } else if ($element->getFont()->getSubScript()) {
- $cellData .= '';
- }
-
- $cellData .= '';
- }
- }
- } else {
- if ($this->_preCalculateFormulas) {
- $cellData = Style_NumberFormat::toFormattedString(
- $cell->getCalculatedValue(),
- $pSheet->getParent()->getCellXfByIndex( $cell->getXfIndex() )->getNumberFormat()->getFormatCode(),
- array($this, 'formatColor')
- );
- } else {
- $cellData = Style_NumberFormat::ToFormattedString(
- $cell->getValue(),
- $pSheet->getParent()->getCellXfByIndex( $cell->getXfIndex() )->getNumberFormat()->getFormatCode(),
- array($this, 'formatColor')
- );
- }
- $cellData = htmlspecialchars($cellData);
- if ($pSheet->getParent()->getCellXfByIndex( $cell->getXfIndex() )->getFont()->getSuperScript()) {
- $cellData = ''.$cellData.'';
- } elseif ($pSheet->getParent()->getCellXfByIndex( $cell->getXfIndex() )->getFont()->getSubScript()) {
- $cellData = ''.$cellData.'';
- }
- }
-
- // Converts the cell content so that spaces occuring at beginning of each new line are replaced by
- // Example: " Hello\n to the world" is converted to " Hello\n to the world"
- $cellData = preg_replace("/(?m)(?:^|\\G) /", ' ', $cellData);
-
- // convert newline "\n" to '
'
- $cellData = nl2br($cellData);
-
- // Extend CSS class?
- if (!$this->_useInlineCss) {
- $cssClass .= ' style' . $cell->getXfIndex();
- $cssClass .= ' ' . $cell->getDataType();
- } else {
- if (isset($this->_cssStyles['td.style' . $cell->getXfIndex()])) {
- $cssClass = array_merge($cssClass, $this->_cssStyles['td.style' . $cell->getXfIndex()]);
- }
-
- // General horizontal alignment: Actual horizontal alignment depends on dataType
- $sharedStyle = $pSheet->getParent()->getCellXfByIndex( $cell->getXfIndex() );
- if ($sharedStyle->getAlignment()->getHorizontal() == Style_Alignment::HORIZONTAL_GENERAL
- && isset($this->_cssStyles['.' . $cell->getDataType()]['text-align']))
- {
- $cssClass['text-align'] = $this->_cssStyles['.' . $cell->getDataType()]['text-align'];
- }
- }
- }
-
- // Hyperlink?
- if ($pSheet->hyperlinkExists($coordinate) && !$pSheet->getHyperlink($coordinate)->isInternal()) {
- $cellData = '' . $cellData . '';
- }
-
- // Should the cell be written or is it swallowed by a rowspan or colspan?
- $writeCell = ! ( isset($this->_isSpannedCell[$pSheet->getParent()->getIndex($pSheet)][$pRow + 1][$colNum])
- && $this->_isSpannedCell[$pSheet->getParent()->getIndex($pSheet)][$pRow + 1][$colNum] );
-
- // Colspan and Rowspan
- $colspan = 1;
- $rowspan = 1;
- if (isset($this->_isBaseCell[$pSheet->getParent()->getIndex($pSheet)][$pRow + 1][$colNum])) {
- $spans = $this->_isBaseCell[$pSheet->getParent()->getIndex($pSheet)][$pRow + 1][$colNum];
- $rowSpan = $spans['rowspan'];
- $colSpan = $spans['colspan'];
-
- // Also apply style from last cell in merge to fix borders -
- // relies on !important for non-none border declarations in _createCSSStyleBorder
- $endCellCoord = Cell::stringFromColumnIndex($colNum + $colSpan - 1) . ($pRow + $rowSpan);
- if (!$this->_useInlineCss) {
- $cssClass .= ' style' . $pSheet->getCell($endCellCoord)->getXfIndex();
- }
- }
-
- // Write
- if ($writeCell) {
- // Column start
- $html .= ' _useInlineCss) {
- $html .= ' class="' . $cssClass . '"';
- } else {
- //** Necessary redundant code for the sake of PHPExcel\Writer_PDF **
- // We must explicitly write the width of the element because TCPDF
- // does not recognize e.g. element because TCPDF
- // does not recognize e.g.
- if (isset($this->_cssStyles['table.sheet' . $sheetIndex . ' tr.row' . $pRow]['height'])) {
- $height = $this->_cssStyles['table.sheet' . $sheetIndex . ' tr.row' . $pRow]['height'];
- $cssClass['height'] = $height;
- }
- //** end of redundant code **
-
- $html .= ' style="' . $this->_assembleCSS($cssClass) . '"';
- }
- if ($colSpan > 1) {
- $html .= ' colspan="' . $colSpan . '"';
- }
- if ($rowSpan > 1) {
- $html .= ' rowspan="' . $rowSpan . '"';
- }
- $html .= '>';
-
- // Image?
- $html .= $this->_writeImageInCell($pSheet, $coordinate);
-
- // Chart?
- if ($this->_includeCharts) {
- $html .= $this->_writeChartInCell($pSheet, $coordinate);
- }
-
- // Cell data
- $html .= $cellData;
-
- // Column end
- $html .= '' . PHP_EOL;
- }
-
- // Next column
- ++$colNum;
- }
-
- // Write row end
- $html .= ' ' . PHP_EOL;
-
- // Return
- return $html;
- } else {
- throw new Writer_Exception("Invalid parameters passed.");
- }
- }
-
- /**
- * Takes array where of CSS properties / values and converts to CSS string
- *
- * @param array
- * @return string
- */
- private function _assembleCSS($pValue = array())
- {
- $pairs = array();
- foreach ($pValue as $property => $value) {
- $pairs[] = $property . ':' . $value;
- }
- $string = implode('; ', $pairs);
-
- return $string;
- }
-
- /**
- * Get images root
- *
- * @return string
- */
- public function getImagesRoot() {
- return $this->_imagesRoot;
- }
-
- /**
- * Set images root
- *
- * @param string $pValue
- * @return PHPExcel\Writer_HTML
- */
- public function setImagesRoot($pValue = '.') {
- $this->_imagesRoot = $pValue;
- return $this;
- }
-
- /**
- * Get embed images
- *
- * @return boolean
- */
- public function getEmbedImages() {
- return $this->_embedImages;
- }
-
- /**
- * Set embed images
- *
- * @param boolean $pValue
- * @return PHPExcel\Writer_HTML
- */
- public function setEmbedImages($pValue = '.') {
- $this->_embedImages = $pValue;
- return $this;
- }
-
- /**
- * Get use inline CSS?
- *
- * @return boolean
- */
- public function getUseInlineCss() {
- return $this->_useInlineCss;
- }
-
- /**
- * Set use inline CSS?
- *
- * @param boolean $pValue
- * @return PHPExcel\Writer_HTML
- */
- public function setUseInlineCss($pValue = false) {
- $this->_useInlineCss = $pValue;
- return $this;
- }
-
- /**
- * Add color to formatted string as inline style
- *
- * @param string $pValue Plain formatted value without color
- * @param string $pFormat Format code
- * @return string
- */
- public function formatColor($pValue, $pFormat)
- {
- // Color information, e.g. [Red] is always at the beginning
- $color = null; // initialize
- $matches = array();
-
- $color_regex = '/^\\[[a-zA-Z]+\\]/';
- if (preg_match($color_regex, $pFormat, $matches)) {
- $color = str_replace('[', '', $matches[0]);
- $color = str_replace(']', '', $color);
- $color = strtolower($color);
- }
-
- // convert to PCDATA
- $value = htmlspecialchars($pValue);
-
- // color span tag
- if ($color !== null) {
- $value = '' . $value . '';
- }
-
- return $value;
- }
-
- /**
- * Calculate information about HTML colspan and rowspan which is not always the same as Excel's
- */
- private function _calculateSpans()
- {
- // Identify all cells that should be omitted in HTML due to cell merge.
- // In HTML only the upper-left cell should be written and it should have
- // appropriate rowspan / colspan attribute
- $sheetIndexes = $this->_sheetIndex !== null ?
- array($this->_sheetIndex) : range(0, $this->_phpExcel->getSheetCount() - 1);
-
- foreach ($sheetIndexes as $sheetIndex) {
- $sheet = $this->_phpExcel->getSheet($sheetIndex);
-
- $candidateSpannedRow = array();
-
- // loop through all Excel merged cells
- foreach ($sheet->getMergeCells() as $cells) {
- list($cells, ) = Cell::splitRange($cells);
- $first = $cells[0];
- $last = $cells[1];
-
- list($fc, $fr) = Cell::coordinateFromString($first);
- $fc = Cell::columnIndexFromString($fc) - 1;
-
- list($lc, $lr) = Cell::coordinateFromString($last);
- $lc = Cell::columnIndexFromString($lc) - 1;
-
- // loop through the individual cells in the individual merge
- $r = $fr - 1;
- while($r++ < $lr) {
- // also, flag this row as a HTML row that is candidate to be omitted
- $candidateSpannedRow[$r] = $r;
-
- $c = $fc - 1;
- while($c++ < $lc) {
- if ( !($c == $fc && $r == $fr) ) {
- // not the upper-left cell (should not be written in HTML)
- $this->_isSpannedCell[$sheetIndex][$r][$c] = array(
- 'baseCell' => array($fr, $fc),
- );
- } else {
- // upper-left is the base cell that should hold the colspan/rowspan attribute
- $this->_isBaseCell[$sheetIndex][$r][$c] = array(
- 'xlrowspan' => $lr - $fr + 1, // Excel rowspan
- 'rowspan' => $lr - $fr + 1, // HTML rowspan, value may change
- 'xlcolspan' => $lc - $fc + 1, // Excel colspan
- 'colspan' => $lc - $fc + 1, // HTML colspan, value may change
- );
- }
- }
- }
- }
-
- // Identify which rows should be omitted in HTML. These are the rows where all the cells
- // participate in a merge and the where base cells are somewhere above.
- $countColumns = Cell::columnIndexFromString($sheet->getHighestColumn());
- foreach ($candidateSpannedRow as $rowIndex) {
- if (isset($this->_isSpannedCell[$sheetIndex][$rowIndex])) {
- if (count($this->_isSpannedCell[$sheetIndex][$rowIndex]) == $countColumns) {
- $this->_isSpannedRow[$sheetIndex][$rowIndex] = $rowIndex;
- };
- }
- }
-
- // For each of the omitted rows we found above, the affected rowspans should be subtracted by 1
- if ( isset($this->_isSpannedRow[$sheetIndex]) ) {
- foreach ($this->_isSpannedRow[$sheetIndex] as $rowIndex) {
- $adjustedBaseCells = array();
- $c = -1;
- $e = $countColumns - 1;
- while($c++ < $e) {
- $baseCell = $this->_isSpannedCell[$sheetIndex][$rowIndex][$c]['baseCell'];
-
- if ( !in_array($baseCell, $adjustedBaseCells) ) {
- // subtract rowspan by 1
- --$this->_isBaseCell[$sheetIndex][ $baseCell[0] ][ $baseCell[1] ]['rowspan'];
- $adjustedBaseCells[] = $baseCell;
- }
- }
- }
- }
-
- // TODO: Same for columns
- }
-
- // We have calculated the spans
- $this->_spansAreCalculated = true;
- }
-
- private function _setMargins(Worksheet $pSheet) {
- $htmlPage = '@page { ';
- $htmlBody = 'body { ';
-
- $left = Shared_String::FormatNumber($pSheet->getPageMargins()->getLeft()) . 'in; ';
- $htmlPage .= 'left-margin: ' . $left;
- $htmlBody .= 'left-margin: ' . $left;
- $right = Shared_String::FormatNumber($pSheet->getPageMargins()->getRight()) . 'in; ';
- $htmlPage .= 'right-margin: ' . $right;
- $htmlBody .= 'right-margin: ' . $right;
- $top = Shared_String::FormatNumber($pSheet->getPageMargins()->getTop()) . 'in; ';
- $htmlPage .= 'top-margin: ' . $top;
- $htmlBody .= 'top-margin: ' . $top;
- $bottom = Shared_String::FormatNumber($pSheet->getPageMargins()->getBottom()) . 'in; ';
- $htmlPage .= 'bottom-margin: ' . $bottom;
- $htmlBody .= 'bottom-margin: ' . $bottom;
-
- $htmlPage .= "}\n";
- $htmlBody .= "}\n";
-
- return "\n";
- }
-
+ /**
+ * PHPExcel object
+ *
+ * @var PHPExcel
+ */
+ protected $_phpExcel;
+
+ /**
+ * Sheet index to write
+ *
+ * @var int
+ */
+ private $_sheetIndex = 0;
+
+ /**
+ * Images root
+ *
+ * @var string
+ */
+ private $_imagesRoot = '.';
+
+ /**
+ * embed images, or link to images
+ *
+ * @var boolean
+ */
+ private $_embedImages = false;
+
+ /**
+ * Use inline CSS?
+ *
+ * @var boolean
+ */
+ private $_useInlineCss = false;
+
+ /**
+ * Array of CSS styles
+ *
+ * @var array
+ */
+ private $_cssStyles = null;
+
+ /**
+ * Array of column widths in points
+ *
+ * @var array
+ */
+ private $_columnWidths = null;
+
+ /**
+ * Default font
+ *
+ * @var PHPExcel\Style_Font
+ */
+ private $_defaultFont;
+
+ /**
+ * Flag whether spans have been calculated
+ *
+ * @var boolean
+ */
+ private $_spansAreCalculated = false;
+
+ /**
+ * Excel cells that should not be written as HTML cells
+ *
+ * @var array
+ */
+ private $_isSpannedCell = array();
+
+ /**
+ * Excel cells that are upper-left corner in a cell merge
+ *
+ * @var array
+ */
+ private $_isBaseCell = array();
+
+ /**
+ * Excel rows that should not be written as HTML rows
+ *
+ * @var array
+ */
+ private $_isSpannedRow = array();
+
+ /**
+ * Is the current writer creating PDF?
+ *
+ * @var boolean
+ */
+ protected $_isPdf = false;
+
+ /**
+ * Generate the Navigation block
+ *
+ * @var boolean
+ */
+ private $_generateSheetNavigationBlock = true;
+
+ /**
+ * Create a new PHPExcel\Writer_HTML
+ *
+ * @param PHPExcel\Workbook $phpExcel PHPExcel object
+ */
+ public function __construct(Workbook $phpExcel) {
+ $this->_phpExcel = $phpExcel;
+ $this->_defaultFont = $this->_phpExcel->getDefaultStyle()->getFont();
+ }
+
+ /**
+ * Save PHPExcel to file
+ *
+ * @param string $pFilename
+ * @throws PHPExcel\Writer_Exception
+ */
+ public function save($pFilename = null) {
+ // garbage collect
+ $this->_phpExcel->garbageCollect();
+
+ $saveDebugLog = Calculation::getInstance($this->_phpExcel)->getDebugLog()->getWriteDebugLog();
+ Calculation::getInstance($this->_phpExcel)->getDebugLog()->setWriteDebugLog(false);
+ $saveArrayReturnType = Calculation::getArrayReturnType();
+ Calculation::setArrayReturnType(Calculation::RETURN_ARRAY_AS_VALUE);
+
+ // Build CSS
+ $this->buildCSS(!$this->_useInlineCss);
+
+ // Open file
+ $fileHandle = fopen($pFilename, 'wb+');
+ if ($fileHandle === false) {
+ throw new Writer_Exception("Could not open file $pFilename for writing.");
+ }
+
+ // Write headers
+ fwrite($fileHandle, $this->generateHTMLHeader(!$this->_useInlineCss));
+
+ // Write navigation (tabs)
+ if ((!$this->_isPdf) && ($this->_generateSheetNavigationBlock)) {
+ fwrite($fileHandle, $this->generateNavigation());
+ }
+
+ // Write data
+ fwrite($fileHandle, $this->generateSheetData());
+
+ // Write footer
+ fwrite($fileHandle, $this->generateHTMLFooter());
+
+ // Close file
+ fclose($fileHandle);
+
+ Calculation::setArrayReturnType($saveArrayReturnType);
+ Calculation::getInstance($this->_phpExcel)->getDebugLog()->setWriteDebugLog($saveDebugLog);
+ }
+
+ /**
+ * Map VAlign
+ *
+ * @param string $vAlign Vertical alignment
+ * @return string
+ */
+ private function _mapVAlign($vAlign) {
+ switch ($vAlign) {
+ case Style_Alignment::VERTICAL_BOTTOM: return 'bottom';
+ case Style_Alignment::VERTICAL_TOP: return 'top';
+ case Style_Alignment::VERTICAL_CENTER:
+ case Style_Alignment::VERTICAL_JUSTIFY: return 'middle';
+ default: return 'baseline';
+ }
+ }
+
+ /**
+ * Map HAlign
+ *
+ * @param string $hAlign Horizontal alignment
+ * @return string|false
+ */
+ private function _mapHAlign($hAlign) {
+ switch ($hAlign) {
+ case Style_Alignment::HORIZONTAL_GENERAL: return false;
+ case Style_Alignment::HORIZONTAL_LEFT: return 'left';
+ case Style_Alignment::HORIZONTAL_RIGHT: return 'right';
+ case Style_Alignment::HORIZONTAL_CENTER:
+ case Style_Alignment::HORIZONTAL_CENTER_CONTINUOUS: return 'center';
+ case Style_Alignment::HORIZONTAL_JUSTIFY: return 'justify';
+ default: return false;
+ }
+ }
+
+ /**
+ * Map border style
+ *
+ * @param int $borderStyle Sheet index
+ * @return string
+ */
+ private function _mapBorderStyle($borderStyle) {
+ switch ($borderStyle) {
+ case Style_Border::BORDER_NONE: return 'none';
+ case Style_Border::BORDER_DASHDOT: return '1px dashed';
+ case Style_Border::BORDER_DASHDOTDOT: return '1px dotted';
+ case Style_Border::BORDER_DASHED: return '1px dashed';
+ case Style_Border::BORDER_DOTTED: return '1px dotted';
+ case Style_Border::BORDER_DOUBLE: return '3px double';
+ case Style_Border::BORDER_HAIR: return '1px solid';
+ case Style_Border::BORDER_MEDIUM: return '2px solid';
+ case Style_Border::BORDER_MEDIUMDASHDOT: return '2px dashed';
+ case Style_Border::BORDER_MEDIUMDASHDOTDOT: return '2px dotted';
+ case Style_Border::BORDER_MEDIUMDASHED: return '2px dashed';
+ case Style_Border::BORDER_SLANTDASHDOT: return '2px dashed';
+ case Style_Border::BORDER_THICK: return '3px solid';
+ case Style_Border::BORDER_THIN: return '1px solid';
+ default: return '1px solid'; // map others to thin
+ }
+ }
+
+ /**
+ * Get sheet index
+ *
+ * @return int
+ */
+ public function getSheetIndex() {
+ return $this->_sheetIndex;
+ }
+
+ /**
+ * Set sheet index
+ *
+ * @param int $pValue Sheet index
+ * @return PHPExcel\Writer_HTML
+ */
+ public function setSheetIndex($pValue = 0) {
+ $this->_sheetIndex = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get sheet index
+ *
+ * @return boolean
+ */
+ public function getGenerateSheetNavigationBlock() {
+ return $this->_generateSheetNavigationBlock;
+ }
+
+ /**
+ * Set sheet index
+ *
+ * @param boolean $pValue Flag indicating whether the sheet navigation block should be generated or not
+ * @return PHPExcel\Writer_HTML
+ */
+ public function setGenerateSheetNavigationBlock($pValue = true) {
+ $this->_generateSheetNavigationBlock = (bool) $pValue;
+ return $this;
+ }
+
+ /**
+ * Write all sheets (resets sheetIndex to null)
+ */
+ public function writeAllSheets() {
+ $this->_sheetIndex = null;
+ return $this;
+ }
+
+ /**
+ * Generate HTML header
+ *
+ * @param boolean $pIncludeStyles Include styles?
+ * @return string
+ * @throws PHPExcel\Writer_Exception
+ */
+ public function generateHTMLHeader($pIncludeStyles = false) {
+ // PHPExcel object known?
+ if (is_null($this->_phpExcel)) {
+ throw new Writer_Exception('Internal PHPExcel object not set to an instance of an object.');
+ }
+
+ // Construct HTML
+ $properties = $this->_phpExcel->getProperties();
+ $html = '' . PHP_EOL;
+ $html .= '' . PHP_EOL;
+ $html .= '' . PHP_EOL;
+ $html .= ' ' . PHP_EOL;
+ $html .= ' ' . PHP_EOL;
+ if ($properties->getTitle() > '')
+ $html .= ' ';
+ for ($col = 'A'; $col != $colMax; ++$col) {
+ $html .= ' ';
+ }
+ return $html;
+ }
+
+
+ /**
+ * Generate image tag in cell
+ *
+ * @param PHPExcel\Worksheet $pSheet PHPExcel Worksheet
+ * @param string $coordinates Cell coordinates
+ * @return string
+ * @throws PHPExcel\Writer_Exception
+ */
+ private function _writeImageInCell(Worksheet $pSheet, $coordinates) {
+ // Construct HTML
+ $html = '';
+
+ // Write images
+ foreach ($pSheet->getDrawingCollection() as $drawing) {
+ if ($drawing instanceof Worksheet_Drawing) {
+ if ($drawing->getCoordinates() == $coordinates) {
+ $filename = $drawing->getPath();
+
+ // Strip off eventual '.'
+ if (substr($filename, 0, 1) == '.') {
+ $filename = substr($filename, 1);
+ }
+
+ // Prepend images root
+ $filename = $this->getImagesRoot() . $filename;
+
+ // Strip off eventual '.'
+ if (substr($filename, 0, 1) == '.' && substr($filename, 0, 2) != './') {
+ $filename = substr($filename, 1);
+ }
+
+ // Convert UTF8 data to PCDATA
+ $filename = htmlspecialchars($filename);
+
+ $html .= PHP_EOL;
+ if ((!$this->_embedImages) || ($this->_isPdf)) {
+ $imageData = $filename;
+ } else {
+ $imageDetails = getimagesize($filename);
+ if ($fp = fopen($filename,"rb", 0)) {
+ $picture = fread($fp,filesize($filename));
+ fclose($fp);
+ // base64 encode the binary data, then break it
+ // into chunks according to RFC 2045 semantics
+ $base64 = chunk_split(base64_encode($picture));
+ $imageData = 'data:'.$imageDetails['mime'].';base64,' . $base64;
+ } else {
+ $imageData = $filename;
+ }
+ }
+
+ $html .= '';
+ $html .= $this->_writeImageInCell($pSheet, $col.$row);
+ if ($this->_includeCharts) {
+ $html .= $this->_writeChartInCell($pSheet, $col.$row);
+ }
+ $html .= ' ';
+ }
+ ++$row;
+ $html .= '' . PHP_EOL;
+ } else {
+ $style = isset($this->_cssStyles['table']) ?
+ $this->_assembleCSS($this->_cssStyles['table']) : '';
+
+ if ($this->_isPdf && $pSheet->getShowGridLines()) {
+ $html .= '
' . PHP_EOL;
+ } else {
+ $html .= '
+ $html .= $this->_generateTableFooter();
+
+ // insert page break
+ $html .= '';
+
+ // open table again: ' . PHP_EOL;
+ }
+ }
+
+ // Write
' . PHP_EOL;
+
+ // Return
+ return $html;
+ }
+
+ /**
+ * Generate row
+ *
+ * @param PHPExcel\Worksheet $pSheet Worksheet
+ * @param array $pValues Array containing cells in a row
+ * @param int $pRow Row number (0-based)
+ * @return string
+ * @throws PHPExcel\Writer_Exception
+ */
+ private function _generateRow(Worksheet $pSheet, $pValues = null, $pRow = 0) {
+ if (is_array($pValues)) {
+ // Construct HTML
+ $html = '';
+
+ // Sheet index
+ $sheetIndex = $pSheet->getParent()->getIndex($pSheet);
+
+ // DomPDF and breaks
+ if ($this->_isPdf && count($pSheet->getBreaks()) > 0) {
+ $breaks = $pSheet->getBreaks();
+
+ // check if a break is needed before this row
+ if (isset($breaks['A' . $pRow])) {
+ // close table: +
' . PHP_EOL;
+ } else {
+ $style = isset($this->_cssStyles['table.sheet' . $sheetIndex . ' tr.row' . $pRow])
+ ? $this->_assembleCSS($this->_cssStyles['table.sheet' . $sheetIndex . ' tr.row' . $pRow]) : '';
+
+ $html .= ' ' . PHP_EOL;
+ }
+
+ // Write cells
+ $colNum = 0;
+ foreach ($pValues as $cell) {
+ $coordinate = Cell::stringFromColumnIndex($colNum) . ($pRow + 1);
+
+ if (!$this->_useInlineCss) {
+ $cssClass = '';
+ $cssClass = 'column' . $colNum;
+ } else {
+ $cssClass = array();
+ if (isset($this->_cssStyles['table.sheet' . $sheetIndex . ' td.column' . $colNum])) {
+ $this->_cssStyles['table.sheet' . $sheetIndex . ' td.column' . $colNum];
+ }
+ }
+ $colSpan = 1;
+ $rowSpan = 1;
+
+ // initialize
+ $cellData = ' ';
+
+ // PHPExcel Cell
+ if ($cell instanceof Cell) {
+ $cellData = '';
+ if (is_null($cell->getParent())) {
+ $cell->attach($pSheet);
+ }
+ // Value
+ if ($cell->getValue() instanceof RichText) {
+ // Loop through rich text elements
+ $elements = $cell->getValue()->getRichTextElements();
+ foreach ($elements as $element) {
+ // Rich text start?
+ if ($element instanceof RichText_Run) {
+ $cellData .= '';
+
+ if ($element->getFont()->getSuperScript()) {
+ $cellData .= '';
+ } else if ($element->getFont()->getSubScript()) {
+ $cellData .= '';
+ }
+ }
+
+ // Convert UTF8 data to PCDATA
+ $cellText = $element->getText();
+ $cellData .= htmlspecialchars($cellText);
+
+ if ($element instanceof RichText_Run) {
+ if ($element->getFont()->getSuperScript()) {
+ $cellData .= '';
+ } else if ($element->getFont()->getSubScript()) {
+ $cellData .= '';
+ }
+
+ $cellData .= '';
+ }
+ }
+ } else {
+ if ($this->_preCalculateFormulas) {
+ $cellData = Style_NumberFormat::toFormattedString(
+ $cell->getCalculatedValue(),
+ $pSheet->getParent()->getCellXfByIndex( $cell->getXfIndex() )->getNumberFormat()->getFormatCode(),
+ array($this, 'formatColor')
+ );
+ } else {
+ $cellData = Style_NumberFormat::ToFormattedString(
+ $cell->getValue(),
+ $pSheet->getParent()->getCellXfByIndex( $cell->getXfIndex() )->getNumberFormat()->getFormatCode(),
+ array($this, 'formatColor')
+ );
+ }
+ $cellData = htmlspecialchars($cellData);
+ if ($pSheet->getParent()->getCellXfByIndex( $cell->getXfIndex() )->getFont()->getSuperScript()) {
+ $cellData = ''.$cellData.'';
+ } elseif ($pSheet->getParent()->getCellXfByIndex( $cell->getXfIndex() )->getFont()->getSubScript()) {
+ $cellData = ''.$cellData.'';
+ }
+ }
+
+ // Converts the cell content so that spaces occuring at beginning of each new line are replaced by
+ // Example: " Hello\n to the world" is converted to " Hello\n to the world"
+ $cellData = preg_replace("/(?m)(?:^|\\G) /", ' ', $cellData);
+
+ // convert newline "\n" to '
'
+ $cellData = nl2br($cellData);
+
+ // Extend CSS class?
+ if (!$this->_useInlineCss) {
+ $cssClass .= ' style' . $cell->getXfIndex();
+ $cssClass .= ' ' . $cell->getDataType();
+ } else {
+ if (isset($this->_cssStyles['td.style' . $cell->getXfIndex()])) {
+ $cssClass = array_merge($cssClass, $this->_cssStyles['td.style' . $cell->getXfIndex()]);
+ }
+
+ // General horizontal alignment: Actual horizontal alignment depends on dataType
+ $sharedStyle = $pSheet->getParent()->getCellXfByIndex( $cell->getXfIndex() );
+ if ($sharedStyle->getAlignment()->getHorizontal() == Style_Alignment::HORIZONTAL_GENERAL
+ && isset($this->_cssStyles['.' . $cell->getDataType()]['text-align']))
+ {
+ $cssClass['text-align'] = $this->_cssStyles['.' . $cell->getDataType()]['text-align'];
+ }
+ }
+ }
+
+ // Hyperlink?
+ if ($pSheet->hyperlinkExists($coordinate) && !$pSheet->getHyperlink($coordinate)->isInternal()) {
+ $cellData = '' . $cellData . '';
+ }
+
+ // Should the cell be written or is it swallowed by a rowspan or colspan?
+ $writeCell = ! ( isset($this->_isSpannedCell[$pSheet->getParent()->getIndex($pSheet)][$pRow + 1][$colNum])
+ && $this->_isSpannedCell[$pSheet->getParent()->getIndex($pSheet)][$pRow + 1][$colNum] );
+
+ // Colspan and Rowspan
+ $colspan = 1;
+ $rowspan = 1;
+ if (isset($this->_isBaseCell[$pSheet->getParent()->getIndex($pSheet)][$pRow + 1][$colNum])) {
+ $spans = $this->_isBaseCell[$pSheet->getParent()->getIndex($pSheet)][$pRow + 1][$colNum];
+ $rowSpan = $spans['rowspan'];
+ $colSpan = $spans['colspan'];
+
+ // Also apply style from last cell in merge to fix borders -
+ // relies on !important for non-none border declarations in _createCSSStyleBorder
+ $endCellCoord = Cell::stringFromColumnIndex($colNum + $colSpan - 1) . ($pRow + $rowSpan);
+ if (!$this->_useInlineCss) {
+ $cssClass .= ' style' . $pSheet->getCell($endCellCoord)->getXfIndex();
+ }
+ }
+
+ // Write
+ if ($writeCell) {
+ // Column start
+ $html .= ' _useInlineCss) {
+ $html .= ' class="' . $cssClass . '"';
+ } else {
+ //** Necessary redundant code for the sake of PHPExcel\Writer_PDF **
+ // We must explicitly write the width of the element because TCPDF
+ // does not recognize e.g. element because TCPDF
+ // does not recognize e.g.
+ if (isset($this->_cssStyles['table.sheet' . $sheetIndex . ' tr.row' . $pRow]['height'])) {
+ $height = $this->_cssStyles['table.sheet' . $sheetIndex . ' tr.row' . $pRow]['height'];
+ $cssClass['height'] = $height;
+ }
+ //** end of redundant code **
+
+ $html .= ' style="' . $this->_assembleCSS($cssClass) . '"';
+ }
+ if ($colSpan > 1) {
+ $html .= ' colspan="' . $colSpan . '"';
+ }
+ if ($rowSpan > 1) {
+ $html .= ' rowspan="' . $rowSpan . '"';
+ }
+ $html .= '>';
+
+ // Image?
+ $html .= $this->_writeImageInCell($pSheet, $coordinate);
+
+ // Chart?
+ if ($this->_includeCharts) {
+ $html .= $this->_writeChartInCell($pSheet, $coordinate);
+ }
+
+ // Cell data
+ $html .= $cellData;
+
+ // Column end
+ $html .= '' . PHP_EOL;
+ }
+
+ // Next column
+ ++$colNum;
+ }
+
+ // Write row end
+ $html .= ' ' . PHP_EOL;
+
+ // Return
+ return $html;
+ } else {
+ throw new Writer_Exception("Invalid parameters passed.");
+ }
+ }
+
+ /**
+ * Takes array where of CSS properties / values and converts to CSS string
+ *
+ * @param array
+ * @return string
+ */
+ private function _assembleCSS($pValue = array())
+ {
+ $pairs = array();
+ foreach ($pValue as $property => $value) {
+ $pairs[] = $property . ':' . $value;
+ }
+ $string = implode('; ', $pairs);
+
+ return $string;
+ }
+
+ /**
+ * Get images root
+ *
+ * @return string
+ */
+ public function getImagesRoot() {
+ return $this->_imagesRoot;
+ }
+
+ /**
+ * Set images root
+ *
+ * @param string $pValue
+ * @return PHPExcel\Writer_HTML
+ */
+ public function setImagesRoot($pValue = '.') {
+ $this->_imagesRoot = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get embed images
+ *
+ * @return boolean
+ */
+ public function getEmbedImages() {
+ return $this->_embedImages;
+ }
+
+ /**
+ * Set embed images
+ *
+ * @param boolean $pValue
+ * @return PHPExcel\Writer_HTML
+ */
+ public function setEmbedImages($pValue = '.') {
+ $this->_embedImages = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get use inline CSS?
+ *
+ * @return boolean
+ */
+ public function getUseInlineCss() {
+ return $this->_useInlineCss;
+ }
+
+ /**
+ * Set use inline CSS?
+ *
+ * @param boolean $pValue
+ * @return PHPExcel\Writer_HTML
+ */
+ public function setUseInlineCss($pValue = false) {
+ $this->_useInlineCss = $pValue;
+ return $this;
+ }
+
+ /**
+ * Add color to formatted string as inline style
+ *
+ * @param string $pValue Plain formatted value without color
+ * @param string $pFormat Format code
+ * @return string
+ */
+ public function formatColor($pValue, $pFormat)
+ {
+ // Color information, e.g. [Red] is always at the beginning
+ $color = null; // initialize
+ $matches = array();
+
+ $color_regex = '/^\\[[a-zA-Z]+\\]/';
+ if (preg_match($color_regex, $pFormat, $matches)) {
+ $color = str_replace('[', '', $matches[0]);
+ $color = str_replace(']', '', $color);
+ $color = strtolower($color);
+ }
+
+ // convert to PCDATA
+ $value = htmlspecialchars($pValue);
+
+ // color span tag
+ if ($color !== null) {
+ $value = '' . $value . '';
+ }
+
+ return $value;
+ }
+
+ /**
+ * Calculate information about HTML colspan and rowspan which is not always the same as Excel's
+ */
+ private function _calculateSpans()
+ {
+ // Identify all cells that should be omitted in HTML due to cell merge.
+ // In HTML only the upper-left cell should be written and it should have
+ // appropriate rowspan / colspan attribute
+ $sheetIndexes = $this->_sheetIndex !== null ?
+ array($this->_sheetIndex) : range(0, $this->_phpExcel->getSheetCount() - 1);
+
+ foreach ($sheetIndexes as $sheetIndex) {
+ $sheet = $this->_phpExcel->getSheet($sheetIndex);
+
+ $candidateSpannedRow = array();
+
+ // loop through all Excel merged cells
+ foreach ($sheet->getMergeCells() as $cells) {
+ list($cells, ) = Cell::splitRange($cells);
+ $first = $cells[0];
+ $last = $cells[1];
+
+ list($fc, $fr) = Cell::coordinateFromString($first);
+ $fc = Cell::columnIndexFromString($fc) - 1;
+
+ list($lc, $lr) = Cell::coordinateFromString($last);
+ $lc = Cell::columnIndexFromString($lc) - 1;
+
+ // loop through the individual cells in the individual merge
+ $r = $fr - 1;
+ while($r++ < $lr) {
+ // also, flag this row as a HTML row that is candidate to be omitted
+ $candidateSpannedRow[$r] = $r;
+
+ $c = $fc - 1;
+ while($c++ < $lc) {
+ if ( !($c == $fc && $r == $fr) ) {
+ // not the upper-left cell (should not be written in HTML)
+ $this->_isSpannedCell[$sheetIndex][$r][$c] = array(
+ 'baseCell' => array($fr, $fc),
+ );
+ } else {
+ // upper-left is the base cell that should hold the colspan/rowspan attribute
+ $this->_isBaseCell[$sheetIndex][$r][$c] = array(
+ 'xlrowspan' => $lr - $fr + 1, // Excel rowspan
+ 'rowspan' => $lr - $fr + 1, // HTML rowspan, value may change
+ 'xlcolspan' => $lc - $fc + 1, // Excel colspan
+ 'colspan' => $lc - $fc + 1, // HTML colspan, value may change
+ );
+ }
+ }
+ }
+ }
+
+ // Identify which rows should be omitted in HTML. These are the rows where all the cells
+ // participate in a merge and the where base cells are somewhere above.
+ $countColumns = Cell::columnIndexFromString($sheet->getHighestColumn());
+ foreach ($candidateSpannedRow as $rowIndex) {
+ if (isset($this->_isSpannedCell[$sheetIndex][$rowIndex])) {
+ if (count($this->_isSpannedCell[$sheetIndex][$rowIndex]) == $countColumns) {
+ $this->_isSpannedRow[$sheetIndex][$rowIndex] = $rowIndex;
+ };
+ }
+ }
+
+ // For each of the omitted rows we found above, the affected rowspans should be subtracted by 1
+ if ( isset($this->_isSpannedRow[$sheetIndex]) ) {
+ foreach ($this->_isSpannedRow[$sheetIndex] as $rowIndex) {
+ $adjustedBaseCells = array();
+ $c = -1;
+ $e = $countColumns - 1;
+ while($c++ < $e) {
+ $baseCell = $this->_isSpannedCell[$sheetIndex][$rowIndex][$c]['baseCell'];
+
+ if ( !in_array($baseCell, $adjustedBaseCells) ) {
+ // subtract rowspan by 1
+ --$this->_isBaseCell[$sheetIndex][ $baseCell[0] ][ $baseCell[1] ]['rowspan'];
+ $adjustedBaseCells[] = $baseCell;
+ }
+ }
+ }
+ }
+
+ // TODO: Same for columns
+ }
+
+ // We have calculated the spans
+ $this->_spansAreCalculated = true;
+ }
+
+ private function _setMargins(Worksheet $pSheet) {
+ $htmlPage = '@page { ';
+ $htmlBody = 'body { ';
+
+ $left = Shared_String::FormatNumber($pSheet->getPageMargins()->getLeft()) . 'in; ';
+ $htmlPage .= 'left-margin: ' . $left;
+ $htmlBody .= 'left-margin: ' . $left;
+ $right = Shared_String::FormatNumber($pSheet->getPageMargins()->getRight()) . 'in; ';
+ $htmlPage .= 'right-margin: ' . $right;
+ $htmlBody .= 'right-margin: ' . $right;
+ $top = Shared_String::FormatNumber($pSheet->getPageMargins()->getTop()) . 'in; ';
+ $htmlPage .= 'top-margin: ' . $top;
+ $htmlBody .= 'top-margin: ' . $top;
+ $bottom = Shared_String::FormatNumber($pSheet->getPageMargins()->getBottom()) . 'in; ';
+ $htmlPage .= 'bottom-margin: ' . $bottom;
+ $htmlBody .= 'bottom-margin: ' . $bottom;
+
+ $htmlPage .= "}\n";
+ $htmlBody .= "}\n";
+
+ return "\n";
+ }
}
diff --git a/Classes/PHPExcel/Writer/IWriter.php b/Classes/PHPExcel/Writer/IWriter.php
index 36f08f6..fac4c7c 100644
--- a/Classes/PHPExcel/Writer/IWriter.php
+++ b/Classes/PHPExcel/Writer/IWriter.php
@@ -43,6 +43,5 @@ interface Writer_IWriter
* @param string $pFilename Name of the file to save
* @throws PHPExcel\Writer_Exception
*/
- public function save($pFilename = NULL);
-
+ public function save($pFilename = null);
}
diff --git a/Classes/PHPExcel/Writer/PDF.php b/Classes/PHPExcel/Writer/PDF.php
index 214f135..daa621c 100644
--- a/Classes/PHPExcel/Writer/PDF.php
+++ b/Classes/PHPExcel/Writer/PDF.php
@@ -43,7 +43,7 @@ class Writer_PDF
*
* @var PHPExcel\Writer_PDF_Core
*/
- private $_renderer = NULL;
+ private $_renderer = null;
/**
* Instantiate a new renderer of the configured type within this container class
@@ -82,11 +82,10 @@ class Writer_PDF
*/
public function __call($name, $arguments)
{
- if ($this->_renderer === NULL) {
+ if ($this->_renderer === null) {
throw new Writer_Exception("PDF Rendering library has not been defined.");
}
return call_user_func_array(array($this->_renderer, $name), $arguments);
}
-
}
diff --git a/Classes/PHPExcel/Writer/PDF/Core.php b/Classes/PHPExcel/Writer/PDF/Core.php
index af5b251..d9c93b5 100644
--- a/Classes/PHPExcel/Writer/PDF/Core.php
+++ b/Classes/PHPExcel/Writer/PDF/Core.php
@@ -42,28 +42,28 @@ abstract class Writer_PDF_Core extends Writer_HTML
*
* @var string
*/
- protected $_tempDir = '';
+ protected $tempDir = '';
/**
* Font
*
* @var string
*/
- protected $_font = 'freesans';
+ protected $font = 'freesans';
/**
* Orientation (Over-ride)
*
* @var string
*/
- protected $_orientation = NULL;
+ protected $orientation = null;
/**
* Paper size (Over-ride)
*
* @var int
*/
- protected $_paperSize = NULL;
+ protected $paperSize = null;
/**
@@ -71,14 +71,14 @@ abstract class Writer_PDF_Core extends Writer_HTML
*
* @var string
*/
- private $_saveArrayReturnType;
+ private $saveArrayReturnType;
/**
* Paper Sizes xRef List
*
* @var array
*/
- protected static $_paperSizes = array(
+ protected static $paperSizes = array(
Worksheet_PageSetup::PAPERSIZE_LETTER
=> 'LETTER', // (8.5 in. by 11 in.)
Worksheet_PageSetup::PAPERSIZE_LETTER_SMALL
@@ -221,8 +221,8 @@ abstract class Writer_PDF_Core extends Writer_HTML
public function __construct(Workbook $phpExcel)
{
parent::__construct($phpExcel);
- $this->setUseInlineCss(TRUE);
- $this->_tempDir = Shared_File::sys_get_temp_dir();
+ $this->setUseInlineCss(true);
+ $this->tempDir = Shared_File::sys_get_temp_dir();
}
/**
@@ -232,7 +232,7 @@ abstract class Writer_PDF_Core extends Writer_HTML
*/
public function getFont()
{
- return $this->_font;
+ return $this->font;
}
/**
@@ -246,7 +246,7 @@ abstract class Writer_PDF_Core extends Writer_HTML
*/
public function setFont($fontName)
{
- $this->_font = $fontName;
+ $this->font = $fontName;
return $this;
}
@@ -257,7 +257,7 @@ abstract class Writer_PDF_Core extends Writer_HTML
*/
public function getPaperSize()
{
- return $this->_paperSize;
+ return $this->paperSize;
}
/**
@@ -268,7 +268,7 @@ abstract class Writer_PDF_Core extends Writer_HTML
*/
public function setPaperSize($pValue = Worksheet_PageSetup::PAPERSIZE_LETTER)
{
- $this->_paperSize = $pValue;
+ $this->paperSize = $pValue;
return $this;
}
@@ -279,7 +279,7 @@ abstract class Writer_PDF_Core extends Writer_HTML
*/
public function getOrientation()
{
- return $this->_orientation;
+ return $this->orientation;
}
/**
@@ -290,7 +290,7 @@ abstract class Writer_PDF_Core extends Writer_HTML
*/
public function setOrientation($pValue = Worksheet_PageSetup::ORIENTATION_DEFAULT)
{
- $this->_orientation = $pValue;
+ $this->orientation = $pValue;
return $this;
}
@@ -301,7 +301,7 @@ abstract class Writer_PDF_Core extends Writer_HTML
*/
public function getTempDir()
{
- return $this->_tempDir;
+ return $this->tempDir;
}
/**
@@ -314,7 +314,7 @@ abstract class Writer_PDF_Core extends Writer_HTML
public function setTempDir($pValue = '')
{
if (is_dir($pValue)) {
- $this->_tempDir = $pValue;
+ $this->tempDir = $pValue;
} else {
throw new Writer_Exception("Directory does not exist: $pValue");
}
@@ -327,7 +327,7 @@ abstract class Writer_PDF_Core extends Writer_HTML
* @param string $pFilename Name of the file to save as
* @throws PHPExcel\Writer_Exception
*/
- protected function prepareForSave($pFilename = NULL)
+ protected function prepareForSave($pFilename = null)
{
// garbage collect
$this->_phpExcel->garbageCollect();
@@ -337,14 +337,14 @@ abstract class Writer_PDF_Core extends Writer_HTML
// Open file
$fileHandle = fopen($pFilename, 'w');
- if ($fileHandle === FALSE) {
+ if ($fileHandle === false) {
throw new Writer_Exception("Could not open file $pFilename for writing.");
}
// Set PDF
- $this->_isPdf = TRUE;
+ $this->_isPdf = true;
// Build CSS
- $this->buildCSS(TRUE);
+ $this->buildCSS(true);
return $fileHandle;
}
@@ -362,5 +362,4 @@ abstract class Writer_PDF_Core extends Writer_HTML
Calculation::setArrayReturnType($this->_saveArrayReturnType);
}
-
}
diff --git a/Classes/PHPExcel/Writer/PDF/DomPDF.php b/Classes/PHPExcel/Writer/PDF/DomPDF.php
index 9c797f5..74ad022 100644
--- a/Classes/PHPExcel/Writer/PDF/DomPDF.php
+++ b/Classes/PHPExcel/Writer/PDF/DomPDF.php
@@ -61,7 +61,7 @@ class Writer_PDF_DomPDF extends Writer_PDF_Core implements Writer_IWriter
* @param string $pFilename Name of the file to save as
* @throws PHPExcel\Writer_Exception
*/
- public function save($pFilename = NULL)
+ public function save($pFilename = null)
{
$fileHandle = parent::prepareForSave($pFilename);
@@ -107,7 +107,7 @@ class Writer_PDF_DomPDF extends Writer_PDF_Core implements Writer_IWriter
$pdf->set_paper(strtolower($paperSize), $orientation);
$pdf->load_html(
- $this->generateHTMLHeader(FALSE) .
+ $this->generateHTMLHeader(false) .
$this->generateSheetData() .
$this->generateHTMLFooter()
);
@@ -116,7 +116,6 @@ class Writer_PDF_DomPDF extends Writer_PDF_Core implements Writer_IWriter
// Write to file
fwrite($fileHandle, $pdf->output());
- parent::restoreStateAfterSave($fileHandle);
+ parent::restoreStateAfterSave($fileHandle);
}
-
}
diff --git a/Classes/PHPExcel/Writer/PDF/mPDF.php b/Classes/PHPExcel/Writer/PDF/mPDF.php
index 61eeda1..6e6d31c 100644
--- a/Classes/PHPExcel/Writer/PDF/mPDF.php
+++ b/Classes/PHPExcel/Writer/PDF/mPDF.php
@@ -61,7 +61,7 @@ class Writer_PDF_mPDF extends Writer_PDF_Core implements Writer_IWriter
* @param string $pFilename Name of the file to save as
* @throws PHPExcel\Writer_Exception
*/
- public function save($pFilename = NULL)
+ public function save($pFilename = null)
{
$fileHandle = parent::prepareForSave($pFilename);
@@ -118,7 +118,7 @@ class Writer_PDF_mPDF extends Writer_PDF_Core implements Writer_IWriter
$pdf->SetCreator($this->_phpExcel->getProperties()->getCreator());
$pdf->WriteHTML(
- $this->generateHTMLHeader(FALSE) .
+ $this->generateHTMLHeader(false) .
$this->generateSheetData() .
$this->generateHTMLFooter()
);
@@ -126,7 +126,6 @@ class Writer_PDF_mPDF extends Writer_PDF_Core implements Writer_IWriter
// Write to file
fwrite($fileHandle, $pdf->Output('', 'S'));
- parent::restoreStateAfterSave($fileHandle);
+ parent::restoreStateAfterSave($fileHandle);
}
-
}
diff --git a/Classes/PHPExcel/Writer/PDF/tcPDF.php b/Classes/PHPExcel/Writer/PDF/tcPDF.php
index 15746e6..4093b2a 100644
--- a/Classes/PHPExcel/Writer/PDF/tcPDF.php
+++ b/Classes/PHPExcel/Writer/PDF/tcPDF.php
@@ -62,7 +62,7 @@ class Writer_PDF_tcPDF extends Writer_PDF_Core implements Writer_IWriter
* @param string $pFilename Name of the file to save as
* @throws PHPExcel\Writer_Exception
*/
- public function save($pFilename = NULL)
+ public function save($pFilename = null)
{
$fileHandle = parent::prepareForSave($pFilename);
@@ -104,20 +104,20 @@ class Writer_PDF_tcPDF extends Writer_PDF_Core implements Writer_IWriter
// Create PDF
$pdf = new TCPDF($orientation, 'pt', $paperSize);
- $pdf->setFontSubsetting(FALSE);
+ $pdf->setFontSubsetting(false);
// Set margins, converting inches to points (using 72 dpi)
$pdf->SetMargins($printMargins->getLeft() * 72, $printMargins->getTop() * 72, $printMargins->getRight() * 72);
$pdf->SetAutoPageBreak(TRUE, $printMargins->getBottom() * 72);
- $pdf->setPrintHeader(FALSE);
- $pdf->setPrintFooter(FALSE);
+ $pdf->setPrintHeader(false);
+ $pdf->setPrintFooter(false);
$pdf->AddPage();
// Set the appropriate font
$pdf->SetFont($this->getFont());
$pdf->writeHTML(
- $this->generateHTMLHeader(FALSE) .
+ $this->generateHTMLHeader(false) .
$this->generateSheetData() .
$this->generateHTMLFooter()
);
@@ -132,7 +132,6 @@ class Writer_PDF_tcPDF extends Writer_PDF_Core implements Writer_IWriter
// Write to file
fwrite($fileHandle, $pdf->output($pFilename, 'S'));
- parent::restoreStateAfterSave($fileHandle);
+ parent::restoreStateAfterSave($fileHandle);
}
-
}