PageRenderTime 437ms CodeModel.GetById 91ms app.highlight 231ms RepoModel.GetById 101ms app.codeStats 1ms

/htdocs/includes/phpexcel/PHPExcel/Writer/Excel5/Parser.php

https://bitbucket.org/speedealing/speedealing
PHP | 1611 lines | 1433 code | 19 blank | 159 comment | 13 complexity | 4d64da1f42b214d92c189f3828249d6c MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   1<?php
   2/**
   3 * PHPExcel
   4 *
   5 * Copyright (c) 2006 - 2011 PHPExcel
   6 *
   7 * This library is free software; you can redistribute it and/or
   8 * modify it under the terms of the GNU Lesser General Public
   9 * License as published by the Free Software Foundation; either
  10 * version 2.1 of the License, or (at your option) any later version.
  11 *
  12 * This library is distributed in the hope that it will be useful,
  13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  15 * Lesser General Public License for more details.
  16 *
  17 * You should have received a copy of the GNU Lesser General Public
  18 * License along with this library; if not, write to the Free Software
  19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
  20 *
  21 * @category   PHPExcel
  22 * @package    PHPExcel_Writer_Excel5
  23 * @copyright  Copyright (c) 2006 - 2011 PHPExcel (http://www.codeplex.com/PHPExcel)
  24 * @license    http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt	LGPL
  25 * @version    1.7.6, 2011-02-27
  26 */
  27
  28// Original file header of PEAR::Spreadsheet_Excel_Writer_Parser (used as the base for this class):
  29// -----------------------------------------------------------------------------------------
  30// *  Class for parsing Excel formulas
  31// *
  32// *  License Information:
  33// *
  34// *    Spreadsheet_Excel_Writer:  A library for generating Excel Spreadsheets
  35// *    Copyright (c) 2002-2003 Xavier Noguer xnoguer@rezebra.com
  36// *
  37// *    This library is free software; you can redistribute it and/or
  38// *    modify it under the terms of the GNU Lesser General Public
  39// *    License as published by the Free Software Foundation; either
  40// *    version 2.1 of the License, or (at your option) any later version.
  41// *
  42// *    This library is distributed in the hope that it will be useful,
  43// *    but WITHOUT ANY WARRANTY; without even the implied warranty of
  44// *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  45// *    Lesser General Public License for more details.
  46// *
  47// *    You should have received a copy of the GNU Lesser General Public
  48// *    License along with this library; if not, write to the Free Software
  49// *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  50// */
  51
  52
  53/**
  54 * PHPExcel_Writer_Excel5_Parser
  55 *
  56 * @category   PHPExcel
  57 * @package    PHPExcel_Writer_Excel5
  58 * @copyright  Copyright (c) 2006 - 2011 PHPExcel (http://www.codeplex.com/PHPExcel)
  59 */
  60class PHPExcel_Writer_Excel5_Parser
  61{
  62	/**	Constants				*/
  63	// Sheet title in unquoted form
  64	// Invalid sheet title characters cannot occur in the sheet title:
  65	// 		*:/\?[]
  66	// Moreover, there are valid sheet title characters that cannot occur in unquoted form (there may be more?)
  67	// +-% '^&<>=,;#()"{}
  68	const REGEX_SHEET_TITLE_UNQUOTED = '[^\*\:\/\\\\\?\[\]\+\-\% \\\'\^\&\<\>\=\,\;\#\(\)\"\{\}]+';
  69
  70	// Sheet title in quoted form (without surrounding quotes)
  71	// Invalid sheet title characters cannot occur in the sheet title:
  72	// *:/\?[]					(usual invalid sheet title characters)
  73	// Single quote is represented as a pair ''
  74	const REGEX_SHEET_TITLE_QUOTED = '(([^\*\:\/\\\\\?\[\]\\\'])+|(\\\'\\\')+)+';
  75
  76	/**
  77	 * The index of the character we are currently looking at
  78	 * @var integer
  79	 */
  80	public $_current_char;
  81
  82	/**
  83	 * The token we are working on.
  84	 * @var string
  85	 */
  86	public $_current_token;
  87
  88	/**
  89	 * The formula to parse
  90	 * @var string
  91	 */
  92	public $_formula;
  93
  94	/**
  95	 * The character ahead of the current char
  96	 * @var string
  97	 */
  98	public $_lookahead;
  99
 100	/**
 101	 * The parse tree to be generated
 102	 * @var string
 103	 */
 104	public $_parse_tree;
 105
 106	/**
 107	 * Array of external sheets
 108	 * @var array
 109	 */
 110	public $_ext_sheets;
 111
 112	/**
 113	 * Array of sheet references in the form of REF structures
 114	 * @var array
 115	 */
 116	public $_references;
 117
 118	/**
 119	 * The BIFF version for the workbook
 120	 * @var integer
 121	 */
 122	public $_BIFF_version;
 123
 124	/**
 125	 * The class constructor
 126	 *
 127	 * @param integer $byte_order The byte order (Little endian or Big endian) of the architecture
 128	 *                           (optional). 1 => big endian, 0 (default) little endian.
 129	 */
 130	public function __construct($biff_version)
 131	{
 132		$this->_current_char  = 0;
 133		$this->_BIFF_version  = $biff_version;
 134		$this->_current_token = '';       // The token we are working on.
 135		$this->_formula       = '';       // The formula to parse.
 136		$this->_lookahead     = '';       // The character ahead of the current char.
 137		$this->_parse_tree    = '';       // The parse tree to be generated.
 138		$this->_initializeHashes();      // Initialize the hashes: ptg's and function's ptg's
 139		$this->_ext_sheets = array();
 140		$this->_references = array();
 141	}
 142
 143	/**
 144	 * Initialize the ptg and function hashes.
 145	 *
 146	 * @access private
 147	 */
 148	function _initializeHashes()
 149	{
 150		// The Excel ptg indices
 151		$this->ptg = array(
 152			'ptgExp'       => 0x01,
 153			'ptgTbl'       => 0x02,
 154			'ptgAdd'       => 0x03,
 155			'ptgSub'       => 0x04,
 156			'ptgMul'       => 0x05,
 157			'ptgDiv'       => 0x06,
 158			'ptgPower'     => 0x07,
 159			'ptgConcat'    => 0x08,
 160			'ptgLT'        => 0x09,
 161			'ptgLE'        => 0x0A,
 162			'ptgEQ'        => 0x0B,
 163			'ptgGE'        => 0x0C,
 164			'ptgGT'        => 0x0D,
 165			'ptgNE'        => 0x0E,
 166			'ptgIsect'     => 0x0F,
 167			'ptgUnion'     => 0x10,
 168			'ptgRange'     => 0x11,
 169			'ptgUplus'     => 0x12,
 170			'ptgUminus'    => 0x13,
 171			'ptgPercent'   => 0x14,
 172			'ptgParen'     => 0x15,
 173			'ptgMissArg'   => 0x16,
 174			'ptgStr'       => 0x17,
 175			'ptgAttr'      => 0x19,
 176			'ptgSheet'     => 0x1A,
 177			'ptgEndSheet'  => 0x1B,
 178			'ptgErr'       => 0x1C,
 179			'ptgBool'      => 0x1D,
 180			'ptgInt'       => 0x1E,
 181			'ptgNum'       => 0x1F,
 182			'ptgArray'     => 0x20,
 183			'ptgFunc'      => 0x21,
 184			'ptgFuncVar'   => 0x22,
 185			'ptgName'      => 0x23,
 186			'ptgRef'       => 0x24,
 187			'ptgArea'      => 0x25,
 188			'ptgMemArea'   => 0x26,
 189			'ptgMemErr'    => 0x27,
 190			'ptgMemNoMem'  => 0x28,
 191			'ptgMemFunc'   => 0x29,
 192			'ptgRefErr'    => 0x2A,
 193			'ptgAreaErr'   => 0x2B,
 194			'ptgRefN'      => 0x2C,
 195			'ptgAreaN'     => 0x2D,
 196			'ptgMemAreaN'  => 0x2E,
 197			'ptgMemNoMemN' => 0x2F,
 198			'ptgNameX'     => 0x39,
 199			'ptgRef3d'     => 0x3A,
 200			'ptgArea3d'    => 0x3B,
 201			'ptgRefErr3d'  => 0x3C,
 202			'ptgAreaErr3d' => 0x3D,
 203			'ptgArrayV'    => 0x40,
 204			'ptgFuncV'     => 0x41,
 205			'ptgFuncVarV'  => 0x42,
 206			'ptgNameV'     => 0x43,
 207			'ptgRefV'      => 0x44,
 208			'ptgAreaV'     => 0x45,
 209			'ptgMemAreaV'  => 0x46,
 210			'ptgMemErrV'   => 0x47,
 211			'ptgMemNoMemV' => 0x48,
 212			'ptgMemFuncV'  => 0x49,
 213			'ptgRefErrV'   => 0x4A,
 214			'ptgAreaErrV'  => 0x4B,
 215			'ptgRefNV'     => 0x4C,
 216			'ptgAreaNV'    => 0x4D,
 217			'ptgMemAreaNV' => 0x4E,
 218			'ptgMemNoMemN' => 0x4F,
 219			'ptgFuncCEV'   => 0x58,
 220			'ptgNameXV'    => 0x59,
 221			'ptgRef3dV'    => 0x5A,
 222			'ptgArea3dV'   => 0x5B,
 223			'ptgRefErr3dV' => 0x5C,
 224			'ptgAreaErr3d' => 0x5D,
 225			'ptgArrayA'    => 0x60,
 226			'ptgFuncA'     => 0x61,
 227			'ptgFuncVarA'  => 0x62,
 228			'ptgNameA'     => 0x63,
 229			'ptgRefA'      => 0x64,
 230			'ptgAreaA'     => 0x65,
 231			'ptgMemAreaA'  => 0x66,
 232			'ptgMemErrA'   => 0x67,
 233			'ptgMemNoMemA' => 0x68,
 234			'ptgMemFuncA'  => 0x69,
 235			'ptgRefErrA'   => 0x6A,
 236			'ptgAreaErrA'  => 0x6B,
 237			'ptgRefNA'     => 0x6C,
 238			'ptgAreaNA'    => 0x6D,
 239			'ptgMemAreaNA' => 0x6E,
 240			'ptgMemNoMemN' => 0x6F,
 241			'ptgFuncCEA'   => 0x78,
 242			'ptgNameXA'    => 0x79,
 243			'ptgRef3dA'    => 0x7A,
 244			'ptgArea3dA'   => 0x7B,
 245			'ptgRefErr3dA' => 0x7C,
 246			'ptgAreaErr3d' => 0x7D
 247			);
 248
 249		// Thanks to Michael Meeks and Gnumeric for the initial arg values.
 250		//
 251		// The following hash was generated by "function_locale.pl" in the distro.
 252		// Refer to function_locale.pl for non-English function names.
 253		//
 254		// The array elements are as follow:
 255		// ptg:   The Excel function ptg code.
 256		// args:  The number of arguments that the function takes:
 257		//           >=0 is a fixed number of arguments.
 258		//           -1  is a variable  number of arguments.
 259		// class: The reference, value or array class of the function args.
 260		// vol:   The function is volatile.
 261		//
 262		$this->_functions = array(
 263			  // function                  ptg  args  class  vol
 264			  'COUNT'           => array(   0,   -1,    0,    0 ),
 265			  'IF'              => array(   1,   -1,    1,    0 ),
 266			  'ISNA'            => array(   2,    1,    1,    0 ),
 267			  'ISERROR'         => array(   3,    1,    1,    0 ),
 268			  'SUM'             => array(   4,   -1,    0,    0 ),
 269			  'AVERAGE'         => array(   5,   -1,    0,    0 ),
 270			  'MIN'             => array(   6,   -1,    0,    0 ),
 271			  'MAX'             => array(   7,   -1,    0,    0 ),
 272			  'ROW'             => array(   8,   -1,    0,    0 ),
 273			  'COLUMN'          => array(   9,   -1,    0,    0 ),
 274			  'NA'              => array(  10,    0,    0,    0 ),
 275			  'NPV'             => array(  11,   -1,    1,    0 ),
 276			  'STDEV'           => array(  12,   -1,    0,    0 ),
 277			  'DOLLAR'          => array(  13,   -1,    1,    0 ),
 278			  'FIXED'           => array(  14,   -1,    1,    0 ),
 279			  'SIN'             => array(  15,    1,    1,    0 ),
 280			  'COS'             => array(  16,    1,    1,    0 ),
 281			  'TAN'             => array(  17,    1,    1,    0 ),
 282			  'ATAN'            => array(  18,    1,    1,    0 ),
 283			  'PI'              => array(  19,    0,    1,    0 ),
 284			  'SQRT'            => array(  20,    1,    1,    0 ),
 285			  'EXP'             => array(  21,    1,    1,    0 ),
 286			  'LN'              => array(  22,    1,    1,    0 ),
 287			  'LOG10'           => array(  23,    1,    1,    0 ),
 288			  'ABS'             => array(  24,    1,    1,    0 ),
 289			  'INT'             => array(  25,    1,    1,    0 ),
 290			  'SIGN'            => array(  26,    1,    1,    0 ),
 291			  'ROUND'           => array(  27,    2,    1,    0 ),
 292			  'LOOKUP'          => array(  28,   -1,    0,    0 ),
 293			  'INDEX'           => array(  29,   -1,    0,    1 ),
 294			  'REPT'            => array(  30,    2,    1,    0 ),
 295			  'MID'             => array(  31,    3,    1,    0 ),
 296			  'LEN'             => array(  32,    1,    1,    0 ),
 297			  'VALUE'           => array(  33,    1,    1,    0 ),
 298			  'TRUE'            => array(  34,    0,    1,    0 ),
 299			  'FALSE'           => array(  35,    0,    1,    0 ),
 300			  'AND'             => array(  36,   -1,    0,    0 ),
 301			  'OR'              => array(  37,   -1,    0,    0 ),
 302			  'NOT'             => array(  38,    1,    1,    0 ),
 303			  'MOD'             => array(  39,    2,    1,    0 ),
 304			  'DCOUNT'          => array(  40,    3,    0,    0 ),
 305			  'DSUM'            => array(  41,    3,    0,    0 ),
 306			  'DAVERAGE'        => array(  42,    3,    0,    0 ),
 307			  'DMIN'            => array(  43,    3,    0,    0 ),
 308			  'DMAX'            => array(  44,    3,    0,    0 ),
 309			  'DSTDEV'          => array(  45,    3,    0,    0 ),
 310			  'VAR'             => array(  46,   -1,    0,    0 ),
 311			  'DVAR'            => array(  47,    3,    0,    0 ),
 312			  'TEXT'            => array(  48,    2,    1,    0 ),
 313			  'LINEST'          => array(  49,   -1,    0,    0 ),
 314			  'TREND'           => array(  50,   -1,    0,    0 ),
 315			  'LOGEST'          => array(  51,   -1,    0,    0 ),
 316			  'GROWTH'          => array(  52,   -1,    0,    0 ),
 317			  'PV'              => array(  56,   -1,    1,    0 ),
 318			  'FV'              => array(  57,   -1,    1,    0 ),
 319			  'NPER'            => array(  58,   -1,    1,    0 ),
 320			  'PMT'             => array(  59,   -1,    1,    0 ),
 321			  'RATE'            => array(  60,   -1,    1,    0 ),
 322			  'MIRR'            => array(  61,    3,    0,    0 ),
 323			  'IRR'             => array(  62,   -1,    0,    0 ),
 324			  'RAND'            => array(  63,    0,    1,    1 ),
 325			  'MATCH'           => array(  64,   -1,    0,    0 ),
 326			  'DATE'            => array(  65,    3,    1,    0 ),
 327			  'TIME'            => array(  66,    3,    1,    0 ),
 328			  'DAY'             => array(  67,    1,    1,    0 ),
 329			  'MONTH'           => array(  68,    1,    1,    0 ),
 330			  'YEAR'            => array(  69,    1,    1,    0 ),
 331			  'WEEKDAY'         => array(  70,   -1,    1,    0 ),
 332			  'HOUR'            => array(  71,    1,    1,    0 ),
 333			  'MINUTE'          => array(  72,    1,    1,    0 ),
 334			  'SECOND'          => array(  73,    1,    1,    0 ),
 335			  'NOW'             => array(  74,    0,    1,    1 ),
 336			  'AREAS'           => array(  75,    1,    0,    1 ),
 337			  'ROWS'            => array(  76,    1,    0,    1 ),
 338			  'COLUMNS'         => array(  77,    1,    0,    1 ),
 339			  'OFFSET'          => array(  78,   -1,    0,    1 ),
 340			  'SEARCH'          => array(  82,   -1,    1,    0 ),
 341			  'TRANSPOSE'       => array(  83,    1,    1,    0 ),
 342			  'TYPE'            => array(  86,    1,    1,    0 ),
 343			  'ATAN2'           => array(  97,    2,    1,    0 ),
 344			  'ASIN'            => array(  98,    1,    1,    0 ),
 345			  'ACOS'            => array(  99,    1,    1,    0 ),
 346			  'CHOOSE'          => array( 100,   -1,    1,    0 ),
 347			  'HLOOKUP'         => array( 101,   -1,    0,    0 ),
 348			  'VLOOKUP'         => array( 102,   -1,    0,    0 ),
 349			  'ISREF'           => array( 105,    1,    0,    0 ),
 350			  'LOG'             => array( 109,   -1,    1,    0 ),
 351			  'CHAR'            => array( 111,    1,    1,    0 ),
 352			  'LOWER'           => array( 112,    1,    1,    0 ),
 353			  'UPPER'           => array( 113,    1,    1,    0 ),
 354			  'PROPER'          => array( 114,    1,    1,    0 ),
 355			  'LEFT'            => array( 115,   -1,    1,    0 ),
 356			  'RIGHT'           => array( 116,   -1,    1,    0 ),
 357			  'EXACT'           => array( 117,    2,    1,    0 ),
 358			  'TRIM'            => array( 118,    1,    1,    0 ),
 359			  'REPLACE'         => array( 119,    4,    1,    0 ),
 360			  'SUBSTITUTE'      => array( 120,   -1,    1,    0 ),
 361			  'CODE'            => array( 121,    1,    1,    0 ),
 362			  'FIND'            => array( 124,   -1,    1,    0 ),
 363			  'CELL'            => array( 125,   -1,    0,    1 ),
 364			  'ISERR'           => array( 126,    1,    1,    0 ),
 365			  'ISTEXT'          => array( 127,    1,    1,    0 ),
 366			  'ISNUMBER'        => array( 128,    1,    1,    0 ),
 367			  'ISBLANK'         => array( 129,    1,    1,    0 ),
 368			  'T'               => array( 130,    1,    0,    0 ),
 369			  'N'               => array( 131,    1,    0,    0 ),
 370			  'DATEVALUE'       => array( 140,    1,    1,    0 ),
 371			  'TIMEVALUE'       => array( 141,    1,    1,    0 ),
 372			  'SLN'             => array( 142,    3,    1,    0 ),
 373			  'SYD'             => array( 143,    4,    1,    0 ),
 374			  'DDB'             => array( 144,   -1,    1,    0 ),
 375			  'INDIRECT'        => array( 148,   -1,    1,    1 ),
 376			  'CALL'            => array( 150,   -1,    1,    0 ),
 377			  'CLEAN'           => array( 162,    1,    1,    0 ),
 378			  'MDETERM'         => array( 163,    1,    2,    0 ),
 379			  'MINVERSE'        => array( 164,    1,    2,    0 ),
 380			  'MMULT'           => array( 165,    2,    2,    0 ),
 381			  'IPMT'            => array( 167,   -1,    1,    0 ),
 382			  'PPMT'            => array( 168,   -1,    1,    0 ),
 383			  'COUNTA'          => array( 169,   -1,    0,    0 ),
 384			  'PRODUCT'         => array( 183,   -1,    0,    0 ),
 385			  'FACT'            => array( 184,    1,    1,    0 ),
 386			  'DPRODUCT'        => array( 189,    3,    0,    0 ),
 387			  'ISNONTEXT'       => array( 190,    1,    1,    0 ),
 388			  'STDEVP'          => array( 193,   -1,    0,    0 ),
 389			  'VARP'            => array( 194,   -1,    0,    0 ),
 390			  'DSTDEVP'         => array( 195,    3,    0,    0 ),
 391			  'DVARP'           => array( 196,    3,    0,    0 ),
 392			  'TRUNC'           => array( 197,   -1,    1,    0 ),
 393			  'ISLOGICAL'       => array( 198,    1,    1,    0 ),
 394			  'DCOUNTA'         => array( 199,    3,    0,    0 ),
 395			  'USDOLLAR'        => array( 204,   -1,    1,    0 ),
 396			  'FINDB'           => array( 205,   -1,    1,    0 ),
 397			  'SEARCHB'         => array( 206,   -1,    1,    0 ),
 398			  'REPLACEB'        => array( 207,    4,    1,    0 ),
 399			  'LEFTB'           => array( 208,   -1,    1,    0 ),
 400			  'RIGHTB'          => array( 209,   -1,    1,    0 ),
 401			  'MIDB'            => array( 210,    3,    1,    0 ),
 402			  'LENB'            => array( 211,    1,    1,    0 ),
 403			  'ROUNDUP'         => array( 212,    2,    1,    0 ),
 404			  'ROUNDDOWN'       => array( 213,    2,    1,    0 ),
 405			  'ASC'             => array( 214,    1,    1,    0 ),
 406			  'DBCS'            => array( 215,    1,    1,    0 ),
 407			  'RANK'            => array( 216,   -1,    0,    0 ),
 408			  'ADDRESS'         => array( 219,   -1,    1,    0 ),
 409			  'DAYS360'         => array( 220,   -1,    1,    0 ),
 410			  'TODAY'           => array( 221,    0,    1,    1 ),
 411			  'VDB'             => array( 222,   -1,    1,    0 ),
 412			  'MEDIAN'          => array( 227,   -1,    0,    0 ),
 413			  'SUMPRODUCT'      => array( 228,   -1,    2,    0 ),
 414			  'SINH'            => array( 229,    1,    1,    0 ),
 415			  'COSH'            => array( 230,    1,    1,    0 ),
 416			  'TANH'            => array( 231,    1,    1,    0 ),
 417			  'ASINH'           => array( 232,    1,    1,    0 ),
 418			  'ACOSH'           => array( 233,    1,    1,    0 ),
 419			  'ATANH'           => array( 234,    1,    1,    0 ),
 420			  'DGET'            => array( 235,    3,    0,    0 ),
 421			  'INFO'            => array( 244,    1,    1,    1 ),
 422			  'DB'              => array( 247,   -1,    1,    0 ),
 423			  'FREQUENCY'       => array( 252,    2,    0,    0 ),
 424			  'ERROR.TYPE'      => array( 261,    1,    1,    0 ),
 425			  'REGISTER.ID'     => array( 267,   -1,    1,    0 ),
 426			  'AVEDEV'          => array( 269,   -1,    0,    0 ),
 427			  'BETADIST'        => array( 270,   -1,    1,    0 ),
 428			  'GAMMALN'         => array( 271,    1,    1,    0 ),
 429			  'BETAINV'         => array( 272,   -1,    1,    0 ),
 430			  'BINOMDIST'       => array( 273,    4,    1,    0 ),
 431			  'CHIDIST'         => array( 274,    2,    1,    0 ),
 432			  'CHIINV'          => array( 275,    2,    1,    0 ),
 433			  'COMBIN'          => array( 276,    2,    1,    0 ),
 434			  'CONFIDENCE'      => array( 277,    3,    1,    0 ),
 435			  'CRITBINOM'       => array( 278,    3,    1,    0 ),
 436			  'EVEN'            => array( 279,    1,    1,    0 ),
 437			  'EXPONDIST'       => array( 280,    3,    1,    0 ),
 438			  'FDIST'           => array( 281,    3,    1,    0 ),
 439			  'FINV'            => array( 282,    3,    1,    0 ),
 440			  'FISHER'          => array( 283,    1,    1,    0 ),
 441			  'FISHERINV'       => array( 284,    1,    1,    0 ),
 442			  'FLOOR'           => array( 285,    2,    1,    0 ),
 443			  'GAMMADIST'       => array( 286,    4,    1,    0 ),
 444			  'GAMMAINV'        => array( 287,    3,    1,    0 ),
 445			  'CEILING'         => array( 288,    2,    1,    0 ),
 446			  'HYPGEOMDIST'     => array( 289,    4,    1,    0 ),
 447			  'LOGNORMDIST'     => array( 290,    3,    1,    0 ),
 448			  'LOGINV'          => array( 291,    3,    1,    0 ),
 449			  'NEGBINOMDIST'    => array( 292,    3,    1,    0 ),
 450			  'NORMDIST'        => array( 293,    4,    1,    0 ),
 451			  'NORMSDIST'       => array( 294,    1,    1,    0 ),
 452			  'NORMINV'         => array( 295,    3,    1,    0 ),
 453			  'NORMSINV'        => array( 296,    1,    1,    0 ),
 454			  'STANDARDIZE'     => array( 297,    3,    1,    0 ),
 455			  'ODD'             => array( 298,    1,    1,    0 ),
 456			  'PERMUT'          => array( 299,    2,    1,    0 ),
 457			  'POISSON'         => array( 300,    3,    1,    0 ),
 458			  'TDIST'           => array( 301,    3,    1,    0 ),
 459			  'WEIBULL'         => array( 302,    4,    1,    0 ),
 460			  'SUMXMY2'         => array( 303,    2,    2,    0 ),
 461			  'SUMX2MY2'        => array( 304,    2,    2,    0 ),
 462			  'SUMX2PY2'        => array( 305,    2,    2,    0 ),
 463			  'CHITEST'         => array( 306,    2,    2,    0 ),
 464			  'CORREL'          => array( 307,    2,    2,    0 ),
 465			  'COVAR'           => array( 308,    2,    2,    0 ),
 466			  'FORECAST'        => array( 309,    3,    2,    0 ),
 467			  'FTEST'           => array( 310,    2,    2,    0 ),
 468			  'INTERCEPT'       => array( 311,    2,    2,    0 ),
 469			  'PEARSON'         => array( 312,    2,    2,    0 ),
 470			  'RSQ'             => array( 313,    2,    2,    0 ),
 471			  'STEYX'           => array( 314,    2,    2,    0 ),
 472			  'SLOPE'           => array( 315,    2,    2,    0 ),
 473			  'TTEST'           => array( 316,    4,    2,    0 ),
 474			  'PROB'            => array( 317,   -1,    2,    0 ),
 475			  'DEVSQ'           => array( 318,   -1,    0,    0 ),
 476			  'GEOMEAN'         => array( 319,   -1,    0,    0 ),
 477			  'HARMEAN'         => array( 320,   -1,    0,    0 ),
 478			  'SUMSQ'           => array( 321,   -1,    0,    0 ),
 479			  'KURT'            => array( 322,   -1,    0,    0 ),
 480			  'SKEW'            => array( 323,   -1,    0,    0 ),
 481			  'ZTEST'           => array( 324,   -1,    0,    0 ),
 482			  'LARGE'           => array( 325,    2,    0,    0 ),
 483			  'SMALL'           => array( 326,    2,    0,    0 ),
 484			  'QUARTILE'        => array( 327,    2,    0,    0 ),
 485			  'PERCENTILE'      => array( 328,    2,    0,    0 ),
 486			  'PERCENTRANK'     => array( 329,   -1,    0,    0 ),
 487			  'MODE'            => array( 330,   -1,    2,    0 ),
 488			  'TRIMMEAN'        => array( 331,    2,    0,    0 ),
 489			  'TINV'            => array( 332,    2,    1,    0 ),
 490			  'CONCATENATE'     => array( 336,   -1,    1,    0 ),
 491			  'POWER'           => array( 337,    2,    1,    0 ),
 492			  'RADIANS'         => array( 342,    1,    1,    0 ),
 493			  'DEGREES'         => array( 343,    1,    1,    0 ),
 494			  'SUBTOTAL'        => array( 344,   -1,    0,    0 ),
 495			  'SUMIF'           => array( 345,   -1,    0,    0 ),
 496			  'COUNTIF'         => array( 346,    2,    0,    0 ),
 497			  'COUNTBLANK'      => array( 347,    1,    0,    0 ),
 498			  'ISPMT'           => array( 350,    4,    1,    0 ),
 499			  'DATEDIF'         => array( 351,    3,    1,    0 ),
 500			  'DATESTRING'      => array( 352,    1,    1,    0 ),
 501			  'NUMBERSTRING'    => array( 353,    2,    1,    0 ),
 502			  'ROMAN'           => array( 354,   -1,    1,    0 ),
 503			  'GETPIVOTDATA'    => array( 358,   -1,    0,    0 ),
 504			  'HYPERLINK'       => array( 359,   -1,    1,    0 ),
 505			  'PHONETIC'        => array( 360,    1,    0,    0 ),
 506			  'AVERAGEA'        => array( 361,   -1,    0,    0 ),
 507			  'MAXA'            => array( 362,   -1,    0,    0 ),
 508			  'MINA'            => array( 363,   -1,    0,    0 ),
 509			  'STDEVPA'         => array( 364,   -1,    0,    0 ),
 510			  'VARPA'           => array( 365,   -1,    0,    0 ),
 511			  'STDEVA'          => array( 366,   -1,    0,    0 ),
 512			  'VARA'            => array( 367,   -1,    0,    0 ),
 513			  'BAHTTEXT'        => array( 368,    1,    0,    0 ),
 514			  );
 515	}
 516
 517	/**
 518	 * Convert a token to the proper ptg value.
 519	 *
 520	 * @access private
 521	 * @param mixed $token The token to convert.
 522	 * @return mixed the converted token on success
 523	 */
 524	function _convert($token)
 525	{
 526		if (preg_match("/\"([^\"]|\"\"){0,255}\"/", $token)) {
 527			return $this->_convertString($token);
 528
 529		} elseif (is_numeric($token)) {
 530			return $this->_convertNumber($token);
 531
 532		// match references like A1 or $A$1
 533		} elseif (preg_match('/^\$?([A-Ia-i]?[A-Za-z])\$?(\d+)$/',$token)) {
 534			return $this->_convertRef2d($token);
 535
 536		// match external references like Sheet1!A1 or Sheet1:Sheet2!A1 or Sheet1!$A$1 or Sheet1:Sheet2!$A$1
 537		} elseif (preg_match("/^" . self::REGEX_SHEET_TITLE_UNQUOTED . "(\:" . self::REGEX_SHEET_TITLE_UNQUOTED . ")?\!\\$?[A-Ia-i]?[A-Za-z]\\$?(\d+)$/u",$token)) {
 538			return $this->_convertRef3d($token);
 539
 540		// match external references like 'Sheet1'!A1 or 'Sheet1:Sheet2'!A1 or 'Sheet1'!$A$1 or 'Sheet1:Sheet2'!$A$1
 541		} elseif (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . "(\:" . self::REGEX_SHEET_TITLE_QUOTED . ")?'\!\\$?[A-Ia-i]?[A-Za-z]\\$?(\d+)$/u",$token)) {
 542			return $this->_convertRef3d($token);
 543
 544		// match ranges like A1:B2 or $A$1:$B$2
 545		} elseif (preg_match('/^(\$)?[A-Ia-i]?[A-Za-z](\$)?(\d+)\:(\$)?[A-Ia-i]?[A-Za-z](\$)?(\d+)$/', $token)) {
 546			return $this->_convertRange2d($token);
 547
 548		// 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
 549		} 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)) {
 550			return $this->_convertRange3d($token);
 551
 552		// 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
 553		} 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)) {
 554			return $this->_convertRange3d($token);
 555
 556		// operators (including parentheses)
 557		} elseif (isset($this->ptg[$token])) {
 558			return pack("C", $this->ptg[$token]);
 559
 560        // match error codes
 561		} elseif (preg_match("/^#[A-Z0\/]{3,5}[!?]{1}$/", $token) or $token == '#N/A') {
 562		    return $this->_convertError($token);
 563
 564		// commented so argument number can be processed correctly. See toReversePolish().
 565		/*elseif (preg_match("/[A-Z0-9\xc0-\xdc\.]+/",$token))
 566		{
 567			return($this->_convertFunction($token,$this->_func_args));
 568		}*/
 569
 570		// if it's an argument, ignore the token (the argument remains)
 571		} elseif ($token == 'arg') {
 572			return '';
 573		}
 574
 575		// TODO: use real error codes
 576		throw new Exception("Unknown token $token");
 577	}
 578
 579	/**
 580	 * Convert a number token to ptgInt or ptgNum
 581	 *
 582	 * @access private
 583	 * @param mixed $num an integer or double for conversion to its ptg value
 584	 */
 585	function _convertNumber($num)
 586	{
 587		// Integer in the range 0..2**16-1
 588		if ((preg_match("/^\d+$/", $num)) and ($num <= 65535)) {
 589			return pack("Cv", $this->ptg['ptgInt'], $num);
 590		} else { // A float
 591			if (PHPExcel_Writer_Excel5_BIFFwriter::getByteOrder()) { // if it's Big Endian
 592				$num = strrev($num);
 593			}
 594			return pack("Cd", $this->ptg['ptgNum'], $num);
 595		}
 596	}
 597
 598	/**
 599	 * Convert a string token to ptgStr
 600	 *
 601	 * @access private
 602	 * @param string $string A string for conversion to its ptg value.
 603	 * @return mixed the converted token on success
 604	 */
 605	function _convertString($string)
 606	{
 607		// chop away beggining and ending quotes
 608		$string = substr($string, 1, strlen($string) - 2);
 609		if (strlen($string) > 255) {
 610			throw new Exception("String is too long");
 611		}
 612
 613		if ($this->_BIFF_version == 0x0500) {
 614			return pack("CC", $this->ptg['ptgStr'], strlen($string)).$string;
 615		} elseif ($this->_BIFF_version == 0x0600) {
 616			return pack('C', $this->ptg['ptgStr']) . PHPExcel_Shared_String::UTF8toBIFF8UnicodeShort($string);
 617		}
 618	}
 619
 620	/**
 621	 * Convert a function to a ptgFunc or ptgFuncVarV depending on the number of
 622	 * args that it takes.
 623	 *
 624	 * @access private
 625	 * @param string  $token    The name of the function for convertion to ptg value.
 626	 * @param integer $num_args The number of arguments the function receives.
 627	 * @return string The packed ptg for the function
 628	 */
 629	function _convertFunction($token, $num_args)
 630	{
 631		$args     = $this->_functions[$token][1];
 632		$volatile = $this->_functions[$token][3];
 633
 634		// Fixed number of args eg. TIME($i,$j,$k).
 635		if ($args >= 0) {
 636			return pack("Cv", $this->ptg['ptgFuncV'], $this->_functions[$token][0]);
 637		}
 638		// Variable number of args eg. SUM($i,$j,$k, ..).
 639		if ($args == -1) {
 640			return pack("CCv", $this->ptg['ptgFuncVarV'], $num_args, $this->_functions[$token][0]);
 641		}
 642	}
 643
 644	/**
 645	 * Convert an Excel range such as A1:D4 to a ptgRefV.
 646	 *
 647	 * @access private
 648	 * @param string $range An Excel range in the A1:A2
 649	 */
 650	function _convertRange2d($range, $class=0)
 651	{
 652
 653		// TODO: possible class value 0,1,2 check Formula.pm
 654		// Split the range into 2 cell refs
 655		if (preg_match('/^(\$)?([A-Ia-i]?[A-Za-z])(\$)?(\d+)\:(\$)?([A-Ia-i]?[A-Za-z])(\$)?(\d+)$/', $range)) {
 656			list($cell1, $cell2) = explode(':', $range);
 657		} else {
 658			// TODO: use real error codes
 659			throw new Exception("Unknown range separator");
 660		}
 661
 662		// Convert the cell references
 663		$cell_array1 = $this->_cellToPackedRowcol($cell1);
 664		list($row1, $col1) = $cell_array1;
 665		$cell_array2 = $this->_cellToPackedRowcol($cell2);
 666		list($row2, $col2) = $cell_array2;
 667
 668		// The ptg value depends on the class of the ptg.
 669		if ($class == 0) {
 670			$ptgArea = pack("C", $this->ptg['ptgArea']);
 671		} elseif ($class == 1) {
 672			$ptgArea = pack("C", $this->ptg['ptgAreaV']);
 673		} elseif ($class == 2) {
 674			$ptgArea = pack("C", $this->ptg['ptgAreaA']);
 675		} else {
 676			// TODO: use real error codes
 677			throw new Exception("Unknown class $class");
 678		}
 679		return $ptgArea . $row1 . $row2 . $col1. $col2;
 680	}
 681
 682	/**
 683	 * Convert an Excel 3d range such as "Sheet1!A1:D4" or "Sheet1:Sheet2!A1:D4" to
 684	 * a ptgArea3d.
 685	 *
 686	 * @access private
 687	 * @param string $token An Excel range in the Sheet1!A1:A2 format.
 688	 * @return mixed The packed ptgArea3d token on success.
 689	 */
 690	function _convertRange3d($token)
 691	{
 692		$class = 0; // formulas like Sheet1!$A$1:$A$2 in list type data validation need this class (0x3B)
 693
 694		// Split the ref at the ! symbol
 695		list($ext_ref, $range) = explode('!', $token);
 696
 697		// Convert the external reference part (different for BIFF8)
 698		if ($this->_BIFF_version == 0x0500) {
 699			$ext_ref = $this->_packExtRef($ext_ref);
 700		} elseif ($this->_BIFF_version == 0x0600) {
 701			 $ext_ref = $this->_getRefIndex($ext_ref);
 702		}
 703
 704		// Split the range into 2 cell refs
 705		list($cell1, $cell2) = explode(':', $range);
 706
 707		// Convert the cell references
 708		if (preg_match("/^(\\$)?[A-Ia-i]?[A-Za-z](\\$)?(\d+)$/", $cell1)) {
 709			$cell_array1 = $this->_cellToPackedRowcol($cell1);
 710			list($row1, $col1) = $cell_array1;
 711			$cell_array2 = $this->_cellToPackedRowcol($cell2);
 712			list($row2, $col2) = $cell_array2;
 713		} else { // It's a rows range (like 26:27)
 714			 $cells_array = $this->_rangeToPackedRange($cell1.':'.$cell2);
 715			 list($row1, $col1, $row2, $col2) = $cells_array;
 716		}
 717
 718		// The ptg value depends on the class of the ptg.
 719		if ($class == 0) {
 720			$ptgArea = pack("C", $this->ptg['ptgArea3d']);
 721		} elseif ($class == 1) {
 722			$ptgArea = pack("C", $this->ptg['ptgArea3dV']);
 723		} elseif ($class == 2) {
 724			$ptgArea = pack("C", $this->ptg['ptgArea3dA']);
 725		} else {
 726			throw new Exception("Unknown class $class");
 727		}
 728
 729		return $ptgArea . $ext_ref . $row1 . $row2 . $col1. $col2;
 730	}
 731
 732	/**
 733	 * Convert an Excel reference such as A1, $B2, C$3 or $D$4 to a ptgRefV.
 734	 *
 735	 * @access private
 736	 * @param string $cell An Excel cell reference
 737	 * @return string The cell in packed() format with the corresponding ptg
 738	 */
 739	function _convertRef2d($cell)
 740	{
 741		$class = 2; // as far as I know, this is magick.
 742
 743		// Convert the cell reference
 744		$cell_array = $this->_cellToPackedRowcol($cell);
 745		list($row, $col) = $cell_array;
 746
 747		// The ptg value depends on the class of the ptg.
 748		if ($class == 0) {
 749			$ptgRef = pack("C", $this->ptg['ptgRef']);
 750		} elseif ($class == 1) {
 751			$ptgRef = pack("C", $this->ptg['ptgRefV']);
 752		} elseif ($class == 2) {
 753			$ptgRef = pack("C", $this->ptg['ptgRefA']);
 754		} else {
 755			// TODO: use real error codes
 756			throw new Exception("Unknown class $class");
 757		}
 758		return $ptgRef.$row.$col;
 759	}
 760
 761	/**
 762	 * Convert an Excel 3d reference such as "Sheet1!A1" or "Sheet1:Sheet2!A1" to a
 763	 * ptgRef3d.
 764	 *
 765	 * @access private
 766	 * @param string $cell An Excel cell reference
 767	 * @return mixed The packed ptgRef3d token on success.
 768	 */
 769	function _convertRef3d($cell)
 770	{
 771		$class = 2; // as far as I know, this is magick.
 772
 773		// Split the ref at the ! symbol
 774		list($ext_ref, $cell) = explode('!', $cell);
 775
 776		// Convert the external reference part (different for BIFF8)
 777		if ($this->_BIFF_version == 0x0500) {
 778			$ext_ref = $this->_packExtRef($ext_ref);
 779		} elseif ($this->_BIFF_version == 0x0600) {
 780			$ext_ref = $this->_getRefIndex($ext_ref);
 781		}
 782
 783		// Convert the cell reference part
 784		list($row, $col) = $this->_cellToPackedRowcol($cell);
 785
 786		// The ptg value depends on the class of the ptg.
 787		if ($class == 0) {
 788			$ptgRef = pack("C", $this->ptg['ptgRef3d']);
 789		} elseif ($class == 1) {
 790			$ptgRef = pack("C", $this->ptg['ptgRef3dV']);
 791		} elseif ($class == 2) {
 792			$ptgRef = pack("C", $this->ptg['ptgRef3dA']);
 793		} else {
 794			throw new Exception("Unknown class $class");
 795		}
 796
 797		return $ptgRef . $ext_ref. $row . $col;
 798	}
 799
 800    /**
 801     * Convert an error code to a ptgErr
 802     *
 803     * @access private
 804     * @param mixed $num an error codefor conversion to its ptg value
 805     */
 806    function _convertError($errorCode)
 807    {
 808        switch ($errorCode) {
 809            case '#NULL!':	return pack("C", 0x00);
 810            case '#DIV/0!':	return pack("C", 0x07);
 811            case '#VALUE!':	return pack("C", 0x0F);
 812            case '#REF!':	return pack("C", 0x17);
 813            case '#NAME?':	return pack("C", 0x1D);
 814            case '#NUM!':	return pack("C", 0x24);
 815            case '#N/A':	return pack("C", 0x2A);
 816        }
 817        return pack("C", 0xFF);
 818    }
 819
 820	/**
 821	 * Convert the sheet name part of an external reference, for example "Sheet1" or
 822	 * "Sheet1:Sheet2", to a packed structure.
 823	 *
 824	 * @access private
 825	 * @param string $ext_ref The name of the external reference
 826	 * @return string The reference index in packed() format
 827	 */
 828	function _packExtRef($ext_ref)
 829	{
 830		$ext_ref = preg_replace("/^'/", '', $ext_ref); // Remove leading  ' if any.
 831		$ext_ref = preg_replace("/'$/", '', $ext_ref); // Remove trailing ' if any.
 832
 833		// Check if there is a sheet range eg., Sheet1:Sheet2.
 834		if (preg_match("/:/", $ext_ref)) {
 835			list($sheet_name1, $sheet_name2) = explode(':', $ext_ref);
 836
 837			$sheet1 = $this->_getSheetIndex($sheet_name1);
 838			if ($sheet1 == -1) {
 839				throw new Exception("Unknown sheet name $sheet_name1 in formula");
 840			}
 841			$sheet2 = $this->_getSheetIndex($sheet_name2);
 842			if ($sheet2 == -1) {
 843				throw new Exception("Unknown sheet name $sheet_name2 in formula");
 844			}
 845
 846			// Reverse max and min sheet numbers if necessary
 847			if ($sheet1 > $sheet2) {
 848				list($sheet1, $sheet2) = array($sheet2, $sheet1);
 849			}
 850		} else { // Single sheet name only.
 851			$sheet1 = $this->_getSheetIndex($ext_ref);
 852			if ($sheet1 == -1) {
 853				throw new Exception("Unknown sheet name $ext_ref in formula");
 854			}
 855			$sheet2 = $sheet1;
 856		}
 857
 858		// References are stored relative to 0xFFFF.
 859		$offset = -1 - $sheet1;
 860
 861		return pack('vdvv', $offset, 0x00, $sheet1, $sheet2);
 862	}
 863
 864	/**
 865	 * Look up the REF index that corresponds to an external sheet name
 866	 * (or range). If it doesn't exist yet add it to the workbook's references
 867	 * array. It assumes all sheet names given must exist.
 868	 *
 869	 * @access private
 870	 * @param string $ext_ref The name of the external reference
 871	 * @return mixed The reference index in packed() format on success
 872	 */
 873	function _getRefIndex($ext_ref)
 874	{
 875		$ext_ref = preg_replace("/^'/", '', $ext_ref); // Remove leading  ' if any.
 876		$ext_ref = preg_replace("/'$/", '', $ext_ref); // Remove trailing ' if any.
 877		$ext_ref = str_replace('\'\'', '\'', $ext_ref); // Replace escaped '' with '
 878
 879		// Check if there is a sheet range eg., Sheet1:Sheet2.
 880		if (preg_match("/:/", $ext_ref)) {
 881			list($sheet_name1, $sheet_name2) = explode(':', $ext_ref);
 882
 883			$sheet1 = $this->_getSheetIndex($sheet_name1);
 884			if ($sheet1 == -1) {
 885				throw new Exception("Unknown sheet name $sheet_name1 in formula");
 886			}
 887			$sheet2 = $this->_getSheetIndex($sheet_name2);
 888			if ($sheet2 == -1) {
 889				throw new Exception("Unknown sheet name $sheet_name2 in formula");
 890			}
 891
 892			// Reverse max and min sheet numbers if necessary
 893			if ($sheet1 > $sheet2) {
 894				list($sheet1, $sheet2) = array($sheet2, $sheet1);
 895			}
 896		} else { // Single sheet name only.
 897			$sheet1 = $this->_getSheetIndex($ext_ref);
 898			if ($sheet1 == -1) {
 899				throw new Exception("Unknown sheet name $ext_ref in formula");
 900			}
 901			$sheet2 = $sheet1;
 902		}
 903
 904		// assume all references belong to this document
 905		$supbook_index = 0x00;
 906		$ref = pack('vvv', $supbook_index, $sheet1, $sheet2);
 907		$total_references = count($this->_references);
 908		$index = -1;
 909		for ($i = 0; $i < $total_references; ++$i) {
 910			if ($ref == $this->_references[$i]) {
 911				$index = $i;
 912				break;
 913			}
 914		}
 915		// if REF was not found add it to references array
 916		if ($index == -1) {
 917			$this->_references[$total_references] = $ref;
 918			$index = $total_references;
 919		}
 920
 921		return pack('v', $index);
 922	}
 923
 924	/**
 925	 * Look up the index that corresponds to an external sheet name. The hash of
 926	 * sheet names is updated by the addworksheet() method of the
 927	 * PHPExcel_Writer_Excel5_Workbook class.
 928	 *
 929	 * @access private
 930	 * @return integer The sheet index, -1 if the sheet was not found
 931	 */
 932	function _getSheetIndex($sheet_name)
 933	{
 934		if (!isset($this->_ext_sheets[$sheet_name])) {
 935			return -1;
 936		} else {
 937			return $this->_ext_sheets[$sheet_name];
 938		}
 939	}
 940
 941	/**
 942	 * This method is used to update the array of sheet names. It is
 943	 * called by the addWorksheet() method of the
 944	 * PHPExcel_Writer_Excel5_Workbook class.
 945	 *
 946	 * @access public
 947	 * @see PHPExcel_Writer_Excel5_Workbook::addWorksheet()
 948	 * @param string  $name  The name of the worksheet being added
 949	 * @param integer $index The index of the worksheet being added
 950	 */
 951	function setExtSheet($name, $index)
 952	{
 953		$this->_ext_sheets[$name] = $index;
 954	}
 955
 956	/**
 957	 * pack() row and column into the required 3 or 4 byte format.
 958	 *
 959	 * @access private
 960	 * @param string $cell The Excel cell reference to be packed
 961	 * @return array Array containing the row and column in packed() format
 962	 */
 963	function _cellToPackedRowcol($cell)
 964	{
 965		$cell = strtoupper($cell);
 966		list($row, $col, $row_rel, $col_rel) = $this->_cellToRowcol($cell);
 967		if ($col >= 256) {
 968			throw new Exception("Column in: $cell greater than 255");
 969		}
 970		// FIXME: change for BIFF8
 971		if ($row >= 16384) {
 972			throw new Exception("Row in: $cell greater than 16384 ");
 973		}
 974
 975		// Set the high bits to indicate if row or col are relative.
 976		if ($this->_BIFF_version == 0x0500) {
 977			$row    |= $col_rel << 14;
 978			$row    |= $row_rel << 15;
 979			$col     = pack('C', $col);
 980		} elseif ($this->_BIFF_version == 0x0600) {
 981			$col    |= $col_rel << 14;
 982			$col    |= $row_rel << 15;
 983			$col     = pack('v', $col);
 984		}
 985		$row     = pack('v', $row);
 986
 987		return array($row, $col);
 988	}
 989
 990	/**
 991	 * pack() row range into the required 3 or 4 byte format.
 992	 * Just using maximum col/rows, which is probably not the correct solution
 993	 *
 994	 * @access private
 995	 * @param string $range The Excel range to be packed
 996	 * @return array Array containing (row1,col1,row2,col2) in packed() format
 997	 */
 998	function _rangeToPackedRange($range)
 999	{
1000		preg_match('/(\$)?(\d+)\:(\$)?(\d+)/', $range, $match);
1001		// return absolute rows if there is a $ in the ref
1002		$row1_rel = empty($match[1]) ? 1 : 0;
1003		$row1     = $match[2];
1004		$row2_rel = empty($match[3]) ? 1 : 0;
1005		$row2     = $match[4];
1006		// Convert 1-index to zero-index
1007		--$row1;
1008		--$row2;
1009		// Trick poor inocent Excel
1010		$col1 = 0;
1011		$col2 = 16383; // FIXME: maximum possible value for Excel 5 (change this!!!)
1012
1013		// FIXME: this changes for BIFF8
1014		if (($row1 >= 16384) or ($row2 >= 16384)) {
1015			throw new Exception("Row in: $range greater than 16384 ");
1016		}
1017
1018		// Set the high bits to indicate if rows are relative.
1019		if ($this->_BIFF_version == 0x0500) {
1020			$row1    |= $row1_rel << 14; // FIXME: probably a bug
1021			$row2    |= $row2_rel << 15;
1022			$col1     = pack('C', $col1);
1023			$col2     = pack('C', $col2);
1024		} elseif ($this->_BIFF_version == 0x0600) {
1025			$col1    |= $row1_rel << 15;
1026			$col2    |= $row2_rel << 15;
1027			$col1     = pack('v', $col1);
1028			$col2     = pack('v', $col2);
1029		}
1030		$row1     = pack('v', $row1);
1031		$row2     = pack('v', $row2);
1032
1033		return array($row1, $col1, $row2, $col2);
1034	}
1035
1036	/**
1037	 * Convert an Excel cell reference such as A1 or $B2 or C$3 or $D$4 to a zero
1038	 * indexed row and column number. Also returns two (0,1) values to indicate
1039	 * whether the row or column are relative references.
1040	 *
1041	 * @access private
1042	 * @param string $cell The Excel cell reference in A1 format.
1043	 * @return array
1044	 */
1045	function _cellToRowcol($cell)
1046	{
1047		preg_match('/(\$)?([A-I]?[A-Z])(\$)?(\d+)/',$cell,$match);
1048		// return absolute column if there is a $ in the ref
1049		$col_rel = empty($match[1]) ? 1 : 0;
1050		$col_ref = $match[2];
1051		$row_rel = empty($match[3]) ? 1 : 0;
1052		$row     = $match[4];
1053
1054		// Convert base26 column string to a number.
1055		$expn   = strlen($col_ref) - 1;
1056		$col    = 0;
1057		$col_ref_length = strlen($col_ref);
1058		for ($i = 0; $i < $col_ref_length; ++$i) {
1059			$col += (ord($col_ref{$i}) - 64) * pow(26, $expn);
1060			--$expn;
1061		}
1062
1063		// Convert 1-index to zero-index
1064		--$row;
1065		--$col;
1066
1067		return array($row, $col, $row_rel, $col_rel);
1068	}
1069
1070	/**
1071	 * Advance to the next valid token.
1072	 *
1073	 * @access private
1074	 */
1075	function _advance()
1076	{
1077		$i = $this->_current_char;
1078		$formula_length = strlen($this->_formula);
1079		// eat up white spaces
1080		if ($i < $formula_length) {
1081			while ($this->_formula{$i} == " ") {
1082				++$i;
1083			}
1084
1085			if ($i < ($formula_length - 1)) {
1086				$this->_lookahead = $this->_formula{$i+1};
1087			}
1088			$token = '';
1089		}
1090
1091		while ($i < $formula_length) {
1092			$token .= $this->_formula{$i};
1093			if ($i < ($formula_length - 1)) {
1094				$this->_lookahead = $this->_formula{$i+1};
1095			} else {
1096				$this->_lookahead = '';
1097			}
1098
1099			if ($this->_match($token) != '') {
1100				//if ($i < strlen($this->_formula) - 1) {
1101				//    $this->_lookahead = $this->_formula{$i+1};
1102				//}
1103				$this->_current_char = $i + 1;
1104				$this->_current_token = $token;
1105				return 1;
1106			}
1107
1108			if ($i < ($formula_length - 2)) {
1109				$this->_lookahead = $this->_formula{$i+2};
1110			} else { // if we run out of characters _lookahead becomes empty
1111				$this->_lookahead = '';
1112			}
1113			++$i;
1114		}
1115		//die("Lexical error ".$this->_current_char);
1116	}
1117
1118	/**
1119	 * Checks if it's a valid token.
1120	 *
1121	 * @access private
1122	 * @param mixed $token The token to check.
1123	 * @return mixed       The checked token or false on failure
1124	 */
1125	function _match($token)
1126	{
1127		switch($token) {
1128			case "+":
1129			case "-":
1130			case "*":
1131			case "/":
1132			case "(":
1133			case ")":
1134			case ",":
1135			case ";":
1136			case ">=":
1137			case "<=":
1138			case "=":
1139			case "<>":
1140			case "^":
1141			case "&":
1142			case "%":
1143				return $token;
1144				break;
1145			case ">":
1146				if ($this->_lookahead == '=') { // it's a GE token
1147					break;
1148				}
1149				return $token;
1150				break;
1151			case "<":
1152				// it's a LE or a NE token
1153				if (($this->_lookahead == '=') or ($this->_lookahead == '>')) {
1154					break;
1155				}
1156				return $token;
1157				break;
1158			default:
1159				// if it's a reference A1 or $A$1 or $A1 or A$1
1160				if (preg_match('/^\$?[A-Ia-i]?[A-Za-z]\$?[0-9]+$/',$token) and
1161				   !preg_match("/[0-9]/",$this->_lookahead) and
1162				   ($this->_lookahead != ':') and ($this->_lookahead != '.') and
1163				   ($this->_lookahead != '!'))
1164				{
1165					return $token;
1166				}
1167				// If it's an external reference (Sheet1!A1 or Sheet1:Sheet2!A1 or Sheet1!$A$1 or Sheet1:Sheet2!$A$1)
1168				elseif (preg_match("/^" . self::REGEX_SHEET_TITLE_UNQUOTED . "(\:" . self::REGEX_SHEET_TITLE_UNQUOTED . ")?\!\\$?[A-Ia-i]?[A-Za-z]\\$?[0-9]+$/u",$token) and
1169					   !preg_match("/[0-9]/",$this->_lookahead) and
1170					   ($this->_lookahead != ':') and ($this->_lookahead != '.'))
1171				{
1172					return $token;
1173				}
1174				// If it's an external reference ('Sheet1'!A1 or 'Sheet1:Sheet2'!A1 or 'Sheet1'!$A$1 or 'Sheet1:Sheet2'!$A$1)
1175				elseif (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . "(\:" . self::REGEX_SHEET_TITLE_QUOTED . ")?'\!\\$?[A-Ia-i]?[A-Za-z]\\$?[0-9]+$/u",$token) and
1176					   !preg_match("/[0-9]/",$this->_lookahead) and
1177					   ($this->_lookahead != ':') and ($this->_lookahead != '.'))
1178				{
1179					return $token;
1180				}
1181				// if it's a range A1:A2 or $A$1:$A$2
1182				elseif (preg_match('/^(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+:(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+$/', $token) and
1183					   !preg_match("/[0-9]/",$this->_lookahead))
1184				{
1185					return $token;
1186				}
1187				// 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
1188				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
1189					   !preg_match("/[0-9]/",$this->_lookahead))
1190				{
1191					return $token;
1192				}
1193				// 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
1194				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
1195					   !preg_match("/[0-9]/",$this->_lookahead))
1196				{
1197					return $token;
1198				}
1199				// If it's a number (check that it's not a sheet name or range)
1200				elseif (is_numeric($token) and
1201						(!is_numeric($token.$this->_lookahead) or ($this->_lookahead == '')) and
1202						($this->_lookahead != '!') and ($this->_lookahead != ':'))
1203				{
1204					return $token;
1205				}
1206				// If it's a string (of maximum 255 characters)
1207				elseif (preg_match("/\"([^\"]|\"\"){0,255}\"/",$token) and $this->_lookahead != '"' and (substr_count($token, '"')%2 == 0))
1208				{
1209					return $token;
1210				}
1211			    // If it's an error code
1212			    elseif (preg_match("/^#[A-Z0\/]{3,5}[!?]{1}$/", $token) or $token == '#N/A')
1213			    {
1214			        return $token;
1215			    }
1216				// if it's a function call
1217				elseif (preg_match("/^[A-Z0-9\xc0-\xdc\.]+$/i",$token) and ($this->_lookahead == "("))
1218				{
1219					return $token;
1220				}
1221				return '';
1222		}
1223	}
1224
1225	/**
1226	 * The parsing method. It parses a formula.
1227	 *
1228	 * @access public
1229	 * @param string $formula The formula to parse, without the initial equal
1230	 *                        sign (=).
1231	 * @return mixed true on success
1232	 */
1233	function parse($formula)
1234	{
1235		$this->_current_char = 0;
1236		$this->_formula      = $formula;
1237		$this->_lookahead    = isset($formula{1}) ? $formula{1} : '';
1238		$this->_advance();
1239		$this->_parse_tree   = $this->_condition();
1240		return true;
1241	}
1242
1243	/**
1244	 * It parses a condition. It assumes the following rule:
1245	 * Cond -> Expr [(">" | "<") Expr]
1246	 *
1247	 * @access private
1248	 * @return mixed The parsed ptg'd tree on success
1249	 */
1250	function _condition()
1251	{
1252		$result = $this->_expression();
1253		if ($this->_current_token == "<") {
1254			$this->_advance();
1255			$result2 = $this->_expression();
1256			$result = $this->_createTree('ptgLT', $result, $result2);
1257		} elseif ($this->_current_token == ">") {
1258			$this->_advance();
1259			$result2 = $this->_expression();
1260			$result = $this->_createTree('ptgGT', $result, $result2);
1261		} elseif ($this->_current_token == "<=") {
1262			$this->_advance();
1263			$result2 = $this->_expression();
1264			$result = $this->_createTree('ptgLE', $result, $result2);
1265		} elseif ($this->_current_token == ">=") {
1266			$this->_advance();
1267			$result2 = $this->_expression();
1268			$result = $this->_createTree('ptgGE', $result, $result2);
1269		} elseif ($this->_current_token == "=") {
1270			$this->_advance();
1271			$result2 = $this->_expression();
1272			$result = $this->_createTree('ptgEQ', $result, $result2);
1273		} elseif ($this->_current_token == "<>") {
1274			$this->_advance();
1275			$result2 = $this->_expression();
1276			$result = $this->_createTree('ptgNE', $result, $result2);
1277		} elseif ($this->_current_token == "&") {
1278		    $this->_advance();
1279		    $result2 = $this->_expression();
1280		    $result = $this->_createTree('ptgConcat', $result, $result2);
1281		}
1282		return $result;
1283	}
1284
1285	/**
1286	 * It parses a expression. It assumes the following rule:
1287	 * Expr -> Term [("+" | "-") Term]
1288	 *      -> "string"
1289	 *      -> "-" Term : Negative value
1290	 *      -> "+" Term : Positive value
1291	 *      -> Error code
1292	 *
1293	 * @access private
1294	 * @return mixed The parsed ptg'd tree on success
1295	 */
1296	function _expression()
1297	{
1298		// If it's a string return a string node
1299		if (preg_match("/\"([^\"]|\"\"){0,255}\"/", $this->_current_token)) {
1300			$tmp = str_replace('""', '"', $this->_current_token);
1301			if (($tmp == '"') || ($tmp == '')) $tmp = '""';	//	Trap for "" that has been used for an empty string
1302			$result = $this->_createTree($tmp, '', '');
1303			$this->_advance();
1304			return $result;
1305        // If it's an error code
1306        } elseif (preg_match("/^#[A-Z0\/]{3,5}[!?]{1}$/", $this->_current_token) or $this->_current_token == '#N/A'){
1307		    $result = $this->_createTree($this->_current_token, 'ptgErr', '');
1308		    $this->_advance();
1309		    return $result;
1310		// If it's a negative value
1311        } elseif ($this->_current_token == "-") {
1312			// catch "-" Term
1313			$this->_advance();
1314			$result2 = $this->_expression();
1315			$result = $this->_createTree('ptgUminus', $result2, '');
1316			return $result;
1317        // If it's a positive value
1318		} elseif ($this->_current_token == "+") {
1319			// catch "+" Term
1320			$this->_advance();
1321			$result2 = $this->_expression();
1322			$result = $this->_createTree('ptgUplus', $result2, '');
1323			return $result;
1324		}
1325		$result = $this->_term();
1326		while (($this->_current_token == "+") or
1327			   ($this->_current_token == "-") or
1328			   ($this->_current_token == "^")) {
1329		/**/
1330			if ($this->_current_token == "+") {
1331				$this->_advance();
1332				$result2 = $this->_term();
1333				$result = $this->_createTree('ptgAdd', $result, $result2);
1334			} elseif ($this->_current_token == "-") {
1335				$this->_advance();
1336				$result2 = $this->_term();
1337				$result = $this->_createTree('ptgSub', $result, $result2);
1338			} else {
1339				$this->_advance();
1340				$result2 = $this->_term();
1341				$result = $this->_createTree('ptgPower', $result, $result2);
1342			}
1343		}
1344		return $result;
1345	}
1346
1347	/**
1348	 * This function just introduces a ptgParen element in the tree, so that Excel
1349	 * doesn't get confused when working with a parenthesized formula afterwards.
1350	 *
1351	 * @access private
1352	 * @see _fact()
1353	 * @return array The parsed ptg'd tree
1354	 */
1355	function _parenthesizedExpression()
1356	{
1357		$result = $this->_createTree('ptgParen', $this->_expression(), '');
1358		return $result;
1359	}
1360
1361	/**
1362	 * It parses a term. It assumes the following rule:
1363	 * Term -> Fact [("*" | "/") Fact]
1364	 *
1365	 * @access private
1366	 * @return mixed The parsed ptg'd tree on success
1367	 */
1368	function _term()
1369	{
1370		$result = $this->_fact();
1371		while (($this->_current_token == "*") or
1372			   ($this->_current_token == "/")) {
1373		/**/
1374			if ($this->_current_token == "*") {
1375				$this->_advance();
1376				$result2 

Large files files are truncated, but you can click here to view the full file