home *** CD-ROM | disk | FTP | other *** search
/ PC Professionell 2005 June / PCpro_2005_06.ISO / files / opensource / xamp / xampp-win32.exe / xampp / Workbook.php < prev    next >
Encoding:
PHP Script  |  2004-06-02  |  55.2 KB  |  1,545 lines

  1. <?php
  2. /*
  3. *  Module written/ported by Xavier Noguer <xnoguer@rezebra.com>
  4. *
  5. *  The majority of this is _NOT_ my code.  I simply ported it from the
  6. *  PERL Spreadsheet::WriteExcel module.
  7. *
  8. *  The author of the Spreadsheet::WriteExcel module is John McNamara 
  9. *  <jmcnamara@cpan.org>
  10. *
  11. *  I _DO_ maintain this code, and John McNamara has nothing to do with the
  12. *  porting of this code to PHP.  Any questions directly related to this
  13. *  class library should be directed to me.
  14. *
  15. *  License Information:
  16. *
  17. *    Spreadsheet_Excel_Writer:  A library for generating Excel Spreadsheets
  18. *    Copyright (c) 2002-2003 Xavier Noguer xnoguer@rezebra.com
  19. *
  20. *    This library is free software; you can redistribute it and/or
  21. *    modify it under the terms of the GNU Lesser General Public
  22. *    License as published by the Free Software Foundation; either
  23. *    version 2.1 of the License, or (at your option) any later version.
  24. *
  25. *    This library is distributed in the hope that it will be useful,
  26. *    but WITHOUT ANY WARRANTY; without even the implied warranty of
  27. *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  28. *    Lesser General Public License for more details.
  29. *
  30. *    You should have received a copy of the GNU Lesser General Public
  31. *    License along with this library; if not, write to the Free Software
  32. *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  33. */
  34.  
  35. require_once('Spreadsheet/Excel/Writer/Format.php');
  36. require_once('Spreadsheet/Excel/Writer/BIFFwriter.php');
  37. require_once('Spreadsheet/Excel/Writer/Worksheet.php');
  38. require_once('Spreadsheet/Excel/Writer/Parser.php');
  39. require_once('OLE/PPS/Root.php');
  40. require_once('OLE/PPS/File.php');
  41.  
  42. /**
  43. * Class for generating Excel Spreadsheets
  44. *
  45. * @author   Xavier Noguer <xnoguer@rezebra.com>
  46. * @category FileFormats
  47. * @package  Spreadsheet_Excel_Writer
  48. */
  49.  
  50. class Spreadsheet_Excel_Writer_Workbook extends Spreadsheet_Excel_Writer_BIFFwriter
  51. {
  52.     /**
  53.     * Filename for the Workbook
  54.     * @var string
  55.     */
  56.     var $_filename;
  57.  
  58.     /**
  59.     * Formula parser
  60.     * @var object Parser
  61.     */
  62.     var $_parser;
  63.  
  64.     /**
  65.     * Flag for 1904 date system (0 => base date is 1900, 1 => base date is 1904)
  66.     * @var integer
  67.     */
  68.     var $_1904;
  69.  
  70.     /**
  71.     * The active worksheet of the workbook (0 indexed)
  72.     * @var integer
  73.     */
  74.     var $_activesheet;
  75.  
  76.     /**
  77.     * 1st displayed worksheet in the workbook (0 indexed)
  78.     * @var integer
  79.     */
  80.     var $_firstsheet;
  81.  
  82.     /**
  83.     * Number of workbook tabs selected
  84.     * @var integer
  85.     */
  86.     var $_selected;
  87.  
  88.     /**
  89.     * Index for creating adding new formats to the workbook
  90.     * @var integer
  91.     */
  92.     var $_xf_index;
  93.  
  94.     /**
  95.     * Flag for preventing close from being called twice.
  96.     * @var integer
  97.     * @see close()
  98.     */
  99.     var $_fileclosed;
  100.  
  101.     /**
  102.     * The BIFF file size for the workbook.
  103.     * @var integer
  104.     * @see _calcSheetOffsets()
  105.     */
  106.     var $_biffsize;
  107.  
  108.     /**
  109.     * The default sheetname for all sheets created.
  110.     * @var string
  111.     */
  112.     var $_sheetname;
  113.  
  114.     /**
  115.     * The default XF format.
  116.     * @var object Format
  117.     */
  118.     var $_tmp_format;
  119.  
  120.     /**
  121.     * Array containing references to all of this workbook's worksheets
  122.     * @var array
  123.     */
  124.     var $_worksheets;
  125.  
  126.     /**
  127.     * Array of sheetnames for creating the EXTERNSHEET records
  128.     * @var array
  129.     */
  130.     var $_sheetnames;
  131.  
  132.     /**
  133.     * Array containing references to all of this workbook's formats
  134.     * @var array
  135.     */
  136.     var $_formats;
  137.  
  138.     /**
  139.     * Array containing the colour palette
  140.     * @var array
  141.     */
  142.     var $_palette;
  143.  
  144.     /**
  145.     * The default format for URLs.
  146.     * @var object Format
  147.     */
  148.     var $_url_format;
  149.  
  150.     /**
  151.     * The codepage indicates the text encoding used for strings
  152.     * @var integer
  153.     */
  154.     var $_codepage;
  155.  
  156.     /**
  157.     * The country code used for localization
  158.     * @var integer
  159.     */
  160.     var $_country_code;
  161.  
  162.     /**
  163.     * The temporary dir for storing the OLE file
  164.     * @var string
  165.     */
  166.     var $_tmp_dir;
  167.  
  168.     /**
  169.     * number of bytes for sizeinfo of strings
  170.     * @var integer
  171.     */
  172.     var $_string_sizeinfo_size;
  173.  
  174.     /**
  175.     * Class constructor
  176.     *
  177.     * @param string filename for storing the workbook. "-" for writing to stdout.
  178.     * @access public
  179.     */
  180.     function Spreadsheet_Excel_Writer_Workbook($filename)
  181.     {
  182.         // It needs to call its parent's constructor explicitly
  183.         $this->Spreadsheet_Excel_Writer_BIFFwriter();
  184.     
  185.         $this->_filename         = $filename;
  186.         $this->_parser           =& new Spreadsheet_Excel_Writer_Parser($this->_byte_order, $this->_BIFF_version);
  187.         $this->_1904             = 0;
  188.         $this->_activesheet      = 0;
  189.         $this->_firstsheet       = 0;
  190.         $this->_selected         = 0;
  191.         $this->_xf_index         = 16; // 15 style XF's and 1 cell XF.
  192.         $this->_fileclosed       = 0;
  193.         $this->_biffsize         = 0;
  194.         $this->_sheetname        = "Sheet";
  195.         $this->_tmp_format       =& new Spreadsheet_Excel_Writer_Format($this->_BIFF_version);
  196.         $this->_worksheets       = array();
  197.         $this->_sheetnames       = array();
  198.         $this->_formats          = array();
  199.         $this->_palette          = array();
  200.         $this->_codepage         = 0x04E4; // FIXME: should change for BIFF8
  201.         $this->_country_code     = -1;
  202.         $this->_string_sizeinfo  = 3;
  203.  
  204.         // Add the default format for hyperlinks
  205.         $this->_url_format =& $this->addFormat(array('color' => 'blue', 'underline' => 1));
  206.         $this->_str_total       = 0;
  207.         $this->_str_unique      = 0;
  208.         $this->_str_table       = array();
  209.         $this->_setPaletteXl97();
  210.         $this->_tmp_dir         = '';
  211.     }
  212.     
  213.     /**
  214.     * Calls finalization methods.
  215.     * This method should always be the last one to be called on every workbook
  216.     *
  217.     * @access public
  218.     * @return mixed true on success. PEAR_Error on failure
  219.     */
  220.     function close()
  221.     {
  222.         if ($this->_fileclosed) { // Prevent close() from being called twice.
  223.             return true;
  224.         }
  225.         $res = $this->_storeWorkbook();
  226.         if ($this->isError($res)) {
  227.             return $this->raiseError($res->getMessage());
  228.         }
  229.         $this->_fileclosed = 1;
  230.         return true;
  231.     }
  232.  
  233.     /**
  234.     * An accessor for the _worksheets[] array
  235.     * Returns an array of the worksheet objects in a workbook
  236.     * It actually calls to worksheets()
  237.     *
  238.     * @access public
  239.     * @see worksheets()
  240.     * @return array
  241.     */
  242.     function sheets()
  243.     {
  244.         return $this->worksheets();
  245.     }
  246.     
  247.     /**
  248.     * An accessor for the _worksheets[] array.
  249.     * Returns an array of the worksheet objects in a workbook
  250.     *
  251.     * @access public
  252.     * @return array
  253.     */
  254.     function worksheets()
  255.     {
  256.         return $this->_worksheets;
  257.     }
  258.  
  259.     /**
  260.     * Sets the BIFF version.
  261.     * This method exists just to access experimental functionality
  262.     * from BIFF8. It will be deprecated !
  263.     * Only possible value is 8 (Excel 97/2000).
  264.     * For any other value it fails silently.
  265.     *
  266.     * @access public
  267.     * @param integer $version The BIFF version
  268.     */
  269.     function setVersion($version)
  270.     {
  271.         if ($version == 8) { // only accept version 8
  272.             $version = 0x0600;
  273.             $this->_BIFF_version = $version;
  274.             // change BIFFwriter limit for CONTINUE records
  275.             $this->_limit = 8228;
  276.             $this->_tmp_format->_BIFF_version = $version;
  277.             $this->_url_format->_BIFF_version = $version;
  278.             $this->_parser->_BIFF_version = $version;
  279.             $total_worksheets = count($this->_worksheets);
  280.             // change version for all worksheets too
  281.             for ($i = 0; $i < $total_worksheets; $i++) {
  282.                 $this->_worksheets[$i]->_BIFF_version = $version;
  283.             }
  284.             $total_formats = count($this->_formats);
  285.             // change version for all formats too
  286.             for ($i = 0; $i < $total_formats; $i++) {
  287.                 $this->_formats[$i]->_BIFF_version = $version;
  288.             }
  289.         }
  290.     }
  291.  
  292.     /**
  293.     * Set the country identifier for the workbook
  294.     *
  295.     * @access public
  296.     * @param integer $code Is the international calling country code for the
  297.     *                      chosen country.
  298.     */
  299.     function setCountry($code)
  300.     {
  301.         $this->_country_code = $code;
  302.     }
  303.  
  304.     /**
  305.     * Add a new worksheet to the Excel workbook.
  306.     * If no name is given the name of the worksheet will be Sheeti$i, with
  307.     * $i in [1..].
  308.     *
  309.     * @access public
  310.     * @param string $name the optional name of the worksheet
  311.     * @return mixed reference to a worksheet object on success, PEAR_Error
  312.     *               on failure
  313.     */
  314.     function &addWorksheet($name = '')
  315.     {
  316.         $index     = count($this->_worksheets);
  317.         $sheetname = $this->_sheetname;
  318.     
  319.         if ($name == '') {
  320.             $name = $sheetname.($index+1); 
  321.         }
  322.     
  323.         // Check that sheetname is <= 31 chars (Excel limit).
  324.         if (strlen($name) > 31) {
  325.             return $this->raiseError("Sheetname $name must be <= 31 chars");
  326.         }
  327.     
  328.         // Check that the worksheet name doesn't already exist: a fatal Excel error.
  329.         $total_worksheets = count($this->_worksheets);
  330.         for ($i=0; $i < $total_worksheets; $i++)
  331.         {
  332.             if ($name == $this->_worksheets[$i]->getName()) {
  333.                 return $this->raiseError("Worksheet '$name' already exists");
  334.             }
  335.         }
  336.     
  337.         $worksheet = new Spreadsheet_Excel_Writer_Worksheet($this->_BIFF_version,
  338.                                    $name, $index,
  339.                                    $this->_activesheet, $this->_firstsheet,
  340.                                    $this->_str_total, $this->_str_unique,
  341.                                    $this->_str_table, $this->_url_format,
  342.                                    $this->_parser);
  343.  
  344.         $this->_worksheets[$index] = &$worksheet;    // Store ref for iterator
  345.         $this->_sheetnames[$index] = $name;          // Store EXTERNSHEET names
  346.         $this->_parser->setExtSheet($name, $index);  // Register worksheet name with parser
  347.         return $worksheet;
  348.     }
  349.     
  350.     /**
  351.     * Add a new format to the Excel workbook.
  352.     * Also, pass any properties to the Format constructor.
  353.     *
  354.     * @access public
  355.     * @param array $properties array with properties for initializing the format.
  356.     * @return &Spreadsheet_Excel_Writer_Format reference to an Excel Format
  357.     */
  358.     function &addFormat($properties = array())
  359.     {
  360.         $format = new Spreadsheet_Excel_Writer_Format($this->_BIFF_version, $this->_xf_index,$properties);
  361.         $this->_xf_index += 1;
  362.         $this->_formats[] = &$format;
  363.         return $format;
  364.     }
  365.     
  366.     /**
  367.      * Create new validator.
  368.      *
  369.      * @access public
  370.      * @return &Spreadsheet_Excel_Writer_Validator reference to a Validator
  371.      */
  372.     function &addValidator()
  373.     {
  374.         include_once('Spreadsheet/Excel/Writer/Validator.php');
  375.         /* FIXME: check for successful inclusion*/
  376.         $valid = new Spreadsheet_Excel_Writer_Validator($this->_parser);
  377.         return $valid;
  378.     }
  379.  
  380.     /**
  381.     * Change the RGB components of the elements in the colour palette.
  382.     *
  383.     * @access public
  384.     * @param integer $index colour index
  385.     * @param integer $red   red RGB value [0-255]
  386.     * @param integer $green green RGB value [0-255]
  387.     * @param integer $blue  blue RGB value [0-255]
  388.     * @return integer The palette index for the custom color
  389.     */
  390.     function setCustomColor($index,$red,$green,$blue)
  391.     {
  392.         // Match a HTML #xxyyzz style parameter
  393.         /*if (defined $_[1] and $_[1] =~ /^#(\w\w)(\w\w)(\w\w)/ ) {
  394.             @_ = ($_[0], hex $1, hex $2, hex $3);
  395.         }*/
  396.     
  397.         // Check that the colour index is the right range
  398.         if ($index < 8 or $index > 64) {
  399.             // TODO: assign real error codes
  400.             return $this->raiseError("Color index $index outside range: 8 <= index <= 64");
  401.         }
  402.     
  403.         // Check that the colour components are in the right range
  404.         if ( ($red   < 0 or $red   > 255) or
  405.              ($green < 0 or $green > 255) or
  406.              ($blue  < 0 or $blue  > 255) )  
  407.         {
  408.             return $this->raiseError("Color component outside range: 0 <= color <= 255");
  409.         }
  410.     
  411.         $index -= 8; // Adjust colour index (wingless dragonfly)
  412.         
  413.         // Set the RGB value
  414.         $this->_palette[$index] = array($red, $green, $blue, 0);
  415.         return($index + 8);
  416.     }
  417.     
  418.     /**
  419.     * Sets the colour palette to the Excel 97+ default.
  420.     *
  421.     * @access private
  422.     */
  423.     function _setPaletteXl97()
  424.     {
  425.         $this->_palette = array(
  426.                            array(0x00, 0x00, 0x00, 0x00),   // 8
  427.                            array(0xff, 0xff, 0xff, 0x00),   // 9
  428.                            array(0xff, 0x00, 0x00, 0x00),   // 10
  429.                            array(0x00, 0xff, 0x00, 0x00),   // 11
  430.                            array(0x00, 0x00, 0xff, 0x00),   // 12
  431.                            array(0xff, 0xff, 0x00, 0x00),   // 13
  432.                            array(0xff, 0x00, 0xff, 0x00),   // 14
  433.                            array(0x00, 0xff, 0xff, 0x00),   // 15
  434.                            array(0x80, 0x00, 0x00, 0x00),   // 16
  435.                            array(0x00, 0x80, 0x00, 0x00),   // 17
  436.                            array(0x00, 0x00, 0x80, 0x00),   // 18
  437.                            array(0x80, 0x80, 0x00, 0x00),   // 19
  438.                            array(0x80, 0x00, 0x80, 0x00),   // 20
  439.                            array(0x00, 0x80, 0x80, 0x00),   // 21
  440.                            array(0xc0, 0xc0, 0xc0, 0x00),   // 22
  441.                            array(0x80, 0x80, 0x80, 0x00),   // 23
  442.                            array(0x99, 0x99, 0xff, 0x00),   // 24
  443.                            array(0x99, 0x33, 0x66, 0x00),   // 25
  444.                            array(0xff, 0xff, 0xcc, 0x00),   // 26
  445.                            array(0xcc, 0xff, 0xff, 0x00),   // 27
  446.                            array(0x66, 0x00, 0x66, 0x00),   // 28
  447.                            array(0xff, 0x80, 0x80, 0x00),   // 29
  448.                            array(0x00, 0x66, 0xcc, 0x00),   // 30
  449.                            array(0xcc, 0xcc, 0xff, 0x00),   // 31
  450.                            array(0x00, 0x00, 0x80, 0x00),   // 32
  451.                            array(0xff, 0x00, 0xff, 0x00),   // 33
  452.                            array(0xff, 0xff, 0x00, 0x00),   // 34
  453.                            array(0x00, 0xff, 0xff, 0x00),   // 35
  454.                            array(0x80, 0x00, 0x80, 0x00),   // 36
  455.                            array(0x80, 0x00, 0x00, 0x00),   // 37
  456.                            array(0x00, 0x80, 0x80, 0x00),   // 38
  457.                            array(0x00, 0x00, 0xff, 0x00),   // 39
  458.                            array(0x00, 0xcc, 0xff, 0x00),   // 40
  459.                            array(0xcc, 0xff, 0xff, 0x00),   // 41
  460.                            array(0xcc, 0xff, 0xcc, 0x00),   // 42
  461.                            array(0xff, 0xff, 0x99, 0x00),   // 43
  462.                            array(0x99, 0xcc, 0xff, 0x00),   // 44
  463.                            array(0xff, 0x99, 0xcc, 0x00),   // 45
  464.                            array(0xcc, 0x99, 0xff, 0x00),   // 46
  465.                            array(0xff, 0xcc, 0x99, 0x00),   // 47
  466.                            array(0x33, 0x66, 0xff, 0x00),   // 48
  467.                            array(0x33, 0xcc, 0xcc, 0x00),   // 49
  468.                            array(0x99, 0xcc, 0x00, 0x00),   // 50
  469.                            array(0xff, 0xcc, 0x00, 0x00),   // 51
  470.                            array(0xff, 0x99, 0x00, 0x00),   // 52
  471.                            array(0xff, 0x66, 0x00, 0x00),   // 53
  472.                            array(0x66, 0x66, 0x99, 0x00),   // 54
  473.                            array(0x96, 0x96, 0x96, 0x00),   // 55
  474.                            array(0x00, 0x33, 0x66, 0x00),   // 56
  475.                            array(0x33, 0x99, 0x66, 0x00),   // 57
  476.                            array(0x00, 0x33, 0x00, 0x00),   // 58
  477.                            array(0x33, 0x33, 0x00, 0x00),   // 59
  478.                            array(0x99, 0x33, 0x00, 0x00),   // 60
  479.                            array(0x99, 0x33, 0x66, 0x00),   // 61
  480.                            array(0x33, 0x33, 0x99, 0x00),   // 62
  481.                            array(0x33, 0x33, 0x33, 0x00),   // 63
  482.                          );
  483.     }
  484.     
  485.     /**
  486.     * Assemble worksheets into a workbook and send the BIFF data to an OLE
  487.     * storage.
  488.     *
  489.     * @access private
  490.     * @return mixed true on success. PEAR_Error on failure
  491.     */
  492.     function _storeWorkbook()
  493.     {
  494.         // Ensure that at least one worksheet has been selected.
  495.         if ($this->_activesheet == 0) {
  496.             $this->_worksheets[0]->selected = 1;
  497.         }
  498.     
  499.         // Calculate the number of selected worksheet tabs and call the finalization
  500.         // methods for each worksheet
  501.         $total_worksheets = count($this->_worksheets);
  502.         for ($i=0; $i < $total_worksheets; $i++) {
  503.             if ($this->_worksheets[$i]->selected) {
  504.                 $this->_selected++;
  505.             }
  506.             $this->_worksheets[$i]->close($this->_sheetnames);
  507.         }
  508.     
  509.         // Add Workbook globals
  510.         $this->_storeBof(0x0005);
  511.         $this->_storeCodepage();
  512.         if ($this->_BIFF_version == 0x0600) {
  513.             $this->_storeWindow1();
  514.         }
  515.         if ($this->_BIFF_version == 0x0500) {
  516.             $this->_storeExterns();    // For print area and repeat rows
  517.         }
  518.         $this->_storeNames();      // For print area and repeat rows
  519.         if ($this->_BIFF_version == 0x0500) {
  520.             $this->_storeWindow1();
  521.         }
  522.         $this->_storeDatemode();
  523.         $this->_storeAllFonts();
  524.         $this->_storeAllNumFormats();
  525.         $this->_storeAllXfs();
  526.         $this->_storeAllStyles();
  527.         $this->_storePalette();
  528.         $this->_calcSheetOffsets();
  529.     
  530.         // Add BOUNDSHEET records
  531.         for ($i=0; $i < $total_worksheets; $i++) {
  532.             $this->_storeBoundsheet($this->_worksheets[$i]->name,$this->_worksheets[$i]->offset);
  533.         }
  534.  
  535.         if ($this->_country_code != -1) {
  536.             $this->_storeCountry();
  537.         }
  538.  
  539.         if ($this->_BIFF_version == 0x0600) {
  540.             //$this->_storeSupbookInternal();
  541.             /* TODO: store external SUPBOOK records and XCT and CRN records 
  542.             in case of external references for BIFF8 */
  543.             //$this->_storeExternsheetBiff8();
  544.             $this->_storeSharedStringsTable();
  545.         }
  546.  
  547.         // End Workbook globals
  548.         $this->_storeEof();
  549.     
  550.         // Store the workbook in an OLE container
  551.         $res = $this->_storeOLEFile();
  552.         if ($this->isError($res)) {
  553.             return $this->raiseError($res->getMessage());
  554.         }
  555.         return true;
  556.     }
  557.     
  558.     /**
  559.     * Sets the temp dir used for storing the OLE file
  560.     *
  561.     * @access public
  562.     * @param string $dir The dir to be used as temp dir
  563.     * @return true if given dir is valid, false otherwise
  564.     */
  565.     function setTempDir($dir)
  566.     {
  567.         if (is_dir($dir)) {
  568.             $this->_tmp_dir = $dir;
  569.             return true;
  570.         }
  571.         return false;
  572.     }
  573.  
  574.     /**
  575.     * Store the workbook in an OLE container
  576.     *
  577.     * @access private
  578.     * @return mixed true on success. PEAR_Error on failure
  579.     */
  580.     function _storeOLEFile()
  581.     {
  582.         $OLE = new OLE_PPS_File(OLE::Asc2Ucs('Book'));
  583.         if ($this->_tmp_dir != '') {
  584.             $OLE->setTempDir($this->_tmp_dir);
  585.         }
  586.         $res = $OLE->init();
  587.         if ($this->isError($res)) {
  588.             return $this->raiseError("OLE Error: ".$res->getMessage());
  589.         }
  590.         $OLE->append($this->_data);
  591.         $total_worksheets = count($this->_worksheets);
  592.         for ($i = 0; $i < $total_worksheets; $i++)
  593.         {
  594.             while ($tmp = $this->_worksheets[$i]->getData()) {
  595.                 $OLE->append($tmp);
  596.             }
  597.         }
  598.         $root = new OLE_PPS_Root(time(), time(), array($OLE));
  599.         if ($this->_tmp_dir != '') {
  600.             $root->setTempDir($this->_tmp_dir);
  601.         }
  602.         $res = $root->save($this->_filename);
  603.         if ($this->isError($res)) {
  604.             return $this->raiseError("OLE Error: ".$res->getMessage());
  605.         }
  606.         return true;
  607.     }
  608.  
  609.     /**
  610.     * Calculate offsets for Worksheet BOF records.
  611.     *
  612.     * @access private
  613.     */
  614.     function _calcSheetOffsets()
  615.     {
  616.         if ($this->_BIFF_version == 0x0600) {
  617.             $boundsheet_length = 12;  // fixed length for a BOUNDSHEET record
  618.         }
  619.         else {
  620.             $boundsheet_length = 11;
  621.         }
  622.         $EOF               = 4;
  623.         $offset            = $this->_datasize;
  624.  
  625.         if ($this->_BIFF_version == 0x0600) {
  626.             // add the length of the SST
  627.             /* TODO: check this works for a lot of strings (> 8224 bytes) */
  628.             $offset += $this->_calculateSharedStringsSizes();
  629.             if ($this->_country_code != -1) {
  630.                 $offset += 8; // adding COUNTRY record
  631.             }
  632.             // add the lenght of SUPBOOK, EXTERNSHEET and NAME records
  633.             //$offset += 8; // FIXME: calculate real value when storing the records
  634.         }
  635.         $total_worksheets = count($this->_worksheets);
  636.         // add the length of the BOUNDSHEET records 
  637.         for ($i=0; $i < $total_worksheets; $i++) {
  638.             $offset += $boundsheet_length + strlen($this->_worksheets[$i]->name);
  639.         }
  640.         $offset += $EOF;
  641.  
  642.         for ($i=0; $i < $total_worksheets; $i++) {
  643.             $this->_worksheets[$i]->offset = $offset;
  644.             $offset += $this->_worksheets[$i]->_datasize;
  645.         }
  646.         $this->_biffsize = $offset;
  647.     }
  648.     
  649.     /**
  650.     * Store the Excel FONT records.
  651.     *
  652.     * @access private
  653.     */
  654.     function _storeAllFonts()
  655.     {
  656.         // tmp_format is added by the constructor. We use this to write the default XF's
  657.         $format = $this->_tmp_format;
  658.         $font   = $format->getFont();
  659.     
  660.         // Note: Fonts are 0-indexed. According to the SDK there is no index 4,
  661.         // so the following fonts are 0, 1, 2, 3, 5
  662.         //
  663.         for ($i=1; $i <= 5; $i++){
  664.             $this->_append($font);
  665.         }
  666.     
  667.         // Iterate through the XF objects and write a FONT record if it isn't the
  668.         // same as the default FONT and if it hasn't already been used.
  669.         //
  670.         $fonts = array();
  671.         $index = 6;                  // The first user defined FONT
  672.     
  673.         $key = $format->getFontKey(); // The default font from _tmp_format
  674.         $fonts[$key] = 0;             // Index of the default font
  675.  
  676.         $total_formats = count($this->_formats);
  677.         for ($i=0; $i < $total_formats; $i++)
  678.         {
  679.             $key = $this->_formats[$i]->getFontKey();
  680.             if (isset($fonts[$key])) {
  681.                 // FONT has already been used
  682.                 $this->_formats[$i]->font_index = $fonts[$key];
  683.             }
  684.             else {
  685.                 // Add a new FONT record
  686.                 $fonts[$key]        = $index;
  687.                 $this->_formats[$i]->font_index = $index;
  688.                 $index++;
  689.                 $font = $this->_formats[$i]->getFont();
  690.                 $this->_append($font);
  691.             }
  692.         }
  693.     }
  694.     
  695.     /**
  696.     * Store user defined numerical formats i.e. FORMAT records
  697.     *
  698.     * @access private
  699.     */
  700.     function _storeAllNumFormats()
  701.     {
  702.         // Leaning num_format syndrome
  703.         $hash_num_formats = array();
  704.         $num_formats      = array();
  705.         $index = 164;
  706.     
  707.         // Iterate through the XF objects and write a FORMAT record if it isn't a
  708.         // built-in format type and if the FORMAT string hasn't already been used.
  709.         $total_formats = count($this->_formats);
  710.         for ($i=0; $i < $total_formats; $i++)
  711.         {
  712.             $num_format = $this->_formats[$i]->_num_format;
  713.     
  714.             // Check if $num_format is an index to a built-in format.
  715.             // Also check for a string of zeros, which is a valid format string
  716.             // but would evaluate to zero.
  717.             //
  718.             if (!preg_match("/^0+\d/",$num_format))
  719.             {
  720.                 if (preg_match("/^\d+$/",$num_format)) { // built-in format
  721.                     continue;
  722.                 }
  723.             }
  724.     
  725.             if (isset($hash_num_formats[$num_format])) {
  726.                 // FORMAT has already been used
  727.                 $this->_formats[$i]->_num_format = $hash_num_formats[$num_format];
  728.             }
  729.             else{
  730.                 // Add a new FORMAT
  731.                 $hash_num_formats[$num_format]  = $index;
  732.                 $this->_formats[$i]->_num_format = $index;
  733.                 array_push($num_formats,$num_format);
  734.                 $index++;
  735.             }
  736.         }
  737.     
  738.         // Write the new FORMAT records starting from 0xA4
  739.         $index = 164;
  740.         foreach ($num_formats as $num_format) {
  741.             $this->_storeNumFormat($num_format,$index);
  742.             $index++;
  743.         }
  744.     }
  745.     
  746.     /**
  747.     * Write all XF records.
  748.     *
  749.     * @access private
  750.     */
  751.     function _storeAllXfs()
  752.     {
  753.         // _tmp_format is added by the constructor. We use this to write the default XF's
  754.         // The default font index is 0
  755.         //
  756.         $format = $this->_tmp_format;
  757.         for ($i=0; $i <= 14; $i++) {
  758.             $xf = $format->getXf('style'); // Style XF
  759.             $this->_append($xf);
  760.         }
  761.     
  762.         $xf = $format->getXf('cell');      // Cell XF
  763.         $this->_append($xf);
  764.     
  765.         // User defined XFs
  766.         $total_formats = count($this->_formats);
  767.         for ($i=0; $i < $total_formats; $i++) {
  768.             $xf = $this->_formats[$i]->getXf('cell');
  769.             $this->_append($xf);
  770.         }
  771.     }
  772.     
  773.     /**
  774.     * Write all STYLE records.
  775.     *
  776.     * @access private 
  777.     */
  778.     function _storeAllStyles()
  779.     {
  780.         $this->_storeStyle();
  781.     }
  782.     
  783.     /**
  784.     * Write the EXTERNCOUNT and EXTERNSHEET records. These are used as indexes for
  785.     * the NAME records.
  786.     *
  787.     * @access private
  788.     */
  789.     function _storeExterns()
  790.     {
  791.         // Create EXTERNCOUNT with number of worksheets
  792.         $this->_storeExterncount(count($this->_worksheets));
  793.     
  794.         // Create EXTERNSHEET for each worksheet
  795.         foreach ($this->_sheetnames as $sheetname) {
  796.             $this->_storeExternsheet($sheetname);
  797.         }
  798.     }
  799.     
  800.     /**
  801.     * Write the NAME record to define the print area and the repeat rows and cols.
  802.     *
  803.     * @access private
  804.     */
  805.     function _storeNames()
  806.     {
  807.         // Create the print area NAME records
  808.         $total_worksheets = count($this->_worksheets);
  809.         for ($i = 0; $i < $total_worksheets; $i++) {
  810.             // Write a Name record if the print area has been defined
  811.             if (isset($this->_worksheets[$i]->print_rowmin))
  812.             {
  813.                 $this->_storeNameShort(
  814.                     $this->_worksheets[$i]->index,
  815.                     0x06, // NAME type
  816.                     $this->_worksheets[$i]->print_rowmin,
  817.                     $this->_worksheets[$i]->print_rowmax,
  818.                     $this->_worksheets[$i]->print_colmin,
  819.                     $this->_worksheets[$i]->print_colmax
  820.                     );
  821.             }
  822.         }
  823.     
  824.         // Create the print title NAME records
  825.         $total_worksheets = count($this->_worksheets);
  826.         for ($i = 0; $i < $total_worksheets; $i++) {
  827.             $rowmin = $this->_worksheets[$i]->title_rowmin;
  828.             $rowmax = $this->_worksheets[$i]->title_rowmax;
  829.             $colmin = $this->_worksheets[$i]->title_colmin;
  830.             $colmax = $this->_worksheets[$i]->title_colmax;
  831.     
  832.             // Determine if row + col, row, col or nothing has been defined
  833.             // and write the appropriate record
  834.             //
  835.             if (isset($rowmin) and isset($colmin)) {
  836.                 // Row and column titles have been defined.
  837.                 // Row title has been defined.
  838.                 $this->_storeNameLong(
  839.                     $this->_worksheets[$i]->index,
  840.                     0x07, // NAME type
  841.                     $rowmin,
  842.                     $rowmax,
  843.                     $colmin,
  844.                     $colmax
  845.                     );
  846.             }
  847.             elseif (isset($rowmin)) {
  848.                 // Row title has been defined.
  849.                 $this->_storeNameShort(
  850.                     $this->_worksheets[$i]->index,
  851.                     0x07, // NAME type
  852.                     $rowmin,
  853.                     $rowmax,
  854.                     0x00,
  855.                     0xff
  856.                     );
  857.             }
  858.             elseif (isset($colmin)) {
  859.                 // Column title has been defined.
  860.                 $this->_storeNameShort(
  861.                     $this->_worksheets[$i]->index,
  862.                     0x07, // NAME type
  863.                     0x0000,
  864.                     0x3fff,
  865.                     $colmin,
  866.                     $colmax
  867.                     );
  868.             }
  869.             else {
  870.                 // Print title hasn't been defined.
  871.             }
  872.         }
  873.     }
  874.     
  875.     
  876.     
  877.     
  878.     /******************************************************************************
  879.     *
  880.     * BIFF RECORDS
  881.     *
  882.     */
  883.     
  884.     /**
  885.     * Stores the CODEPAGE biff record.
  886.     *
  887.     * @access private
  888.     */
  889.     function _storeCodepage()
  890.     {
  891.         $record          = 0x0042;             // Record identifier
  892.         $length          = 0x0002;             // Number of bytes to follow
  893.         $cv              = $this->_codepage;   // The code page
  894.  
  895.         $header          = pack('vv', $record, $length);
  896.         $data            = pack('v',  $cv);
  897.  
  898.         $this->_append($header.$data);
  899.     }
  900.  
  901.     /**
  902.     * Write Excel BIFF WINDOW1 record.
  903.     *
  904.     * @access private
  905.     */
  906.     function _storeWindow1()
  907.     {
  908.         $record    = 0x003D;                 // Record identifier
  909.         $length    = 0x0012;                 // Number of bytes to follow
  910.     
  911.         $xWn       = 0x0000;                 // Horizontal position of window
  912.         $yWn       = 0x0000;                 // Vertical position of window
  913.         $dxWn      = 0x25BC;                 // Width of window
  914.         $dyWn      = 0x1572;                 // Height of window
  915.     
  916.         $grbit     = 0x0038;                 // Option flags
  917.         $ctabsel   = $this->_selected;       // Number of workbook tabs selected
  918.         $wTabRatio = 0x0258;                 // Tab to scrollbar ratio
  919.     
  920.         $itabFirst = $this->_firstsheet;     // 1st displayed worksheet
  921.         $itabCur   = $this->_activesheet;    // Active worksheet
  922.     
  923.         $header    = pack("vv",        $record, $length);
  924.         $data      = pack("vvvvvvvvv", $xWn, $yWn, $dxWn, $dyWn,
  925.                                        $grbit,
  926.                                        $itabCur, $itabFirst,
  927.                                        $ctabsel, $wTabRatio);
  928.         $this->_append($header.$data);
  929.     }
  930.     
  931.     /**
  932.     * Writes Excel BIFF BOUNDSHEET record.
  933.     * FIXME: inconsistent with BIFF documentation
  934.     *
  935.     * @param string  $sheetname Worksheet name
  936.     * @param integer $offset    Location of worksheet BOF
  937.     * @access private
  938.     */
  939.     function _storeBoundsheet($sheetname,$offset)
  940.     {
  941.         $record    = 0x0085;                    // Record identifier
  942.         if ($this->_BIFF_version == 0x0600) {
  943.             $length    = 0x08 + strlen($sheetname); // Number of bytes to follow
  944.         }
  945.         else {
  946.             $length = 0x07 + strlen($sheetname); // Number of bytes to follow
  947.         }
  948.     
  949.         $grbit     = 0x0000;                    // Visibility and sheet type
  950.         $cch       = strlen($sheetname);        // Length of sheet name
  951.     
  952.         $header    = pack("vv",  $record, $length);
  953.         if ($this->_BIFF_version == 0x0600) {
  954.             $data      = pack("Vvv", $offset, $grbit, $cch);
  955.         }
  956.         else {
  957.             $data      = pack("VvC", $offset, $grbit, $cch);
  958.         }
  959.         $this->_append($header.$data.$sheetname);
  960.     }
  961.  
  962.     /**
  963.     * Write Internal SUPBOOK record
  964.     *
  965.     * @access private
  966.     */
  967.     function _storeSupbookInternal()
  968.     {
  969.         $record    = 0x01AE;   // Record identifier
  970.         $length    = 0x0004;   // Bytes to follow
  971.                                
  972.         $header    = pack("vv", $record, $length);
  973.         $data      = pack("vv", count($this->_worksheets), 0x0104);
  974.         $this->_append($header.$data);
  975.     }
  976.  
  977.     /**
  978.     * Writes the Excel BIFF EXTERNSHEET record. These references are used by
  979.     * formulas. 
  980.     *
  981.     * @param string $sheetname Worksheet name
  982.     * @access private
  983.     */
  984.     function _storeExternsheetBiff8()
  985.     {
  986.         $total_references = count($this->_parser->_references);
  987.         $record   = 0x0017;                     // Record identifier
  988.         $length   = 2 + 6 * $total_references;  // Number of bytes to follow
  989.  
  990.         $supbook_index = 0;           // FIXME: only using internal SUPBOOK record
  991.         $header           = pack("vv",  $record, $length);
  992.         $data             = pack('v', $total_references);
  993.         for ($i = 0; $i < $total_references; $i++) {
  994.             $data .= $this->_parser->_references[$i];
  995.         }
  996.         $this->_append($header.$data);
  997.     }
  998.  
  999.     /**
  1000.     * Write Excel BIFF STYLE records.
  1001.     *
  1002.     * @access private
  1003.     */
  1004.     function _storeStyle()
  1005.     {
  1006.         $record    = 0x0293;   // Record identifier
  1007.         $length    = 0x0004;   // Bytes to follow
  1008.                                
  1009.         $ixfe      = 0x8000;   // Index to style XF
  1010.         $BuiltIn   = 0x00;     // Built-in style
  1011.         $iLevel    = 0xff;     // Outline style level
  1012.     
  1013.         $header    = pack("vv",  $record, $length);
  1014.         $data      = pack("vCC", $ixfe, $BuiltIn, $iLevel);
  1015.         $this->_append($header.$data);
  1016.     }
  1017.     
  1018.     
  1019.     /**
  1020.     * Writes Excel FORMAT record for non "built-in" numerical formats.
  1021.     *
  1022.     * @param string  $format Custom format string
  1023.     * @param integer $ifmt   Format index code
  1024.     * @access private
  1025.     */
  1026.     function _storeNumFormat($format,$ifmt)
  1027.     {
  1028.         $record    = 0x041E;                      // Record identifier
  1029.  
  1030.         if ($this->_BIFF_version == 0x0600) {
  1031.             $length    = 5 + strlen($format);      // Number of bytes to follow
  1032.             $encoding = 0x0;
  1033.         }
  1034.         elseif ($this->_BIFF_version == 0x0500) {
  1035.             $length    = 3 + strlen($format);      // Number of bytes to follow
  1036.         }
  1037.  
  1038.         $cch       = strlen($format);             // Length of format string
  1039.     
  1040.         $header    = pack("vv", $record, $length);
  1041.         if ($this->_BIFF_version == 0x0600) {
  1042.             $data      = pack("vvC", $ifmt, $cch, $encoding);
  1043.         }
  1044.         elseif ($this->_BIFF_version == 0x0500) {
  1045.             $data      = pack("vC", $ifmt, $cch);
  1046.         }
  1047.         $this->_append($header.$data.$format);
  1048.     }
  1049.     
  1050.     /**
  1051.     * Write DATEMODE record to indicate the date system in use (1904 or 1900).
  1052.     *
  1053.     * @access private
  1054.     */
  1055.     function _storeDatemode()
  1056.     {
  1057.         $record    = 0x0022;         // Record identifier
  1058.         $length    = 0x0002;         // Bytes to follow
  1059.     
  1060.         $f1904     = $this->_1904;   // Flag for 1904 date system
  1061.     
  1062.         $header    = pack("vv", $record, $length);
  1063.         $data      = pack("v", $f1904);
  1064.         $this->_append($header.$data);
  1065.     }
  1066.     
  1067.     
  1068.     /**
  1069.     * Write BIFF record EXTERNCOUNT to indicate the number of external sheet
  1070.     * references in the workbook.
  1071.     *
  1072.     * Excel only stores references to external sheets that are used in NAME.
  1073.     * The workbook NAME record is required to define the print area and the repeat
  1074.     * rows and columns.
  1075.     *
  1076.     * A similar method is used in Worksheet.php for a slightly different purpose.
  1077.     *
  1078.     * @param integer $cxals Number of external references
  1079.     * @access private
  1080.     */
  1081.     function _storeExterncount($cxals)
  1082.     {
  1083.         $record   = 0x0016;          // Record identifier
  1084.         $length   = 0x0002;          // Number of bytes to follow
  1085.     
  1086.         $header   = pack("vv", $record, $length);
  1087.         $data     = pack("v",  $cxals);
  1088.         $this->_append($header.$data);
  1089.     }
  1090.     
  1091.     
  1092.     /**
  1093.     * Writes the Excel BIFF EXTERNSHEET record. These references are used by
  1094.     * formulas. NAME record is required to define the print area and the repeat
  1095.     * rows and columns.
  1096.     *
  1097.     * A similar method is used in Worksheet.php for a slightly different purpose.
  1098.     *
  1099.     * @param string $sheetname Worksheet name
  1100.     * @access private
  1101.     */
  1102.     function _storeExternsheet($sheetname)
  1103.     {
  1104.         $record      = 0x0017;                     // Record identifier
  1105.         $length      = 0x02 + strlen($sheetname);  // Number of bytes to follow
  1106.                                                    
  1107.         $cch         = strlen($sheetname);         // Length of sheet name
  1108.         $rgch        = 0x03;                       // Filename encoding
  1109.     
  1110.         $header      = pack("vv",  $record, $length);
  1111.         $data        = pack("CC", $cch, $rgch);
  1112.         $this->_append($header.$data.$sheetname);
  1113.     }
  1114.     
  1115.     
  1116.     /**
  1117.     * Store the NAME record in the short format that is used for storing the print
  1118.     * area, repeat rows only and repeat columns only.
  1119.     *
  1120.     * @param integer $index  Sheet index
  1121.     * @param integer $type   Built-in name type
  1122.     * @param integer $rowmin Start row
  1123.     * @param integer $rowmax End row
  1124.     * @param integer $colmin Start colum
  1125.     * @param integer $colmax End column
  1126.     * @access private
  1127.     */
  1128.     function _storeNameShort($index,$type,$rowmin,$rowmax,$colmin,$colmax)
  1129.     {
  1130.         $record          = 0x0018;       // Record identifier
  1131.         $length          = 0x0024;       // Number of bytes to follow
  1132.     
  1133.         $grbit           = 0x0020;       // Option flags
  1134.         $chKey           = 0x00;         // Keyboard shortcut
  1135.         $cch             = 0x01;         // Length of text name
  1136.         $cce             = 0x0015;       // Length of text definition
  1137.         $ixals           = $index + 1;   // Sheet index
  1138.         $itab            = $ixals;       // Equal to ixals
  1139.         $cchCustMenu     = 0x00;         // Length of cust menu text
  1140.         $cchDescription  = 0x00;         // Length of description text
  1141.         $cchHelptopic    = 0x00;         // Length of help topic text
  1142.         $cchStatustext   = 0x00;         // Length of status bar text
  1143.         $rgch            = $type;        // Built-in name type
  1144.     
  1145.         $unknown03       = 0x3b;
  1146.         $unknown04       = 0xffff-$index;
  1147.         $unknown05       = 0x0000;
  1148.         $unknown06       = 0x0000;
  1149.         $unknown07       = 0x1087;
  1150.         $unknown08       = 0x8005;
  1151.     
  1152.         $header             = pack("vv", $record, $length);
  1153.         $data               = pack("v", $grbit);
  1154.         $data              .= pack("C", $chKey);
  1155.         $data              .= pack("C", $cch);
  1156.         $data              .= pack("v", $cce);
  1157.         $data              .= pack("v", $ixals);
  1158.         $data              .= pack("v", $itab);
  1159.         $data              .= pack("C", $cchCustMenu);
  1160.         $data              .= pack("C", $cchDescription);
  1161.         $data              .= pack("C", $cchHelptopic);
  1162.         $data              .= pack("C", $cchStatustext);
  1163.         $data              .= pack("C", $rgch);
  1164.         $data              .= pack("C", $unknown03);
  1165.         $data              .= pack("v", $unknown04);
  1166.         $data              .= pack("v", $unknown05);
  1167.         $data              .= pack("v", $unknown06);
  1168.         $data              .= pack("v", $unknown07);
  1169.         $data              .= pack("v", $unknown08);
  1170.         $data              .= pack("v", $index);
  1171.         $data              .= pack("v", $index);
  1172.         $data              .= pack("v", $rowmin);
  1173.         $data              .= pack("v", $rowmax);
  1174.         $data              .= pack("C", $colmin);
  1175.         $data              .= pack("C", $colmax);
  1176.         $this->_append($header.$data);
  1177.     }
  1178.     
  1179.     
  1180.     /**
  1181.     * Store the NAME record in the long format that is used for storing the repeat
  1182.     * rows and columns when both are specified. This shares a lot of code with
  1183.     * _storeNameShort() but we use a separate method to keep the code clean.
  1184.     * Code abstraction for reuse can be carried too far, and I should know. ;-)
  1185.     *
  1186.     * @param integer $index Sheet index
  1187.     * @param integer $type  Built-in name type
  1188.     * @param integer $rowmin Start row
  1189.     * @param integer $rowmax End row
  1190.     * @param integer $colmin Start colum
  1191.     * @param integer $colmax End column
  1192.     * @access private
  1193.     */
  1194.     function _storeNameLong($index,$type,$rowmin,$rowmax,$colmin,$colmax)
  1195.     {
  1196.         $record          = 0x0018;       // Record identifier
  1197.         $length          = 0x003d;       // Number of bytes to follow
  1198.         $grbit           = 0x0020;       // Option flags
  1199.         $chKey           = 0x00;         // Keyboard shortcut
  1200.         $cch             = 0x01;         // Length of text name
  1201.         $cce             = 0x002e;       // Length of text definition
  1202.         $ixals           = $index + 1;   // Sheet index
  1203.         $itab            = $ixals;       // Equal to ixals
  1204.         $cchCustMenu     = 0x00;         // Length of cust menu text
  1205.         $cchDescription  = 0x00;         // Length of description text
  1206.         $cchHelptopic    = 0x00;         // Length of help topic text
  1207.         $cchStatustext   = 0x00;         // Length of status bar text
  1208.         $rgch            = $type;        // Built-in name type
  1209.     
  1210.         $unknown01       = 0x29;
  1211.         $unknown02       = 0x002b;
  1212.         $unknown03       = 0x3b;
  1213.         $unknown04       = 0xffff-$index;
  1214.         $unknown05       = 0x0000;
  1215.         $unknown06       = 0x0000;
  1216.         $unknown07       = 0x1087;
  1217.         $unknown08       = 0x8008;
  1218.     
  1219.         $header             = pack("vv",  $record, $length);
  1220.         $data               = pack("v", $grbit);
  1221.         $data              .= pack("C", $chKey);
  1222.         $data              .= pack("C", $cch);
  1223.         $data              .= pack("v", $cce);
  1224.         $data              .= pack("v", $ixals);
  1225.         $data              .= pack("v", $itab);
  1226.         $data              .= pack("C", $cchCustMenu);
  1227.         $data              .= pack("C", $cchDescription);
  1228.         $data              .= pack("C", $cchHelptopic);
  1229.         $data              .= pack("C", $cchStatustext);
  1230.         $data              .= pack("C", $rgch);
  1231.         $data              .= pack("C", $unknown01);
  1232.         $data              .= pack("v", $unknown02);
  1233.         // Column definition
  1234.         $data              .= pack("C", $unknown03);
  1235.         $data              .= pack("v", $unknown04);
  1236.         $data              .= pack("v", $unknown05);
  1237.         $data              .= pack("v", $unknown06);
  1238.         $data              .= pack("v", $unknown07);
  1239.         $data              .= pack("v", $unknown08);
  1240.         $data              .= pack("v", $index);
  1241.         $data              .= pack("v", $index);
  1242.         $data              .= pack("v", 0x0000);
  1243.         $data              .= pack("v", 0x3fff);
  1244.         $data              .= pack("C", $colmin);
  1245.         $data              .= pack("C", $colmax);
  1246.         // Row definition
  1247.         $data              .= pack("C", $unknown03);
  1248.         $data              .= pack("v", $unknown04);
  1249.         $data              .= pack("v", $unknown05);
  1250.         $data              .= pack("v", $unknown06);
  1251.         $data              .= pack("v", $unknown07);
  1252.         $data              .= pack("v", $unknown08);
  1253.         $data              .= pack("v", $index);
  1254.         $data              .= pack("v", $index);
  1255.         $data              .= pack("v", $rowmin);
  1256.         $data              .= pack("v", $rowmax);
  1257.         $data              .= pack("C", 0x00);
  1258.         $data              .= pack("C", 0xff);
  1259.         // End of data
  1260.         $data              .= pack("C", 0x10);
  1261.         $this->_append($header.$data);
  1262.     }
  1263.     
  1264.     /**
  1265.     * Stores the COUNTRY record for localization
  1266.     *
  1267.     * @access private
  1268.     */
  1269.     function _storeCountry()
  1270.     {
  1271.         $record          = 0x008C;    // Record identifier
  1272.         $length          = 4;         // Number of bytes to follow
  1273.  
  1274.         $header = pack('vv',  $record, $length);
  1275.         /* using the same country code always for simplicity */
  1276.         $data = pack('vv', $this->_country_code, $this->_country_code);
  1277.         $this->_append($header.$data);
  1278.     }
  1279.     
  1280.     /**
  1281.     * Stores the PALETTE biff record.
  1282.     *
  1283.     * @access private
  1284.     */
  1285.     function _storePalette()
  1286.     {
  1287.         $aref            = $this->_palette;
  1288.     
  1289.         $record          = 0x0092;                 // Record identifier
  1290.         $length          = 2 + 4 * count($aref);   // Number of bytes to follow
  1291.         $ccv             =         count($aref);   // Number of RGB values to follow
  1292.         $data = '';                                // The RGB data
  1293.     
  1294.         // Pack the RGB data
  1295.         foreach($aref as $color)
  1296.         {
  1297.             foreach($color as $byte) {
  1298.                 $data .= pack("C",$byte);
  1299.             }
  1300.         }
  1301.     
  1302.         $header = pack("vvv",  $record, $length, $ccv);
  1303.         $this->_append($header.$data);
  1304.     }
  1305.  
  1306.     /**
  1307.     * Calculate
  1308.     * Handling of the SST continue blocks is complicated by the need to include an
  1309.     * additional continuation byte depending on whether the string is split between
  1310.     * blocks or whether it starts at the beginning of the block. (There are also
  1311.     * additional complications that will arise later when/if Rich Strings are
  1312.     * supported).
  1313.     *
  1314.     * @access private
  1315.     */
  1316.     function _calculateSharedStringsSizes()
  1317.     {
  1318.         /* Iterate through the strings to calculate the CONTINUE block sizes.
  1319.            For simplicity we use the same size for the SST and CONTINUE records:
  1320.            8228 : Maximum Excel97 block size
  1321.              -4 : Length of block header
  1322.              -8 : Length of additional SST header information
  1323.          = 8216
  1324.         */
  1325.         $continue_limit     = 8216;
  1326.         $block_length       = 0;
  1327.         $written            = 0;
  1328.         $this->_block_sizes = array();
  1329.         $continue           = 0;
  1330.  
  1331.         foreach (array_keys($this->_str_table) as $string) {
  1332.             $string_length = strlen($string);
  1333.  
  1334.             // Block length is the total length of the strings that will be
  1335.             // written out in a single SST or CONTINUE block.
  1336.             $block_length += $string_length;
  1337.  
  1338.             // We can write the string if it doesn't cross a CONTINUE boundary
  1339.             if ($block_length < $continue_limit) {
  1340.                 $written      += $string_length;
  1341.                 continue;
  1342.             }
  1343.  
  1344.             // Deal with the cases where the next string to be written will exceed
  1345.             // the CONTINUE boundary. If the string is very long it may need to be
  1346.             // written in more than one CONTINUE record.
  1347.             while ($block_length >= $continue_limit) {
  1348.  
  1349.                 // We need to avoid the case where a string is continued in the first
  1350.                 // n bytes that contain the string header information.
  1351.                 $header_length   = 3; // Min string + header size -1
  1352.                 $space_remaining = $continue_limit - $written - $continue;
  1353.  
  1354.  
  1355.                 /* TODO: Unicode data should only be split on char (2 byte)
  1356.                 boundaries. Therefore, in some cases we need to reduce the
  1357.                 amount of available
  1358.                 */
  1359.  
  1360.                 if ($space_remaining > $header_length) {
  1361.                     // Write as much as possible of the string in the current block
  1362.                     $written      += $space_remaining;
  1363.  
  1364.                     // Reduce the current block length by the amount written
  1365.                     $block_length -= $continue_limit - $continue;
  1366.  
  1367.                     // Store the max size for this block
  1368.                     $this->_block_sizes[] = $continue_limit;
  1369.  
  1370.                     // If the current string was split then the next CONTINUE block
  1371.                     // should have the string continue flag (grbit) set unless the
  1372.                     // split string fits exactly into the remaining space.
  1373.                     if ($block_length > 0) {
  1374.                         $continue = 1;
  1375.                     }
  1376.                     else {
  1377.                         $continue = 0;
  1378.                     }
  1379.  
  1380.                 }
  1381.                 else {
  1382.                     // Store the max size for this block
  1383.                     $this->_block_sizes[] = $written + $continue;
  1384.  
  1385.                     // Not enough space to start the string in the current block
  1386.                     $block_length -= $continue_limit - $space_remaining - $continue;
  1387.                     $continue = 0;
  1388.  
  1389.                 }
  1390.  
  1391.                 // If the string (or substr) is small enough we can write it in the
  1392.                 // new CONTINUE block. Else, go through the loop again to write it in
  1393.                 // one or more CONTINUE blocks
  1394.                 if ($block_length < $continue_limit) {
  1395.                     $written = $block_length;
  1396.                 }
  1397.                 else {
  1398.                     $written = 0;
  1399.                 }
  1400.             }
  1401.         }
  1402.  
  1403.         // Store the max size for the last block unless it is empty
  1404.         if ($written + $continue) {
  1405.             $this->_block_sizes[] = $written + $continue;
  1406.         }
  1407.  
  1408.  
  1409.         /* Calculate the total length of the SST and associated CONTINUEs (if any).
  1410.          The SST record will have a length even if it contains no strings.
  1411.          This length is required to set the offsets in the BOUNDSHEET records since
  1412.          they must be written before the SST records
  1413.         */
  1414.         $total_offset = array_sum($this->_block_sizes);
  1415.         // SST information
  1416.         $total_offset += 8;
  1417.         if (!empty($this->_block_sizes)) {
  1418.             $total_offset += (count($this->_block_sizes)) * 4; // add CONTINUE headers
  1419.         }
  1420.         return $total_offset;
  1421.     }
  1422.  
  1423.     /**
  1424.     * Write all of the workbooks strings into an indexed array.
  1425.     * See the comments in _calculate_shared_string_sizes() for more information.
  1426.     *
  1427.     * The Excel documentation says that the SST record should be followed by an
  1428.     * EXTSST record. The EXTSST record is a hash table that is used to optimise
  1429.     * access to SST. However, despite the documentation it doesn't seem to be
  1430.     * required so we will ignore it.
  1431.     *
  1432.     * @access private
  1433.     */
  1434.     function _storeSharedStringsTable()
  1435.     {
  1436.         $record  = 0x00fc;  // Record identifier
  1437.         // sizes are upside down
  1438.         $this->_block_sizes = array_reverse($this->_block_sizes);
  1439.         $length = array_pop($this->_block_sizes) + 8; // First block size plus SST information
  1440.  
  1441.         // Write the SST block header information
  1442.         $header      = pack("vv", $record, $length);
  1443.         $data        = pack("VV", $this->_str_total, $this->_str_unique);
  1444.         $this->_append($header.$data);
  1445.  
  1446.  
  1447.         // Iterate through the strings to calculate the CONTINUE block sizes
  1448.         $continue_limit = 8216;
  1449.         $block_length   = 0;
  1450.         $written        = 0;
  1451.         $continue       = 0;
  1452.  
  1453.  
  1454.         /* TODO: not good for performance */
  1455.         foreach (array_keys($this->_str_table) as $string) {
  1456.  
  1457.             $string_length = strlen($string);
  1458.             $encoding      = 0; // assume there are no Unicode strings
  1459.             $split_string  = 0;
  1460.  
  1461.             // Block length is the total length of the strings that will be
  1462.             // written out in a single SST or CONTINUE block.
  1463.             //
  1464.             $block_length += $string_length;
  1465.  
  1466.  
  1467.             // We can write the string if it doesn't cross a CONTINUE boundary
  1468.             if ($block_length < $continue_limit) {
  1469.                 $this->_append($string);
  1470.                 $written += $string_length;
  1471.                 continue;
  1472.             }
  1473.  
  1474.             // Deal with the cases where the next string to be written will exceed
  1475.             // the CONTINUE boundary. If the string is very long it may need to be
  1476.             // written in more than one CONTINUE record.
  1477.             // 
  1478.             while ($block_length >= $continue_limit) {
  1479.  
  1480.                 // We need to avoid the case where a string is continued in the first
  1481.                 // n bytes that contain the string header information.
  1482.                 //
  1483.                 $header_length   = 3; // Min string + header size -1
  1484.                 $space_remaining = $continue_limit - $written - $continue;
  1485.  
  1486.  
  1487.                 // Unicode data should only be split on char (2 byte) boundaries.
  1488.                 // Therefore, in some cases we need to reduce the amount of available
  1489.  
  1490.                 if ($space_remaining > $header_length) {
  1491.                     // Write as much as possible of the string in the current block
  1492.                     $tmp = substr($string, 0, $space_remaining);
  1493.                     $this->_append($tmp);
  1494.  
  1495.                     // The remainder will be written in the next block(s)
  1496.                     $string = substr($string, $space_remaining);
  1497.  
  1498.                     // Reduce the current block length by the amount written
  1499.                     $block_length -= $continue_limit - $continue;
  1500.  
  1501.                     // If the current string was split then the next CONTINUE block
  1502.                     // should have the string continue flag (grbit) set unless the
  1503.                     // split string fits exactly into the remaining space.
  1504.                     //
  1505.                     if ($block_length > 0) {
  1506.                         $continue = 1;
  1507.                     }
  1508.                     else {
  1509.                         $continue = 0;
  1510.                     }
  1511.                 }
  1512.                 else {
  1513.                     // Not enough space to start the string in the current block
  1514.                     $block_length -= $continue_limit - $space_remaining - $continue;
  1515.                     $continue = 0;
  1516.                 }
  1517.  
  1518.                 // Write the CONTINUE block header
  1519.                 if (!empty($this->_block_sizes)) {
  1520.                     $record  = 0x003C;
  1521.                     $length  = array_pop($this->_block_sizes);
  1522.                     $header  = pack('vv', $record, $length);
  1523.                     if ($continue) {
  1524.                         $header .= pack('C', $encoding);
  1525.                     }
  1526.                     $this->_append($header);
  1527.                 }
  1528.  
  1529.                 // If the string (or substr) is small enough we can write it in the
  1530.                 // new CONTINUE block. Else, go through the loop again to write it in
  1531.                 // one or more CONTINUE blocks
  1532.                 //
  1533.                 if ($block_length < $continue_limit) {
  1534.                     $this->_append($string);
  1535.                     $written = $block_length;
  1536.                 }
  1537.                 else {
  1538.                     $written = 0;
  1539.                 }
  1540.             }
  1541.         }
  1542.     }
  1543. }
  1544. ?>
  1545.