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

Documentation generated on Mon, 05 Jan 2009 20:38:20 +0100 by phpDocumentor 1.4.1