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

Source for file Worksheet.php

Documentation is available at Worksheet.php

  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. *    PHPExcel_Writer_Excel5_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 'PHPExcel/Writer/Excel5/Parser.php';
  36. require_once 'PHPExcel/Writer/Excel5/BIFFwriter.php';
  37.  
  38. /**
  39. * Class for generating Excel Spreadsheets
  40. *
  41. * @author   Xavier Noguer <xnoguer@rezebra.com>
  42. * @category FileFormats
  43. * @package  PHPExcel_Writer_Excel5_Writer
  44. */
  45.  
  46. {
  47.     /**
  48.     * Name of the Worksheet
  49.     * @var string 
  50.     */
  51.     var $name;
  52.  
  53.     /**
  54.     * Index for the Worksheet
  55.     * @var integer 
  56.     */
  57.     var $index;
  58.  
  59.     /**
  60.     * Reference to the (default) Format object for URLs
  61.     * @var object Format 
  62.     */
  63.     var $_url_format;
  64.  
  65.     /**
  66.     * Reference to the parser used for parsing formulas
  67.     * @var object Format 
  68.     */
  69.     var $_parser;
  70.  
  71.     /**
  72.     * Filehandle to the temporary file for storing data
  73.     * @var resource 
  74.     */
  75.     var $_filehandle;
  76.  
  77.     /**
  78.     * Boolean indicating if we are using a temporary file for storing data
  79.     * @var bool 
  80.     */
  81.     var $_using_tmpfile;
  82.  
  83.     /**
  84.     * Maximum number of rows for an Excel spreadsheet (BIFF5)
  85.     * @var integer 
  86.     */
  87.     var $_xls_rowmax;
  88.  
  89.     /**
  90.     * Maximum number of columns for an Excel spreadsheet (BIFF5)
  91.     * @var integer 
  92.     */
  93.     var $_xls_colmax;
  94.  
  95.     /**
  96.     * Maximum number of characters for a string (LABEL record in BIFF5)
  97.     * @var integer 
  98.     */
  99.     var $_xls_strmax;
  100.  
  101.     /**
  102.     * First row for the DIMENSIONS record
  103.     * @var integer 
  104.     * @see _storeDimensions()
  105.     */
  106.     var $_dim_rowmin;
  107.  
  108.     /**
  109.     * Last row for the DIMENSIONS record
  110.     * @var integer 
  111.     * @see _storeDimensions()
  112.     */
  113.     var $_dim_rowmax;
  114.  
  115.     /**
  116.     * First column for the DIMENSIONS record
  117.     * @var integer 
  118.     * @see _storeDimensions()
  119.     */
  120.     var $_dim_colmin;
  121.  
  122.     /**
  123.     * Last column for the DIMENSIONS record
  124.     * @var integer 
  125.     * @see _storeDimensions()
  126.     */
  127.     var $_dim_colmax;
  128.  
  129.     /**
  130.     * Array containing format information for columns
  131.     * @var array 
  132.     */
  133.     var $_colinfo;
  134.  
  135.     /**
  136.     * Array containing the selected area for the worksheet
  137.     * @var array 
  138.     */
  139.     var $_selection;
  140.  
  141.     /**
  142.     * Array containing the panes for the worksheet
  143.     * @var array 
  144.     */
  145.     var $_panes;
  146.  
  147.     /**
  148.     * The active pane for the worksheet
  149.     * @var integer 
  150.     */
  151.     var $_active_pane;
  152.  
  153.     /**
  154.     * Bit specifying if panes are frozen
  155.     * @var integer 
  156.     */
  157.     var $_frozen;
  158.  
  159.     /**
  160.     * Bit specifying if the worksheet is selected
  161.     * @var integer 
  162.     */
  163.     var $selected;
  164.  
  165.     /**
  166.     * The paper size (for printing) (DOCUMENT!!!)
  167.     * @var integer 
  168.     */
  169.     var $_paper_size;
  170.  
  171.     /**
  172.     * Bit specifying paper orientation (for printing). 0 => landscape, 1 => portrait
  173.     * @var integer 
  174.     */
  175.     var $_orientation;
  176.  
  177.     /**
  178.     * The page header caption
  179.     * @var string 
  180.     */
  181.     var $_header;
  182.  
  183.     /**
  184.     * The page footer caption
  185.     * @var string 
  186.     */
  187.     var $_footer;
  188.  
  189.     /**
  190.     * The horizontal centering value for the page
  191.     * @var integer 
  192.     */
  193.     var $_hcenter;
  194.  
  195.     /**
  196.     * The vertical centering value for the page
  197.     * @var integer 
  198.     */
  199.     var $_vcenter;
  200.  
  201.     /**
  202.     * The margin for the header
  203.     * @var float 
  204.     */
  205.     var $_margin_head;
  206.  
  207.     /**
  208.     * The margin for the footer
  209.     * @var float 
  210.     */
  211.     var $_margin_foot;
  212.  
  213.     /**
  214.     * The left margin for the worksheet in inches
  215.     * @var float 
  216.     */
  217.     var $_margin_left;
  218.  
  219.     /**
  220.     * The right margin for the worksheet in inches
  221.     * @var float 
  222.     */
  223.     var $_margin_right;
  224.  
  225.     /**
  226.     * The top margin for the worksheet in inches
  227.     * @var float 
  228.     */
  229.     var $_margin_top;
  230.  
  231.     /**
  232.     * The bottom margin for the worksheet in inches
  233.     * @var float 
  234.     */
  235.     var $_margin_bottom;
  236.  
  237.     /**
  238.     * First row to reapeat on each printed page
  239.     * @var integer 
  240.     */
  241.     var $title_rowmin;
  242.  
  243.     /**
  244.     * Last row to reapeat on each printed page
  245.     * @var integer 
  246.     */
  247.     var $title_rowmax;
  248.  
  249.     /**
  250.     * First column to reapeat on each printed page
  251.     * @var integer 
  252.     */
  253.     var $title_colmin;
  254.  
  255.     /**
  256.     * First row of the area to print
  257.     * @var integer 
  258.     */
  259.     var $print_rowmin;
  260.  
  261.     /**
  262.     * Last row to of the area to print
  263.     * @var integer 
  264.     */
  265.     var $print_rowmax;
  266.  
  267.     /**
  268.     * First column of the area to print
  269.     * @var integer 
  270.     */
  271.     var $print_colmin;
  272.  
  273.     /**
  274.     * Last column of the area to print
  275.     * @var integer 
  276.     */
  277.     var $print_colmax;
  278.  
  279.     /**
  280.     * Whether to use outline.
  281.     * @var integer 
  282.     */
  283.     var $_outline_on;
  284.  
  285.     /**
  286.     * Auto outline styles.
  287.     * @var bool 
  288.     */
  289.     var $_outline_style;
  290.  
  291.     /**
  292.     * Whether to have outline summary below.
  293.     * @var bool 
  294.     */
  295.     var $_outline_below;
  296.  
  297.     /**
  298.     * Whether to have outline summary at the right.
  299.     * @var bool 
  300.     */
  301.     var $_outline_right;
  302.  
  303.     /**
  304.     * Outline row level.
  305.     * @var integer 
  306.     */
  307.     var $_outline_row_level;
  308.  
  309.     /**
  310.     * Whether to fit to page when printing or not.
  311.     * @var bool 
  312.     */
  313.     var $_fit_page;
  314.  
  315.     /**
  316.     * Number of pages to fit wide
  317.     * @var integer 
  318.     */
  319.     var $_fit_width;
  320.  
  321.     /**
  322.     * Number of pages to fit high
  323.     * @var integer 
  324.     */
  325.     var $_fit_height;
  326.  
  327.     /**
  328.     * Reference to the total number of strings in the workbook
  329.     * @var integer 
  330.     */
  331.     var $_str_total;
  332.  
  333.     /**
  334.     * Reference to the number of unique strings in the workbook
  335.     * @var integer 
  336.     */
  337.     var $_str_unique;
  338.  
  339.     /**
  340.     * Reference to the array containing all the unique strings in the workbook
  341.     * @var array 
  342.     */
  343.     var $_str_table;
  344.  
  345.     /**
  346.     * Merged cell ranges
  347.     * @var array 
  348.     */
  349.     var $_merged_ranges;
  350.  
  351.     /**
  352.     * Charset encoding currently used when calling writeString()
  353.     * @var string 
  354.     */
  355.     var $_input_encoding;
  356.     
  357.     /**
  358.     * The temporary dir for storing files
  359.     * @var string 
  360.     */
  361.     var $_tmp_dir;
  362.     
  363.     /**
  364.     * List of temporary files created
  365.     * @var array 
  366.     */
  367.     var $_tempFilesCreated = array();
  368.  
  369.     /**
  370.     * Constructor
  371.     *
  372.     * @param string  $name         The name of the new worksheet
  373.     * @param integer $index        The index of the new worksheet
  374.     * @param mixed   &$activesheet The current activesheet of the workbook we belong to
  375.     * @param mixed   &$firstsheet  The first worksheet in the workbook we belong to
  376.     * @param mixed   &$url_format  The default format for hyperlinks
  377.     * @param mixed   &$parser      The formula parser created for the Workbook
  378.     * @param string   $tempDir      The temporary directory to be used
  379.     * @access private
  380.     */
  381.     function PHPExcel_Writer_Excel5_Worksheet($BIFF_version, $name,
  382.                                                 $index, &$activesheet,
  383.                                                 &$firstsheet, &$str_total,
  384.                                                 &$str_unique, &$str_table,
  385.                                                 &$url_format, &$parser, $tempDir = '')
  386.     {
  387.         // It needs to call its parent's constructor explicitly
  388.         $this->PHPExcel_Writer_Excel5_BIFFwriter();
  389.         $this->_BIFF_version    = $BIFF_version;
  390.         $rowmax                    = 65536; // 16384 in Excel 5
  391.         $colmax                    = 256;
  392.  
  393.         $this->name                = $name;
  394.         $this->index            = $index;
  395.         $this->activesheet        = &$activesheet;
  396.         $this->firstsheet        = &$firstsheet;
  397.         $this->_str_total        = &$str_total;
  398.         $this->_str_unique        = &$str_unique;
  399.         $this->_str_table        = &$str_table;
  400.         $this->_url_format        = &$url_format;
  401.         $this->_parser            = &$parser;
  402.  
  403.         //$this->ext_sheets        = array();
  404.         $this->_filehandle        = '';
  405.         $this->_using_tmpfile    = true;
  406.         //$this->fileclosed        = 0;
  407.         //$this->offset            = 0;
  408.         $this->_xls_rowmax        = $rowmax;
  409.         $this->_xls_colmax        = $colmax;
  410.         $this->_xls_strmax        = 255;
  411.         $this->_dim_rowmin        = $rowmax + 1;
  412.         $this->_dim_rowmax        = 0;
  413.         $this->_dim_colmin        = $colmax + 1;
  414.         $this->_dim_colmax        = 0;
  415.         $this->_colinfo            = array();
  416.         $this->_selection        = array(0,0,0,0);
  417.         $this->_panes            = array();
  418.         $this->_active_pane        = 3;
  419.         $this->_frozen            = 0;
  420.         $this->selected            = 0;
  421.  
  422.         $this->_paper_size        = 0x0;
  423.         $this->_orientation        = 0x1;
  424.         $this->_header            = '';
  425.         $this->_footer            = '';
  426.         $this->_hcenter            = 0;
  427.         $this->_vcenter            = 0;
  428.         $this->_margin_head        = 0.50;
  429.         $this->_margin_foot        = 0.50;
  430.         $this->_margin_left        = 0.75;
  431.         $this->_margin_right    = 0.75;
  432.         $this->_margin_top        = 1.00;
  433.         $this->_margin_bottom    = 1.00;
  434.  
  435.         $this->title_rowmin        = null;
  436.         $this->title_rowmax        = null;
  437.         $this->title_colmin        = null;
  438.         $this->title_colmax        = null;
  439.         $this->print_rowmin        = null;
  440.         $this->print_rowmax        = null;
  441.         $this->print_colmin        = null;
  442.         $this->print_colmax        = null;
  443.  
  444.         $this->_print_gridlines        = 1;
  445.         $this->_screen_gridlines    = 1;
  446.         $this->_print_headers        = 0;
  447.  
  448.         $this->_fit_page        = 0;
  449.         $this->_fit_width        = 0;
  450.         $this->_fit_height        = 0;
  451.  
  452.         $this->_hbreaks            = array();
  453.         $this->_vbreaks            = array();
  454.  
  455.         $this->_protect            = 0;
  456.         $this->_password        = null;
  457.  
  458.         $this->col_sizes        = array();
  459.         $this->_row_sizes        = array();
  460.  
  461.         $this->_zoom            = 100;
  462.         $this->_print_scale        = 100;
  463.  
  464.         $this->_outline_row_level    = 0;
  465.         $this->_outline_style        = 0;
  466.         $this->_outline_below        = 1;
  467.         $this->_outline_right        = 1;
  468.         $this->_outline_on            = 1;
  469.  
  470.         $this->_merged_ranges    = array();
  471.  
  472.         $this->_input_encoding    = '';
  473.  
  474.         $this->_dv                = array();
  475.  
  476.         $this->_tmp_dir            = $tempDir;
  477.         
  478.         $this->_initialize();
  479.     }
  480.     
  481.     /**
  482.      * Cleanup
  483.      */
  484.     public function cleanup() {
  485.         @fclose($this->_filehandle);
  486.         
  487.         foreach ($this->_tempFilesCreated as $file) {
  488.             @unlink($file);
  489.         }
  490.     }
  491.  
  492.     /**
  493.     * Open a tmp file to store the majority of the Worksheet data. If this fails,
  494.     * for example due to write permissions, store the data in memory. This can be
  495.     * slow for large files.
  496.     *
  497.     * @access private
  498.     */
  499.     function _initialize()
  500.     {
  501.         // Open tmp file for storing Worksheet data
  502.         $fileName = tempnam($this->_tmp_dir, 'XLSHEET');
  503.         $fh = fopen($fileName, 'w+');
  504.         if ($fh) {
  505.             // Store filehandle
  506.             $this->_filehandle = $fh;
  507.             $this->_tempFilesCreated[] = $fileName;
  508.         } else {
  509.             // If tmpfile() fails store data in memory
  510.             $this->_using_tmpfile = false;
  511.         }
  512.     }
  513.     
  514.     /**
  515.     * Sets the temp dir used for storing files
  516.     *
  517.     * @access public
  518.     * @param string $dir The dir to be used as temp dir
  519.     * @return true if given dir is valid, false otherwise
  520.     */
  521.     function setTempDir($dir)
  522.     {
  523.         if (is_dir($dir)) {
  524.             $this->_tmp_dir = $dir;
  525.             return true;
  526.         }
  527.         return false;
  528.     }
  529.  
  530.     /**
  531.     * Add data to the beginning of the workbook (note the reverse order)
  532.     * and to the end of the workbook.
  533.     *
  534.     * @access public
  535.     * @see PHPExcel_Writer_Excel5_Workbook::storeWorkbook()
  536.     * @param array $sheetnames The array of sheetnames from the Workbook this
  537.     *                           worksheet belongs to
  538.     */
  539.     function close($sheetnames)
  540.     {
  541.         $num_sheets = count($sheetnames);
  542.  
  543.         /***********************************************
  544.         * Prepend in reverse order!!
  545.         */
  546.  
  547.         // Prepend the sheet dimensions
  548.         $this->_storeDimensions();
  549.  
  550.         // Prepend the sheet password
  551.         $this->_storePassword();
  552.  
  553.         // Prepend the sheet protection
  554.         $this->_storeProtect();
  555.  
  556.         // Prepend the page setup
  557.         $this->_storeSetup();
  558.  
  559.         /* FIXME: margins are actually appended */
  560.         // Prepend the bottom margin
  561.         $this->_storeMarginBottom();
  562.  
  563.         // Prepend the top margin
  564.         $this->_storeMarginTop();
  565.  
  566.         // Prepend the right margin
  567.         $this->_storeMarginRight();
  568.  
  569.         // Prepend the left margin
  570.         $this->_storeMarginLeft();
  571.  
  572.         // Prepend the page vertical centering
  573.         $this->_storeVcenter();
  574.  
  575.         // Prepend the page horizontal centering
  576.         $this->_storeHcenter();
  577.  
  578.         // Prepend the page footer
  579.         $this->_storeFooter();
  580.  
  581.         // Prepend the page header
  582.         $this->_storeHeader();
  583.  
  584.         // Prepend the vertical page breaks
  585.         $this->_storeVbreak();
  586.  
  587.         // Prepend the horizontal page breaks
  588.         $this->_storeHbreak();
  589.  
  590.         // Prepend WSBOOL
  591.         $this->_storeWsbool();
  592.  
  593.         // Prepend GRIDSET
  594.         $this->_storeGridset();
  595.  
  596.          //  Prepend GUTS
  597.         if ($this->_BIFF_version == 0x0500) {
  598.             $this->_storeGuts();
  599.         }
  600.  
  601.         // Prepend PRINTGRIDLINES
  602.         $this->_storePrintGridlines();
  603.  
  604.         // Prepend PRINTHEADERS
  605.         $this->_storePrintHeaders();
  606.  
  607.         // Prepend EXTERNSHEET references
  608.         if ($this->_BIFF_version == 0x0500) {
  609.             for ($i = $num_sheets; $i > 0; $i--) {
  610.                 $sheetname = $sheetnames[$i-1];
  611.                 $this->_storeExternsheet($sheetname);
  612.             }
  613.         }
  614.  
  615.         // Prepend the EXTERNCOUNT of external references.
  616.         if ($this->_BIFF_version == 0x0500) {
  617.             $this->_storeExterncount($num_sheets);
  618.         }
  619.  
  620.         // Prepend the COLINFO records if they exist
  621.         if (!empty($this->_colinfo)) {
  622.             $colcount = count($this->_colinfo);
  623.             for ($i = 0; $i < $colcount; $i++) {
  624.                 $this->_storeColinfo($this->_colinfo[$i]);
  625.             }
  626.             $this->_storeDefcol();
  627.         }
  628.  
  629.         // Prepend the BOF record
  630.         $this->_storeBof(0x0010);
  631.  
  632.         /*
  633.         * End of prepend. Read upwards from here.
  634.         ***********************************************/
  635.  
  636.         // Append
  637.         $this->_storeWindow2();
  638.         $this->_storeZoom();
  639.         if (!empty($this->_panes)) {
  640.             $this->_storePanes($this->_panes);
  641.         }
  642.         $this->_storeSelection($this->_selection);
  643.         $this->_storeMergedCells();
  644.         /* TODO: add data validity */
  645.         /*if ($this->_BIFF_version == 0x0600) {
  646.             $this->_storeDataValidity();
  647.         }*/
  648.         $this->_storeEof();
  649.     }
  650.  
  651.     /**
  652.     * Retrieve the worksheet name.
  653.     * This is usefull when creating worksheets without a name.
  654.     *
  655.     * @access public
  656.     * @return string The worksheet's name
  657.     */
  658.     function getName()
  659.     {
  660.         return $this->name;
  661.     }
  662.  
  663.     /**
  664.     * Retrieves data from memory in one chunk, or from disk in $buffer
  665.     * sized chunks.
  666.     *
  667.     * @return string The data
  668.     */
  669.     function getData()
  670.     {
  671.         $buffer = 4096;
  672.  
  673.         // Return data stored in memory
  674.         if (isset($this->_data)) {
  675.             $tmp   = $this->_data;
  676.             unset($this->_data);
  677.             $fh    = $this->_filehandle;
  678.             if ($this->_using_tmpfile) {
  679.                 fseek($fh, 0);
  680.             }
  681.             return $tmp;
  682.         }
  683.         // Return data stored on disk
  684.         if ($this->_using_tmpfile) {
  685.             if ($tmp = fread($this->_filehandle, $buffer)) {
  686.                 return $tmp;
  687.             }
  688.         }
  689.  
  690.         // No data to return
  691.         return '';
  692.     }
  693.  
  694.     /**
  695.     * Sets a merged cell range
  696.     *
  697.     * @access public
  698.     * @param integer $first_row First row of the area to merge
  699.     * @param integer $first_col First column of the area to merge
  700.     * @param integer $last_row  Last row of the area to merge
  701.     * @param integer $last_col  Last column of the area to merge
  702.     */
  703.     function setMerge($first_row, $first_col, $last_row, $last_col)
  704.     {
  705.         if (($last_row < $first_row) || ($last_col < $first_col)) {
  706.             return;
  707.         }
  708.         // don't check rowmin, rowmax, etc... because we don't know when this
  709.         // is going to be called
  710.         $this->_merged_ranges[] = array($first_row, $first_col, $last_row, $last_col);
  711.     }
  712.  
  713.     /**
  714.     * Set this worksheet as a selected worksheet,
  715.     * i.e. the worksheet has its tab highlighted.
  716.     *
  717.     * @access public
  718.     */
  719.     function select()
  720.     {
  721.         $this->selected = 1;
  722.     }
  723.  
  724.     /**
  725.     * Set this worksheet as the active worksheet,
  726.     * i.e. the worksheet that is displayed when the workbook is opened.
  727.     * Also set it as selected.
  728.     *
  729.     * @access public
  730.     */
  731.     function activate()
  732.     {
  733.         $this->selected = 1;
  734.         $this->activesheet = $this->index;
  735.     }
  736.  
  737.     /**
  738.     * Set this worksheet as the first visible sheet.
  739.     * This is necessary when there are a large number of worksheets and the
  740.     * activated worksheet is not visible on the screen.
  741.     *
  742.     * @access public
  743.     */
  744.     function setFirstSheet()
  745.     {
  746.         $this->firstsheet = $this->index;
  747.     }
  748.  
  749.     /**
  750.     * Set the worksheet protection flag
  751.     * to prevent accidental modification and to
  752.     * hide formulas if the locked and hidden format properties have been set.
  753.     *
  754.     * @access public
  755.     * @param string $password The password to use for protecting the sheet.
  756.     */
  757.     function protect($password, $encoded = false)
  758.     {
  759.         $this->_protect   = 1;
  760.         $this->_password  = ($encoded ? $password : $this->_encodePassword($password));
  761.     }
  762.  
  763.     /**
  764.     * Set the width of a single column or a range of columns.
  765.     *
  766.     * @access public
  767.     * @param integer $firstcol first column on the range
  768.     * @param integer $lastcol  last column on the range
  769.     * @param integer $width    width to set
  770.     * @param mixed   $format   The optional XF format to apply to the columns
  771.     * @param integer $hidden   The optional hidden atribute
  772.     * @param integer $level    The optional outline level
  773.     */
  774.     function setColumn($firstcol, $lastcol, $width, $format = null, $hidden = 0, $level = 0)
  775.     {
  776.         $this->_colinfo[] = array($firstcol, $lastcol, $width, &$format, $hidden, $level);
  777.  
  778.         // Set width to zero if column is hidden
  779.         $width = ($hidden) ? 0 : $width;
  780.  
  781.         for ($col = $firstcol; $col <= $lastcol; $col++) {
  782.             $this->col_sizes[$col] = $width;
  783.         }
  784.     }
  785.  
  786.     /**
  787.     * Set which cell or cells are selected in a worksheet
  788.     *
  789.     * @access public
  790.     * @param integer $first_row    first row in the selected quadrant
  791.     * @param integer $first_column first column in the selected quadrant
  792.     * @param integer $last_row     last row in the selected quadrant
  793.     * @param integer $last_column  last column in the selected quadrant
  794.     */
  795.     function setSelection($first_row,$first_column,$last_row,$last_column)
  796.     {
  797.         $this->_selection = array($first_row,$first_column,$last_row,$last_column);
  798.     }
  799.  
  800.     /**
  801.     * Set panes and mark them as frozen.
  802.     *
  803.     * @access public
  804.     * @param array $panes This is the only parameter received and is composed of the following:
  805.     *                      0 => Vertical split position,
  806.     *                      1 => Horizontal split position
  807.     *                      2 => Top row visible
  808.     *                      3 => Leftmost column visible
  809.     *                      4 => Active pane
  810.     */
  811.     function freezePanes($panes)
  812.     {
  813.         $this->_frozen = 1;
  814.         $this->_panes  = $panes;
  815.     }
  816.  
  817.     /**
  818.     * Set panes and mark them as unfrozen.
  819.     *
  820.     * @access public
  821.     * @param array $panes This is the only parameter received and is composed of the following:
  822.     *                      0 => Vertical split position,
  823.     *                      1 => Horizontal split position
  824.     *                      2 => Top row visible
  825.     *                      3 => Leftmost column visible
  826.     *                      4 => Active pane
  827.     */
  828.     function thawPanes($panes)
  829.     {
  830.         $this->_frozen = 0;
  831.         $this->_panes  = $panes;
  832.     }
  833.  
  834.     /**
  835.     * Set the page orientation as portrait.
  836.     *
  837.     * @access public
  838.     */
  839.     function setPortrait()
  840.     {
  841.         $this->_orientation = 1;
  842.     }
  843.  
  844.     /**
  845.     * Set the page orientation as landscape.
  846.     *
  847.     * @access public
  848.     */
  849.     function setLandscape()
  850.     {
  851.         $this->_orientation = 0;
  852.     }
  853.  
  854.     /**
  855.     * Set the paper type. Ex. 1 = US Letter, 9 = A4
  856.     *
  857.     * @access public
  858.     * @param integer $size The type of paper size to use
  859.     */
  860.     function setPaper($size = 0)
  861.     {
  862.         $this->_paper_size = $size;
  863.     }
  864.  
  865.  
  866.     /**
  867.     * Set the page header caption and optional margin.
  868.     *
  869.     * @access public
  870.     * @param string $string The header text
  871.     * @param float  $margin optional head margin in inches.
  872.     */
  873.     function setHeader($string,$margin = 0.50)
  874.     {
  875.         if (strlen($string) >= 255) {
  876.             //carp 'Header string must be less than 255 characters';
  877.             return;
  878.         }
  879.         $this->_header      = $string;
  880.         $this->_margin_head = $margin;
  881.     }
  882.  
  883.     /**
  884.     * Set the page footer caption and optional margin.
  885.     *
  886.     * @access public
  887.     * @param string $string The footer text
  888.     * @param float  $margin optional foot margin in inches.
  889.     */
  890.     function setFooter($string,$margin = 0.50)
  891.     {
  892.         if (strlen($string) >= 255) {
  893.             //carp 'Footer string must be less than 255 characters';
  894.             return;
  895.         }
  896.         $this->_footer      = $string;
  897.         $this->_margin_foot = $margin;
  898.     }
  899.  
  900.     /**
  901.     * Center the page horinzontally.
  902.     *
  903.     * @access public
  904.     * @param integer $center the optional value for centering. Defaults to 1 (center).
  905.     */
  906.     function centerHorizontally($center = 1)
  907.     {
  908.         $this->_hcenter = $center;
  909.     }
  910.  
  911.     /**
  912.     * Center the page vertically.
  913.     *
  914.     * @access public
  915.     * @param integer $center the optional value for centering. Defaults to 1 (center).
  916.     */
  917.     function centerVertically($center = 1)
  918.     {
  919.         $this->_vcenter = $center;
  920.     }
  921.  
  922.     /**
  923.     * Set all the page margins to the same value in inches.
  924.     *
  925.     * @access public
  926.     * @param float $margin The margin to set in inches
  927.     */
  928.     function setMargins($margin)
  929.     {
  930.         $this->setMarginLeft($margin);
  931.         $this->setMarginRight($margin);
  932.         $this->setMarginTop($margin);
  933.         $this->setMarginBottom($margin);
  934.     }
  935.  
  936.     /**
  937.     * Set the left and right margins to the same value in inches.
  938.     *
  939.     * @access public
  940.     * @param float $margin The margin to set in inches
  941.     */
  942.     function setMargins_LR($margin)
  943.     {
  944.         $this->setMarginLeft($margin);
  945.         $this->setMarginRight($margin);
  946.     }
  947.  
  948.     /**
  949.     * Set the top and bottom margins to the same value in inches.
  950.     *
  951.     * @access public
  952.     * @param float $margin The margin to set in inches
  953.     */
  954.     function setMargins_TB($margin)
  955.     {
  956.         $this->setMarginTop($margin);
  957.         $this->setMarginBottom($margin);
  958.     }
  959.  
  960.     /**
  961.     * Set the left margin in inches.
  962.     *
  963.     * @access public
  964.     * @param float $margin The margin to set in inches
  965.     */
  966.     function setMarginLeft($margin = 0.75)
  967.     {
  968.         $this->_margin_left = $margin;
  969.     }
  970.  
  971.     /**
  972.     * Set the right margin in inches.
  973.     *
  974.     * @access public
  975.     * @param float $margin The margin to set in inches
  976.     */
  977.     function setMarginRight($margin = 0.75)
  978.     {
  979.         $this->_margin_right = $margin;
  980.     }
  981.  
  982.     /**
  983.     * Set the top margin in inches.
  984.     *
  985.     * @access public
  986.     * @param float $margin The margin to set in inches
  987.     */
  988.     function setMarginTop($margin = 1.00)
  989.     {
  990.         $this->_margin_top = $margin;
  991.     }
  992.  
  993.     /**
  994.     * Set the bottom margin in inches.
  995.     *
  996.     * @access public
  997.     * @param float $margin The margin to set in inches
  998.     */
  999.     function setMarginBottom($margin = 1.00)
  1000.     {
  1001.         $this->_margin_bottom = $margin;
  1002.     }
  1003.  
  1004.     /**
  1005.     * Set the rows to repeat at the top of each printed page.
  1006.     *
  1007.     * @access public
  1008.     * @param integer $first_row First row to repeat
  1009.     * @param integer $last_row  Last row to repeat. Optional.
  1010.     */
  1011.     function repeatRows($first_row, $last_row = null)
  1012.     {
  1013.         $this->title_rowmin  = $first_row;
  1014.         if (isset($last_row)) { //Second row is optional
  1015.             $this->title_rowmax  = $last_row;
  1016.         } else {
  1017.             $this->title_rowmax  = $first_row;
  1018.         }
  1019.     }
  1020.  
  1021.     /**
  1022.     * Set the columns to repeat at the left hand side of each printed page.
  1023.     *
  1024.     * @access public
  1025.     * @param integer $first_col First column to repeat
  1026.     * @param integer $last_col  Last column to repeat. Optional.
  1027.     */
  1028.     function repeatColumns($first_col, $last_col = null)
  1029.     {
  1030.         $this->title_colmin  = $first_col;
  1031.         if (isset($last_col)) { // Second col is optional
  1032.             $this->title_colmax  = $last_col;
  1033.         } else {
  1034.             $this->title_colmax  = $first_col;
  1035.         }
  1036.     }
  1037.  
  1038.     /**
  1039.     * Set the area of each worksheet that will be printed.
  1040.     *
  1041.     * @access public
  1042.     * @param integer $first_row First row of the area to print
  1043.     * @param integer $first_col First column of the area to print
  1044.     * @param integer $last_row  Last row of the area to print
  1045.     * @param integer $last_col  Last column of the area to print
  1046.     */
  1047.     function printArea($first_row, $first_col, $last_row, $last_col)
  1048.     {
  1049.         $this->print_rowmin  = $first_row;
  1050.         $this->print_colmin  = $first_col;
  1051.         $this->print_rowmax  = $last_row;
  1052.         $this->print_colmax  = $last_col;
  1053.     }
  1054.  
  1055.  
  1056.     /**
  1057.     * Set the option to hide gridlines on the printed page.
  1058.     *
  1059.     * @access public
  1060.     */
  1061.     function hideGridlines()
  1062.     {
  1063.         $this->_print_gridlines = 0;
  1064.     }
  1065.  
  1066.     /**
  1067.     * Set the option to hide gridlines on the worksheet (as seen on the screen).
  1068.     *
  1069.     * @access public
  1070.     */
  1071.     function hideScreenGridlines()
  1072.     {
  1073.         $this->_screen_gridlines = 0;
  1074.     }
  1075.  
  1076.     /**
  1077.     * Set the option to print the row and column headers on the printed page.
  1078.     *
  1079.     * @access public
  1080.     * @param integer $print Whether to print the headers or not. Defaults to 1 (print).
  1081.     */
  1082.     function printRowColHeaders($print = 1)
  1083.     {
  1084.         $this->_print_headers = $print;
  1085.     }
  1086.  
  1087.     /**
  1088.     * Set the vertical and horizontal number of pages that will define the maximum area printed.
  1089.     * It doesn't seem to work with OpenOffice.
  1090.     *
  1091.     * @access public
  1092.     * @param  integer $width  Maximun width of printed area in pages
  1093.     * @param  integer $height Maximun heigth of printed area in pages
  1094.     * @see setPrintScale()
  1095.     */
  1096.     function fitToPages($width, $height)
  1097.     {
  1098.         $this->_fit_page      = 1;
  1099.         $this->_fit_width     = $width;
  1100.         $this->_fit_height    = $height;
  1101.     }
  1102.  
  1103.     /**
  1104.     * Store the horizontal page breaks on a worksheet (for printing).
  1105.     * The breaks represent the row after which the break is inserted.
  1106.     *
  1107.     * @access public
  1108.     * @param array $breaks Array containing the horizontal page breaks
  1109.     */
  1110.     function setHPagebreaks($breaks)
  1111.     {
  1112.         foreach ($breaks as $break) {
  1113.             array_push($this->_hbreaks, $break);
  1114.         }
  1115.     }
  1116.  
  1117.     /**
  1118.     * Store the vertical page breaks on a worksheet (for printing).
  1119.     * The breaks represent the column after which the break is inserted.
  1120.     *
  1121.     * @access public
  1122.     * @param array $breaks Array containing the vertical page breaks
  1123.     */
  1124.     function setVPagebreaks($breaks)
  1125.     {
  1126.         foreach ($breaks as $break) {
  1127.             array_push($this->_vbreaks, $break);
  1128.         }
  1129.     }
  1130.  
  1131.  
  1132.     /**
  1133.     * Set the worksheet zoom factor.
  1134.     *
  1135.     * @access public
  1136.     * @param integer $scale The zoom factor
  1137.     */
  1138.     function setZoom($scale = 100)
  1139.     {
  1140.         // Confine the scale to Excel's range
  1141.         if ($scale < 10 || $scale > 400) {
  1142.             throw new Exception("Zoom factor $scale outside range: 10 <= zoom <= 400");
  1143.             $scale = 100;
  1144.         }
  1145.  
  1146.         $this->_zoom = floor($scale);
  1147.     }
  1148.  
  1149.     /**
  1150.     * Set the scale factor for the printed page.
  1151.     * It turns off the "fit to page" option
  1152.     *
  1153.     * @access public
  1154.     * @param integer $scale The optional scale factor. Defaults to 100
  1155.     */
  1156.     function setPrintScale($scale = 100)
  1157.     {
  1158.         // Confine the scale to Excel's range
  1159.         if ($scale < 10 || $scale > 400) {
  1160.             throw new Exception("Print scale $scale outside range: 10 <= zoom <= 400");
  1161.             $scale = 100;
  1162.         }
  1163.  
  1164.         // Turn off "fit to page" option
  1165.         $this->_fit_page = 0;
  1166.  
  1167.         $this->_print_scale = floor($scale);
  1168.     }
  1169.  
  1170.     /**
  1171.     * Map to the appropriate write method acording to the token recieved.
  1172.     *
  1173.     * @access public
  1174.     * @param integer $row    The row of the cell we are writing to
  1175.     * @param integer $col    The column of the cell we are writing to
  1176.     * @param mixed   $token  What we are writing
  1177.     * @param mixed   $format The optional format to apply to the cell
  1178.     */
  1179.     function write($row, $col, $token, $format = null, $numberFormat = null)
  1180.     {
  1181.         // Check for a cell reference in A1 notation and substitute row and column
  1182.         /*if ($_[0] =~ /^\D/) {
  1183.             @_ = $this->_substituteCellref(@_);
  1184.         }*/
  1185.  
  1186.         if (($numberFormat != 'General') && (PHPExcel_Shared_Date::isDateTimeFormatCode($numberFormat))) {
  1187.             if (is_string($token)) {
  1188.                 //    Error string
  1189.                 return $this->writeString($row, $col, $token, $format);
  1190.             } elseif (!is_float($token)) {
  1191.                 //    PHP serialized date/time or date/time object
  1192.                 return $this->writeNumber($row, $col, PHPExcel_Shared_Date::PHPToExcel($token), $format);
  1193.             } else {
  1194.                 //    Excel serialized date/time
  1195.                 return $this->writeNumber($row, $col, $token, $format);
  1196.             }
  1197.         } elseif (preg_match("/^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/", $token)) {
  1198.             // Match number
  1199.             return $this->writeNumber($row, $col, $token, $format);
  1200.         } elseif (preg_match("/^[fh]tt?p:\/\//", $token)) {
  1201.             // Match http or ftp URL
  1202.             return $this->writeUrl($row, $col, $token, '', $format);
  1203.         } elseif (preg_match("/^mailto:/", $token)) {
  1204.             // Match mailto:
  1205.             return $this->writeUrl($row, $col, $token, '', $format);
  1206.         } elseif (preg_match("/^(?:in|ex)ternal:/", $token)) {
  1207.             // Match internal or external sheet link
  1208.             return $this->writeUrl($row, $col, $token, '', $format);
  1209.         } elseif (preg_match("/^=/", $token)) {
  1210.             // Match formula
  1211.             return $this->writeFormula($row, $col, $token, $format);
  1212.         } elseif (preg_match("/^@/", $token)) {
  1213.             // Match formula
  1214.             return $this->writeFormula($row, $col, $token, $format);
  1215.         } elseif ($token == '') {
  1216.             // Match blank
  1217.             return $this->writeBlank($row, $col, $format);
  1218.         } else {
  1219.             // Default: match string
  1220.             return $this->writeString($row, $col, $token, $format);
  1221.         }
  1222.     }
  1223.  
  1224.     /**
  1225.     * Write an array of values as a row
  1226.     *
  1227.     * @access public
  1228.     * @param integer $row    The row we are writing to
  1229.     * @param integer $col    The first col (leftmost col) we are writing to
  1230.     * @param array   $val    The array of values to write
  1231.     * @param mixed   $format The optional format to apply to the cell
  1232.     */
  1233.  
  1234.     function writeRow($row, $col, $val, $format = null, $numberFormat = null)
  1235.     {
  1236.         $retval = '';
  1237.         if (is_array($val)) {
  1238.             foreach ($val as $v) {
  1239.                 if (is_array($v)) {
  1240.                     $this->writeCol($row, $col, $v, $format, $numberFormat = null);
  1241.                 } else {
  1242.                     $this->write($row, $col, $v, $format, $numberFormat);
  1243.                 }
  1244.                 $col++;
  1245.             }
  1246.         } else {
  1247.             throw new Exception('$val needs to be an array');
  1248.         }
  1249.         return($retval);
  1250.     }
  1251.  
  1252.     /**
  1253.     * Write an array of values as a column
  1254.     *
  1255.     * @access public
  1256.     * @param integer $row    The first row (uppermost row) we are writing to
  1257.     * @param integer $col    The col we are writing to
  1258.     * @param array   $val    The array of values to write
  1259.     * @param mixed   $format The optional format to apply to the cell
  1260.     */
  1261.  
  1262.     function writeCol($row, $col, $val, $format = null, $numberFormat = null)
  1263.     {
  1264.         $retval = '';
  1265.         if (is_array($val)) {
  1266.             foreach ($val as $v) {
  1267.                 $this->write($row, $col, $v, $format, $numberFormat);
  1268.                 $row++;
  1269.             }
  1270.         } else {
  1271.             throw new Exception('$val needs to be an array');
  1272.         }
  1273.         return($retval);
  1274.     }
  1275.  
  1276.     /**
  1277.     * Returns an index to the XF record in the workbook
  1278.     *
  1279.     * @access private
  1280.     * @param mixed &$format The optional XF format
  1281.     * @return integer The XF record index
  1282.     */
  1283.     function _XF(&$format)
  1284.     {
  1285.         if ($format) {
  1286.             return($format->getXfIndex());
  1287.         } else {
  1288.             return(0x0F);
  1289.         }
  1290.     }
  1291.  
  1292.  
  1293.     /******************************************************************************
  1294.     *******************************************************************************
  1295.     *
  1296.     * Internal methods
  1297.     */
  1298.  
  1299.  
  1300.     /**
  1301.     * Store Worksheet data in memory using the parent's class append() or to a
  1302.     * temporary file, the default.
  1303.     *
  1304.     * @access private
  1305.     * @param string $data The binary data to append
  1306.     */
  1307.     function _append($data)
  1308.     {
  1309.         if ($this->_using_tmpfile) {
  1310.             // Add CONTINUE records if necessary
  1311.             if (strlen($data) > $this->_limit) {
  1312.                 $data = $this->_addContinue($data);
  1313.             }
  1314.             fwrite($this->_filehandle, $data);
  1315.             $this->_datasize += strlen($data);
  1316.         } else {
  1317.             parent::_append($data);
  1318.         }
  1319.     }
  1320.  
  1321.     /**
  1322.     * Substitute an Excel cell reference in A1 notation for  zero based row and
  1323.     * column values in an argument list.
  1324.     *
  1325.     * Ex: ("A4", "Hello") is converted to (3, 0, "Hello").
  1326.     *
  1327.     * @access private
  1328.     * @param string $cell The cell reference. Or range of cells.
  1329.     * @return array 
  1330.     */
  1331.     function _substituteCellref($cell)
  1332.     {
  1333.         $cell = strtoupper($cell);
  1334.  
  1335.         // Convert a column range: 'A:A' or 'B:G'
  1336.         if (preg_match("/([A-I]?[A-Z]):([A-I]?[A-Z])/", $cell, $match)) {
  1337.             list($no_use, $col1) =  $this->_cellToRowcol($match[1] .'1'); // Add a dummy row
  1338.             list($no_use, $col2) =  $this->_cellToRowcol($match[2] .'1'); // Add a dummy row
  1339.             return(array($col1, $col2));
  1340.         }
  1341.  
  1342.         // Convert a cell range: 'A1:B7'
  1343.         if (preg_match("/\$?([A-I]?[A-Z]\$?\d+):\$?([A-I]?[A-Z]\$?\d+)/", $cell, $match)) {
  1344.             list($row1, $col1) =  $this->_cellToRowcol($match[1]);
  1345.             list($row2, $col2) =  $this->_cellToRowcol($match[2]);
  1346.             return(array($row1, $col1, $row2, $col2));
  1347.         }
  1348.  
  1349.         // Convert a cell reference: 'A1' or 'AD2000'
  1350.         if (preg_match("/\$?([A-I]?[A-Z]\$?\d+)/", $cell)) {
  1351.             list($row1, $col1) =  $this->_cellToRowcol($match[1]);
  1352.             return(array($row1, $col1));
  1353.         }
  1354.  
  1355.         // TODO use real error codes
  1356.         throw new Exception("Unknown cell reference $cell");
  1357.     }
  1358.  
  1359.     /**
  1360.     * Convert an Excel cell reference in A1 notation to a zero based row and column
  1361.     * reference; converts C1 to (0, 2).
  1362.     *
  1363.     * @access private
  1364.     * @param string $cell The cell reference.
  1365.     * @return array containing (row, column)
  1366.     */
  1367.     function _cellToRowcol($cell)
  1368.     {
  1369.         preg_match("/\$?([A-I]?[A-Z])\$?(\d+)/",$cell,$match);
  1370.         $col     = $match[1];
  1371.         $row     = $match[2];
  1372.  
  1373.         // Convert base26 column string to number
  1374.         $chars = split('', $col);
  1375.         $expn  = 0;
  1376.         $col   = 0;
  1377.  
  1378.         while ($chars) {
  1379.             $char = array_pop($chars);        // LS char first
  1380.             $col += (ord($char) -ord('A') +1) * pow(26,$expn);
  1381.             $expn++;
  1382.         }
  1383.  
  1384.         // Convert 1-index to zero-index
  1385.         $row--;
  1386.         $col--;
  1387.  
  1388.         return(array($row, $col));
  1389.     }
  1390.  
  1391.     /**
  1392.     * Based on the algorithm provided by Daniel Rentz of OpenOffice.
  1393.     *
  1394.     * @access private
  1395.     * @param string $plaintext The password to be encoded in plaintext.
  1396.     * @return string The encoded password
  1397.     */
  1398.     function _encodePassword($plaintext)
  1399.     {
  1400.         $password = 0x0000;
  1401.         $i        = 1;       // char position
  1402.  
  1403.         // split the plain text password in its component characters
  1404.         $chars = preg_split('//', $plaintext, -1, PREG_SPLIT_NO_EMPTY);
  1405.         foreach ($chars as $char) {
  1406.             $value        = ord($char) << $i;   // shifted ASCII value
  1407.             $rotated_bits = $value >> 15;       // rotated bits beyond bit 15
  1408.             $value       &= 0x7fff;             // first 15 bits
  1409.             $password    ^= ($value | $rotated_bits);
  1410.             $i++;
  1411.         }
  1412.  
  1413.         $password ^= strlen($plaintext);
  1414.         $password ^= 0xCE4B;
  1415.  
  1416.         return($password);
  1417.     }
  1418.  
  1419.     /**
  1420.     * This method sets the properties for outlining and grouping. The defaults
  1421.     * correspond to Excel's defaults.
  1422.     *
  1423.     * @param bool $visible 
  1424.     * @param bool $symbols_below 
  1425.     * @param bool $symbols_right 
  1426.     * @param bool $auto_style 
  1427.     */
  1428.     function setOutline($visible = true, $symbols_below = true, $symbols_right = true, $auto_style = false)
  1429.     {
  1430.         $this->_outline_on    = $visible;
  1431.         $this->_outline_below = $symbols_below;
  1432.         $this->_outline_right = $symbols_right;
  1433.         $this->_outline_style = $auto_style;
  1434.  
  1435.         // Ensure this is a boolean vale for Window2
  1436.         if ($this->_outline_on) {
  1437.             $this->_outline_on = 1;
  1438.         }
  1439.      }
  1440.  
  1441.     /******************************************************************************
  1442.     *******************************************************************************
  1443.     *
  1444.     * BIFF RECORDS
  1445.     */
  1446.  
  1447.  
  1448.     /**
  1449.     * Write a double to the specified row and column (zero indexed).
  1450.     * An integer can be written as a double. Excel will display an
  1451.     * integer. $format is optional.
  1452.     *
  1453.     * Returns  0 : normal termination
  1454.     *         -2 : row or column out of range
  1455.     *
  1456.     * @access public
  1457.     * @param integer $row    Zero indexed row
  1458.     * @param integer $col    Zero indexed column
  1459.     * @param float   $num    The number to write
  1460.     * @param mixed   $format The optional XF format
  1461.     * @return integer 
  1462.     */
  1463.     function writeNumber($row, $col, $num, $format = null)
  1464.     {
  1465.         $record    = 0x0203;                 // Record identifier
  1466.         $length    = 0x000E;                 // Number of bytes to follow
  1467.  
  1468.         $xf        = $this->_XF($format);    // The cell format
  1469.  
  1470.         // Check that row and col are valid and store max and min values
  1471.         if ($row >= $this->_xls_rowmax) {
  1472.             return(-2);
  1473.         }
  1474.         if ($col >= $this->_xls_colmax) {
  1475.             return(-2);
  1476.         }
  1477.         if ($row <  $this->_dim_rowmin)  {
  1478.             $this->_dim_rowmin = $row;
  1479.         }
  1480.         if ($row >  $this->_dim_rowmax)  {
  1481.             $this->_dim_rowmax = $row;
  1482.         }
  1483.         if ($col <  $this->_dim_colmin)  {
  1484.             $this->_dim_colmin = $col;
  1485.         }
  1486.         if ($col >  $this->_dim_colmax)  {
  1487.             $this->_dim_colmax = $col;
  1488.         }
  1489.  
  1490.         $header    = pack("vv",  $record, $length);
  1491.         $data      = pack("vvv", $row, $col, $xf);
  1492.         $xl_double = pack("d",   $num);
  1493.         if ($this->_byte_order) { // if it's Big Endian
  1494.             $xl_double = strrev($xl_double);
  1495.         }
  1496.  
  1497.         $this->_append($header.$data.$xl_double);
  1498.         return(0);
  1499.     }
  1500.  
  1501.     /**
  1502.     * Write a string to the specified row and column (zero indexed).
  1503.     * NOTE: there is an Excel 5 defined limit of 255 characters.
  1504.     * $format is optional.
  1505.     * Returns  0 : normal termination
  1506.     *         -2 : row or column out of range
  1507.     *         -3 : long string truncated to 255 chars
  1508.     *
  1509.     * @access public
  1510.     * @param integer $row    Zero indexed row
  1511.     * @param integer $col    Zero indexed column
  1512.     * @param string  $str    The string to write
  1513.     * @param mixed   $format The XF format for the cell
  1514.     * @return integer 
  1515.     */
  1516.     function writeString($row, $col, $str, $format = null)
  1517.     {
  1518.         if ($this->_BIFF_version == 0x0600) {
  1519.             return $this->writeStringBIFF8($row, $col, $str, $format);
  1520.         }
  1521.         $strlen    = strlen($str);
  1522.         $record    = 0x0204;                   // Record identifier
  1523.         $length    = 0x0008 + $strlen;         // Bytes to follow
  1524.         $xf        = $this->_XF($format);      // The cell format
  1525.  
  1526.         $str_error = 0;
  1527.  
  1528.         // Check that row and col are valid and store max and min values
  1529.         if ($row >= $this->_xls_rowmax) {
  1530.             return(-2);
  1531.         }
  1532.         if ($col >= $this->_xls_colmax) {
  1533.             return(-2);
  1534.         }
  1535.         if ($row <  $this->_dim_rowmin) {
  1536.             $this->_dim_rowmin = $row;
  1537.         }
  1538.         if ($row >  $this->_dim_rowmax) {
  1539.             $this->_dim_rowmax = $row;
  1540.         }
  1541.         if ($col <  $this->_dim_colmin) {
  1542.             $this->_dim_colmin = $col;
  1543.         }
  1544.         if ($col >  $this->_dim_colmax) {
  1545.             $this->_dim_colmax = $col;
  1546.         }
  1547.  
  1548.         if ($strlen > $this->_xls_strmax) { // LABEL must be < 255 chars
  1549.             $str       = substr($str, 0, $this->_xls_strmax);
  1550.             $length    = 0x0008 + $this->_xls_strmax;
  1551.             $strlen    = $this->_xls_strmax;
  1552.             $str_error = -3;
  1553.         }
  1554.  
  1555.         $header    = pack("vv",   $record, $length);
  1556.         $data      = pack("vvvv", $row, $col, $xf, $strlen);
  1557.         $this->_append($header . $data . $str);
  1558.         return($str_error);
  1559.     }
  1560.  
  1561.     var $_biff8_input_encoding = 'UTF-16LE';
  1562.     function setBIFF8InputEncoding($encoding) {
  1563.         if ($encoding != 'UTF-16LE' && !function_exists('iconv')) {
  1564.             $this->raiseError("Using an input encoding other than UTF-16LE requires PHP support for iconv");
  1565.         }
  1566.         $this->_biff8_input_encoding = $encoding;
  1567.     }
  1568.  
  1569.     /**
  1570.     * Sets Input Encoding for writing strings
  1571.     *
  1572.     * @access public
  1573.     * @param string $encoding The encoding. Ex: 'UTF-16LE', 'utf-8', 'ISO-859-7'
  1574.     */
  1575.     function setInputEncoding($encoding)
  1576.     {
  1577.          if ($encoding != 'UTF-16LE' && !function_exists('iconv')) {
  1578.              throw new Exception("Using an input encoding other than UTF-16LE requires PHP support for iconv");
  1579.          }
  1580.          $this->_input_encoding = $encoding;
  1581.     }
  1582.  
  1583.     /**
  1584.     * Write a string to the specified row and column (zero indexed).
  1585.     * This is the BIFF8 version (no 255 chars limit).
  1586.     * $format is optional.
  1587.     * Returns  0 : normal termination
  1588.     *         -2 : row or column out of range
  1589.     *         -3 : long string truncated to 255 chars
  1590.     *
  1591.     * @access public
  1592.     * @param integer $row    Zero indexed row
  1593.     * @param integer $col    Zero indexed column
  1594.     * @param string  $str    The string to write
  1595.     * @param mixed   $format The XF format for the cell
  1596.     * @return integer 
  1597.     */
  1598.     function writeStringBIFF8($row, $col, $str, $format = null)
  1599.     {
  1600.         if ($this->_input_encoding == 'UTF-16LE')
  1601.         {
  1602.             $strlen = function_exists('mb_strlen') ? mb_strlen($str, 'UTF-16LE') : (strlen($str) / 2);
  1603.             $encoding  = 0x1;
  1604.         }
  1605.         elseif ($this->_input_encoding != '')
  1606.         {
  1607.             $str = iconv($this->_input_encoding, 'UTF-16LE', $str);
  1608.             $strlen = function_exists('mb_strlen') ? mb_strlen($str, 'UTF-16LE') : (strlen($str) / 2);
  1609.             $encoding  = 0x1;
  1610.         }
  1611.         else
  1612.         {
  1613.             $strlen    = strlen($str);
  1614.             $encoding  = 0x0;
  1615.         }
  1616.         $record    = 0x00FD;                   // Record identifier
  1617.         $length    = 0x000A;                   // Bytes to follow
  1618.         $xf        = $this->_XF($format);      // The cell format
  1619.  
  1620.         $str_error = 0;
  1621.  
  1622.         // Check that row and col are valid and store max and min values
  1623.         if ($this->_checkRowCol($row, $col) == false) {
  1624.             return -2;
  1625.         }
  1626.  
  1627.         $str = pack('vC', $strlen, $encoding).$str;
  1628.  
  1629.         /* check if string is already present */
  1630.         if (!isset($this->_str_table[$str])) {
  1631.             $this->_str_table[$str] = $this->_str_unique++;
  1632.         }
  1633.         $this->_str_total++;
  1634.  
  1635.         $header    = pack('vv',   $record, $length);
  1636.         $data      = pack('vvvV', $row, $col, $xf, $this->_str_table[$str]);
  1637.         $this->_append($header.$data);
  1638.         return $str_error;
  1639.     }
  1640.  
  1641.     /**
  1642.     * Check row and col before writing to a cell, and update the sheet's
  1643.     * dimensions accordingly
  1644.     *
  1645.     * @access private
  1646.     * @param integer $row    Zero indexed row
  1647.     * @param integer $col    Zero indexed column
  1648.     * @return boolean true for success, false if row and/or col are grester
  1649.     *                  then maximums allowed.
  1650.     */
  1651.     function _checkRowCol($row, $col)
  1652.     {
  1653.         if ($row >= $this->_xls_rowmax) {
  1654.             return false;
  1655.         }
  1656.         if ($col >= $this->_xls_colmax) {
  1657.             return false;
  1658.         }
  1659.         if ($row <  $this->_dim_rowmin) {
  1660.             $this->_dim_rowmin = $row;
  1661.         }
  1662.         if ($row >  $this->_dim_rowmax) {
  1663.             $this->_dim_rowmax = $row;
  1664.         }
  1665.         if ($col <  $this->_dim_colmin) {
  1666.             $this->_dim_colmin = $col;
  1667.         }
  1668.         if ($col >  $this->_dim_colmax) {
  1669.             $this->_dim_colmax = $col;
  1670.         }
  1671.         return true;
  1672.     }
  1673.  
  1674.     /**
  1675.     * Writes a note associated with the cell given by the row and column.
  1676.     * NOTE records don't have a length limit.
  1677.     *
  1678.     * @access public
  1679.     * @param integer $row    Zero indexed row
  1680.     * @param integer $col    Zero indexed column
  1681.     * @param string  $note   The note to write
  1682.     */
  1683.     function writeNote($row, $col, $note)
  1684.     {
  1685.         $note_length    = strlen($note);
  1686.         $record         = 0x001C;                // Record identifier
  1687.         $max_length     = 2048;                  // Maximun length for a NOTE record
  1688.         //$length      = 0x0006 + $note_length;    // Bytes to follow
  1689.  
  1690.         // Check that row and col are valid and store max and min values
  1691.         if ($row >= $this->_xls_rowmax) {
  1692.             return(-2);
  1693.         }
  1694.         if ($col >= $this->_xls_colmax) {
  1695.             return(-2);
  1696.         }
  1697.         if ($row <  $this->_dim_rowmin) {
  1698.             $this->_dim_rowmin = $row;
  1699.         }
  1700.         if ($row >  $this->_dim_rowmax) {
  1701.             $this->_dim_rowmax = $row;
  1702.         }
  1703.         if ($col <  $this->_dim_colmin) {
  1704.             $this->_dim_colmin = $col;
  1705.         }
  1706.         if ($col >  $this->_dim_colmax) {
  1707.             $this->_dim_colmax = $col;
  1708.         }
  1709.  
  1710.         // Length for this record is no more than 2048 + 6
  1711.         $length    = 0x0006 + min($note_length, 2048);
  1712.         $header    = pack("vv",   $record, $length);
  1713.         $data      = pack("vvv", $row, $col, $note_length);
  1714.         $this->_append($header . $data . substr($note, 0, 2048));
  1715.  
  1716.         for ($i = $max_length; $i < $note_length; $i += $max_length) {
  1717.             $chunk  = substr($note, $i, $max_length);
  1718.             $length = 0x0006 + strlen($chunk);
  1719.             $header = pack("vv",   $record, $length);
  1720.             $data   = pack("vvv", -1, 0, strlen($chunk));
  1721.             $this->_append($header.$data.$chunk);
  1722.         }
  1723.         return(0);
  1724.     }
  1725.  
  1726.     /**
  1727.     * Write a blank cell to the specified row and column (zero indexed).
  1728.     * A blank cell is used to specify formatting without adding a string
  1729.     * or a number.
  1730.     *
  1731.     * A blank cell without a format serves no purpose. Therefore, we don't write
  1732.     * a BLANK record unless a format is specified.
  1733.     *
  1734.     * Returns  0 : normal termination (including no format)
  1735.     *         -1 : insufficient number of arguments
  1736.     *         -2 : row or column out of range
  1737.     *
  1738.     * @access public
  1739.     * @param integer $row    Zero indexed row
  1740.     * @param integer $col    Zero indexed column
  1741.     * @param mixed   $format The XF format
  1742.     */
  1743.     function writeBlank($row, $col, $format)
  1744.     {
  1745.         // Don't write a blank cell unless it has a format
  1746.         if (!$format) {
  1747.             return(0);
  1748.         }
  1749.  
  1750.         $record    = 0x0201;                 // Record identifier
  1751.         $length    = 0x0006;                 // Number of bytes to follow
  1752.         $xf        = $this->_XF($format);    // The cell format
  1753.  
  1754.         // Check that row and col are valid and store max and min values
  1755.         if ($row >= $this->_xls_rowmax) {
  1756.             return(-2);
  1757.         }
  1758.         if ($col >= $this->_xls_colmax) {
  1759.             return(-2);
  1760.         }
  1761.         if ($row <  $this->_dim_rowmin) {
  1762.             $this->_dim_rowmin = $row;
  1763.         }
  1764.         if ($row >  $this->_dim_rowmax) {
  1765.             $this->_dim_rowmax = $row;
  1766.         }
  1767.         if ($col <  $this->_dim_colmin) {
  1768.             $this->_dim_colmin = $col;
  1769.         }
  1770.         if ($col >  $this->_dim_colmax) {
  1771.             $this->_dim_colmax = $col;
  1772.         }
  1773.  
  1774.         $header    = pack("vv",  $record, $length);
  1775.         $data      = pack("vvv", $row, $col, $xf);
  1776.         $this->_append($header . $data);
  1777.         return 0;
  1778.     }
  1779.  
  1780.     /**
  1781.     * Write a formula to the specified row and column (zero indexed).
  1782.     * The textual representation of the formula is passed to the parser in
  1783.     * Parser.php which returns a packed binary string.
  1784.     *
  1785.     * Returns  0 : normal termination
  1786.     *         -1 : formula errors (bad formula)
  1787.     *         -2 : row or column out of range
  1788.     *
  1789.     * @access public
  1790.     * @param integer $row     Zero indexed row
  1791.     * @param integer $col     Zero indexed column
  1792.     * @param string  $formula The formula text string
  1793.     * @param mixed   $format  The optional XF format
  1794.     * @return integer 
  1795.     */
  1796.     function writeFormula($row, $col, $formula, $format = null)
  1797.     {
  1798.         $record    = 0x0006;     // Record identifier
  1799.  
  1800.         // Excel normally stores the last calculated value of the formula in $num.
  1801.         // Clearly we are not in a position to calculate this a priori. Instead
  1802.         // we set $num to zero and set the option flags in $grbit to ensure
  1803.         // automatic calculation of the formula when the file is opened.
  1804.         //
  1805.         $xf        = $this->_XF($format); // The cell format
  1806.         $num       = 0x00;                // Current value of formula
  1807.         $grbit     = 0x03;                // Option flags
  1808.         $unknown   = 0x0000;              // Must be zero
  1809.  
  1810.  
  1811.         // Check that row and col are valid and store max and min values
  1812.         if ($this->_checkRowCol($row, $col) == false) {
  1813.             return -2;
  1814.         }
  1815.  
  1816.         // Strip the '=' or '@' sign at the beginning of the formula string
  1817.         if (preg_match("/^=/", $formula)) {
  1818.             $formula = preg_replace("/(^=)/", "", $formula);
  1819.         } elseif (preg_match("/^@/", $formula)) {
  1820.             $formula = preg_replace("/(^@)/", "", $formula);
  1821.         } else {
  1822.             // Error handling
  1823.             $this->writeString($row, $col, 'Unrecognised character for formula');
  1824.             return -1;
  1825.         }
  1826.  
  1827.         // Parse the formula using the parser in Parser.php
  1828.         $error = $this->_parser->parse($formula);
  1829.  
  1830.         $formula = $this->_parser->toReversePolish();
  1831.  
  1832.         $formlen    = strlen($formula);    // Length of the binary string
  1833.         $length     = 0x16 + $formlen;     // Length of the record data
  1834.  
  1835.         $header    = pack("vv",      $record, $length);
  1836.         $data      = pack("vvvdvVv", $row, $col, $xf, $num,
  1837.                                      $grbit, $unknown, $formlen);
  1838.  
  1839.         $this->_append($header . $data . $formula);
  1840.         return 0;
  1841.     }
  1842.  
  1843.     /**
  1844.     * Write a hyperlink.
  1845.     * This is comprised of two elements: the visible label and
  1846.     * the invisible link. The visible label is the same as the link unless an
  1847.     * alternative string is specified. The label is written using the
  1848.     * writeString() method. Therefore the 255 characters string limit applies.
  1849.     * $string and $format are optional.
  1850.     *
  1851.     * The hyperlink can be to a http, ftp, mail, internal sheet (not yet), or external
  1852.     * directory url.
  1853.     *
  1854.     * Returns  0 : normal termination
  1855.     *         -2 : row or column out of range
  1856.     *         -3 : long string truncated to 255 chars
  1857.     *
  1858.     * @access public
  1859.     * @param integer $row    Row
  1860.     * @param integer $col    Column
  1861.     * @param string  $url    URL string
  1862.     * @param string  $string Alternative label
  1863.     * @param mixed   $format The cell format
  1864.     * @return integer 
  1865.     */
  1866.     function writeUrl($row, $col, $url, $string = '', $format = null)
  1867.     {
  1868.         // Add start row and col to arg list
  1869.         return($this->_writeUrlRange($row, $col, $row, $col, $url, $string, $format));
  1870.     }
  1871.  
  1872.     /**
  1873.     * This is the more general form of writeUrl(). It allows a hyperlink to be
  1874.     * written to a range of cells. This function also decides the type of hyperlink
  1875.     * to be written. These are either, Web (http, ftp, mailto), Internal
  1876.     * (Sheet1!A1) or external ('c:\temp\foo.xls#Sheet1!A1').
  1877.     *
  1878.     * @access private
  1879.     * @see writeUrl()
  1880.     * @param integer $row1   Start row
  1881.     * @param integer $col1   Start column
  1882.     * @param integer $row2   End row
  1883.     * @param integer $col2   End column
  1884.     * @param string  $url    URL string
  1885.     * @param string  $string Alternative label
  1886.     * @param mixed   $format The cell format
  1887.     * @return integer 
  1888.     */
  1889.  
  1890.     function _writeUrlRange($row1, $col1, $row2, $col2, $url, $string = '', $format = null)
  1891.     {
  1892.  
  1893.         // Check for internal/external sheet links or default to web link
  1894.         if (preg_match('[^internal:]', $url)) {
  1895.             return($this->_writeUrlInternal($row1, $col1, $row2, $col2, $url, $string, $format));
  1896.         }
  1897.         if (preg_match('[^external:]', $url)) {
  1898.             return($this->_writeUrlExternal($row1, $col1, $row2, $col2, $url, $string, $format));
  1899.         }
  1900.         return($this->_writeUrlWeb($row1, $col1, $row2, $col2, $url, $string, $format));
  1901.     }
  1902.  
  1903.  
  1904.     /**
  1905.     * Used to write http, ftp and mailto hyperlinks.
  1906.     * The link type ($options) is 0x03 is the same as absolute dir ref without
  1907.     * sheet. However it is differentiated by the $unknown2 data stream.
  1908.     *
  1909.     * @access private
  1910.     * @see writeUrl()
  1911.     * @param integer $row1   Start row
  1912.     * @param integer $col1   Start column
  1913.     * @param integer $row2   End row
  1914.     * @param integer $col2   End column
  1915.     * @param string  $url    URL string
  1916.     * @param string  $str    Alternative label
  1917.     * @param mixed   $format The cell format
  1918.     * @return integer 
  1919.     */
  1920.     function _writeUrlWeb($row1, $col1, $row2, $col2, $url, $str, $format = null)
  1921.     {
  1922.         $record      = 0x01B8;                       // Record identifier
  1923.         $length      = 0x00000;                      // Bytes to follow
  1924.  
  1925.         if (!$format) {
  1926.             $format = $this->_url_format;
  1927.         }
  1928.  
  1929.         // Write the visible label using the writeString() method.
  1930.         if ($str == '') {
  1931.             $str = $url;
  1932.         }
  1933.         $str_error = $this->writeString($row1, $col1, $str, $format);
  1934.         if (($str_error == -2) || ($str_error == -3)) {
  1935.             return $str_error;
  1936.         }
  1937.  
  1938.         // Pack the undocumented parts of the hyperlink stream
  1939.         $unknown1    = pack("H*", "D0C9EA79F9BACE118C8200AA004BA90B02000000");
  1940.         $unknown2    = pack("H*", "E0C9EA79F9BACE118C8200AA004BA90B");
  1941.  
  1942.         // Pack the option flags
  1943.         $options     = pack("V", 0x03);
  1944.  
  1945.         // Convert URL to a null terminated wchar string
  1946.         $url         = join("\0", preg_split("''", $url, -1, PREG_SPLIT_NO_EMPTY));
  1947.         $url         = $url . "\0\0\0";
  1948.  
  1949.         // Pack the length of the URL
  1950.         $url_len     = pack("V", strlen($url));
  1951.  
  1952.         // Calculate the data length
  1953.         $length      = 0x34 + strlen($url);
  1954.  
  1955.         // Pack the header data
  1956.         $header      = pack("vv",   $record, $length);
  1957.         $data        = pack("vvvv", $row1, $row2, $col1, $col2);
  1958.  
  1959.         // Write the packed data
  1960.         $this->_append($header . $data .
  1961.                        $unknown1 . $options .
  1962.                        $unknown2 . $url_len . $url);
  1963.         return($str_error);
  1964.     }
  1965.  
  1966.     /**
  1967.     * Used to write internal reference hyperlinks such as "Sheet1!A1".
  1968.     *
  1969.     * @access private
  1970.     * @see writeUrl()
  1971.     * @param integer $row1   Start row
  1972.     * @param integer $col1   Start column
  1973.     * @param integer $row2   End row
  1974.     * @param integer $col2   End column
  1975.     * @param string  $url    URL string
  1976.     * @param string  $str    Alternative label
  1977.     * @param mixed   $format The cell format
  1978.     * @return integer 
  1979.     */
  1980.     function _writeUrlInternal($row1, $col1, $row2, $col2, $url, $str, $format = null)
  1981.     {
  1982.         $record      = 0x01B8;                       // Record identifier
  1983.         $length      = 0x00000;                      // Bytes to follow
  1984.  
  1985.         if (!$format) {
  1986.             $format = $this->_url_format;
  1987.         }
  1988.  
  1989.         // Strip URL type
  1990.         $url = preg_replace('/^internal:/', '', $url);
  1991.  
  1992.         // Write the visible label
  1993.         if ($str == '') {
  1994.             $str = $url;
  1995.         }
  1996.         $str_error = $this->writeString($row1, $col1, $str, $format);
  1997.         if (($str_error == -2) || ($str_error == -3)) {
  1998.             return $str_error;
  1999.         }
  2000.  
  2001.         // Pack the undocumented parts of the hyperlink stream
  2002.         $unknown1    = pack("H*", "D0C9EA79F9BACE118C8200AA004BA90B02000000");
  2003.  
  2004.         // Pack the option flags
  2005.         $options     = pack("V", 0x08);
  2006.  
  2007.         // Convert the URL type and to a null terminated wchar string
  2008.         $url         = join("\0", preg_split("''", $url, -1, PREG_SPLIT_NO_EMPTY));
  2009.         $url         = $url . "\0\0\0";
  2010.  
  2011.         // Pack the length of the URL as chars (not wchars)
  2012.         $url_len     = pack("V", floor(strlen($url)/2));
  2013.  
  2014.         // Calculate the data length
  2015.         $length      = 0x24 + strlen($url);
  2016.  
  2017.         // Pack the header data
  2018.         $header      = pack("vv",   $record, $length);
  2019.         $data        = pack("vvvv", $row1, $row2, $col1, $col2);
  2020.  
  2021.         // Write the packed data
  2022.         $this->_append($header . $data .
  2023.                        $unknown1 . $options .
  2024.                        $url_len . $url);
  2025.         return($str_error);
  2026.     }
  2027.  
  2028.     /**
  2029.     * Write links to external directory names such as 'c:\foo.xls',
  2030.     * c:\foo.xls#Sheet1!A1', '../../foo.xls'. and '../../foo.xls#Sheet1!A1'.
  2031.     *
  2032.     * Note: Excel writes some relative links with the $dir_long string. We ignore
  2033.     * these cases for the sake of simpler code.
  2034.     *
  2035.     * @access private
  2036.     * @see writeUrl()
  2037.     * @param integer $row1   Start row
  2038.     * @param integer $col1   Start column
  2039.     * @param integer $row2   End row
  2040.     * @param integer $col2   End column
  2041.     * @param string  $url    URL string
  2042.     * @param string  $str    Alternative label
  2043.     * @param mixed   $format The cell format
  2044.     * @return integer 
  2045.     */
  2046.     function _writeUrlExternal($row1, $col1, $row2, $col2, $url, $str, $format = null)
  2047.     {
  2048.         // Network drives are different. We will handle them separately
  2049.         // MS/Novell network drives and shares start with \\
  2050.         if (preg_match('[^external:\\\\]', $url)) {
  2051.             return; //($this->_writeUrlExternal_net($row1, $col1, $row2, $col2, $url, $str, $format));
  2052.         }
  2053.  
  2054.         $record      = 0x01B8;                       // Record identifier
  2055.         $length      = 0x00000;                      // Bytes to follow
  2056.  
  2057.         if (!$format) {
  2058.             $format = $this->_url_format;
  2059.         }
  2060.  
  2061.         // Strip URL type and change Unix dir separator to Dos style (if needed)
  2062.         //
  2063.         $url = preg_replace('/^external:/', '', $url);
  2064.         $url = preg_replace('/\//', "\\", $url);
  2065.  
  2066.         // Write the visible label
  2067.         if ($str == '') {
  2068.             $str = preg_replace('/\#/', ' - ', $url);
  2069.         }
  2070.         $str_error = $this->writeString($row1, $col1, $str, $format);
  2071.         if (($str_error == -2) or ($str_error == -3)) {
  2072.             return $str_error;
  2073.         }
  2074.  
  2075.         // Determine if the link is relative or absolute:
  2076.         //   relative if link contains no dir separator, "somefile.xls"
  2077.         //   relative if link starts with up-dir, "..\..\somefile.xls"
  2078.         //   otherwise, absolute
  2079.  
  2080.         $absolute    = 0x02; // Bit mask
  2081.         if (!preg_match("/\\\/", $url)) {
  2082.             $absolute    = 0x00;
  2083.         }
  2084.         if (preg_match("/^\.\.\\\/", $url)) {
  2085.             $absolute    = 0x00;
  2086.         }
  2087.         $link_type               = 0x01 | $absolute;
  2088.  
  2089.         // Determine if the link contains a sheet reference and change some of the
  2090.         // parameters accordingly.
  2091.         // Split the dir name and sheet name (if it exists)
  2092.         /*if (preg_match("/\#/", $url)) {
  2093.             list($dir_long, $sheet) = split("\#", $url);
  2094.         } else {
  2095.             $dir_long = $url;
  2096.         }
  2097.  
  2098.         if (isset($sheet)) {
  2099.             $link_type |= 0x08;
  2100.             $sheet_len  = pack("V", strlen($sheet) + 0x01);
  2101.             $sheet      = join("\0", split('', $sheet));
  2102.             $sheet     .= "\0\0\0";
  2103.         } else {
  2104.             $sheet_len   = '';
  2105.             $sheet       = '';
  2106.         }*/
  2107.         $dir_long = $url;
  2108.         if (preg_match("/\#/", $url)) {
  2109.             $link_type |= 0x08;
  2110.         }
  2111.  
  2112.  
  2113.  
  2114.         // Pack the link type
  2115.         $link_type   = pack("V", $link_type);
  2116.  
  2117.         // Calculate the up-level dir count e.g.. (..\..\..\ == 3)
  2118.         $up_count    = preg_match_all("/\.\.\\\/", $dir_long, $useless);
  2119.         $up_count    = pack("v", $up_count);
  2120.  
  2121.         // Store the short dos dir name (null terminated)
  2122.         $dir_short   = preg_replace("/\.\.\\\/", '', $dir_long) . "\0";
  2123.  
  2124.         // Store the long dir name as a wchar string (non-null terminated)
  2125.         //$dir_long       = join("\0", split('', $dir_long));
  2126.         $dir_long       = $dir_long . "\0";
  2127.  
  2128.         // Pack the lengths of the dir strings
  2129.         $dir_short_len = pack("V", strlen($dir_short)      );
  2130.         $dir_long_len  = pack("V", strlen($dir_long)       );
  2131.         $stream_len    = pack("V", 0);//strlen($dir_long) + 0x06);
  2132.  
  2133.         // Pack the undocumented parts of the hyperlink stream
  2134.         $unknown1 = pack("H*",'D0C9EA79F9BACE118C8200AA004BA90B02000000'       );
  2135.         $unknown2 = pack("H*",'0303000000000000C000000000000046'               );
  2136.         $unknown3 = pack("H*",'FFFFADDE000000000000000000000000000000000000000');
  2137.         $unknown4 = pack("v",  0x03                                            );
  2138.  
  2139.         // Pack the main data stream
  2140.         $data        = pack("vvvv", $row1, $row2, $col1, $col2) .
  2141.                           $unknown1     .
  2142.                           $link_type    .
  2143.                           $unknown2     .
  2144.                           $up_count     .
  2145.                           $dir_short_len.
  2146.                           $dir_short    .
  2147.                           $unknown3     .
  2148.                           $stream_len   ;/*.
  2149.                           $dir_long_len .
  2150.                           $unknown4     .
  2151.                           $dir_long     .
  2152.                           $sheet_len    .
  2153.                           $sheet        ;*/
  2154.  
  2155.         // Pack the header data
  2156.         $length   = strlen($data);
  2157.         $header   = pack("vv", $record, $length);
  2158.  
  2159.         // Write the packed data
  2160.         $this->_append($header. $data);
  2161.         return($str_error);
  2162.     }
  2163.  
  2164.  
  2165.     /**
  2166.     * This method is used to set the height and format for a row.
  2167.     *
  2168.     * @access public
  2169.     * @param integer $row    The row to set
  2170.     * @param integer $height Height we are giving to the row.
  2171.     *                         Use null to set XF without setting height
  2172.     * @param mixed   $format XF format we are giving to the row
  2173.     * @param bool    $hidden The optional hidden attribute
  2174.     * @param integer $level  The optional outline level for row, in range [0,7]
  2175.     */
  2176.     function setRow($row, $height, $format = null, $hidden = false, $level = 0)
  2177.     {
  2178.         $record      = 0x0208;               // Record identifier
  2179.         $length      = 0x0010;               // Number of bytes to follow
  2180.  
  2181.         $colMic      = 0x0000;               // First defined column
  2182.         $colMac      = 0x0000;               // Last defined column
  2183.         $irwMac      = 0x0000;               // Used by Excel to optimise loading
  2184.         $reserved    = 0x0000;               // Reserved
  2185.         $grbit       = 0x0000;               // Option flags
  2186.         $ixfe        = $this->_XF($format);  // XF index
  2187.  
  2188.         if ( $height < 0 ){
  2189.             $height = null;
  2190.         }
  2191.  
  2192.         // set _row_sizes so _sizeRow() can use it
  2193.         $this->_row_sizes[$row] = $height;
  2194.  
  2195.         // Use setRow($row, null, $XF) to set XF format without setting height
  2196.         if ($height != null) {
  2197.             $miyRw = $height * 20;  // row height
  2198.         } else {
  2199.             $miyRw = 0xff;          // default row height is 256
  2200.         }
  2201.  
  2202.         $level = max(0, min($level, 7));  // level should be between 0 and 7
  2203.         $this->_outline_row_level = max($level, $this->_outline_row_level);
  2204.  
  2205.  
  2206.         // Set the options flags. fUnsynced is used to show that the font and row
  2207.         // heights are not compatible. This is usually the case for WriteExcel.
  2208.         // The collapsed flag 0x10 doesn't seem to be used to indicate that a row
  2209.         // is collapsed. Instead it is used to indicate that the previous row is
  2210.         // collapsed. The zero height flag, 0x20, is used to collapse a row.
  2211.  
  2212.         $grbit |= $level;
  2213.         if ($hidden) {
  2214.             $grbit |= 0x0020;
  2215.         }
  2216.         $grbit |= 0x0040; // fUnsynced
  2217.         if ($format) {
  2218.             $grbit |= 0x0080;
  2219.         }
  2220.         $grbit |= 0x0100;
  2221.  
  2222.         $header   = pack("vv",       $record, $length);
  2223.         $data     = pack("vvvvvvvv", $row, $colMic, $colMac, $miyRw,
  2224.                                      $irwMac,$reserved, $grbit, $ixfe);
  2225.         $this->_append($header.$data);
  2226.     }
  2227.  
  2228.     /**
  2229.     * Writes Excel DIMENSIONS to define the area in which there is data.
  2230.     *
  2231.     * @access private
  2232.     */
  2233.     function _storeDimensions()
  2234.     {
  2235.         $record    = 0x0200;                 // Record identifier
  2236.         $row_min   = $this->_dim_rowmin;     // First row
  2237.         $row_max   = $this->_dim_rowmax + 1; // Last row plus 1
  2238.         $col_min   = $this->_dim_colmin;     // First column
  2239.         $col_max   = $this->_dim_colmax + 1; // Last column plus 1
  2240.         $reserved  = 0x0000;                 // Reserved by Excel
  2241.  
  2242.         if ($this->_BIFF_version == 0x0500) {
  2243.             $length    = 0x000A;               // Number of bytes to follow
  2244.             $data      = pack("vvvvv", $row_min, $row_max,
  2245.                                        $col_min, $col_max, $reserved);
  2246.         } elseif ($this->_BIFF_version == 0x0600) {
  2247.             $length    = 0x000E;
  2248.             $data      = pack("VVvvv", $row_min, $row_max,
  2249.                                        $col_min, $col_max, $reserved);
  2250.         }
  2251.         $header = pack("vv", $record, $length);
  2252.         $this->_prepend($header.$data);
  2253.     }
  2254.  
  2255.     /**
  2256.     * Write BIFF record Window2.
  2257.     *
  2258.     * @access private
  2259.     */
  2260.     function _storeWindow2()
  2261.     {
  2262.         $record         = 0x023E;     // Record identifier
  2263.         if ($this->_BIFF_version == 0x0500) {
  2264.             $length         = 0x000A;     // Number of bytes to follow
  2265.         } elseif ($this->_BIFF_version == 0x0600) {
  2266.             $length         = 0x0012;
  2267.         }
  2268.  
  2269.         $grbit          = 0x00B6;     // Option flags
  2270.         $rwTop          = 0x0000;     // Top row visible in window
  2271.         $colLeft        = 0x0000;     // Leftmost column visible in window
  2272.  
  2273.  
  2274.         // The options flags that comprise $grbit
  2275.         $fDspFmla       = 0;                     // 0 - bit
  2276.         $fDspGrid       = $this->_screen_gridlines; // 1
  2277.         $fDspRwCol      = 1;                     // 2
  2278.         $fFrozen        = $this->_frozen;        // 3
  2279.         $fDspZeros      = 1;                     // 4
  2280.         $fDefaultHdr    = 1;                     // 5
  2281.         $fArabic        = 0;                     // 6
  2282.         $fDspGuts       = $this->_outline_on;    // 7
  2283.         $fFrozenNoSplit = 0;                     // 0 - bit
  2284.         $fSelected      = $this->selected;       // 1
  2285.         $fPaged         = 1;                     // 2
  2286.  
  2287.         $grbit             = $fDspFmla;
  2288.         $grbit            |= $fDspGrid       << 1;
  2289.         $grbit            |= $fDspRwCol      << 2;
  2290.         $grbit            |= $fFrozen        << 3;
  2291.         $grbit            |= $fDspZeros      << 4;
  2292.         $grbit            |= $fDefaultHdr    << 5;
  2293.         $grbit            |= $fArabic        << 6;
  2294.         $grbit            |= $fDspGuts       << 7;
  2295.         $grbit            |= $fFrozenNoSplit << 8;
  2296.         $grbit            |= $fSelected      << 9;
  2297.         $grbit            |= $fPaged         << 10;
  2298.  
  2299.         $header  = pack("vv",   $record, $length);
  2300.         $data    = pack("vvv", $grbit, $rwTop, $colLeft);
  2301.         // FIXME !!!
  2302.         if ($this->_BIFF_version == 0x0500) {
  2303.             $rgbHdr         = 0x00000000; // Row/column heading and gridline color
  2304.             $data .= pack("V", $rgbHdr);
  2305.         } elseif ($this->_BIFF_version == 0x0600) {
  2306.             $rgbHdr       = 0x0040; // Row/column heading and gridline color index
  2307.             $zoom_factor_page_break = 0x0000;
  2308.             $zoom_factor_normal     = 0x0000;
  2309.             $data .= pack("vvvvV", $rgbHdr, 0x0000, $zoom_factor_page_break, $zoom_factor_normal, 0x00000000);
  2310.         }
  2311.         $this->_append($header.$data);
  2312.     }
  2313.  
  2314.     /**
  2315.     * Write BIFF record DEFCOLWIDTH if COLINFO records are in use.
  2316.     *
  2317.     * @access private
  2318.     */
  2319.     function _storeDefcol()
  2320.     {
  2321.         $record   = 0x0055;      // Record identifier
  2322.         $length   = 0x0002;      // Number of bytes to follow
  2323.         $colwidth = 0x0008;      // Default column width
  2324.  
  2325.         $header   = pack("vv", $record, $length);
  2326.         $data     = pack("v",  $colwidth);
  2327.         $this->_prepend($header . $data);
  2328.     }
  2329.  
  2330.     /**
  2331.     * Write BIFF record COLINFO to define column widths
  2332.     *
  2333.     * Note: The SDK says the record length is 0x0B but Excel writes a 0x0C
  2334.     * length record.
  2335.     *
  2336.     * @access private
  2337.     * @param array $col_array This is the only parameter received and is composed of the following:
  2338.     *                 0 => First formatted column,
  2339.     *                 1 => Last formatted column,
  2340.     *                 2 => Col width (8.43 is Excel default),
  2341.     *                 3 => The optional XF format of the column,
  2342.     *                 4 => Option flags.
  2343.     *                 5 => Optional outline level
  2344.     */
  2345.     function _storeColinfo($col_array)
  2346.     {
  2347.         if (isset($col_array[0])) {
  2348.             $colFirst = $col_array[0];
  2349.         }
  2350.         if (isset($col_array[1])) {
  2351.             $colLast = $col_array[1];
  2352.         }
  2353.         if (isset($col_array[2])) {
  2354.             $coldx = $col_array[2];
  2355.         } else {
  2356.             $coldx = 8.43;
  2357.         }
  2358.         if (isset($col_array[3])) {
  2359.             $format = $col_array[3];
  2360.         } else {
  2361.             $format = 0;
  2362.         }
  2363.         if (isset($col_array[4])) {
  2364.             $grbit = $col_array[4];
  2365.         } else {
  2366.             $grbit = 0;
  2367.         }
  2368.         if (isset($col_array[5])) {
  2369.             $level = $col_array[5];
  2370.         } else {
  2371.             $level = 0;
  2372.         }
  2373.         $record   = 0x007D;          // Record identifier
  2374.         $length   = 0x000B;          // Number of bytes to follow
  2375.  
  2376.         $coldx   += 0.72;            // Fudge. Excel subtracts 0.72 !?
  2377.         $coldx   *= 256;             // Convert to units of 1/256 of a char
  2378.  
  2379.         $ixfe     = $this->_XF($format);
  2380.         $reserved = 0x00;            // Reserved
  2381.  
  2382.         $level = max(0, min($level, 7));
  2383.         $grbit |= $level << 8;
  2384.  
  2385.         $header   = pack("vv",     $record, $length);
  2386.         $data     = pack("vvvvvC", $colFirst, $colLast, $coldx,
  2387.                                    $ixfe, $grbit, $reserved);
  2388.         $this->_prepend($header.$data);
  2389.     }
  2390.  
  2391.     /**
  2392.     * Write BIFF record SELECTION.
  2393.     *
  2394.     * @access private
  2395.     * @param array $array array containing ($rwFirst,$colFirst,$rwLast,$colLast)
  2396.     * @see setSelection()
  2397.     */
  2398.     function _storeSelection($array)
  2399.     {
  2400.         list($rwFirst,$colFirst,$rwLast,$colLast) = $array;
  2401.         $record   = 0x001D;                  // Record identifier
  2402.         $length   = 0x000F;                  // Number of bytes to follow
  2403.  
  2404.         $pnn      = $this->_active_pane;     // Pane position
  2405.         $rwAct    = $rwFirst;                // Active row
  2406.         $colAct   = $colFirst;               // Active column
  2407.         $irefAct  = 0;                       // Active cell ref
  2408.         $cref     = 1;                       // Number of refs
  2409.  
  2410.         if (!isset($rwLast)) {
  2411.             $rwLast   = $rwFirst;       // Last  row in reference
  2412.         }
  2413.         if (!isset($colLast)) {
  2414.             $colLast  = $colFirst;      // Last  col in reference
  2415.         }
  2416.  
  2417.         // Swap last row/col for first row/col as necessary
  2418.         if ($rwFirst > $rwLast) {
  2419.             list($rwFirst, $rwLast) = array($rwLast, $rwFirst);
  2420.         }
  2421.  
  2422.         if ($colFirst > $colLast) {
  2423.             list($colFirst, $colLast) = array($colLast, $colFirst);
  2424.         }
  2425.  
  2426.         $header   = pack("vv",         $record, $length);
  2427.         $data     = pack("CvvvvvvCC",  $pnn, $rwAct, $colAct,
  2428.                                        $irefAct, $cref,
  2429.                                        $rwFirst, $rwLast,
  2430.                                        $colFirst, $colLast);
  2431.         $this->_append($header . $data);
  2432.     }
  2433.  
  2434.     /**
  2435.     * Store the MERGEDCELLS record for all ranges of merged cells
  2436.     *
  2437.     * @access private
  2438.     */
  2439.     function _storeMergedCells()
  2440.     {
  2441.         // if there are no merged cell ranges set, return
  2442.         if (count($this->_merged_ranges) == 0) {
  2443.             return;
  2444.         }
  2445.         $record   = 0x00E5;
  2446.         $length   = 2 + count($this->_merged_ranges) * 8;
  2447.  
  2448.         $header   = pack('vv', $record, $length);
  2449.         $data     = pack('v',  count($this->_merged_ranges));
  2450.         foreach ($this->_merged_ranges as $range) {
  2451.             $data .= pack('vvvv', $range[0], $range[2], $range[1], $range[3]);
  2452.         }
  2453.         $this->_append($header . $data);
  2454.     }
  2455.  
  2456.     /**
  2457.     * Write BIFF record EXTERNCOUNT to indicate the number of external sheet
  2458.     * references in a worksheet.
  2459.     *
  2460.     * Excel only stores references to external sheets that are used in formulas.
  2461.     * For simplicity we store references to all the sheets in the workbook
  2462.     * regardless of whether they are used or not. This reduces the overall
  2463.     * complexity and eliminates the need for a two way dialogue between the formula
  2464.     * parser the worksheet objects.
  2465.     *
  2466.     * @access private
  2467.     * @param integer $count The number of external sheet references in this worksheet
  2468.     */
  2469.     function _storeExterncount($count)
  2470.     {
  2471.         $record = 0x0016;          // Record identifier
  2472.         $length = 0x0002;          // Number of bytes to follow
  2473.  
  2474.         $header = pack("vv", $record, $length);
  2475.         $data   = pack("v",  $count);
  2476.         $this->_prepend($header . $data);
  2477.     }
  2478.  
  2479.     /**
  2480.     * Writes the Excel BIFF EXTERNSHEET record. These references are used by
  2481.     * formulas. A formula references a sheet name via an index. Since we store a
  2482.     * reference to all of the external worksheets the EXTERNSHEET index is the same
  2483.     * as the worksheet index.
  2484.     *
  2485.     * @access private
  2486.     * @param string $sheetname The name of a external worksheet
  2487.     */
  2488.     function _storeExternsheet($sheetname)
  2489.     {
  2490.         $record    = 0x0017;         // Record identifier
  2491.  
  2492.         // References to the current sheet are encoded differently to references to
  2493.         // external sheets.
  2494.         //
  2495.         if ($this->name == $sheetname) {
  2496.             $sheetname = '';
  2497.             $length    = 0x02;  // The following 2 bytes
  2498.             $cch       = 1;     // The following byte
  2499.             $rgch      = 0x02;  // Self reference
  2500.         } else {
  2501.             $length    = 0x02 + strlen($sheetname);
  2502.             $cch       = strlen($sheetname);
  2503.             $rgch      = 0x03;  // Reference to a sheet in the current workbook
  2504.         }
  2505.  
  2506.         $header = pack("vv",  $record, $length);
  2507.         $data   = pack("CC", $cch, $rgch);
  2508.         $this->_prepend($header . $data . $sheetname);
  2509.     }
  2510.  
  2511.     /**
  2512.     * Writes the Excel BIFF PANE record.
  2513.     * The panes can either be frozen or thawed (unfrozen).
  2514.     * Frozen panes are specified in terms of an integer number of rows and columns.
  2515.     * Thawed panes are specified in terms of Excel's units for rows and columns.
  2516.     *
  2517.     * @access private
  2518.     * @param array $panes This is the only parameter received and is composed of the following:
  2519.     *                      0 => Vertical split position,
  2520.     *                      1 => Horizontal split position
  2521.     *                      2 => Top row visible
  2522.     *                      3 => Leftmost column visible
  2523.     *                      4 => Active pane
  2524.     */
  2525.     function _storePanes($panes)
  2526.     {
  2527.         $y       = isset($panes[0]) ? $panes[0] : null;
  2528.         $x       = isset($panes[1]) ? $panes[1] : null;
  2529.         $rwTop   = isset($panes[2]) ? $panes[2] : null;
  2530.         $colLeft = isset($panes[3]) ? $panes[3] : null;
  2531.         if (count($panes) > 4) { // if Active pane was received
  2532.             $pnnAct = $panes[4];
  2533.         } else {
  2534.             $pnnAct = null;
  2535.         }
  2536.         $record  = 0x0041;       // Record identifier
  2537.         $length  = 0x000A;       // Number of bytes to follow
  2538.  
  2539.         // Code specific to frozen or thawed panes.
  2540.         if ($this->_frozen) {
  2541.             // Set default values for $rwTop and $colLeft
  2542.             if (!isset($rwTop)) {
  2543.                 $rwTop   = $y;
  2544.             }
  2545.             if (!isset($colLeft)) {
  2546.                 $colLeft = $x;
  2547.             }
  2548.         } else {
  2549.             // Set default values for $rwTop and $colLeft
  2550.             if (!isset($rwTop)) {
  2551.                 $rwTop   = 0;
  2552.             }
  2553.             if (!isset($colLeft)) {
  2554.                 $colLeft = 0;
  2555.             }
  2556.  
  2557.             // Convert Excel's row and column units to the internal units.
  2558.             // The default row height is 12.75
  2559.             // The default column width is 8.43
  2560.             // The following slope and intersection values were interpolated.
  2561.             //
  2562.             $y = 20*$y      + 255;
  2563.             $x = 113.879*$x + 390;
  2564.         }
  2565.  
  2566.  
  2567.         // Determine which pane should be active. There is also the undocumented
  2568.         // option to override this should it be necessary: may be removed later.
  2569.         //
  2570.         if (!isset($pnnAct)) {
  2571.             if ($x != 0 && $y != 0) {
  2572.                 $pnnAct = 0; // Bottom right
  2573.             }
  2574.             if ($x != 0 && $y == 0) {
  2575.                 $pnnAct = 1; // Top right
  2576.             }
  2577.             if ($x == 0 && $y != 0) {
  2578.                 $pnnAct = 2; // Bottom left
  2579.             }
  2580.             if ($x == 0 && $y == 0) {
  2581.                 $pnnAct = 3; // Top left
  2582.             }
  2583.         }
  2584.  
  2585.         $this->_active_pane = $pnnAct; // Used in _storeSelection
  2586.  
  2587.         $header     = pack("vv",    $record, $length);
  2588.         $data       = pack("vvvvv", $x, $y, $rwTop, $colLeft, $pnnAct);
  2589.         $this->_append($header . $data);
  2590.     }
  2591.  
  2592.     /**
  2593.     * Store the page setup SETUP BIFF record.
  2594.     *
  2595.     * @access private
  2596.     */
  2597.     function _storeSetup()
  2598.     {
  2599.         $record       = 0x00A1;                  // Record identifier
  2600.         $length       = 0x0022;                  // Number of bytes to follow
  2601.  
  2602.         $iPaperSize   = $this->_paper_size;    // Paper size
  2603.         $iScale       = $this->_print_scale;   // Print scaling factor
  2604.         $iPageStart   = 0x01;                 // Starting page number
  2605.         $iFitWidth    = $this->_fit_width;    // Fit to number of pages wide
  2606.         $iFitHeight   = $this->_fit_height;   // Fit to number of pages high
  2607.         $grbit        = 0x00;                 // Option flags
  2608.         $iRes         = 0x0258;               // Print resolution
  2609.         $iVRes        = 0x0258;               // Vertical print resolution
  2610.         $numHdr       = $this->_margin_head;  // Header Margin
  2611.         $numFtr       = $this->_margin_foot;   // Footer Margin
  2612.         $iCopies      = 0x01;                 // Number of copies
  2613.  
  2614.         $fLeftToRight = 0x0;                     // Print over then down
  2615.         $fLandscape   = $this->_orientation;     // Page orientation
  2616.         $fNoPls       = 0x0;                     // Setup not read from printer
  2617.         $fNoColor     = 0x0;                     // Print black and white
  2618.         $fDraft       = 0x0;                     // Print draft quality
  2619.         $fNotes       = 0x0;                     // Print notes
  2620.         $fNoOrient    = 0x0;                     // Orientation not set
  2621.         $fUsePage     = 0x0;                     // Use custom starting page
  2622.  
  2623.         $grbit           = $fLeftToRight;
  2624.         $grbit          |= $fLandscape    << 1;
  2625.         $grbit          |= $fNoPls        << 2;
  2626.         $grbit          |= $fNoColor      << 3;
  2627.         $grbit          |= $fDraft        << 4;
  2628.         $grbit          |= $fNotes        << 5;
  2629.         $grbit          |= $fNoOrient     << 6;
  2630.         $grbit          |= $fUsePage      << 7;
  2631.  
  2632.         $numHdr = pack("d", $numHdr);
  2633.         $numFtr = pack("d", $numFtr);
  2634.         if ($this->_byte_order) { // if it's Big Endian
  2635.             $numHdr = strrev($numHdr);
  2636.             $numFtr = strrev($numFtr);
  2637.         }
  2638.  
  2639.         $header = pack("vv", $record, $length);
  2640.         $data1  = pack("vvvvvvvv", $iPaperSize,
  2641.                                    $iScale,
  2642.                                    $iPageStart,
  2643.                                    $iFitWidth,
  2644.                                    $iFitHeight,
  2645.                                    $grbit,
  2646.                                    $iRes,
  2647.                                    $iVRes);
  2648.         $data2  = $numHdr.$numFtr;
  2649.         $data3  = pack("v", $iCopies);
  2650.         $this->_prepend($header . $data1 . $data2 . $data3);
  2651.     }
  2652.  
  2653.     /**
  2654.     * Store the header caption BIFF record.
  2655.     *
  2656.     * @access private
  2657.     */
  2658.     function _storeHeader()
  2659.     {
  2660.         $record  = 0x0014;               // Record identifier
  2661.  
  2662.         $str      = $this->_header;       // header string
  2663.         $cch      = strlen($str);         // Length of header string
  2664.         if ($this->_BIFF_version == 0x0600) {
  2665.             $encoding = 0x0;                  // TODO: Unicode support
  2666.             $length   = 3 + $cch;             // Bytes to follow
  2667.         } else {
  2668.             $length  = 1 + $cch;             // Bytes to follow
  2669.         }
  2670.  
  2671.         $header   = pack("vv", $record, $length);
  2672.         if ($this->_BIFF_version == 0x0600) {
  2673.             $data     = pack("vC",  $cch, $encoding);
  2674.         } else {
  2675.             $data      = pack("C",  $cch);
  2676.         }
  2677.  
  2678.         $this->_prepend($header.$data.$str);
  2679.     }
  2680.  
  2681.     /**
  2682.     * Store the footer caption BIFF record.
  2683.     *
  2684.     * @access private
  2685.     */
  2686.     function _storeFooter()
  2687.     {
  2688.         $record  = 0x0015;               // Record identifier
  2689.  
  2690.         $str      = $this->_footer;       // Footer string
  2691.         $cch      = strlen($str);         // Length of footer string
  2692.         if ($this->_BIFF_version == 0x0600) {
  2693.             $encoding = 0x0;                  // TODO: Unicode support
  2694.             $length   = 3 + $cch;             // Bytes to follow
  2695.         } else {
  2696.             $length  = 1 + $cch;
  2697.         }
  2698.  
  2699.         $header    = pack("vv", $record, $length);
  2700.         if ($this->_BIFF_version == 0x0600) {
  2701.             $data      = pack("vC",  $cch, $encoding);
  2702.         } else {
  2703.             $data      = pack("C",  $cch);
  2704.         }
  2705.  
  2706.         $this->_prepend($header . $data . $str);
  2707.     }
  2708.  
  2709.     /**
  2710.     * Store the horizontal centering HCENTER BIFF record.
  2711.     *
  2712.     * @access private
  2713.     */
  2714.     function _storeHcenter()
  2715.     {
  2716.         $record   = 0x0083;              // Record identifier
  2717.         $length   = 0x0002;              // Bytes to follow
  2718.  
  2719.         $fHCenter = $this->_hcenter;     // Horizontal centering
  2720.  
  2721.         $header    = pack("vv", $record, $length);
  2722.         $data      = pack("v",  $fHCenter);
  2723.  
  2724.         $this->_prepend($header.$data);
  2725.     }
  2726.  
  2727.     /**
  2728.     * Store the vertical centering VCENTER BIFF record.
  2729.     *
  2730.     * @access private
  2731.     */
  2732.     function _storeVcenter()
  2733.     {
  2734.         $record   = 0x0084;              // Record identifier
  2735.         $length   = 0x0002;              // Bytes to follow
  2736.  
  2737.         $fVCenter = $this->_vcenter;     // Horizontal centering
  2738.  
  2739.         $header    = pack("vv", $record, $length);
  2740.         $data      = pack("v",  $fVCenter);
  2741.         $this->_prepend($header . $data);
  2742.     }
  2743.  
  2744.     /**
  2745.     * Store the LEFTMARGIN BIFF record.
  2746.     *
  2747.     * @access private
  2748.     */
  2749.     function _storeMarginLeft()
  2750.     {
  2751.         $record  = 0x0026;                   // Record identifier
  2752.         $length  = 0x0008;                   // Bytes to follow
  2753.  
  2754.         $margin  = $this->_margin_left;       // Margin in inches
  2755.  
  2756.         $header    = pack("vv",  $record, $length);
  2757.         $data      = pack("d",   $margin);
  2758.         if ($this->_byte_order) { // if it's Big Endian
  2759.             $data = strrev($data);
  2760.         }
  2761.  
  2762.         $this->_prepend($header . $data);
  2763.     }
  2764.  
  2765.     /**
  2766.     * Store the RIGHTMARGIN BIFF record.
  2767.     *
  2768.     * @access private
  2769.     */
  2770.     function _storeMarginRight()
  2771.     {
  2772.         $record  = 0x0027;                   // Record identifier
  2773.         $length  = 0x0008;                   // Bytes to follow
  2774.  
  2775.         $margin  = $this->_margin_right;      // Margin in inches
  2776.  
  2777.         $header    = pack("vv",  $record, $length);
  2778.         $data      = pack("d",   $margin);
  2779.         if ($this->_byte_order) { // if it's Big Endian
  2780.             $data = strrev($data);
  2781.         }
  2782.  
  2783.         $this->_prepend($header . $data);
  2784.     }
  2785.  
  2786.     /**
  2787.     * Store the TOPMARGIN BIFF record.
  2788.     *
  2789.     * @access private
  2790.     */
  2791.     function _storeMarginTop()
  2792.     {
  2793.         $record  = 0x0028;                   // Record identifier
  2794.         $length  = 0x0008;                   // Bytes to follow
  2795.  
  2796.         $margin  = $this->_margin_top;        // Margin in inches
  2797.  
  2798.         $header    = pack("vv",  $record, $length);
  2799.         $data      = pack("d",   $margin);
  2800.         if ($this->_byte_order) { // if it's Big Endian
  2801.             $data = strrev($data);
  2802.         }
  2803.  
  2804.         $this->_prepend($header . $data);
  2805.     }
  2806.  
  2807.     /**
  2808.     * Store the BOTTOMMARGIN BIFF record.
  2809.     *
  2810.     * @access private
  2811.     */
  2812.     function _storeMarginBottom()
  2813.     {
  2814.         $record  = 0x0029;                   // Record identifier
  2815.         $length  = 0x0008;                   // Bytes to follow
  2816.  
  2817.         $margin  = $this->_margin_bottom;     // Margin in inches
  2818.  
  2819.         $header    = pack("vv",  $record, $length);
  2820.         $data      = pack("d",   $margin);
  2821.         if ($this->_byte_order) { // if it's Big Endian
  2822.             $data = strrev($data);
  2823.         }
  2824.  
  2825.         $this->_prepend($header . $data);
  2826.     }
  2827.  
  2828.     /**
  2829.     * Merges the area given by its arguments.
  2830.     * This is an Excel97/2000 method. It is required to perform more complicated
  2831.     * merging than the normal setAlign('merge').
  2832.     *
  2833.     * @access public
  2834.     * @param integer $first_row First row of the area to merge
  2835.     * @param integer $first_col First column of the area to merge
  2836.     * @param integer $last_row  Last row of the area to merge
  2837.     * @param integer $last_col  Last column of the area to merge
  2838.     */
  2839.     function mergeCells($first_row, $first_col, $last_row, $last_col)
  2840.     {
  2841.         $record  = 0x00E5;                   // Record identifier
  2842.         $length  = 0x000A;                   // Bytes to follow
  2843.         $cref     = 1;                       // Number of refs
  2844.  
  2845.         // Swap last row/col for first row/col as necessary
  2846.         if ($first_row > $last_row) {
  2847.             list($first_row, $last_row) = array($last_row, $first_row);
  2848.         }
  2849.  
  2850.         if ($first_col > $last_col) {
  2851.             list($first_col, $last_col) = array($last_col, $first_col);
  2852.         }
  2853.  
  2854.         $header   = pack("vv",    $record, $length);
  2855.         $data     = pack("vvvvv", $cref, $first_row, $last_row,
  2856.                                   $first_col, $last_col);
  2857.  
  2858.         $this->_append($header.$data);
  2859.     }
  2860.  
  2861.     /**
  2862.     * Write the PRINTHEADERS BIFF record.
  2863.     *
  2864.     * @access private
  2865.     */
  2866.     function _storePrintHeaders()
  2867.     {
  2868.         $record      = 0x002a;                   // Record identifier
  2869.         $length      = 0x0002;                   // Bytes to follow
  2870.  
  2871.         $fPrintRwCol = $this->_print_headers;     // Boolean flag
  2872.  
  2873.         $header      = pack("vv", $record, $length);
  2874.         $data        = pack("v", $fPrintRwCol);
  2875.         $this->_prepend($header . $data);
  2876.     }
  2877.  
  2878.     /**
  2879.     * Write the PRINTGRIDLINES BIFF record. Must be used in conjunction with the
  2880.     * GRIDSET record.
  2881.     *
  2882.     * @access private
  2883.     */
  2884.     function _storePrintGridlines()
  2885.     {
  2886.         $record      = 0x002b;                    // Record identifier
  2887.         $length      = 0x0002;                    // Bytes to follow
  2888.  
  2889.         $fPrintGrid  = $this->_print_gridlines;    // Boolean flag
  2890.  
  2891.         $header      = pack("vv", $record, $length);
  2892.         $data        = pack("v", $fPrintGrid);
  2893.         $this->_prepend($header . $data);
  2894.     }
  2895.  
  2896.     /**
  2897.     * Write the GRIDSET BIFF record. Must be used in conjunction with the
  2898.     * PRINTGRIDLINES record.
  2899.     *
  2900.     * @access private
  2901.     */
  2902.     function _storeGridset()
  2903.     {
  2904.         $record      = 0x0082;                        // Record identifier
  2905.         $length      = 0x0002;                        // Bytes to follow
  2906.  
  2907.         $fGridSet    = !($this->_print_gridlines);     // Boolean flag
  2908.  
  2909.         $header      = pack("vv",  $record, $length);
  2910.         $data        = pack("v",   $fGridSet);
  2911.         $this->_prepend($header . $data);
  2912.     }
  2913.  
  2914.     /**
  2915.     * Write the GUTS BIFF record. This is used to configure the gutter margins
  2916.     * where Excel outline symbols are displayed. The visibility of the gutters is
  2917.     * controlled by a flag in WSBOOL.
  2918.     *
  2919.     * @see _storeWsbool()
  2920.     * @access private
  2921.     */
  2922.     function _storeGuts()
  2923.     {
  2924.         $record      = 0x0080;   // Record identifier
  2925.         $length      = 0x0008;   // Bytes to follow
  2926.  
  2927.         $dxRwGut     = 0x0000;   // Size of row gutter
  2928.         $dxColGut    = 0x0000;   // Size of col gutter
  2929.  
  2930.         $row_level   = $this->_outline_row_level;
  2931.         $col_level   = 0;
  2932.  
  2933.         // Calculate the maximum column outline level. The equivalent calculation
  2934.         // for the row outline level is carried out in setRow().
  2935.         $colcount = count($this->_colinfo);
  2936.         for ($i = 0; $i < $colcount; $i++) {
  2937.            // Skip cols without outline level info.
  2938.            if (count($col_level) >= 6) {
  2939.               $col_level = max($this->_colinfo[$i][5], $col_level);
  2940.            }
  2941.         }
  2942.  
  2943.         // Set the limits for the outline levels (0 <= x <= 7).
  2944.         $col_level = max(0, min($col_level, 7));
  2945.  
  2946.         // The displayed level is one greater than the max outline levels
  2947.         if ($row_level) {
  2948.             $row_level++;
  2949.         }
  2950.         if ($col_level) {
  2951.             $col_level++;
  2952.         }
  2953.  
  2954.         $header      = pack("vv",   $record, $length);
  2955.         $data        = pack("vvvv", $dxRwGut, $dxColGut, $row_level, $col_level);
  2956.  
  2957.         $this->_prepend($header.$data);
  2958.     }
  2959.  
  2960.  
  2961.     /**
  2962.     * Write the WSBOOL BIFF record, mainly for fit-to-page. Used in conjunction
  2963.     * with the SETUP record.
  2964.     *
  2965.     * @access private
  2966.     */
  2967.     function _storeWsbool()
  2968.     {
  2969.         $record      = 0x0081;   // Record identifier
  2970.         $length      = 0x0002;   // Bytes to follow
  2971.         $grbit       = 0x0000;
  2972.  
  2973.         // The only option that is of interest is the flag for fit to page. So we
  2974.         // set all the options in one go.
  2975.         //
  2976.         /*if ($this->_fit_page) {
  2977.             $grbit = 0x05c1;
  2978.         } else {
  2979.             $grbit = 0x04c1;
  2980.         }*/
  2981.         // Set the option flags
  2982.         $grbit |= 0x0001;                           // Auto page breaks visible
  2983.         if ($this->_outline_style) {
  2984.             $grbit |= 0x0020; // Auto outline styles
  2985.         }
  2986.         if ($this->_outline_below) {
  2987.             $grbit |= 0x0040; // Outline summary below
  2988.         }
  2989.         if ($this->_outline_right) {
  2990.             $grbit |= 0x0080; // Outline summary right
  2991.         }
  2992.         if ($this->_fit_page) {
  2993.             $grbit |= 0x0100; // Page setup fit to page
  2994.         }
  2995.         if ($this->_outline_on) {
  2996.             $grbit |= 0x0400; // Outline symbols displayed
  2997.         }
  2998.  
  2999.         $header      = pack("vv", $record, $length);
  3000.         $data        = pack("v",  $grbit);
  3001.         $this->_prepend($header . $data);
  3002.     }
  3003.  
  3004.     /**
  3005.     * Write the HORIZONTALPAGEBREAKS BIFF record.
  3006.     *
  3007.     * @access private
  3008.     */
  3009.     function _storeHbreak()
  3010.     {
  3011.         // Return if the user hasn't specified pagebreaks
  3012.         if (empty($this->_hbreaks)) {
  3013.             return;
  3014.         }
  3015.  
  3016.         // Sort and filter array of page breaks
  3017.         $breaks = $this->_hbreaks;
  3018.         sort($breaks, SORT_NUMERIC);
  3019.         if ($breaks[0] == 0) { // don't use first break if it's 0
  3020.             array_shift($breaks);
  3021.         }
  3022.  
  3023.         $record  = 0x001b;               // Record identifier
  3024.         $cbrk    = count($breaks);       // Number of page breaks
  3025.         if ($this->_BIFF_version == 0x0600) {
  3026.             $length  = 2 + 6*$cbrk;      // Bytes to follow
  3027.         } else {
  3028.             $length  = 2 + 2*$cbrk;      // Bytes to follow
  3029.         }
  3030.  
  3031.         $header  = pack("vv", $record, $length);
  3032.         $data    = pack("v",  $cbrk);
  3033.  
  3034.         // Append each page break
  3035.         foreach ($breaks as $break) {
  3036.             if ($this->_BIFF_version == 0x0600) {
  3037.                 $data .= pack("vvv", $break, 0x0000, 0x00ff);
  3038.             } else {
  3039.                 $data .= pack("v", $break);
  3040.             }
  3041.         }
  3042.  
  3043.         $this->_prepend($header.$data);
  3044.     }
  3045.  
  3046.  
  3047.     /**
  3048.     * Write the VERTICALPAGEBREAKS BIFF record.
  3049.     *
  3050.     * @access private
  3051.     */
  3052.     function _storeVbreak()
  3053.     {
  3054.         // Return if the user hasn't specified pagebreaks
  3055.         if (empty($this->_vbreaks)) {
  3056.             return;
  3057.         }
  3058.  
  3059.         // 1000 vertical pagebreaks appears to be an internal Excel 5 limit.
  3060.         // It is slightly higher in Excel 97/200, approx. 1026
  3061.         $breaks = array_slice($this->_vbreaks,0,1000);
  3062.  
  3063.         // Sort and filter array of page breaks
  3064.         sort($breaks, SORT_NUMERIC);
  3065.         if ($breaks[0] == 0) { // don't use first break if it's 0
  3066.             array_shift($breaks);
  3067.         }
  3068.  
  3069.         $record  = 0x001a;               // Record identifier
  3070.         $cbrk    = count($breaks);       // Number of page breaks
  3071.         if ($this->_BIFF_version == 0x0600) {
  3072.             $length  = 2 + 6*$cbrk;      // Bytes to follow
  3073.         } else {
  3074.             $length  = 2 + 2*$cbrk;      // Bytes to follow
  3075.         }
  3076.  
  3077.         $header  = pack("vv",  $record, $length);
  3078.         $data    = pack("v",   $cbrk);
  3079.  
  3080.         // Append each page break
  3081.         foreach ($breaks as $break) {
  3082.             if ($this->_BIFF_version == 0x0600) {
  3083.                 $data .= pack("vvv", $break, 0x0000, 0xffff);
  3084.             } else {
  3085.                 $data .= pack("v", $break);
  3086.             }
  3087.         }
  3088.  
  3089.         $this->_prepend($header . $data);
  3090.     }
  3091.  
  3092.     /**
  3093.     * Set the Biff PROTECT record to indicate that the worksheet is protected.
  3094.     *
  3095.     * @access private
  3096.     */
  3097.     function _storeProtect()
  3098.     {
  3099.         // Exit unless sheet protection has been specified
  3100.         if ($this->_protect == 0) {
  3101.             return;
  3102.         }
  3103.  
  3104.         $record      = 0x0012;             // Record identifier
  3105.         $length      = 0x0002;             // Bytes to follow
  3106.  
  3107.         $fLock       = $this->_protect;    // Worksheet is protected
  3108.  
  3109.         $header      = pack("vv", $record, $length);
  3110.         $data        = pack("v",  $fLock);
  3111.  
  3112.         $this->_prepend($header.$data);
  3113.     }
  3114.  
  3115.     /**
  3116.     * Write the worksheet PASSWORD record.
  3117.     *
  3118.     * @access private
  3119.     */
  3120.     function _storePassword()
  3121.     {
  3122.         // Exit unless sheet protection and password have been specified
  3123.         if (($this->_protect == 0) || (!isset($this->_password))) {
  3124.             return;
  3125.         }
  3126.  
  3127.         $record      = 0x0013;               // Record identifier
  3128.         $length      = 0x0002;               // Bytes to follow
  3129.  
  3130.         $wPassword   = $this->_password;     // Encoded password
  3131.  
  3132.         $header      = pack("vv", $record, $length);
  3133.         $data        = pack("v",  $wPassword);
  3134.  
  3135.         $this->_prepend($header . $data);
  3136.     }
  3137.  
  3138.  
  3139.     /**
  3140.     * Insert a 24bit bitmap image in a worksheet.
  3141.     *
  3142.     * @access public
  3143.     * @param integer $row     The row we are going to insert the bitmap into
  3144.     * @param integer $col     The column we are going to insert the bitmap into
  3145.     * @param mixed   $bitmap  The bitmap filename or GD-image resource
  3146.     * @param integer $x       The horizontal position (offset) of the image inside the cell.
  3147.     * @param integer $y       The vertical position (offset) of the image inside the cell.
  3148.     * @param float   $scale_x The horizontal scale
  3149.     * @param float   $scale_y The vertical scale
  3150.     */
  3151.     function insertBitmap($row, $col, $bitmap, $x = 0, $y = 0, $scale_x = 1, $scale_y = 1)
  3152.     {
  3153.         $bitmap_array = (is_resource($bitmap) ? $this->_processBitmapGd($bitmap) : $this->_processBitmap($bitmap));
  3154.         list($width, $height, $size, $data) = $bitmap_array; //$this->_processBitmap($bitmap);
  3155.  
  3156.         // Scale the frame of the image.
  3157.         $width  *= $scale_x;
  3158.         $height *= $scale_y;
  3159.  
  3160.         // Calculate the vertices of the image and write the OBJ record
  3161.         $this->_positionImage($col, $row, $x, $y, $width, $height);
  3162.  
  3163.         // Write the IMDATA record to store the bitmap data
  3164.         $record      = 0x007f;
  3165.         $length      = 8 + $size;
  3166.         $cf          = 0x09;
  3167.         $env         = 0x01;
  3168.         $lcb         = $size;
  3169.  
  3170.         $header      = pack("vvvvV", $record, $length, $cf, $env, $lcb);
  3171.         $this->_append($header.$data);
  3172.     }
  3173.  
  3174.     /**
  3175.     * Calculate the vertices that define the position of the image as required by
  3176.     * the OBJ record.
  3177.     *
  3178.     *         +------------+------------+
  3179.     *         |     A      |      B     |
  3180.     *   +-----+------------+------------+
  3181.     *   |     |(x1,y1)     |            |
  3182.     *   |  1  |(A1)._______|______      |
  3183.     *   |     |    |              |     |
  3184.     *   |     |    |              |     |
  3185.     *   +-----+----|    BITMAP    |-----+
  3186.     *   |     |    |              |     |
  3187.     *   |  2  |    |______________.     |
  3188.     *   |     |            |        (B2)|
  3189.     *   |     |            |     (x2,y2)|
  3190.     *   +---- +------------+------------+
  3191.     *
  3192.     * Example of a bitmap that covers some of the area from cell A1 to cell B2.
  3193.     *
  3194.     * Based on the width and height of the bitmap we need to calculate 8 vars:
  3195.     *     $col_start, $row_start, $col_end, $row_end, $x1, $y1, $x2, $y2.
  3196.     * The width and height of the cells are also variable and have to be taken into
  3197.     * account.
  3198.     * The values of $col_start and $row_start are passed in from the calling
  3199.     * function. The values of $col_end and $row_end are calculated by subtracting
  3200.     * the width and height of the bitmap from the width and height of the
  3201.     * underlying cells.
  3202.     * The vertices are expressed as a percentage of the underlying cell width as
  3203.     * follows (rhs values are in pixels):
  3204.     *
  3205.     *       x1 = X / W *1024
  3206.     *       y1 = Y / H *256
  3207.     *       x2 = (X-1) / W *1024
  3208.     *       y2 = (Y-1) / H *256
  3209.     *
  3210.     *       Where:  X is distance from the left side of the underlying cell
  3211.     *               Y is distance from the top of the underlying cell
  3212.     *               W is the width of the cell
  3213.     *               H is the height of the cell
  3214.     *
  3215.     * @access private
  3216.     * @note  the SDK incorrectly states that the height should be expressed as a
  3217.     *         percentage of 1024.
  3218.     * @param integer $col_start Col containing upper left corner of object
  3219.     * @param integer $row_start Row containing top left corner of object
  3220.     * @param integer $x1        Distance to left side of object
  3221.     * @param integer $y1        Distance to top of object
  3222.     * @param integer $width     Width of image frame
  3223.     * @param integer $height    Height of image frame
  3224.     */
  3225.     function _positionImage($col_start, $row_start, $x1, $y1, $width, $height)
  3226.     {
  3227.         // Initialise end cell to the same as the start cell
  3228.         $col_end    = $col_start;  // Col containing lower right corner of object
  3229.         $row_end    = $row_start;  // Row containing bottom right corner of object
  3230.  
  3231.         // Zero the specified offset if greater than the cell dimensions
  3232.         if ($x1 >= $this->_sizeCol($col_start)) {
  3233.             $x1 = 0;
  3234.         }
  3235.         if ($y1 >= $this->_sizeRow($row_start)) {
  3236.             $y1 = 0;
  3237.         }
  3238.  
  3239.         $width      = $width  + $x1 -1;
  3240.         $height     = $height + $y1 -1;
  3241.  
  3242.         // Subtract the underlying cell widths to find the end cell of the image
  3243.         while ($width >= $this->_sizeCol($col_end)) {
  3244.             $width -= $this->_sizeCol($col_end);
  3245.             $col_end++;
  3246.         }
  3247.  
  3248.         // Subtract the underlying cell heights to find the end cell of the image
  3249.         while ($height >= $this->_sizeRow($row_end)) {
  3250.             $height -= $this->_sizeRow($row_end);
  3251.             $row_end++;
  3252.         }
  3253.  
  3254.         // Bitmap isn't allowed to start or finish in a hidden cell, i.e. a cell
  3255.         // with zero eight or width.
  3256.         //
  3257.         if ($this->_sizeCol($col_start) == 0) {
  3258.             return;
  3259.         }
  3260.         if ($this->_sizeCol($col_end)   == 0) {
  3261.             return;
  3262.         }
  3263.         if ($this->_sizeRow($row_start) == 0) {
  3264.             return;
  3265.         }
  3266.         if ($this->_sizeRow($row_end)   == 0) {
  3267.             return;
  3268.         }
  3269.  
  3270.         // Convert the pixel values to the percentage value expected by Excel
  3271.         $x1 = $x1     / $this->_sizeCol($col_start)   * 1024;
  3272.         $y1 = $y1     / $this->_sizeRow($row_start)   *  256;
  3273.         $x2 = $width  / $this->_sizeCol($col_end)     * 1024; // Distance to right side of object
  3274.         $y2 = $height / $this->_sizeRow($row_end)     *  256; // Distance to bottom of object
  3275.  
  3276.         $this->_storeObjPicture($col_start, $x1,
  3277.                                  $row_start, $y1,
  3278.                                  $col_end, $x2,
  3279.                                  $row_end, $y2);
  3280.     }
  3281.  
  3282.     /**
  3283.     * Convert the width of a cell from user's units to pixels. By interpolation
  3284.     * the relationship is: y = 7x +5. If the width hasn't been set by the user we
  3285.     * use the default value. If the col is hidden we use a value of zero.
  3286.     *
  3287.     * @access private
  3288.     * @param integer $col The column
  3289.     * @return integer The width in pixels
  3290.     */
  3291.     function _sizeCol($col)
  3292.     {
  3293.         // Look up the cell value to see if it has been changed
  3294.         if (isset($this->col_sizes[$col])) {
  3295.             if ($this->col_sizes[$col] == 0) {
  3296.                 return(0);
  3297.             } else {
  3298.                 return(floor(7 * $this->col_sizes[$col] + 5));
  3299.             }
  3300.         } else {
  3301.             return(64);
  3302.         }
  3303.     }
  3304.  
  3305.     /**
  3306.     * Convert the height of a cell from user's units to pixels. By interpolation
  3307.     * the relationship is: y = 4/3x. If the height hasn't been set by the user we
  3308.     * use the default value. If the row is hidden we use a value of zero. (Not
  3309.     * possible to hide row yet).
  3310.     *
  3311.     * @access private
  3312.     * @param integer $row The row
  3313.     * @return integer The width in pixels
  3314.     */
  3315.     function _sizeRow($row)
  3316.     {
  3317.         // Look up the cell value to see if it has been changed
  3318.         if (isset($this->_row_sizes[$row])) {
  3319.             if ($this->_row_sizes[$row] == 0) {
  3320.                 return(0);
  3321.             } else {
  3322.                 return(floor(4/3 * $this->_row_sizes[$row]));
  3323.             }
  3324.         } else {
  3325.             return(17);
  3326.         }
  3327.     }
  3328.  
  3329.     /**
  3330.     * Store the OBJ record that precedes an IMDATA record. This could be generalise
  3331.     * to support other Excel objects.
  3332.     *
  3333.     * @access private
  3334.     * @param integer $colL Column containing upper left corner of object
  3335.     * @param integer $dxL  Distance from left side of cell
  3336.     * @param integer $rwT  Row containing top left corner of object
  3337.     * @param integer $dyT  Distance from top of cell
  3338.     * @param integer $colR Column containing lower right corner of object
  3339.     * @param integer $dxR  Distance from right of cell
  3340.     * @param integer $rwB  Row containing bottom right corner of object
  3341.     * @param integer $dyB  Distance from bottom of cell
  3342.     */
  3343.     function _storeObjPicture($colL,$dxL,$rwT,$dyT,$colR,$dxR,$rwB,$dyB)
  3344.     {
  3345.         $record      = 0x005d;   // Record identifier
  3346.         $length      = 0x003c;   // Bytes to follow
  3347.  
  3348.         $cObj        = 0x0001;   // Count of objects in file (set to 1)
  3349.         $OT          = 0x0008;   // Object type. 8 = Picture
  3350.         $id          = 0x0001;   // Object ID
  3351.         $grbit       = 0x0614;   // Option flags
  3352.  
  3353.         $cbMacro     = 0x0000;   // Length of FMLA structure
  3354.         $Reserved1   = 0x0000;   // Reserved
  3355.         $Reserved2   = 0x0000;   // Reserved
  3356.  
  3357.         $icvBack     = 0x09;     // Background colour
  3358.         $icvFore     = 0x09;     // Foreground colour
  3359.         $fls         = 0x00;     // Fill pattern
  3360.         $fAuto       = 0x00;     // Automatic fill
  3361.         $icv         = 0x08;     // Line colour
  3362.         $lns         = 0xff;     // Line style
  3363.         $lnw         = 0x01;     // Line weight
  3364.         $fAutoB      = 0x00;     // Automatic border
  3365.         $frs         = 0x0000;   // Frame style
  3366.         $cf          = 0x0009;   // Image format, 9 = bitmap
  3367.         $Reserved3   = 0x0000;   // Reserved
  3368.         $cbPictFmla  = 0x0000;   // Length of FMLA structure
  3369.         $Reserved4   = 0x0000;   // Reserved
  3370.         $grbit2      = 0x0001;   // Option flags
  3371.         $Reserved5   = 0x0000;   // Reserved
  3372.  
  3373.  
  3374.         $header      = pack("vv", $record, $length);
  3375.         $data        = pack("V", $cObj);
  3376.         $data       .= pack("v", $OT);
  3377.         $data       .= pack("v", $id);
  3378.         $data       .= pack("v", $grbit);
  3379.         $data       .= pack("v", $colL);
  3380.         $data       .= pack("v", $dxL);
  3381.         $data       .= pack("v", $rwT);
  3382.         $data       .= pack("v", $dyT);
  3383.         $data       .= pack("v", $colR);
  3384.         $data       .= pack("v", $dxR);
  3385.         $data       .= pack("v", $rwB);
  3386.         $data       .= pack("v", $dyB);
  3387.         $data       .= pack("v", $cbMacro);
  3388.         $data       .= pack("V", $Reserved1);
  3389.         $data       .= pack("v", $Reserved2);
  3390.         $data       .= pack("C", $icvBack);
  3391.         $data       .= pack("C", $icvFore);
  3392.         $data       .= pack("C", $fls);
  3393.         $data       .= pack("C", $fAuto);
  3394.         $data       .= pack("C", $icv);
  3395.         $data       .= pack("C", $lns);
  3396.         $data       .= pack("C", $lnw);
  3397.         $data       .= pack("C", $fAutoB);
  3398.         $data       .= pack("v", $frs);
  3399.         $data       .= pack("V", $cf);
  3400.         $data       .= pack("v", $Reserved3);
  3401.         $data       .= pack("v", $cbPictFmla);
  3402.         $data       .= pack("v", $Reserved4);
  3403.         $data       .= pack("v", $grbit2);
  3404.         $data       .= pack("V", $Reserved5);
  3405.  
  3406.         $this->_append($header . $data);
  3407.     }
  3408.  
  3409.     /**
  3410.     * Convert a GD-image into the internal format.
  3411.     *
  3412.     * @access private
  3413.     * @param resource $image The image to process
  3414.     * @return array Array with data and properties of the bitmap
  3415.     */
  3416.     function _processBitmapGd($image) {
  3417.         $width = imagesx($image);
  3418.         $height = imagesy($image);
  3419.  
  3420.         $data = pack("Vvvvv", 0x000c, $width, $height, 0x01, 0x18);
  3421.         for ($j=$height; $j--; ) {
  3422.             for ($i=0; $i < $width; $i++) {
  3423.                 $color = imagecolorsforindex($image, imagecolorat($image, $i, $j));
  3424.                 foreach (array("red", "green", "blue") as $key) {
  3425.                     $color[$key] = $color[$key] + round((255 - $color[$key]) * $color["alpha"] / 127);
  3426.                 }
  3427.                 $data .= chr($color["blue"]) . chr($color["green"]) . chr($color["red"]);
  3428.             }
  3429.             if (3*$width % 4) {
  3430.                 $data .= str_repeat("\x00", 4 - 3*$width % 4);
  3431.             }
  3432.         }
  3433.  
  3434.         return array($width, $height, strlen($data), $data);
  3435.     }
  3436.  
  3437.     /**
  3438.     * Convert a 24 bit bitmap into the modified internal format used by Windows.
  3439.     * This is described in BITMAPCOREHEADER and BITMAPCOREINFO structures in the
  3440.     * MSDN library.
  3441.     *
  3442.     * @access private
  3443.     * @param string $bitmap The bitmap to process
  3444.     * @return array Array with data and properties of the bitmap
  3445.     */
  3446.     function _processBitmap($bitmap)
  3447.     {
  3448.         // Open file.
  3449.         $bmp_fd = @fopen($bitmap,"rb");
  3450.         if (!$bmp_fd) {
  3451.             throw new Exception("Couldn't import $bitmap");
  3452.         }
  3453.  
  3454.         // Slurp the file into a string.
  3455.         $data = fread($bmp_fd, filesize($bitmap));
  3456.  
  3457.         // Check that the file is big enough to be a bitmap.
  3458.         if (strlen($data) <= 0x36) {
  3459.             throw new Exception("$bitmap doesn't contain enough data.\n");
  3460.         }
  3461.  
  3462.         // The first 2 bytes are used to identify the bitmap.
  3463.         $identity = unpack("A2ident", $data);
  3464.         if ($identity['ident'] != "BM") {
  3465.             throw new Exception("$bitmap doesn't appear to be a valid bitmap image.\n");
  3466.         }
  3467.  
  3468.         // Remove bitmap data: ID.
  3469.         $data = substr($data, 2);
  3470.  
  3471.         // Read and remove the bitmap size. This is more reliable than reading
  3472.         // the data size at offset 0x22.
  3473.         //
  3474.         $size_array   = unpack("Vsa", substr($data, 0, 4));
  3475.         $size   = $size_array['sa'];
  3476.         $data   = substr($data, 4);
  3477.         $size  -= 0x36; // Subtract size of bitmap header.
  3478.         $size  += 0x0C; // Add size of BIFF header.
  3479.  
  3480.         // Remove bitmap data: reserved, offset, header length.
  3481.         $data = substr($data, 12);
  3482.  
  3483.         // Read and remove the bitmap width and height. Verify the sizes.
  3484.         $width_and_height = unpack("V2", substr($data, 0, 8));
  3485.         $width  = $width_and_height[1];
  3486.         $height = $width_and_height[2];
  3487.         $data   = substr($data, 8);
  3488.         if ($width > 0xFFFF) {
  3489.             throw new Exception("$bitmap: largest image width supported is 65k.\n");
  3490.         }
  3491.         if ($height > 0xFFFF) {
  3492.             throw new Exception("$bitmap: largest image height supported is 65k.\n");
  3493.         }
  3494.  
  3495.         // Read and remove the bitmap planes and bpp data. Verify them.
  3496.         $planes_and_bitcount = unpack("v2", substr($data, 0, 4));
  3497.         $data = substr($data, 4);
  3498.         if ($planes_and_bitcount[2] != 24) { // Bitcount
  3499.             throw new Exception("$bitmap isn't a 24bit true color bitmap.\n");
  3500.         }
  3501.         if ($planes_and_bitcount[1] != 1) {
  3502.             throw new Exception("$bitmap: only 1 plane supported in bitmap image.\n");
  3503.         }
  3504.  
  3505.         // Read and remove the bitmap compression. Verify compression.
  3506.         $compression = unpack("Vcomp", substr($data, 0, 4));
  3507.         $data = substr($data, 4);
  3508.  
  3509.         //$compression = 0;
  3510.         if ($compression['comp'] != 0) {
  3511.             throw new Exception("$bitmap: compression not supported in bitmap image.\n");
  3512.         }
  3513.  
  3514.         // Remove bitmap data: data size, hres, vres, colours, imp. colours.
  3515.         $data = substr($data, 20);
  3516.  
  3517.         // Add the BITMAPCOREHEADER data
  3518.         $header  = pack("Vvvvv", 0x000c, $width, $height, 0x01, 0x18);
  3519.         $data    = $header . $data;
  3520.  
  3521.         return (array($width, $height, $size, $data));
  3522.     }
  3523.  
  3524.     /**
  3525.     * Store the window zoom factor. This should be a reduced fraction but for
  3526.     * simplicity we will store all fractions with a numerator of 100.
  3527.     *
  3528.     * @access private
  3529.     */
  3530.     function _storeZoom()
  3531.     {
  3532.         // If scale is 100 we don't need to write a record
  3533.         if ($this->_zoom == 100) {
  3534.             return;
  3535.         }
  3536.  
  3537.         $record      = 0x00A0;               // Record identifier
  3538.         $length      = 0x0004;               // Bytes to follow
  3539.  
  3540.         $header      = pack("vv", $record, $length);
  3541.         $data        = pack("vv", $this->_zoom, 100);
  3542.         $this->_append($header . $data);
  3543.     }
  3544.  
  3545.     /**
  3546.     * Store the DVAL and DV records.
  3547.     *
  3548.     * @access private
  3549.     */
  3550.     function _storeDataValidity()
  3551.     {
  3552.         $record      = 0x01b2;      // Record identifier
  3553.         $length      = 0x0012;      // Bytes to follow
  3554.  
  3555.         $grbit       = 0x0002;      // Prompt box at cell, no cached validity data at DV records
  3556.         $horPos      = 0x00000000;  // Horizontal position of prompt box, if fixed position
  3557.         $verPos      = 0x00000000;  // Vertical position of prompt box, if fixed position
  3558.         $objId       = 0xffffffff;  // Object identifier of drop down arrow object, or -1 if not visible
  3559.  
  3560.         $header      = pack('vv', $record, $length);
  3561.         $data        = pack('vVVVV', $grbit, $horPos, $verPos, $objId,
  3562.                                      count($this->_dv));
  3563.         $this->_append($header.$data);
  3564.  
  3565.         $record = 0x01be;              // Record identifier
  3566.         foreach ($this->_dv as $dv) {
  3567.             $length = strlen($dv);      // Bytes to follow
  3568.             $header = pack("vv", $record, $length);
  3569.             $this->_append($header . $dv);
  3570.         }
  3571.     }
  3572. }

Documentation generated on Mon, 25 Aug 2008 13:53:27 +0200 by phpDocumentor 1.4.1