PHPExcel_Writer_Excel5_Writer
[ class tree: PHPExcel_Writer_Excel5_Writer ] [ index: PHPExcel_Writer_Excel5_Writer ] [ all elements ]

Source for file Parser.php

Documentation is available at Parser.php

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

Documentation generated on Mon, 25 Aug 2008 13:46:40 +0200 by phpDocumentor 1.4.1