From e18ba38f16c020fd69bb6b01b5ec9e4aaf3f5b4f Mon Sep 17 00:00:00 2001 From: MarkBaker Date: Fri, 15 May 2015 09:11:18 +0100 Subject: [PATCH 1/5] More psr-2 for charts --- Classes/PHPExcel/Chart/Axis.php | 182 ++++++----- Classes/PHPExcel/Chart/DataSeries.php | 90 +++--- Classes/PHPExcel/Chart/DataSeriesValues.php | 86 +++--- Classes/PHPExcel/Chart/GridLines.php | 137 ++++----- Classes/PHPExcel/Chart/Layout.php | 98 +++--- Classes/PHPExcel/Chart/Legend.php | 82 ++--- Classes/PHPExcel/Chart/PlotArea.php | 22 +- Classes/PHPExcel/Chart/Properties.php | 23 +- Classes/PHPExcel/Chart/Renderer/jpgraph.php | 325 ++++++++++---------- Classes/PHPExcel/Chart/Title.php | 36 +-- 10 files changed, 545 insertions(+), 536 deletions(-) diff --git a/Classes/PHPExcel/Chart/Axis.php b/Classes/PHPExcel/Chart/Axis.php index b032bf4b..9aeafc6a 100644 --- a/Classes/PHPExcel/Chart/Axis.php +++ b/Classes/PHPExcel/Chart/Axis.php @@ -14,7 +14,7 @@ class PHPExcel_Chart_Axis extends PHPExcel_Chart_Properties * * @var array of mixed */ - private $_axis_number = array( + private $axisNumber = array( 'format' => self::FORMAT_CODE_GENERAL, 'source_linked' => 1 ); @@ -24,7 +24,7 @@ class PHPExcel_Chart_Axis extends PHPExcel_Chart_Properties * * @var array of mixed */ - private $_axis_options = array( + private $axisOptions = array( 'minimum' => null, 'maximum' => null, 'major_unit' => null, @@ -42,7 +42,7 @@ class PHPExcel_Chart_Axis extends PHPExcel_Chart_Properties * * @var array of mixed */ - private $_fill_properties = array( + private $fillProperties = array( 'type' => self::EXCEL_COLOR_TYPE_ARGB, 'value' => null, 'alpha' => 0 @@ -53,7 +53,7 @@ class PHPExcel_Chart_Axis extends PHPExcel_Chart_Properties * * @var array of mixed */ - private $_line_properties = array( + private $lineProperties = array( 'type' => self::EXCEL_COLOR_TYPE_ARGB, 'value' => null, 'alpha' => 0 @@ -64,7 +64,7 @@ class PHPExcel_Chart_Axis extends PHPExcel_Chart_Properties * * @var array of mixed */ - private $_line_style_properties = array( + private $lineStyleProperties = array( 'width' => '9525', 'compound' => self::LINE_STYLE_COMPOUND_SIMPLE, 'dash' => self::LINE_STYLE_DASH_SOLID, @@ -87,7 +87,7 @@ class PHPExcel_Chart_Axis extends PHPExcel_Chart_Properties * * @var array of mixed */ - private $_shadow_properties = array( + private $shadowProperties = array( 'presets' => self::SHADOW_PRESETS_NOSHADOW, 'effect' => null, 'color' => array( @@ -112,7 +112,7 @@ class PHPExcel_Chart_Axis extends PHPExcel_Chart_Properties * * @var array of mixed */ - private $_glow_properties = array( + private $glowProperties = array( 'size' => null, 'color' => array( 'type' => self::EXCEL_COLOR_TYPE_STANDARD, @@ -126,7 +126,7 @@ class PHPExcel_Chart_Axis extends PHPExcel_Chart_Properties * * @var array of mixed */ - private $_soft_edges = array( + private $softEdges = array( 'size' => null ); @@ -137,8 +137,8 @@ class PHPExcel_Chart_Axis extends PHPExcel_Chart_Properties */ public function setAxisNumberProperties($format_code) { - $this->_axis_number['format'] = (string) $format_code; - $this->_axis_number['source_linked'] = 0; + $this->axisNumber['format'] = (string) $format_code; + $this->axisNumber['source_linked'] = 0; } /** @@ -148,7 +148,7 @@ class PHPExcel_Chart_Axis extends PHPExcel_Chart_Properties */ public function getAxisNumberFormat() { - return $this->_axis_number['format']; + return $this->axisNumber['format']; } /** @@ -158,7 +158,7 @@ class PHPExcel_Chart_Axis extends PHPExcel_Chart_Properties */ public function getAxisNumberSourceLinked() { - return (string) $this->_axis_number['source_linked']; + return (string) $this->axisNumber['source_linked']; } /** @@ -178,17 +178,17 @@ class PHPExcel_Chart_Axis extends PHPExcel_Chart_Properties */ public function setAxisOptionsProperties($axis_labels, $horizontal_crosses_value = null, $horizontal_crosses = null, $axis_orientation = null, $major_tmt = null, $minor_tmt = null, $minimum = null, $maximum = null, $major_unit = null, $minor_unit = null) { - $this->_axis_options['axis_labels'] = (string) $axis_labels; - ($horizontal_crosses_value !== null) ? $this->_axis_options['horizontal_crosses_value'] = (string) $horizontal_crosses_value : null; - ($horizontal_crosses !== null) ? $this->_axis_options['horizontal_crosses'] = (string) $horizontal_crosses : null; - ($axis_orientation !== null) ? $this->_axis_options['orientation'] = (string) $axis_orientation : null; - ($major_tmt !== null) ? $this->_axis_options['major_tick_mark'] = (string) $major_tmt : null; - ($minor_tmt !== null) ? $this->_axis_options['minor_tick_mark'] = (string) $minor_tmt : null; - ($minor_tmt !== null) ? $this->_axis_options['minor_tick_mark'] = (string) $minor_tmt : null; - ($minimum !== null) ? $this->_axis_options['minimum'] = (string) $minimum : null; - ($maximum !== null) ? $this->_axis_options['maximum'] = (string) $maximum : null; - ($major_unit !== null) ? $this->_axis_options['major_unit'] = (string) $major_unit : null; - ($minor_unit !== null) ? $this->_axis_options['minor_unit'] = (string) $minor_unit : null; + $this->axisOptions['axis_labels'] = (string) $axis_labels; + ($horizontal_crosses_value !== null) ? $this->axisOptions['horizontal_crosses_value'] = (string) $horizontal_crosses_value : null; + ($horizontal_crosses !== null) ? $this->axisOptions['horizontal_crosses'] = (string) $horizontal_crosses : null; + ($axis_orientation !== null) ? $this->axisOptions['orientation'] = (string) $axis_orientation : null; + ($major_tmt !== null) ? $this->axisOptions['major_tick_mark'] = (string) $major_tmt : null; + ($minor_tmt !== null) ? $this->axisOptions['minor_tick_mark'] = (string) $minor_tmt : null; + ($minor_tmt !== null) ? $this->axisOptions['minor_tick_mark'] = (string) $minor_tmt : null; + ($minimum !== null) ? $this->axisOptions['minimum'] = (string) $minimum : null; + ($maximum !== null) ? $this->axisOptions['maximum'] = (string) $maximum : null; + ($major_unit !== null) ? $this->axisOptions['major_unit'] = (string) $major_unit : null; + ($minor_unit !== null) ? $this->axisOptions['minor_unit'] = (string) $minor_unit : null; } /** @@ -200,7 +200,7 @@ class PHPExcel_Chart_Axis extends PHPExcel_Chart_Properties */ public function getAxisOptionsProperty($property) { - return $this->_axis_options[$property]; + return $this->axisOptions[$property]; } /** @@ -224,7 +224,7 @@ class PHPExcel_Chart_Axis extends PHPExcel_Chart_Properties */ public function setFillParameters($color, $alpha = 0, $type = self::EXCEL_COLOR_TYPE_ARGB) { - $this->_fill_properties = $this->setColorProperties($color, $alpha, $type); + $this->fillProperties = $this->setColorProperties($color, $alpha, $type); } /** @@ -237,7 +237,7 @@ class PHPExcel_Chart_Axis extends PHPExcel_Chart_Properties */ public function setLineParameters($color, $alpha = 0, $type = self::EXCEL_COLOR_TYPE_ARGB) { - $this->_line_properties = $this->setColorProperties($color, $alpha, $type); + $this->lineProperties = $this->setColorProperties($color, $alpha, $type); } /** @@ -249,7 +249,7 @@ class PHPExcel_Chart_Axis extends PHPExcel_Chart_Properties */ public function getFillProperty($property) { - return $this->_fill_properties[$property]; + return $this->fillProperties[$property]; } /** @@ -261,7 +261,7 @@ class PHPExcel_Chart_Axis extends PHPExcel_Chart_Properties */ public function getLineProperty($property) { - return $this->_line_properties[$property]; + return $this->lineProperties[$property]; } /** @@ -278,16 +278,17 @@ class PHPExcel_Chart_Axis extends PHPExcel_Chart_Properties * @param string $end_arrow_size * */ - public function setLineStyleProperties($line_width = null, $compound_type = null, $dash_type = null, $cap_type = null, $join_type = null, $head_arrow_type = null, $head_arrow_size = null, $end_arrow_type = null, $end_arrow_size = null) { - (!is_null($line_width)) ? $this->_line_style_properties['width'] = $this->getExcelPointsWidth((float) $line_width) : null; - (!is_null($compound_type)) ? $this->_line_style_properties['compound'] = (string) $compound_type : null; - (!is_null($dash_type)) ? $this->_line_style_properties['dash'] = (string) $dash_type : null; - (!is_null($cap_type)) ? $this->_line_style_properties['cap'] = (string) $cap_type : null; - (!is_null($join_type)) ? $this->_line_style_properties['join'] = (string) $join_type : null; - (!is_null($head_arrow_type)) ? $this->_line_style_properties['arrow']['head']['type'] = (string) $head_arrow_type : null; - (!is_null($head_arrow_size)) ? $this->_line_style_properties['arrow']['head']['size'] = (string) $head_arrow_size : null; - (!is_null($end_arrow_type)) ? $this->_line_style_properties['arrow']['end']['type'] = (string) $end_arrow_type : null; - (!is_null($end_arrow_size)) ? $this->_line_style_properties['arrow']['end']['size'] = (string) $end_arrow_size : null; + public function setLineStyleProperties($line_width = null, $compound_type = null, $dash_type = null, $cap_type = null, $join_type = null, $head_arrow_type = null, $head_arrow_size = null, $end_arrow_type = null, $end_arrow_size = null) + { + (!is_null($line_width)) ? $this->lineStyleProperties['width'] = $this->getExcelPointsWidth((float) $line_width) : null; + (!is_null($compound_type)) ? $this->lineStyleProperties['compound'] = (string) $compound_type : null; + (!is_null($dash_type)) ? $this->lineStyleProperties['dash'] = (string) $dash_type : null; + (!is_null($cap_type)) ? $this->lineStyleProperties['cap'] = (string) $cap_type : null; + (!is_null($join_type)) ? $this->lineStyleProperties['join'] = (string) $join_type : null; + (!is_null($head_arrow_type)) ? $this->lineStyleProperties['arrow']['head']['type'] = (string) $head_arrow_type : null; + (!is_null($head_arrow_size)) ? $this->lineStyleProperties['arrow']['head']['size'] = (string) $head_arrow_size : null; + (!is_null($end_arrow_type)) ? $this->lineStyleProperties['arrow']['end']['type'] = (string) $end_arrow_type : null; + (!is_null($end_arrow_size)) ? $this->lineStyleProperties['arrow']['end']['size'] = (string) $end_arrow_size : null; } /** @@ -299,7 +300,7 @@ class PHPExcel_Chart_Axis extends PHPExcel_Chart_Properties */ public function getLineStyleProperty($elements) { - return $this->getArrayElementsValue($this->_line_style_properties, $elements); + return $this->getArrayElementsValue($this->lineStyleProperties, $elements); } /** @@ -311,7 +312,7 @@ class PHPExcel_Chart_Axis extends PHPExcel_Chart_Properties */ public function getLineStyleArrowWidth($arrow) { - return $this->getLineStyleArrowSize($this->_line_style_properties['arrow'][$arrow]['size'], 'w'); + return $this->getLineStyleArrowSize($this->lineStyleProperties['arrow'][$arrow]['size'], 'w'); } /** @@ -323,7 +324,7 @@ class PHPExcel_Chart_Axis extends PHPExcel_Chart_Properties */ public function getLineStyleArrowLength($arrow) { - return $this->getLineStyleArrowSize($this->_line_style_properties['arrow'][$arrow]['size'], 'len'); + return $this->getLineStyleArrowSize($this->lineStyleProperties['arrow'][$arrow]['size'], 'len'); } /** @@ -338,15 +339,17 @@ class PHPExcel_Chart_Axis extends PHPExcel_Chart_Properties * @param float $sh_distance * */ - public function setShadowProperties($sh_presets, $sh_color_value = null, $sh_color_type = null, $sh_color_alpha = null, $sh_blur = null, $sh_angle = null, $sh_distance = null) { - $this->_setShadowPresetsProperties((int) $sh_presets) - ->_setShadowColor( - is_null($sh_color_value) ? $this->_shadow_properties['color']['value'] : $sh_color_value - , is_null($sh_color_alpha) ? (int) $this->_shadow_properties['color']['alpha'] : $sh_color_alpha - , is_null($sh_color_type) ? $this->_shadow_properties['color']['type'] : $sh_color_type) - ->_setShadowBlur($sh_blur) - ->_setShadowAngle($sh_angle) - ->_setShadowDistance($sh_distance); + public function setShadowProperties($sh_presets, $sh_color_value = null, $sh_color_type = null, $sh_color_alpha = null, $sh_blur = null, $sh_angle = null, $sh_distance = null) + { + $this->setShadowPresetsProperties((int) $sh_presets) + ->setShadowColor( + is_null($sh_color_value) ? $this->shadowProperties['color']['value'] : $sh_color_value, + is_null($sh_color_alpha) ? (int) $this->shadowProperties['color']['alpha'] : $sh_color_alpha, + is_null($sh_color_type) ? $this->shadowProperties['color']['type'] : $sh_color_type + ) + ->setShadowBlur($sh_blur) + ->setShadowAngle($sh_angle) + ->setShadowDistance($sh_distance); } /** @@ -356,9 +359,10 @@ class PHPExcel_Chart_Axis extends PHPExcel_Chart_Properties * * @return PHPExcel_Chart_Axis */ - private function _setShadowPresetsProperties($shadow_presets) { - $this->_shadow_properties['presets'] = $shadow_presets; - $this->_setShadowProperiesMapValues($this->getShadowPresetsMap($shadow_presets)); + private function setShadowPresetsProperties($shadow_presets) + { + $this->shadowProperties['presets'] = $shadow_presets; + $this->setShadowProperiesMapValues($this->getShadowPresetsMap($shadow_presets)); return $this; } @@ -371,19 +375,20 @@ class PHPExcel_Chart_Axis extends PHPExcel_Chart_Properties * * @return PHPExcel_Chart_Axis */ - private function _setShadowProperiesMapValues(array $properties_map, &$reference = null) { + private function setShadowProperiesMapValues(array $properties_map, &$reference = null) + { $base_reference = $reference; foreach ($properties_map as $property_key => $property_val) { if (is_array($property_val)) { if ($reference === null) { - $reference = & $this->_shadow_properties[$property_key]; + $reference = & $this->shadowProperties[$property_key]; } else { $reference = & $reference[$property_key]; } - $this->_setShadowProperiesMapValues($property_val, $reference); + $this->setShadowProperiesMapValues($property_val, $reference); } else { if ($base_reference === null) { - $this->_shadow_properties[$property_key] = $property_val; + $this->shadowProperties[$property_key] = $property_val; } else { $reference[$property_key] = $property_val; } @@ -402,8 +407,9 @@ class PHPExcel_Chart_Axis extends PHPExcel_Chart_Properties * * @return PHPExcel_Chart_Axis */ - private function _setShadowColor($color, $alpha, $type) { - $this->_shadow_properties['color'] = $this->setColorProperties($color, $alpha, $type); + private function setShadowColor($color, $alpha, $type) + { + $this->shadowProperties['color'] = $this->setColorProperties($color, $alpha, $type); return $this; } @@ -415,9 +421,10 @@ class PHPExcel_Chart_Axis extends PHPExcel_Chart_Properties * * @return PHPExcel_Chart_Axis */ - private function _setShadowBlur($blur) { + private function setShadowBlur($blur) + { if ($blur !== null) { - $this->_shadow_properties['blur'] = (string) $this->getExcelPointsWidth($blur); + $this->shadowProperties['blur'] = (string) $this->getExcelPointsWidth($blur); } return $this; @@ -430,9 +437,10 @@ class PHPExcel_Chart_Axis extends PHPExcel_Chart_Properties * * @return PHPExcel_Chart_Axis */ - private function _setShadowAngle($angle) { + private function setShadowAngle($angle) + { if ($angle !== null) { - $this->_shadow_properties['direction'] = (string) $this->getExcelPointsAngle($angle); + $this->shadowProperties['direction'] = (string) $this->getExcelPointsAngle($angle); } return $this; @@ -445,9 +453,10 @@ class PHPExcel_Chart_Axis extends PHPExcel_Chart_Properties * * @return PHPExcel_Chart_Axis */ - private function _setShadowDistance($distance) { + private function setShadowDistance($distance) + { if ($distance !== null) { - $this->_shadow_properties['distance'] = (string) $this->getExcelPointsWidth($distance); + $this->shadowProperties['distance'] = (string) $this->getExcelPointsWidth($distance); } return $this; @@ -461,8 +470,9 @@ class PHPExcel_Chart_Axis extends PHPExcel_Chart_Properties * @param int $color_alpha * @param string $color_type */ - public function getShadowProperty($elements) { - return $this->getArrayElementsValue($this->_shadow_properties, $elements); + public function getShadowProperty($elements) + { + return $this->getArrayElementsValue($this->shadowProperties, $elements); } /** @@ -473,12 +483,13 @@ class PHPExcel_Chart_Axis extends PHPExcel_Chart_Properties * @param int $color_alpha * @param string $color_type */ - public function setGlowProperties($size, $color_value = null, $color_alpha = null, $color_type = null) { - $this->_setGlowSize($size) - ->_setGlowColor( - is_null($color_value) ? $this->_glow_properties['color']['value'] : $color_value - , is_null($color_alpha) ? (int) $this->_glow_properties['color']['alpha'] : $color_alpha - , is_null($color_type) ? $this->_glow_properties['color']['type'] : $color_type + public function setGlowProperties($size, $color_value = null, $color_alpha = null, $color_type = null) + { + $this->setGlowSize($size) + ->setGlowColor( + is_null($color_value) ? $this->glowProperties['color']['value'] : $color_value, + is_null($color_alpha) ? (int) $this->glowProperties['color']['alpha'] : $color_alpha, + is_null($color_type) ? $this->glowProperties['color']['type'] : $color_type ); } @@ -489,8 +500,9 @@ class PHPExcel_Chart_Axis extends PHPExcel_Chart_Properties * * @return string */ - public function getGlowProperty($property) { - return $this->getArrayElementsValue($this->_glow_properties, $property); + public function getGlowProperty($property) + { + return $this->getArrayElementsValue($this->glowProperties, $property); } /** @@ -500,9 +512,10 @@ class PHPExcel_Chart_Axis extends PHPExcel_Chart_Properties * * @return PHPExcel_Chart_Axis */ - private function _setGlowSize($size) { + private function setGlowSize($size) + { if (!is_null($size)) { - $this->_glow_properties['size'] = $this->getExcelPointsWidth($size); + $this->glowProperties['size'] = $this->getExcelPointsWidth($size); } return $this; @@ -517,8 +530,9 @@ class PHPExcel_Chart_Axis extends PHPExcel_Chart_Properties * * @return PHPExcel_Chart_Axis */ - private function _setGlowColor($color, $alpha, $type) { - $this->_glow_properties['color'] = $this->setColorProperties($color, $alpha, $type); + private function setGlowColor($color, $alpha, $type) + { + $this->glowProperties['color'] = $this->setColorProperties($color, $alpha, $type); return $this; } @@ -528,9 +542,10 @@ class PHPExcel_Chart_Axis extends PHPExcel_Chart_Properties * * @param float $size */ - public function setSoftEdges($size) { + public function setSoftEdges($size) + { if (!is_null($size)) { - $_soft_edges['size'] = (string) $this->getExcelPointsWidth($size); + $softEdges['size'] = (string) $this->getExcelPointsWidth($size); } } @@ -539,7 +554,8 @@ class PHPExcel_Chart_Axis extends PHPExcel_Chart_Properties * * @return string */ - public function getSoftEdgesSize() { - return $this->_soft_edges['size']; + public function getSoftEdgesSize() + { + return $this->softEdges['size']; } } diff --git a/Classes/PHPExcel/Chart/DataSeries.php b/Classes/PHPExcel/Chart/DataSeries.php index 617c8a91..9ecd543a 100644 --- a/Classes/PHPExcel/Chart/DataSeries.php +++ b/Classes/PHPExcel/Chart/DataSeries.php @@ -75,90 +75,90 @@ class PHPExcel_Chart_DataSeries * * @var string */ - private $_plotType = null; + private $plotType; /** * Plot Grouping Type * * @var boolean */ - private $_plotGrouping = null; + private $plotGrouping; /** * Plot Direction * * @var boolean */ - private $_plotDirection = null; + private $plotDirection; /** * Plot Style * * @var string */ - private $_plotStyle = null; + private $plotStyle; /** * Order of plots in Series * * @var array of integer */ - private $_plotOrder = array(); + private $plotOrder = array(); /** * Plot Label * * @var array of PHPExcel_Chart_DataSeriesValues */ - private $_plotLabel = array(); + private $plotLabel = array(); /** * Plot Category * * @var array of PHPExcel_Chart_DataSeriesValues */ - private $_plotCategory = array(); + private $plotCategory = array(); /** * Smooth Line * * @var string */ - private $_smoothLine = null; + private $smoothLine; /** * Plot Values * * @var array of PHPExcel_Chart_DataSeriesValues */ - private $_plotValues = array(); + private $plotValues = array(); /** * Create a new PHPExcel_Chart_DataSeries */ public function __construct($plotType = null, $plotGrouping = null, $plotOrder = array(), $plotLabel = array(), $plotCategory = array(), $plotValues = array(), $plotDirection = null, $smoothLine = null, $plotStyle = null) { - $this->_plotType = $plotType; - $this->_plotGrouping = $plotGrouping; - $this->_plotOrder = $plotOrder; + $this->plotType = $plotType; + $this->plotGrouping = $plotGrouping; + $this->plotOrder = $plotOrder; $keys = array_keys($plotValues); - $this->_plotValues = $plotValues; + $this->plotValues = $plotValues; if ((count($plotLabel) == 0) || (is_null($plotLabel[$keys[0]]))) { $plotLabel[$keys[0]] = new PHPExcel_Chart_DataSeriesValues(); } - $this->_plotLabel = $plotLabel; + $this->plotLabel = $plotLabel; if ((count($plotCategory) == 0) || (is_null($plotCategory[$keys[0]]))) { $plotCategory[$keys[0]] = new PHPExcel_Chart_DataSeriesValues(); } - $this->_plotCategory = $plotCategory; - $this->_smoothLine = $smoothLine; - $this->_plotStyle = $plotStyle; + $this->plotCategory = $plotCategory; + $this->smoothLine = $smoothLine; + $this->plotStyle = $plotStyle; if (is_null($plotDirection)) { $plotDirection = self::DIRECTION_COL; } - $this->_plotDirection = $plotDirection; + $this->plotDirection = $plotDirection; } /** @@ -168,7 +168,7 @@ class PHPExcel_Chart_DataSeries */ public function getPlotType() { - return $this->_plotType; + return $this->plotType; } /** @@ -179,7 +179,7 @@ class PHPExcel_Chart_DataSeries */ public function setPlotType($plotType = '') { - $this->_plotType = $plotType; + $this->plotType = $plotType; return $this; } @@ -190,7 +190,7 @@ class PHPExcel_Chart_DataSeries */ public function getPlotGrouping() { - return $this->_plotGrouping; + return $this->plotGrouping; } /** @@ -201,7 +201,7 @@ class PHPExcel_Chart_DataSeries */ public function setPlotGrouping($groupingType = null) { - $this->_plotGrouping = $groupingType; + $this->plotGrouping = $groupingType; return $this; } @@ -212,7 +212,7 @@ class PHPExcel_Chart_DataSeries */ public function getPlotDirection() { - return $this->_plotDirection; + return $this->plotDirection; } /** @@ -223,7 +223,7 @@ class PHPExcel_Chart_DataSeries */ public function setPlotDirection($plotDirection = null) { - $this->_plotDirection = $plotDirection; + $this->plotDirection = $plotDirection; return $this; } @@ -234,7 +234,7 @@ class PHPExcel_Chart_DataSeries */ public function getPlotOrder() { - return $this->_plotOrder; + return $this->plotOrder; } /** @@ -244,7 +244,7 @@ class PHPExcel_Chart_DataSeries */ public function getPlotLabels() { - return $this->_plotLabel; + return $this->plotLabel; } /** @@ -254,11 +254,11 @@ class PHPExcel_Chart_DataSeries */ public function getPlotLabelByIndex($index) { - $keys = array_keys($this->_plotLabel); + $keys = array_keys($this->plotLabel); if (in_array($index, $keys)) { - return $this->_plotLabel[$index]; + return $this->plotLabel[$index]; } elseif (isset($keys[$index])) { - return $this->_plotLabel[$keys[$index]]; + return $this->plotLabel[$keys[$index]]; } return false; } @@ -270,7 +270,7 @@ class PHPExcel_Chart_DataSeries */ public function getPlotCategories() { - return $this->_plotCategory; + return $this->plotCategory; } /** @@ -280,11 +280,11 @@ class PHPExcel_Chart_DataSeries */ public function getPlotCategoryByIndex($index) { - $keys = array_keys($this->_plotCategory); + $keys = array_keys($this->plotCategory); if (in_array($index, $keys)) { - return $this->_plotCategory[$index]; + return $this->plotCategory[$index]; } elseif (isset($keys[$index])) { - return $this->_plotCategory[$keys[$index]]; + return $this->plotCategory[$keys[$index]]; } return false; } @@ -296,7 +296,7 @@ class PHPExcel_Chart_DataSeries */ public function getPlotStyle() { - return $this->_plotStyle; + return $this->plotStyle; } /** @@ -307,7 +307,7 @@ class PHPExcel_Chart_DataSeries */ public function setPlotStyle($plotStyle = null) { - $this->_plotStyle = $plotStyle; + $this->plotStyle = $plotStyle; return $this; } @@ -318,7 +318,7 @@ class PHPExcel_Chart_DataSeries */ public function getPlotValues() { - return $this->_plotValues; + return $this->plotValues; } /** @@ -328,11 +328,11 @@ class PHPExcel_Chart_DataSeries */ public function getPlotValuesByIndex($index) { - $keys = array_keys($this->_plotValues); + $keys = array_keys($this->plotValues); if (in_array($index, $keys)) { - return $this->_plotValues[$index]; + return $this->plotValues[$index]; } elseif (isset($keys[$index])) { - return $this->_plotValues[$keys[$index]]; + return $this->plotValues[$keys[$index]]; } return false; } @@ -344,7 +344,7 @@ class PHPExcel_Chart_DataSeries */ public function getPlotSeriesCount() { - return count($this->_plotValues); + return count($this->plotValues); } /** @@ -354,7 +354,7 @@ class PHPExcel_Chart_DataSeries */ public function getSmoothLine() { - return $this->_smoothLine; + return $this->smoothLine; } /** @@ -365,23 +365,23 @@ class PHPExcel_Chart_DataSeries */ public function setSmoothLine($smoothLine = true) { - $this->_smoothLine = $smoothLine; + $this->smoothLine = $smoothLine; return $this; } public function refresh(PHPExcel_Worksheet $worksheet) { - foreach ($this->_plotValues as $plotValues) { + foreach ($this->plotValues as $plotValues) { if ($plotValues !== null) { $plotValues->refresh($worksheet, true); } } - foreach ($this->_plotLabel as $plotValues) { + foreach ($this->plotLabel as $plotValues) { if ($plotValues !== null) { $plotValues->refresh($worksheet, true); } } - foreach ($this->_plotCategory as $plotValues) { + foreach ($this->plotCategory as $plotValues) { if ($plotValues !== null) { $plotValues->refresh($worksheet, false); } diff --git a/Classes/PHPExcel/Chart/DataSeriesValues.php b/Classes/PHPExcel/Chart/DataSeriesValues.php index df88d622..23d185de 100644 --- a/Classes/PHPExcel/Chart/DataSeriesValues.php +++ b/Classes/PHPExcel/Chart/DataSeriesValues.php @@ -31,7 +31,7 @@ class PHPExcel_Chart_DataSeriesValues const DATASERIES_TYPE_STRING = 'String'; const DATASERIES_TYPE_NUMBER = 'Number'; - private static $_dataTypeValues = array( + private static $dataTypeValues = array( self::DATASERIES_TYPE_STRING, self::DATASERIES_TYPE_NUMBER, ); @@ -41,42 +41,42 @@ class PHPExcel_Chart_DataSeriesValues * * @var string */ - private $_dataType = null; + private $dataType; /** * Series Data Source * * @var string */ - private $_dataSource = null; + private $dataSource; /** * Format Code * * @var string */ - private $_formatCode = null; + private $formatCode; /** * Series Point Marker * * @var string */ - private $_marker = null; + private $pointMarker; /** * Point Count (The number of datapoints in the dataseries) * * @var integer */ - private $_pointCount = 0; + private $pointCount = 0; /** * Data Values * * @var array of mixed */ - private $_dataValues = array(); + private $dataValues = array(); /** * Create a new PHPExcel_Chart_DataSeriesValues object @@ -84,11 +84,11 @@ class PHPExcel_Chart_DataSeriesValues public function __construct($dataType = self::DATASERIES_TYPE_NUMBER, $dataSource = null, $formatCode = null, $pointCount = 0, $dataValues = array(), $marker = null) { $this->setDataType($dataType); - $this->_dataSource = $dataSource; - $this->_formatCode = $formatCode; - $this->_pointCount = $pointCount; - $this->_dataValues = $dataValues; - $this->_marker = $marker; + $this->dataSource = $dataSource; + $this->formatCode = $formatCode; + $this->pointCount = $pointCount; + $this->dataValues = $dataValues; + $this->pointMarker = $marker; } /** @@ -98,7 +98,7 @@ class PHPExcel_Chart_DataSeriesValues */ public function getDataType() { - return $this->_dataType; + return $this->dataType; } /** @@ -114,10 +114,10 @@ class PHPExcel_Chart_DataSeriesValues */ public function setDataType($dataType = self::DATASERIES_TYPE_NUMBER) { - if (!in_array($dataType, self::$_dataTypeValues)) { + if (!in_array($dataType, self::$dataTypeValues)) { throw new PHPExcel_Chart_Exception('Invalid datatype for chart data series values'); } - $this->_dataType = $dataType; + $this->dataType = $dataType; return $this; } @@ -129,7 +129,7 @@ class PHPExcel_Chart_DataSeriesValues */ public function getDataSource() { - return $this->_dataSource; + return $this->dataSource; } /** @@ -140,7 +140,7 @@ class PHPExcel_Chart_DataSeriesValues */ public function setDataSource($dataSource = null, $refreshDataValues = true) { - $this->_dataSource = $dataSource; + $this->dataSource = $dataSource; if ($refreshDataValues) { // TO DO @@ -156,7 +156,7 @@ class PHPExcel_Chart_DataSeriesValues */ public function getPointMarker() { - return $this->_marker; + return $this->pointMarker; } /** @@ -167,7 +167,7 @@ class PHPExcel_Chart_DataSeriesValues */ public function setPointMarker($marker = null) { - $this->_marker = $marker; + $this->pointMarker = $marker; return $this; } @@ -179,7 +179,7 @@ class PHPExcel_Chart_DataSeriesValues */ public function getFormatCode() { - return $this->_formatCode; + return $this->formatCode; } /** @@ -190,7 +190,7 @@ class PHPExcel_Chart_DataSeriesValues */ public function setFormatCode($formatCode = null) { - $this->_formatCode = $formatCode; + $this->formatCode = $formatCode; return $this; } @@ -202,7 +202,7 @@ class PHPExcel_Chart_DataSeriesValues */ public function getPointCount() { - return $this->_pointCount; + return $this->pointCount; } /** @@ -212,8 +212,8 @@ class PHPExcel_Chart_DataSeriesValues */ public function isMultiLevelSeries() { - if (count($this->_dataValues) > 0) { - return is_array($this->_dataValues[0]); + if (count($this->dataValues) > 0) { + return is_array($this->dataValues[0]); } return null; } @@ -226,8 +226,8 @@ class PHPExcel_Chart_DataSeriesValues public function multiLevelCount() { $levelCount = 0; - foreach ($this->_dataValues as $dataValueSet) { - $levelCount = max($levelCount,count($dataValueSet)); + foreach ($this->dataValues as $dataValueSet) { + $levelCount = max($levelCount, count($dataValueSet)); } return $levelCount; } @@ -239,7 +239,7 @@ class PHPExcel_Chart_DataSeriesValues */ public function getDataValues() { - return $this->_dataValues; + return $this->dataValues; } /** @@ -249,13 +249,13 @@ class PHPExcel_Chart_DataSeriesValues */ public function getDataValue() { - $count = count($this->_dataValues); + $count = count($this->dataValues); if ($count == 0) { return null; } elseif ($count == 1) { - return $this->_dataValues[0]; + return $this->dataValues[0]; } - return $this->_dataValues; + return $this->dataValues; } /** @@ -263,14 +263,14 @@ class PHPExcel_Chart_DataSeriesValues * * @param array $dataValues * @param boolean $refreshDataSource - * TRUE - refresh the value of _dataSource based on the values of $dataValues - * FALSE - don't change the value of _dataSource + * TRUE - refresh the value of dataSource based on the values of $dataValues + * FALSE - don't change the value of dataSource * @return PHPExcel_Chart_DataSeriesValues */ public function setDataValues($dataValues = array(), $refreshDataSource = true) { - $this->_dataValues = PHPExcel_Calculation_Functions::flattenArray($dataValues); - $this->_pointCount = count($dataValues); + $this->dataValues = PHPExcel_Calculation_Functions::flattenArray($dataValues); + $this->pointCount = count($dataValues); if ($refreshDataSource) { // TO DO @@ -279,39 +279,39 @@ class PHPExcel_Chart_DataSeriesValues return $this; } - private function _stripNulls($var) + private function stripNulls($var) { return $var !== null; } public function refresh(PHPExcel_Worksheet $worksheet, $flatten = true) { - if ($this->_dataSource !== null) { + if ($this->dataSource !== null) { $calcEngine = PHPExcel_Calculation::getInstance($worksheet->getParent()); $newDataValues = PHPExcel_Calculation::_unwrapResult( $calcEngine->_calculateFormulaValue( - '='.$this->_dataSource, + '='.$this->dataSource, null, $worksheet->getCell('A1') ) ); if ($flatten) { - $this->_dataValues = PHPExcel_Calculation_Functions::flattenArray($newDataValues); - foreach ($this->_dataValues as &$dataValue) { + $this->dataValues = PHPExcel_Calculation_Functions::flattenArray($newDataValues); + foreach ($this->dataValues as &$dataValue) { if ((!empty($dataValue)) && ($dataValue[0] == '#')) { $dataValue = 0.0; } } unset($dataValue); } else { - $cellRange = explode('!', $this->_dataSource); + $cellRange = explode('!', $this->dataSource); if (count($cellRange) > 1) { list(, $cellRange) = $cellRange; } $dimensions = PHPExcel_Cell::rangeDimension(str_replace('$', '', $cellRange)); if (($dimensions[0] == 1) || ($dimensions[1] == 1)) { - $this->_dataValues = PHPExcel_Calculation_Functions::flattenArray($newDataValues); + $this->dataValues = PHPExcel_Calculation_Functions::flattenArray($newDataValues); } else { $newArray = array_values(array_shift($newDataValues)); foreach ($newArray as $i => $newDataSet) { @@ -324,10 +324,10 @@ class PHPExcel_Chart_DataSeriesValues array_unshift($newArray[$i++], $newDataVal); } } - $this->_dataValues = $newArray; + $this->dataValues = $newArray; } } - $this->_pointCount = count($this->_dataValues); + $this->pointCount = count($this->dataValues); } } } diff --git a/Classes/PHPExcel/Chart/GridLines.php b/Classes/PHPExcel/Chart/GridLines.php index 69d8ed54..898012eb 100644 --- a/Classes/PHPExcel/Chart/GridLines.php +++ b/Classes/PHPExcel/Chart/GridLines.php @@ -20,9 +20,9 @@ class PHPExcel_Chart_GridLines extends PHPExcel_Chart_Properties * */ - private $_object_state = false; + private $objectState = false; - private $_line_properties = array( + private $lineProperties = array( 'color' => array( 'type' => self::EXCEL_COLOR_TYPE_STANDARD, 'value' => null, @@ -47,7 +47,7 @@ class PHPExcel_Chart_GridLines extends PHPExcel_Chart_Properties ) ); - private $_shadow_properties = array( + private $shadowProperties = array( 'presets' => self::SHADOW_PRESETS_NOSHADOW, 'effect' => null, 'color' => array( @@ -67,7 +67,7 @@ class PHPExcel_Chart_GridLines extends PHPExcel_Chart_Properties 'rotWithShape' => null ); - private $_glow_properties = array( + private $glowProperties = array( 'size' => null, 'color' => array( 'type' => self::EXCEL_COLOR_TYPE_STANDARD, @@ -76,7 +76,7 @@ class PHPExcel_Chart_GridLines extends PHPExcel_Chart_Properties ) ); - private $_soft_edges = array( + private $softEdges = array( 'size' => null ); @@ -88,7 +88,7 @@ class PHPExcel_Chart_GridLines extends PHPExcel_Chart_Properties public function getObjectState() { - return $this->_object_state; + return $this->objectState; } /** @@ -97,9 +97,9 @@ class PHPExcel_Chart_GridLines extends PHPExcel_Chart_Properties * @return PHPExcel_Chart_GridLines */ - private function _activateObject() + private function activateObject() { - $this->_object_state = true; + $this->objectState = true; return $this; } @@ -114,12 +114,12 @@ class PHPExcel_Chart_GridLines extends PHPExcel_Chart_Properties public function setLineColorProperties($value, $alpha = 0, $type = self::EXCEL_COLOR_TYPE_STANDARD) { - $this - ->_activateObject() - ->_line_properties['color'] = $this->setColorProperties( + $this->activateObject() + ->lineProperties['color'] = $this->setColorProperties( $value, $alpha, - $type); + $type + ); } /** @@ -138,33 +138,33 @@ class PHPExcel_Chart_GridLines extends PHPExcel_Chart_Properties public function setLineStyleProperties($line_width = null, $compound_type = null, $dash_type = null, $cap_type = null, $join_type = null, $head_arrow_type = null, $head_arrow_size = null, $end_arrow_type = null, $end_arrow_size = null) { - $this->_activateObject(); + $this->activateObject(); (!is_null($line_width)) - ? $this->_line_properties['style']['width'] = $this->getExcelPointsWidth((float) $line_width) + ? $this->lineProperties['style']['width'] = $this->getExcelPointsWidth((float) $line_width) : null; (!is_null($compound_type)) - ? $this->_line_properties['style']['compound'] = (string) $compound_type + ? $this->lineProperties['style']['compound'] = (string) $compound_type : null; (!is_null($dash_type)) - ? $this->_line_properties['style']['dash'] = (string) $dash_type + ? $this->lineProperties['style']['dash'] = (string) $dash_type : null; (!is_null($cap_type)) - ? $this->_line_properties['style']['cap'] = (string) $cap_type + ? $this->lineProperties['style']['cap'] = (string) $cap_type : null; (!is_null($join_type)) - ? $this->_line_properties['style']['join'] = (string) $join_type + ? $this->lineProperties['style']['join'] = (string) $join_type : null; (!is_null($head_arrow_type)) - ? $this->_line_properties['style']['arrow']['head']['type'] = (string) $head_arrow_type + ? $this->lineProperties['style']['arrow']['head']['type'] = (string) $head_arrow_type : null; (!is_null($head_arrow_size)) - ? $this->_line_properties['style']['arrow']['head']['size'] = (string) $head_arrow_size + ? $this->lineProperties['style']['arrow']['head']['size'] = (string) $head_arrow_size : null; (!is_null($end_arrow_type)) - ? $this->_line_properties['style']['arrow']['end']['type'] = (string) $end_arrow_type + ? $this->lineProperties['style']['arrow']['end']['type'] = (string) $end_arrow_type : null; (!is_null($end_arrow_size)) - ? $this->_line_properties['style']['arrow']['end']['size'] = (string) $end_arrow_size + ? $this->lineProperties['style']['arrow']['end']['size'] = (string) $end_arrow_size : null; } @@ -178,7 +178,7 @@ class PHPExcel_Chart_GridLines extends PHPExcel_Chart_Properties public function getLineColorProperty($parameter) { - return $this->_line_properties['color'][$parameter]; + return $this->lineProperties['color'][$parameter]; } /** @@ -191,7 +191,7 @@ class PHPExcel_Chart_GridLines extends PHPExcel_Chart_Properties public function getLineStyleProperty($elements) { - return $this->getArrayElementsValue($this->_line_properties['style'], $elements); + return $this->getArrayElementsValue($this->lineProperties['style'], $elements); } /** @@ -207,9 +207,9 @@ class PHPExcel_Chart_GridLines extends PHPExcel_Chart_Properties public function setGlowProperties($size, $color_value = null, $color_alpha = null, $color_type = null) { $this - ->_activateObject() - ->_setGlowSize($size) - ->_setGlowColor($color_value, $color_alpha, $color_type); + ->activateObject() + ->setGlowSize($size) + ->setGlowColor($color_value, $color_alpha, $color_type); } /** @@ -222,7 +222,7 @@ class PHPExcel_Chart_GridLines extends PHPExcel_Chart_Properties public function getGlowColor($property) { - return $this->_glow_properties['color'][$property]; + return $this->glowProperties['color'][$property]; } /** @@ -233,7 +233,7 @@ class PHPExcel_Chart_GridLines extends PHPExcel_Chart_Properties public function getGlowSize() { - return $this->_glow_properties['size']; + return $this->glowProperties['size']; } /** @@ -244,9 +244,9 @@ class PHPExcel_Chart_GridLines extends PHPExcel_Chart_Properties * @return PHPExcel_Chart_GridLines */ - private function _setGlowSize($size) + private function setGlowSize($size) { - $this->_glow_properties['size'] = $this->getExcelPointsWidth((float) $size); + $this->glowProperties['size'] = $this->getExcelPointsWidth((float) $size); return $this; } @@ -261,16 +261,16 @@ class PHPExcel_Chart_GridLines extends PHPExcel_Chart_Properties * @return PHPExcel_Chart_GridLines */ - private function _setGlowColor($color, $alpha, $type) + private function setGlowColor($color, $alpha, $type) { if (!is_null($color)) { - $this->_glow_properties['color']['value'] = (string) $color; + $this->glowProperties['color']['value'] = (string) $color; } if (!is_null($alpha)) { - $this->_glow_properties['color']['alpha'] = $this->getTrueAlpha((int) $alpha); + $this->glowProperties['color']['alpha'] = $this->getTrueAlpha((int) $alpha); } if (!is_null($type)) { - $this->_glow_properties['color']['type'] = (string) $type; + $this->glowProperties['color']['type'] = (string) $type; } return $this; @@ -287,7 +287,7 @@ class PHPExcel_Chart_GridLines extends PHPExcel_Chart_Properties public function getLineStyleArrowParameters($arrow_selector, $property_selector) { - return $this->getLineStyleArrowSize($this->_line_properties['style']['arrow'][$arrow_selector]['size'], $property_selector); + return $this->getLineStyleArrowSize($this->lineProperties['style']['arrow'][$arrow_selector]['size'], $property_selector); } /** @@ -305,17 +305,16 @@ class PHPExcel_Chart_GridLines extends PHPExcel_Chart_Properties public function setShadowProperties($sh_presets, $sh_color_value = null, $sh_color_type = null, $sh_color_alpha = null, $sh_blur = null, $sh_angle = null, $sh_distance = null) { - $this - ->_activateObject() - ->_setShadowPresetsProperties((int) $sh_presets) - ->_setShadowColor( - is_null($sh_color_value) ? $this->_shadow_properties['color']['value'] : $sh_color_value - , is_null($sh_color_alpha) ? (int) $this->_shadow_properties['color']['alpha'] - : $this->getTrueAlpha($sh_color_alpha) - , is_null($sh_color_type) ? $this->_shadow_properties['color']['type'] : $sh_color_type) - ->_setShadowBlur($sh_blur) - ->_setShadowAngle($sh_angle) - ->_setShadowDistance($sh_distance); + $this->activateObject() + ->setShadowPresetsProperties((int) $sh_presets) + ->setShadowColor( + is_null($sh_color_value) ? $this->shadowProperties['color']['value'] : $sh_color_value, + is_null($sh_color_alpha) ? (int) $this->shadowProperties['color']['alpha'] : $this->getTrueAlpha($sh_color_alpha), + is_null($sh_color_type) ? $this->shadowProperties['color']['type'] : $sh_color_type + ) + ->setShadowBlur($sh_blur) + ->setShadowAngle($sh_angle) + ->setShadowDistance($sh_distance); } /** @@ -326,10 +325,10 @@ class PHPExcel_Chart_GridLines extends PHPExcel_Chart_Properties * @return PHPExcel_Chart_GridLines */ - private function _setShadowPresetsProperties($shadow_presets) + private function setShadowPresetsProperties($shadow_presets) { - $this->_shadow_properties['presets'] = $shadow_presets; - $this->_setShadowProperiesMapValues($this->getShadowPresetsMap($shadow_presets)); + $this->shadowProperties['presets'] = $shadow_presets; + $this->setShadowProperiesMapValues($this->getShadowPresetsMap($shadow_presets)); return $this; } @@ -343,20 +342,20 @@ class PHPExcel_Chart_GridLines extends PHPExcel_Chart_Properties * @return PHPExcel_Chart_GridLines */ - private function _setShadowProperiesMapValues(array $properties_map, &$reference = null) + private function setShadowProperiesMapValues(array $properties_map, &$reference = null) { $base_reference = $reference; foreach ($properties_map as $property_key => $property_val) { if (is_array($property_val)) { if ($reference === null) { - $reference = & $this->_shadow_properties[$property_key]; + $reference = & $this->shadowProperties[$property_key]; } else { $reference = & $reference[$property_key]; } - $this->_setShadowProperiesMapValues($property_val, $reference); + $this->setShadowProperiesMapValues($property_val, $reference); } else { if ($base_reference === null) { - $this->_shadow_properties[$property_key] = $property_val; + $this->shadowProperties[$property_key] = $property_val; } else { $reference[$property_key] = $property_val; } @@ -374,16 +373,16 @@ class PHPExcel_Chart_GridLines extends PHPExcel_Chart_Properties * @param string $type * @return PHPExcel_Chart_GridLines */ - private function _setShadowColor($color, $alpha, $type) + private function setShadowColor($color, $alpha, $type) { if (!is_null($color)) { - $this->_shadow_properties['color']['value'] = (string) $color; + $this->shadowProperties['color']['value'] = (string) $color; } if (!is_null($alpha)) { - $this->_shadow_properties['color']['alpha'] = $this->getTrueAlpha((int) $alpha); + $this->shadowProperties['color']['alpha'] = $this->getTrueAlpha((int) $alpha); } if (!is_null($type)) { - $this->_shadow_properties['color']['type'] = (string) $type; + $this->shadowProperties['color']['type'] = (string) $type; } return $this; @@ -396,10 +395,10 @@ class PHPExcel_Chart_GridLines extends PHPExcel_Chart_Properties * * @return PHPExcel_Chart_GridLines */ - private function _setShadowBlur($blur) + private function setShadowBlur($blur) { if ($blur !== null) { - $this->_shadow_properties['blur'] = (string) $this->getExcelPointsWidth($blur); + $this->shadowProperties['blur'] = (string) $this->getExcelPointsWidth($blur); } return $this; @@ -412,10 +411,10 @@ class PHPExcel_Chart_GridLines extends PHPExcel_Chart_Properties * @return PHPExcel_Chart_GridLines */ - private function _setShadowAngle($angle) + private function setShadowAngle($angle) { if ($angle !== null) { - $this->_shadow_properties['direction'] = (string) $this->getExcelPointsAngle($angle); + $this->shadowProperties['direction'] = (string) $this->getExcelPointsAngle($angle); } return $this; @@ -427,10 +426,10 @@ class PHPExcel_Chart_GridLines extends PHPExcel_Chart_Properties * @param float $distance * @return PHPExcel_Chart_GridLines */ - private function _setShadowDistance($distance) + private function setShadowDistance($distance) { if ($distance !== null) { - $this->_shadow_properties['distance'] = (string) $this->getExcelPointsWidth($distance); + $this->shadowProperties['distance'] = (string) $this->getExcelPointsWidth($distance); } return $this; @@ -445,7 +444,7 @@ class PHPExcel_Chart_GridLines extends PHPExcel_Chart_Properties */ public function getShadowProperty($elements) { - return $this->getArrayElementsValue($this->_shadow_properties, $elements); + return $this->getArrayElementsValue($this->shadowProperties, $elements); } /** @@ -456,8 +455,8 @@ class PHPExcel_Chart_GridLines extends PHPExcel_Chart_Properties public function setSoftEdgesSize($size) { if (!is_null($size)) { - $this->_activateObject(); - $_soft_edges['size'] = (string) $this->getExcelPointsWidth($size); + $this->activateObject(); + $softEdges['size'] = (string) $this->getExcelPointsWidth($size); } } @@ -468,6 +467,6 @@ class PHPExcel_Chart_GridLines extends PHPExcel_Chart_Properties */ public function getSoftEdgesSize() { - return $this->_soft_edges['size']; + return $this->softEdges['size']; } -} \ No newline at end of file +} diff --git a/Classes/PHPExcel/Chart/Layout.php b/Classes/PHPExcel/Chart/Layout.php index 53a447c9..7fef0741 100644 --- a/Classes/PHPExcel/Chart/Layout.php +++ b/Classes/PHPExcel/Chart/Layout.php @@ -40,49 +40,49 @@ class PHPExcel_Chart_Layout * * @var string */ - private $_layoutTarget = null; + private $layoutTarget; /** * X Mode * * @var string */ - private $_xMode = null; + private $xMode; /** * Y Mode * * @var string */ - private $_yMode = null; + private $yMode; /** * X-Position * * @var float */ - private $_xPos = null; + private $xPos; /** * Y-Position * * @var float */ - private $_yPos = null; + private $yPos; /** * width * * @var float */ - private $_width = null; + private $width; /** * height * * @var float */ - private $_height = null; + private $height; /** * show legend key @@ -90,7 +90,7 @@ class PHPExcel_Chart_Layout * * @var boolean */ - private $_showLegendKey = null; + private $showLegendKey; /** * show value @@ -98,7 +98,7 @@ class PHPExcel_Chart_Layout * * @var boolean */ - private $_showVal = null; + private $showVal; /** * show category name @@ -106,7 +106,7 @@ class PHPExcel_Chart_Layout * * @var boolean */ - private $_showCatName = null; + private $showCatName; /** * show data series name @@ -114,7 +114,7 @@ class PHPExcel_Chart_Layout * * @var boolean */ - private $_showSerName = null; + private $showSerName; /** * show percentage @@ -122,14 +122,14 @@ class PHPExcel_Chart_Layout * * @var boolean */ - private $_showPercent = null; + private $showPercent; /** * show bubble size * * @var boolean */ - private $_showBubbleSize = null; + private $showBubbleSize; /** * show leader lines @@ -137,7 +137,7 @@ class PHPExcel_Chart_Layout * * @var boolean */ - private $_showLeaderLines = null; + private $showLeaderLines; /** @@ -146,25 +146,25 @@ class PHPExcel_Chart_Layout public function __construct($layout = array()) { if (isset($layout['layoutTarget'])) { - $this->_layoutTarget = $layout['layoutTarget']; + $this->layoutTarget = $layout['layoutTarget']; } if (isset($layout['xMode'])) { - $this->_xMode = $layout['xMode']; + $this->xMode = $layout['xMode']; } if (isset($layout['yMode'])) { - $this->_yMode = $layout['yMode']; + $this->yMode = $layout['yMode']; } if (isset($layout['x'])) { - $this->_xPos = (float) $layout['x']; + $this->xPos = (float) $layout['x']; } if (isset($layout['y'])) { - $this->_yPos = (float) $layout['y']; + $this->yPos = (float) $layout['y']; } if (isset($layout['w'])) { - $this->_width = (float) $layout['w']; + $this->width = (float) $layout['w']; } if (isset($layout['h'])) { - $this->_height = (float) $layout['h']; + $this->height = (float) $layout['h']; } } @@ -175,7 +175,7 @@ class PHPExcel_Chart_Layout */ public function getLayoutTarget() { - return $this->_layoutTarget; + return $this->layoutTarget; } /** @@ -186,7 +186,7 @@ class PHPExcel_Chart_Layout */ public function setLayoutTarget($value) { - $this->_layoutTarget = $value; + $this->layoutTarget = $value; return $this; } @@ -197,7 +197,7 @@ class PHPExcel_Chart_Layout */ public function getXMode() { - return $this->_xMode; + return $this->xMode; } /** @@ -208,7 +208,7 @@ class PHPExcel_Chart_Layout */ public function setXMode($value) { - $this->_xMode = $value; + $this->xMode = $value; return $this; } @@ -219,7 +219,7 @@ class PHPExcel_Chart_Layout */ public function getYMode() { - return $this->_yMode; + return $this->yMode; } /** @@ -230,7 +230,7 @@ class PHPExcel_Chart_Layout */ public function setYMode($value) { - $this->_yMode = $value; + $this->yMode = $value; return $this; } @@ -241,7 +241,7 @@ class PHPExcel_Chart_Layout */ public function getXPosition() { - return $this->_xPos; + return $this->xPos; } /** @@ -252,7 +252,7 @@ class PHPExcel_Chart_Layout */ public function setXPosition($value) { - $this->_xPos = $value; + $this->xPos = $value; return $this; } @@ -263,7 +263,7 @@ class PHPExcel_Chart_Layout */ public function getYPosition() { - return $this->_yPos; + return $this->yPos; } /** @@ -274,7 +274,7 @@ class PHPExcel_Chart_Layout */ public function setYPosition($value) { - $this->_yPos = $value; + $this->yPos = $value; return $this; } @@ -285,7 +285,7 @@ class PHPExcel_Chart_Layout */ public function getWidth() { - return $this->_width; + return $this->width; } /** @@ -296,7 +296,7 @@ class PHPExcel_Chart_Layout */ public function setWidth($value) { - $this->_width = $value; + $this->width = $value; return $this; } @@ -307,7 +307,7 @@ class PHPExcel_Chart_Layout */ public function getHeight() { - return $this->_height; + return $this->height; } /** @@ -318,7 +318,7 @@ class PHPExcel_Chart_Layout */ public function setHeight($value) { - $this->_height = $value; + $this->height = $value; return $this; } @@ -330,7 +330,7 @@ class PHPExcel_Chart_Layout */ public function getShowLegendKey() { - return $this->_showLegendKey; + return $this->showLegendKey; } /** @@ -342,7 +342,7 @@ class PHPExcel_Chart_Layout */ public function setShowLegendKey($value) { - $this->_showLegendKey = $value; + $this->showLegendKey = $value; return $this; } @@ -353,7 +353,7 @@ class PHPExcel_Chart_Layout */ public function getShowVal() { - return $this->_showVal; + return $this->showVal; } /** @@ -365,7 +365,7 @@ class PHPExcel_Chart_Layout */ public function setShowVal($value) { - $this->_showVal = $value; + $this->showVal = $value; return $this; } @@ -376,7 +376,7 @@ class PHPExcel_Chart_Layout */ public function getShowCatName() { - return $this->_showCatName; + return $this->showCatName; } /** @@ -388,7 +388,7 @@ class PHPExcel_Chart_Layout */ public function setShowCatName($value) { - $this->_showCatName = $value; + $this->showCatName = $value; return $this; } @@ -399,7 +399,7 @@ class PHPExcel_Chart_Layout */ public function getShowSerName() { - return $this->_showSerName; + return $this->showSerName; } /** @@ -411,7 +411,7 @@ class PHPExcel_Chart_Layout */ public function setShowSerName($value) { - $this->_showSerName = $value; + $this->showSerName = $value; return $this; } @@ -422,7 +422,7 @@ class PHPExcel_Chart_Layout */ public function getShowPercent() { - return $this->_showPercent; + return $this->showPercent; } /** @@ -434,7 +434,7 @@ class PHPExcel_Chart_Layout */ public function setShowPercent($value) { - $this->_showPercent = $value; + $this->showPercent = $value; return $this; } @@ -445,7 +445,7 @@ class PHPExcel_Chart_Layout */ public function getShowBubbleSize() { - return $this->_showBubbleSize; + return $this->showBubbleSize; } /** @@ -457,7 +457,7 @@ class PHPExcel_Chart_Layout */ public function setShowBubbleSize($value) { - $this->_showBubbleSize = $value; + $this->showBubbleSize = $value; return $this; } @@ -468,7 +468,7 @@ class PHPExcel_Chart_Layout */ public function getShowLeaderLines() { - return $this->_showLeaderLines; + return $this->showLeaderLines; } /** @@ -480,7 +480,7 @@ class PHPExcel_Chart_Layout */ public function setShowLeaderLines($value) { - $this->_showLeaderLines = $value; + $this->showLeaderLines = $value; return $this; } } diff --git a/Classes/PHPExcel/Chart/Legend.php b/Classes/PHPExcel/Chart/Legend.php index c44003bd..60f47c80 100644 --- a/Classes/PHPExcel/Chart/Legend.php +++ b/Classes/PHPExcel/Chart/Legend.php @@ -28,26 +28,26 @@ class PHPExcel_Chart_Legend { /** Legend positions */ - const xlLegendPositionBottom = -4107; // Below the chart. - const xlLegendPositionCorner = 2; // In the upper right-hand corner of the chart border. - const xlLegendPositionCustom = -4161; // A custom position. - const xlLegendPositionLeft = -4131; // Left of the chart. - const xlLegendPositionRight = -4152; // Right of the chart. - const xlLegendPositionTop = -4160; // Above the chart. + const xlLegendPositionBottom = -4107; // Below the chart. + const xlLegendPositionCorner = 2; // In the upper right-hand corner of the chart border. + const xlLegendPositionCustom = -4161; // A custom position. + const xlLegendPositionLeft = -4131; // Left of the chart. + const xlLegendPositionRight = -4152; // Right of the chart. + const xlLegendPositionTop = -4160; // Above the chart. const POSITION_RIGHT = 'r'; - const POSITION_LEFT = 'l'; - const POSITION_BOTTOM = 'b'; - const POSITION_TOP = 't'; - const POSITION_TOPRIGHT = 'tr'; + const POSITION_LEFT = 'l'; + const POSITION_BOTTOM = 'b'; + const POSITION_TOP = 't'; + const POSITION_TOPRIGHT = 'tr'; private static $_positionXLref = array( - self::xlLegendPositionBottom => self::POSITION_BOTTOM, - self::xlLegendPositionCorner => self::POSITION_TOPRIGHT, - self::xlLegendPositionCustom => '??', - self::xlLegendPositionLeft => self::POSITION_LEFT, - self::xlLegendPositionRight => self::POSITION_RIGHT, - self::xlLegendPositionTop => self::POSITION_TOP + self::xlLegendPositionBottom => self::POSITION_BOTTOM, + self::xlLegendPositionCorner => self::POSITION_TOPRIGHT, + self::xlLegendPositionCustom => '??', + self::xlLegendPositionLeft => self::POSITION_LEFT, + self::xlLegendPositionRight => self::POSITION_RIGHT, + self::xlLegendPositionTop => self::POSITION_TOP ); /** @@ -55,30 +55,30 @@ class PHPExcel_Chart_Legend * * @var string */ - private $_position = self::POSITION_RIGHT; + private $position = self::POSITION_RIGHT; /** * Allow overlay of other elements? * * @var boolean */ - private $_overlay = TRUE; + private $overlay = true; /** * Legend Layout * * @var PHPExcel_Chart_Layout */ - private $_layout = NULL; + private $layout = null; /** * Create a new PHPExcel_Chart_Legend */ - public function __construct($position = self::POSITION_RIGHT, PHPExcel_Chart_Layout $layout = NULL, $overlay = FALSE) + public function __construct($position = self::POSITION_RIGHT, PHPExcel_Chart_Layout $layout = null, $overlay = false) { $this->setPosition($position); - $this->_layout = $layout; + $this->layout = $layout; $this->setOverlay($overlay); } @@ -87,8 +87,9 @@ class PHPExcel_Chart_Legend * * @return string */ - public function getPosition() { - return $this->_position; + public function getPosition() + { + return $this->position; } /** @@ -96,12 +97,13 @@ class PHPExcel_Chart_Legend * * @param string $position */ - public function setPosition($position = self::POSITION_RIGHT) { - if (!in_array($position,self::$_positionXLref)) { + public function setPosition($position = self::POSITION_RIGHT) + { + if (!in_array($position, self::$_positionXLref)) { return false; } - $this->_position = $position; + $this->position = $position; return true; } @@ -110,8 +112,9 @@ class PHPExcel_Chart_Legend * * @return number */ - public function getPositionXL() { - return array_search($this->_position,self::$_positionXLref); + public function getPositionXL() + { + return array_search($this->position, self::$_positionXLref); } /** @@ -119,12 +122,13 @@ class PHPExcel_Chart_Legend * * @param number $positionXL */ - public function setPositionXL($positionXL = self::xlLegendPositionRight) { - if (!array_key_exists($positionXL,self::$_positionXLref)) { + public function setPositionXL($positionXL = self::xlLegendPositionRight) + { + if (!array_key_exists($positionXL, self::$_positionXLref)) { return false; } - $this->_position = self::$_positionXLref[$positionXL]; + $this->position = self::$_positionXLref[$positionXL]; return true; } @@ -133,8 +137,9 @@ class PHPExcel_Chart_Legend * * @return boolean */ - public function getOverlay() { - return $this->_overlay; + public function getOverlay() + { + return $this->overlay; } /** @@ -143,12 +148,13 @@ class PHPExcel_Chart_Legend * @param boolean $overlay * @return boolean */ - public function setOverlay($overlay = FALSE) { + public function setOverlay($overlay = false) + { if (!is_bool($overlay)) { return false; } - $this->_overlay = $overlay; + $this->overlay = $overlay; return true; } @@ -157,8 +163,8 @@ class PHPExcel_Chart_Legend * * @return PHPExcel_Chart_Layout */ - public function getLayout() { - return $this->_layout; + public function getLayout() + { + return $this->layout; } - } diff --git a/Classes/PHPExcel/Chart/PlotArea.php b/Classes/PHPExcel/Chart/PlotArea.php index c2ff157e..551cc517 100644 --- a/Classes/PHPExcel/Chart/PlotArea.php +++ b/Classes/PHPExcel/Chart/PlotArea.php @@ -32,22 +32,22 @@ class PHPExcel_Chart_PlotArea * * @var PHPExcel_Chart_Layout */ - private $_layout = null; + private $layout = null; /** * Plot Series * * @var array of PHPExcel_Chart_DataSeries */ - private $_plotSeries = array(); + private $plotSeries = array(); /** * Create a new PHPExcel_Chart_PlotArea */ public function __construct(PHPExcel_Chart_Layout $layout = null, $plotSeries = array()) { - $this->_layout = $layout; - $this->_plotSeries = $plotSeries; + $this->layout = $layout; + $this->plotSeries = $plotSeries; } /** @@ -57,7 +57,7 @@ class PHPExcel_Chart_PlotArea */ public function getLayout() { - return $this->_layout; + return $this->layout; } /** @@ -67,7 +67,7 @@ class PHPExcel_Chart_PlotArea */ public function getPlotGroupCount() { - return count($this->_plotSeries); + return count($this->plotSeries); } /** @@ -78,7 +78,7 @@ class PHPExcel_Chart_PlotArea public function getPlotSeriesCount() { $seriesCount = 0; - foreach ($this->_plotSeries as $plot) { + foreach ($this->plotSeries as $plot) { $seriesCount += $plot->getPlotSeriesCount(); } return $seriesCount; @@ -91,7 +91,7 @@ class PHPExcel_Chart_PlotArea */ public function getPlotGroup() { - return $this->_plotSeries; + return $this->plotSeries; } /** @@ -101,7 +101,7 @@ class PHPExcel_Chart_PlotArea */ public function getPlotGroupByIndex($index) { - return $this->_plotSeries[$index]; + return $this->plotSeries[$index]; } /** @@ -112,14 +112,14 @@ class PHPExcel_Chart_PlotArea */ public function setPlotSeries($plotSeries = array()) { - $this->_plotSeries = $plotSeries; + $this->plotSeries = $plotSeries; return $this; } public function refresh(PHPExcel_Worksheet $worksheet) { - foreach ($this->_plotSeries as $plotSeries) { + foreach ($this->plotSeries as $plotSeries) { $plotSeries->refresh($worksheet); } } diff --git a/Classes/PHPExcel/Chart/Properties.php b/Classes/PHPExcel/Chart/Properties.php index 3181f654..9bb6e933 100644 --- a/Classes/PHPExcel/Chart/Properties.php +++ b/Classes/PHPExcel/Chart/Properties.php @@ -70,7 +70,7 @@ abstract class PHPExcel_Chart_Properties LINE_STYLE_JOIN_MITER = 'miter', LINE_STYLE_JOIN_BEVEL = 'bevel', - LINE_STYLE_ARROW_TYPE_NOARROW = NULL, + LINE_STYLE_ARROW_TYPE_NOARROW = null, LINE_STYLE_ARROW_TYPE_ARROW = 'triangle', LINE_STYLE_ARROW_TYPE_OPEN = 'arrow', LINE_STYLE_ARROW_TYPE_STEALTH = 'stealth', @@ -88,7 +88,7 @@ abstract class PHPExcel_Chart_Properties LINE_STYLE_ARROW_SIZE_9 = 9; const - SHADOW_PRESETS_NOSHADOW = NULL, + SHADOW_PRESETS_NOSHADOW = null, SHADOW_PRESETS_OUTER_BOTTTOM_RIGHT = 1, SHADOW_PRESETS_OUTER_BOTTOM = 2, SHADOW_PRESETS_OUTER_BOTTOM_LEFT = 3, @@ -113,19 +113,19 @@ abstract class PHPExcel_Chart_Properties SHADOW_PRESETS_PERSPECTIVE_LOWER_RIGHT = 22, SHADOW_PRESETS_PERSPECTIVE_LOWER_LEFT = 23; - protected function getExcelPointsWidth($width) + protected function getExcelPointsWidth($width) { - return $width * 12700; + return $width * 12700; } protected function getExcelPointsAngle($angle) { - return $angle * 60000; + return $angle * 60000; } protected function getTrueAlpha($alpha) { - return (string) 100 - $alpha . '000'; + return (string) 100 - $alpha . '000'; } protected function setColorProperties($color, $alpha, $type) @@ -137,7 +137,8 @@ abstract class PHPExcel_Chart_Properties ); } - protected function getLineStyleArrowSize($array_selector, $array_kay_selector) { + protected function getLineStyleArrowSize($array_selector, $array_kay_selector) + { $sizes = array( 1 => array('w' => 'sm', 'len' => 'sm'), 2 => array('w' => 'sm', 'len' => 'med'), @@ -153,7 +154,8 @@ abstract class PHPExcel_Chart_Properties return $sizes[$array_selector][$array_kay_selector]; } - protected function getShadowPresetsMap($shadow_presets_option) { + protected function getShadowPresetsMap($shadow_presets_option) + { $presets_options = array( //OUTER 1 => array( @@ -345,7 +347,8 @@ abstract class PHPExcel_Chart_Properties return $presets_options[$shadow_presets_option]; } - protected function getArrayElementsValue($properties, $elements) { + protected function getArrayElementsValue($properties, $elements) + { $reference = & $properties; if (!is_array($elements)) { return $reference[$elements]; @@ -357,4 +360,4 @@ abstract class PHPExcel_Chart_Properties } return $this; } -} \ No newline at end of file +} diff --git a/Classes/PHPExcel/Chart/Renderer/jpgraph.php b/Classes/PHPExcel/Chart/Renderer/jpgraph.php index 2b49e651..a62f0b79 100644 --- a/Classes/PHPExcel/Chart/Renderer/jpgraph.php +++ b/Classes/PHPExcel/Chart/Renderer/jpgraph.php @@ -1,7 +1,9 @@ MARK_DIAMOND, - 'square' => MARK_SQUARE, - 'triangle' => MARK_UTRIANGLE, - 'x' => MARK_X, - 'star' => MARK_STAR, - 'dot' => MARK_FILLEDCIRCLE, - 'dash' => MARK_DTRIANGLE, - 'circle' => MARK_CIRCLE, - 'plus' => MARK_CROSS - ); + private static $markSet = array( + 'diamond' => MARK_DIAMOND, + 'square' => MARK_SQUARE, + 'triangle' => MARK_UTRIANGLE, + 'x' => MARK_X, + 'star' => MARK_STAR, + 'dot' => MARK_FILLEDCIRCLE, + 'dash' => MARK_DTRIANGLE, + 'circle' => MARK_CIRCLE, + 'plus' => MARK_CROSS + ); - private $_chart = null; + private $chart; - private $_graph = null; + private $graph; - private static $_plotColour = 0; + private static $_plotColour = 0; - private static $_plotMark = 0; + private static $_plotMark = 0; - private function _formatPointMarker($seriesPlot, $markerID) { - $plotMarkKeys = array_keys(self::$_markSet); + private function formatPointMarker($seriesPlot, $markerID) { + $plotMarkKeys = array_keys(self::$markSet); if (is_null($markerID)) { // Use default plot marker (next marker in the series) - self::$_plotMark %= count(self::$_markSet); - $seriesPlot->mark->SetType(self::$_markSet[$plotMarkKeys[self::$_plotMark++]]); + self::$_plotMark %= count(self::$markSet); + $seriesPlot->mark->SetType(self::$markSet[$plotMarkKeys[self::$_plotMark++]]); } elseif ($markerID !== 'none') { // Use specified plot marker (if it exists) - if (isset(self::$_markSet[$markerID])) { - $seriesPlot->mark->SetType(self::$_markSet[$markerID]); + if (isset(self::$markSet[$markerID])) { + $seriesPlot->mark->SetType(self::$markSet[$markerID]); } else { // If the specified plot marker doesn't exist, use default plot marker (next marker in the series) - self::$_plotMark %= count(self::$_markSet); - $seriesPlot->mark->SetType(self::$_markSet[$plotMarkKeys[self::$_plotMark++]]); + self::$_plotMark %= count(self::$markSet); + $seriesPlot->mark->SetType(self::$markSet[$plotMarkKeys[self::$_plotMark++]]); } } else { // Hide plot marker $seriesPlot->mark->Hide(); } - $seriesPlot->mark->SetColor(self::$_colourSet[self::$_plotColour]); - $seriesPlot->mark->SetFillColor(self::$_colourSet[self::$_plotColour]); - $seriesPlot->SetColor(self::$_colourSet[self::$_plotColour++]); + $seriesPlot->mark->SetColor(self::$colourSet[self::$_plotColour]); + $seriesPlot->mark->SetFillColor(self::$colourSet[self::$_plotColour]); + $seriesPlot->SetColor(self::$colourSet[self::$_plotColour++]); return $seriesPlot; - } // function _formatPointMarker() + } - private function _formatDataSetLabels($groupID, $datasetLabels, $labelCount, $rotation = '') { - $datasetLabelFormatCode = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex(0)->getFormatCode(); + private function formatDataSetLabels($groupID, $datasetLabels, $labelCount, $rotation = '') { + $datasetLabelFormatCode = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex(0)->getFormatCode(); if (!is_null($datasetLabelFormatCode)) { // Retrieve any label formatting code $datasetLabelFormatCode = stripslashes($datasetLabelFormatCode); @@ -124,16 +116,16 @@ class PHPExcel_Chart_Renderer_jpgraph } return $datasetLabels; - } // function _formatDataSetLabels() + } private function _percentageSumCalculation($groupID, $seriesCount) { // Adjust our values to a percentage value across all series in the group for($i = 0; $i < $seriesCount; ++$i) { if ($i == 0) { - $sumValues = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getDataValues(); + $sumValues = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getDataValues(); } else { - $nextValues = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getDataValues(); + $nextValues = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getDataValues(); foreach ($nextValues as $k => $value) { if (isset($sumValues[$k])) { $sumValues[$k] += $value; @@ -173,75 +165,75 @@ class PHPExcel_Chart_Renderer_jpgraph private function _renderTitle() { - $title = $this->_getCaption($this->_chart->getTitle()); + $title = $this->_getCaption($this->chart->getTitle()); if (!is_null($title)) { - $this->_graph->title->Set($title); + $this->graph->title->Set($title); } } // function _renderTitle() private function _renderLegend() { - $legend = $this->_chart->getLegend(); + $legend = $this->chart->getLegend(); if (!is_null($legend)) { $legendPosition = $legend->getPosition(); $legendOverlay = $legend->getOverlay(); switch ($legendPosition) { case 'r' : - $this->_graph->legend->SetPos(0.01,0.5,'right','center'); // right - $this->_graph->legend->SetColumns(1); + $this->graph->legend->SetPos(0.01,0.5,'right','center'); // right + $this->graph->legend->SetColumns(1); break; case 'l' : - $this->_graph->legend->SetPos(0.01,0.5,'left','center'); // left - $this->_graph->legend->SetColumns(1); + $this->graph->legend->SetPos(0.01,0.5,'left','center'); // left + $this->graph->legend->SetColumns(1); break; case 't' : - $this->_graph->legend->SetPos(0.5,0.01,'center','top'); // top + $this->graph->legend->SetPos(0.5,0.01,'center','top'); // top break; case 'b' : - $this->_graph->legend->SetPos(0.5,0.99,'center','bottom'); // bottom + $this->graph->legend->SetPos(0.5,0.99,'center','bottom'); // bottom break; default : - $this->_graph->legend->SetPos(0.01,0.01,'right','top'); // top-right - $this->_graph->legend->SetColumns(1); + $this->graph->legend->SetPos(0.01,0.01,'right','top'); // top-right + $this->graph->legend->SetColumns(1); break; } } else { - $this->_graph->legend->Hide(); + $this->graph->legend->Hide(); } } // function _renderLegend() private function _renderCartesianPlotArea($type='textlin') { - $this->_graph = new Graph(self::$_width,self::$_height); - $this->_graph->SetScale($type); + $this->graph = new Graph(self::$width,self::$height); + $this->graph->SetScale($type); $this->_renderTitle(); // Rotate for bar rather than column chart - $rotation = $this->_chart->getPlotArea()->getPlotGroupByIndex(0)->getPlotDirection(); + $rotation = $this->chart->getPlotArea()->getPlotGroupByIndex(0)->getPlotDirection(); $reverse = ($rotation == 'bar') ? true : false; - $xAxisLabel = $this->_chart->getXAxisLabel(); + $xAxisLabel = $this->chart->getXAxisLabel(); if (!is_null($xAxisLabel)) { $title = $this->_getCaption($xAxisLabel); if (!is_null($title)) { - $this->_graph->xaxis->SetTitle($title,'center'); - $this->_graph->xaxis->title->SetMargin(35); + $this->graph->xaxis->SetTitle($title,'center'); + $this->graph->xaxis->title->SetMargin(35); if ($reverse) { - $this->_graph->xaxis->title->SetAngle(90); - $this->_graph->xaxis->title->SetMargin(90); + $this->graph->xaxis->title->SetAngle(90); + $this->graph->xaxis->title->SetMargin(90); } } } - $yAxisLabel = $this->_chart->getYAxisLabel(); + $yAxisLabel = $this->chart->getYAxisLabel(); if (!is_null($yAxisLabel)) { $title = $this->_getCaption($yAxisLabel); if (!is_null($title)) { - $this->_graph->yaxis->SetTitle($title,'center'); + $this->graph->yaxis->SetTitle($title,'center'); if ($reverse) { - $this->_graph->yaxis->title->SetAngle(0); - $this->_graph->yaxis->title->SetMargin(-55); + $this->graph->yaxis->title->SetAngle(0); + $this->graph->yaxis->title->SetMargin(-55); } } } @@ -249,31 +241,31 @@ class PHPExcel_Chart_Renderer_jpgraph private function _renderPiePlotArea($doughnut = False) { - $this->_graph = new PieGraph(self::$_width,self::$_height); + $this->graph = new PieGraph(self::$width,self::$height); $this->_renderTitle(); } // function _renderPiePlotArea() private function _renderRadarPlotArea() { - $this->_graph = new RadarGraph(self::$_width,self::$_height); - $this->_graph->SetScale('lin'); + $this->graph = new RadarGraph(self::$width,self::$height); + $this->graph->SetScale('lin'); $this->_renderTitle(); } // function _renderRadarPlotArea() private function _renderPlotLine($groupID, $filled = false, $combination = false, $dimensions = '2d') { - $grouping = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotGrouping(); + $grouping = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotGrouping(); - $labelCount = count($this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex(0)->getPointCount()); + $labelCount = count($this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex(0)->getPointCount()); if ($labelCount > 0) { - $datasetLabels = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex(0)->getDataValues(); - $datasetLabels = $this->_formatDataSetLabels($groupID, $datasetLabels, $labelCount); - $this->_graph->xaxis->SetTickLabels($datasetLabels); + $datasetLabels = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex(0)->getDataValues(); + $datasetLabels = $this->formatDataSetLabels($groupID, $datasetLabels, $labelCount); + $this->graph->xaxis->SetTickLabels($datasetLabels); } - $seriesCount = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); + $seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); $seriesPlots = array(); if ($grouping == 'percentStacked') { $sumValues = $this->_percentageSumCalculation($groupID, $seriesCount); @@ -281,8 +273,8 @@ class PHPExcel_Chart_Renderer_jpgraph // Loop through each data series in turn for($i = 0; $i < $seriesCount; ++$i) { - $dataValues = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getDataValues(); - $marker = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getPointMarker(); + $dataValues = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getDataValues(); + $marker = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getPointMarker(); if ($grouping == 'percentStacked') { $dataValues = $this->_percentageAdjustValues($dataValues, $sumValues); @@ -306,12 +298,12 @@ class PHPExcel_Chart_Renderer_jpgraph if ($filled) { $seriesPlot->SetFilled(true); $seriesPlot->SetColor('black'); - $seriesPlot->SetFillColor(self::$_colourSet[self::$_plotColour++]); + $seriesPlot->SetFillColor(self::$colourSet[self::$_plotColour++]); } else { // Set the appropriate plot marker - $this->_formatPointMarker($seriesPlot, $marker); + $this->formatPointMarker($seriesPlot, $marker); } - $dataLabel = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotLabelByIndex($i)->getDataValue(); + $dataLabel = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotLabelByIndex($i)->getDataValue(); $seriesPlot->SetLegend($dataLabel); $seriesPlots[] = $seriesPlot; @@ -322,34 +314,34 @@ class PHPExcel_Chart_Renderer_jpgraph } else { $groupPlot = new AccLinePlot($seriesPlots); } - $this->_graph->Add($groupPlot); + $this->graph->Add($groupPlot); } // function _renderPlotLine() private function _renderPlotBar($groupID, $dimensions = '2d') { - $rotation = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotDirection(); + $rotation = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotDirection(); // Rotate for bar rather than column chart if (($groupID == 0) && ($rotation == 'bar')) { - $this->_graph->Set90AndMargin(); + $this->graph->Set90AndMargin(); } - $grouping = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotGrouping(); + $grouping = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotGrouping(); - $labelCount = count($this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex(0)->getPointCount()); + $labelCount = count($this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex(0)->getPointCount()); if ($labelCount > 0) { - $datasetLabels = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex(0)->getDataValues(); - $datasetLabels = $this->_formatDataSetLabels($groupID, $datasetLabels, $labelCount, $rotation); + $datasetLabels = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex(0)->getDataValues(); + $datasetLabels = $this->formatDataSetLabels($groupID, $datasetLabels, $labelCount, $rotation); // Rotate for bar rather than column chart if ($rotation == 'bar') { $datasetLabels = array_reverse($datasetLabels); - $this->_graph->yaxis->SetPos('max'); - $this->_graph->yaxis->SetLabelAlign('center','top'); - $this->_graph->yaxis->SetLabelSide(SIDE_RIGHT); + $this->graph->yaxis->SetPos('max'); + $this->graph->yaxis->SetLabelAlign('center','top'); + $this->graph->yaxis->SetLabelSide(SIDE_RIGHT); } - $this->_graph->xaxis->SetTickLabels($datasetLabels); + $this->graph->xaxis->SetTickLabels($datasetLabels); } - $seriesCount = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); + $seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); $seriesPlots = array(); if ($grouping == 'percentStacked') { $sumValues = $this->_percentageSumCalculation($groupID, $seriesCount); @@ -357,7 +349,7 @@ class PHPExcel_Chart_Renderer_jpgraph // Loop through each data series in turn for($j = 0; $j < $seriesCount; ++$j) { - $dataValues = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($j)->getDataValues(); + $dataValues = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($j)->getDataValues(); if ($grouping == 'percentStacked') { $dataValues = $this->_percentageAdjustValues($dataValues, $sumValues); } @@ -378,14 +370,14 @@ class PHPExcel_Chart_Renderer_jpgraph } $seriesPlot = new BarPlot($dataValues); $seriesPlot->SetColor('black'); - $seriesPlot->SetFillColor(self::$_colourSet[self::$_plotColour++]); + $seriesPlot->SetFillColor(self::$colourSet[self::$_plotColour++]); if ($dimensions == '3d') { $seriesPlot->SetShadow(); } - if (!$this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotLabelByIndex($j)) { + if (!$this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotLabelByIndex($j)) { $dataLabel = ''; } else { - $dataLabel = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotLabelByIndex($j)->getDataValue(); + $dataLabel = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotLabelByIndex($j)->getDataValue(); } $seriesPlot->SetLegend($dataLabel); @@ -407,21 +399,21 @@ class PHPExcel_Chart_Renderer_jpgraph } } - $this->_graph->Add($groupPlot); + $this->graph->Add($groupPlot); } // function _renderPlotBar() private function _renderPlotScatter($groupID, $bubble) { - $grouping = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotGrouping(); - $scatterStyle = $bubbleSize = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotStyle(); + $grouping = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotGrouping(); + $scatterStyle = $bubbleSize = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotStyle(); - $seriesCount = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); + $seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); $seriesPlots = array(); // Loop through each data series in turn for($i = 0; $i < $seriesCount; ++$i) { - $dataValuesY = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex($i)->getDataValues(); - $dataValuesX = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getDataValues(); + $dataValuesY = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex($i)->getDataValues(); + $dataValuesX = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getDataValues(); foreach ($dataValuesY as $k => $dataValueY) { $dataValuesY[$k] = $k; @@ -430,43 +422,43 @@ class PHPExcel_Chart_Renderer_jpgraph $seriesPlot = new ScatterPlot($dataValuesX, $dataValuesY); if ($scatterStyle == 'lineMarker') { $seriesPlot->SetLinkPoints(); - $seriesPlot->link->SetColor(self::$_colourSet[self::$_plotColour]); + $seriesPlot->link->SetColor(self::$colourSet[self::$_plotColour]); } elseif ($scatterStyle == 'smoothMarker') { $spline = new Spline($dataValuesY, $dataValuesX); - list($splineDataY, $splineDataX) = $spline->Get(count($dataValuesX) * self::$_width / 20); + list($splineDataY, $splineDataX) = $spline->Get(count($dataValuesX) * self::$width / 20); $lplot = new LinePlot($splineDataX, $splineDataY); - $lplot->SetColor(self::$_colourSet[self::$_plotColour]); + $lplot->SetColor(self::$colourSet[self::$_plotColour]); - $this->_graph->Add($lplot); + $this->graph->Add($lplot); } if ($bubble) { - $this->_formatPointMarker($seriesPlot,'dot'); + $this->formatPointMarker($seriesPlot,'dot'); $seriesPlot->mark->SetColor('black'); $seriesPlot->mark->SetSize($bubbleSize); } else { - $marker = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getPointMarker(); - $this->_formatPointMarker($seriesPlot, $marker); + $marker = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getPointMarker(); + $this->formatPointMarker($seriesPlot, $marker); } - $dataLabel = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotLabelByIndex($i)->getDataValue(); + $dataLabel = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotLabelByIndex($i)->getDataValue(); $seriesPlot->SetLegend($dataLabel); - $this->_graph->Add($seriesPlot); + $this->graph->Add($seriesPlot); } } // function _renderPlotScatter() private function _renderPlotRadar($groupID) { - $radarStyle = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotStyle(); + $radarStyle = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotStyle(); - $seriesCount = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); + $seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); $seriesPlots = array(); // Loop through each data series in turn for($i = 0; $i < $seriesCount; ++$i) { - $dataValuesY = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex($i)->getDataValues(); - $dataValuesX = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getDataValues(); - $marker = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getPointMarker(); + $dataValuesY = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex($i)->getDataValues(); + $dataValuesX = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getDataValues(); + $marker = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getPointMarker(); $dataValues = array(); foreach ($dataValuesY as $k => $dataValueY) { @@ -477,51 +469,51 @@ class PHPExcel_Chart_Renderer_jpgraph $tmp = array_shift($dataValuesX); $dataValuesX[] = $tmp; - $this->_graph->SetTitles(array_reverse($dataValues)); + $this->graph->SetTitles(array_reverse($dataValues)); $seriesPlot = new RadarPlot(array_reverse($dataValuesX)); - $dataLabel = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotLabelByIndex($i)->getDataValue(); - $seriesPlot->SetColor(self::$_colourSet[self::$_plotColour++]); + $dataLabel = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotLabelByIndex($i)->getDataValue(); + $seriesPlot->SetColor(self::$colourSet[self::$_plotColour++]); if ($radarStyle == 'filled') { - $seriesPlot->SetFillColor(self::$_colourSet[self::$_plotColour]); + $seriesPlot->SetFillColor(self::$colourSet[self::$_plotColour]); } - $this->_formatPointMarker($seriesPlot, $marker); + $this->formatPointMarker($seriesPlot, $marker); $seriesPlot->SetLegend($dataLabel); - $this->_graph->Add($seriesPlot); + $this->graph->Add($seriesPlot); } } // function _renderPlotRadar() private function _renderPlotContour($groupID) { - $contourStyle = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotStyle(); + $contourStyle = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotStyle(); - $seriesCount = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); + $seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); $seriesPlots = array(); $dataValues = array(); // Loop through each data series in turn for($i = 0; $i < $seriesCount; ++$i) { - $dataValuesY = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex($i)->getDataValues(); - $dataValuesX = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getDataValues(); + $dataValuesY = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex($i)->getDataValues(); + $dataValuesX = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getDataValues(); $dataValues[$i] = $dataValuesX; } $seriesPlot = new ContourPlot($dataValues); - $this->_graph->Add($seriesPlot); + $this->graph->Add($seriesPlot); } // function _renderPlotContour() private function _renderPlotStock($groupID) { - $seriesCount = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); - $plotOrder = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotOrder(); + $seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); + $plotOrder = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotOrder(); $dataValues = array(); // Loop through each data series in turn and build the plot arrays foreach ($plotOrder as $i => $v) { - $dataValuesX = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($v)->getDataValues(); + $dataValuesX = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($v)->getDataValues(); foreach ($dataValuesX as $j => $dataValueX) { $dataValues[$plotOrder[$i]][$j] = $dataValueX; } @@ -539,17 +531,17 @@ class PHPExcel_Chart_Renderer_jpgraph } // Set the x-axis labels - $labelCount = count($this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex(0)->getPointCount()); + $labelCount = count($this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex(0)->getPointCount()); if ($labelCount > 0) { - $datasetLabels = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex(0)->getDataValues(); - $datasetLabels = $this->_formatDataSetLabels($groupID, $datasetLabels, $labelCount); - $this->_graph->xaxis->SetTickLabels($datasetLabels); + $datasetLabels = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex(0)->getDataValues(); + $datasetLabels = $this->formatDataSetLabels($groupID, $datasetLabels, $labelCount); + $this->graph->xaxis->SetTickLabels($datasetLabels); } $seriesPlot = new StockPlot($dataValuesPlot); $seriesPlot->SetWidth(20); - $this->_graph->Add($seriesPlot); + $this->graph->Add($seriesPlot); } // function _renderPlotStock() @@ -620,23 +612,23 @@ class PHPExcel_Chart_Renderer_jpgraph $iLimit = ($multiplePlots) ? $groupCount : 1; for($groupID = 0; $groupID < $iLimit; ++$groupID) { - $grouping = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotGrouping(); - $exploded = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotStyle(); + $grouping = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotGrouping(); + $exploded = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotStyle(); if ($groupID == 0) { - $labelCount = count($this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex(0)->getPointCount()); + $labelCount = count($this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex(0)->getPointCount()); if ($labelCount > 0) { - $datasetLabels = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex(0)->getDataValues(); - $datasetLabels = $this->_formatDataSetLabels($groupID, $datasetLabels, $labelCount); + $datasetLabels = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex(0)->getDataValues(); + $datasetLabels = $this->formatDataSetLabels($groupID, $datasetLabels, $labelCount); } } - $seriesCount = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); + $seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); $seriesPlots = array(); // For pie charts, we only display the first series: doughnut charts generally display all series $jLimit = ($multiplePlots) ? $seriesCount : 1; // Loop through each data series in turn for($j = 0; $j < $jLimit; ++$j) { - $dataValues = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($j)->getDataValues(); + $dataValues = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($j)->getDataValues(); // Fill in any missing values in the $dataValues array $testCurrentIndex = 0; @@ -666,7 +658,7 @@ class PHPExcel_Chart_Renderer_jpgraph $seriesPlot->SetMidColor('white'); } - $seriesPlot->SetColor(self::$_colourSet[self::$_plotColour++]); + $seriesPlot->SetColor(self::$colourSet[self::$_plotColour++]); if (count($datasetLabels) > 0) $seriesPlot->SetLabels(array_fill(0,count($datasetLabels),'')); if ($dimensions != '3d') { @@ -679,7 +671,7 @@ class PHPExcel_Chart_Renderer_jpgraph $seriesPlot->SetLegends($datasetLabels); } - $this->_graph->Add($seriesPlot); + $this->graph->Add($seriesPlot); } } } // function _renderPieChart() @@ -729,7 +721,7 @@ class PHPExcel_Chart_Renderer_jpgraph for($i = 0; $i < $groupCount; ++$i) { $dimensions = null; - $chartType = $this->_chart->getPlotArea()->getPlotGroupByIndex($i)->getPlotType(); + $chartType = $this->chart->getPlotArea()->getPlotGroupByIndex($i)->getPlotType(); switch ($chartType) { case 'area3DChart' : $dimensions = '3d'; @@ -753,14 +745,14 @@ class PHPExcel_Chart_Renderer_jpgraph $this->_renderPlotScatter($i,true); break; default : - $this->_graph = null; + $this->graph = null; return false; } } $this->_renderLegend(); - $this->_graph->Stroke($outputDestination); + $this->graph->Stroke($outputDestination); return true; } // function _renderCombinationChart() @@ -768,15 +760,15 @@ class PHPExcel_Chart_Renderer_jpgraph public function render($outputDestination) { self::$_plotColour = 0; - $groupCount = $this->_chart->getPlotArea()->getPlotGroupCount(); + $groupCount = $this->chart->getPlotArea()->getPlotGroupCount(); $dimensions = null; if ($groupCount == 1) { - $chartType = $this->_chart->getPlotArea()->getPlotGroupByIndex(0)->getPlotType(); + $chartType = $this->chart->getPlotArea()->getPlotGroupByIndex(0)->getPlotType(); } else { $chartTypes = array(); for($i = 0; $i < $groupCount; ++$i) { - $chartTypes[] = $this->_chart->getPlotArea()->getPlotGroupByIndex($i)->getPlotType(); + $chartTypes[] = $this->chart->getPlotArea()->getPlotGroupByIndex($i)->getPlotType(); } $chartTypes = array_unique($chartTypes); if (count($chartTypes) == 1) { @@ -838,9 +830,9 @@ class PHPExcel_Chart_Renderer_jpgraph } $this->_renderLegend(); - $this->_graph->Stroke($outputDestination); + $this->graph->Stroke($outputDestination); return true; - } // function render() + } /** @@ -848,8 +840,7 @@ class PHPExcel_Chart_Renderer_jpgraph */ public function __construct(PHPExcel_Chart $chart) { - $this->_graph = null; - $this->_chart = $chart; - } // function __construct() - -} // PHPExcel_Chart_Renderer_jpgraph + $this->graph = null; + $this->chart = $chart; + } +} diff --git a/Classes/PHPExcel/Chart/Title.php b/Classes/PHPExcel/Chart/Title.php index c68a0b91..d8dc14f2 100644 --- a/Classes/PHPExcel/Chart/Title.php +++ b/Classes/PHPExcel/Chart/Title.php @@ -1,6 +1,7 @@ _caption = $caption; - $this->_layout = $layout; + $this->caption = $caption; + $this->layout = $layout; } /** @@ -64,8 +56,9 @@ class PHPExcel_Chart_Title * * @return string */ - public function getCaption() { - return $this->_caption; + public function getCaption() + { + return $this->caption; } /** @@ -74,8 +67,9 @@ class PHPExcel_Chart_Title * @param string $caption * @return PHPExcel_Chart_Title */ - public function setCaption($caption = null) { - $this->_caption = $caption; + public function setCaption($caption = null) + { + $this->caption = $caption; return $this; } @@ -85,8 +79,8 @@ class PHPExcel_Chart_Title * * @return PHPExcel_Chart_Layout */ - public function getLayout() { - return $this->_layout; + public function getLayout() + { + return $this->layout; } - } From 96f3d0e6eeba904ed643dc6c798cda6f96831d8f Mon Sep 17 00:00:00 2001 From: Progi1984 Date: Fri, 15 May 2015 12:55:10 +0200 Subject: [PATCH 2/5] PSR-2 : Fixes --- Classes/PHPExcel/Comment.php | 69 +- Classes/PHPExcel/Exception.php | 6 +- Classes/PHPExcel/HashTable.php | 2 +- Classes/PHPExcel/IOFactory.php | 10 +- Classes/PHPExcel/NamedRange.php | 48 +- Classes/PHPExcel/ReferenceHelper.php | 121 +- Classes/PHPExcel/Shared/Drawing.php | 120 +- Classes/PHPExcel/Shared/Escher.php | 1 - Classes/PHPExcel/Shared/File.php | 42 +- Classes/PHPExcel/Shared/OLE.php | 41 +- Classes/PHPExcel/Shared/PCLZip/pclzip.lib.php | 10677 ++++++++-------- Classes/PHPExcel/Shared/ZipStreamWrapper.php | 40 +- Classes/PHPExcel/Style.php | 3 +- .../PHPExcel/Writer/Excel2007/DocProps.php | 10 +- Classes/PHPExcel/Writer/Excel2007/Drawing.php | 553 +- .../PHPExcel/Writer/Excel2007/StringTable.php | 7 +- .../PHPExcel/Writer/Excel2007/Worksheet.php | 426 +- Classes/PHPExcel/Writer/Excel5/Parser.php | 44 +- 18 files changed, 6048 insertions(+), 6172 deletions(-) diff --git a/Classes/PHPExcel/Comment.php b/Classes/PHPExcel/Comment.php index bdadfbf5..0546f4ae 100644 --- a/Classes/PHPExcel/Comment.php +++ b/Classes/PHPExcel/Comment.php @@ -98,10 +98,10 @@ class PHPExcel_Comment implements PHPExcel_IComparable public function __construct() { // Initialise variables - $this->_author = 'Author'; + $this->_author = 'Author'; $this->_text = new PHPExcel_RichText(); - $this->_fillColor = new PHPExcel_Style_Color('FFFFFFE1'); - $this->_alignment = PHPExcel_Style_Alignment::HORIZONTAL_GENERAL; + $this->_fillColor = new PHPExcel_Style_Color('FFFFFFE1'); + $this->_alignment = PHPExcel_Style_Alignment::HORIZONTAL_GENERAL; } /** @@ -109,7 +109,8 @@ class PHPExcel_Comment implements PHPExcel_IComparable * * @return string */ - public function getAuthor() { + public function getAuthor() + { return $this->_author; } @@ -119,7 +120,8 @@ class PHPExcel_Comment implements PHPExcel_IComparable * @param string $pValue * @return PHPExcel_Comment */ - public function setAuthor($pValue = '') { + public function setAuthor($pValue = '') + { $this->_author = $pValue; return $this; } @@ -129,7 +131,8 @@ class PHPExcel_Comment implements PHPExcel_IComparable * * @return PHPExcel_RichText */ - public function getText() { + public function getText() + { return $this->_text; } @@ -139,7 +142,8 @@ class PHPExcel_Comment implements PHPExcel_IComparable * @param PHPExcel_RichText $pValue * @return PHPExcel_Comment */ - public function setText(PHPExcel_RichText $pValue) { + public function setText(PHPExcel_RichText $pValue) + { $this->_text = $pValue; return $this; } @@ -149,7 +153,8 @@ class PHPExcel_Comment implements PHPExcel_IComparable * * @return string */ - public function getWidth() { + public function getWidth() + { return $this->_width; } @@ -159,7 +164,8 @@ class PHPExcel_Comment implements PHPExcel_IComparable * @param string $value * @return PHPExcel_Comment */ - public function setWidth($value = '96pt') { + public function setWidth($value = '96pt') + { $this->_width = $value; return $this; } @@ -169,7 +175,8 @@ class PHPExcel_Comment implements PHPExcel_IComparable * * @return string */ - public function getHeight() { + public function getHeight() + { return $this->_height; } @@ -179,7 +186,8 @@ class PHPExcel_Comment implements PHPExcel_IComparable * @param string $value * @return PHPExcel_Comment */ - public function setHeight($value = '55.5pt') { + public function setHeight($value = '55.5pt') + { $this->_height = $value; return $this; } @@ -189,7 +197,8 @@ class PHPExcel_Comment implements PHPExcel_IComparable * * @return string */ - public function getMarginLeft() { + public function getMarginLeft() + { return $this->_marginLeft; } @@ -199,7 +208,8 @@ class PHPExcel_Comment implements PHPExcel_IComparable * @param string $value * @return PHPExcel_Comment */ - public function setMarginLeft($value = '59.25pt') { + public function setMarginLeft($value = '59.25pt') + { $this->_marginLeft = $value; return $this; } @@ -209,7 +219,8 @@ class PHPExcel_Comment implements PHPExcel_IComparable * * @return string */ - public function getMarginTop() { + public function getMarginTop() + { return $this->_marginTop; } @@ -219,7 +230,8 @@ class PHPExcel_Comment implements PHPExcel_IComparable * @param string $value * @return PHPExcel_Comment */ - public function setMarginTop($value = '1.5pt') { + public function setMarginTop($value = '1.5pt') + { $this->_marginTop = $value; return $this; } @@ -229,7 +241,8 @@ class PHPExcel_Comment implements PHPExcel_IComparable * * @return boolean */ - public function getVisible() { + public function getVisible() + { return $this->_visible; } @@ -239,7 +252,8 @@ class PHPExcel_Comment implements PHPExcel_IComparable * @param boolean $value * @return PHPExcel_Comment */ - public function setVisible($value = false) { + public function setVisible($value = false) + { $this->_visible = $value; return $this; } @@ -249,7 +263,8 @@ class PHPExcel_Comment implements PHPExcel_IComparable * * @return PHPExcel_Style_Color */ - public function getFillColor() { + public function getFillColor() + { return $this->_fillColor; } @@ -259,7 +274,8 @@ class PHPExcel_Comment implements PHPExcel_IComparable * @param string $pValue * @return PHPExcel_Comment */ - public function setAlignment($pValue = PHPExcel_Style_Alignment::HORIZONTAL_GENERAL) { + public function setAlignment($pValue = PHPExcel_Style_Alignment::HORIZONTAL_GENERAL) + { $this->_alignment = $pValue; return $this; } @@ -269,7 +285,8 @@ class PHPExcel_Comment implements PHPExcel_IComparable * * @return string */ - public function getAlignment() { + public function getAlignment() + { return $this->_alignment; } @@ -278,9 +295,10 @@ class PHPExcel_Comment implements PHPExcel_IComparable * * @return string Hash code */ - public function getHashCode() { + public function getHashCode() + { return md5( - $this->_author + $this->_author . $this->_text->getHashCode() . $this->_width . $this->_height @@ -296,7 +314,8 @@ class PHPExcel_Comment implements PHPExcel_IComparable /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ - public function __clone() { + public function __clone() + { $vars = get_object_vars($this); foreach ($vars as $key => $value) { if (is_object($value)) { @@ -312,8 +331,8 @@ class PHPExcel_Comment implements PHPExcel_IComparable * * @return string */ - public function __toString() { + public function __toString() + { return $this->_text->getPlainText(); } - } diff --git a/Classes/PHPExcel/Exception.php b/Classes/PHPExcel/Exception.php index c2694add..b27750ea 100644 --- a/Classes/PHPExcel/Exception.php +++ b/Classes/PHPExcel/Exception.php @@ -33,7 +33,8 @@ * @package PHPExcel * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) */ -class PHPExcel_Exception extends Exception { +class PHPExcel_Exception extends Exception +{ /** * Error handler callback * @@ -43,7 +44,8 @@ class PHPExcel_Exception extends Exception { * @param mixed $line * @param mixed $context */ - public static function errorHandlerCallback($code, $string, $file, $line, $context) { + public static function errorHandlerCallback($code, $string, $file, $line, $context) + { $e = new self($string, $code); $e->line = $line; $e->file = $file; diff --git a/Classes/PHPExcel/HashTable.php b/Classes/PHPExcel/HashTable.php index 8ec020ba..6fca1431 100644 --- a/Classes/PHPExcel/HashTable.php +++ b/Classes/PHPExcel/HashTable.php @@ -157,7 +157,7 @@ class PHPExcel_HashTable public function getByIndex($pIndex = 0) { if (isset($this->_keyMap[$pIndex])) { - return $this->getByHashCode( $this->_keyMap[$pIndex] ); + return $this->getByHashCode($this->_keyMap[$pIndex]); } return null; diff --git a/Classes/PHPExcel/IOFactory.php b/Classes/PHPExcel/IOFactory.php index 5b9c6353..8b063cd7 100644 --- a/Classes/PHPExcel/IOFactory.php +++ b/Classes/PHPExcel/IOFactory.php @@ -69,7 +69,9 @@ class PHPExcel_IOFactory /** * Private constructor for PHPExcel_IOFactory */ - private function __construct() { } + private function __construct() + { + } /** * Get search locations @@ -135,7 +137,7 @@ class PHPExcel_IOFactory $className = str_replace('{0}', $writerType, $searchLocation['class']); $instance = new $className($phpExcel); - if ($instance !== NULL) { + if ($instance !== null) { return $instance; } } @@ -165,7 +167,7 @@ class PHPExcel_IOFactory $className = str_replace('{0}', $readerType, $searchLocation['class']); $instance = new $className(); - if ($instance !== NULL) { + if ($instance !== null) { return $instance; } } @@ -222,7 +224,7 @@ class PHPExcel_IOFactory // First, lucky guess by inspecting file extension $pathinfo = pathinfo($pFilename); - $extensionType = NULL; + $extensionType = null; if (isset($pathinfo['extension'])) { switch (strtolower($pathinfo['extension'])) { case 'xlsx': // Excel (OfficeOpenXML) Spreadsheet diff --git a/Classes/PHPExcel/NamedRange.php b/Classes/PHPExcel/NamedRange.php index 6d1d73f9..318bcf3b 100644 --- a/Classes/PHPExcel/NamedRange.php +++ b/Classes/PHPExcel/NamedRange.php @@ -75,7 +75,7 @@ class PHPExcel_NamedRange public function __construct($pName = null, PHPExcel_Worksheet $pWorksheet, $pRange = 'A1', $pLocalOnly = false, $pScope = null) { // Validate data - if (($pName === NULL) || ($pWorksheet === NULL) || ($pRange === NULL)) { + if (($pName === null) || ($pWorksheet === null) || ($pRange === null)) { throw new PHPExcel_Exception('Parameters can not be null.'); } @@ -93,7 +93,8 @@ class PHPExcel_NamedRange * * @return string */ - public function getName() { + public function getName() + { return $this->_name; } @@ -103,18 +104,19 @@ class PHPExcel_NamedRange * @param string $value * @return PHPExcel_NamedRange */ - public function setName($value = null) { - if ($value !== NULL) { + public function setName($value = null) + { + if ($value !== null) { // Old title $oldTitle = $this->_name; // Re-attach - if ($this->_worksheet !== NULL) { + if ($this->_worksheet !== null) { $this->_worksheet->getParent()->removeNamedRange($this->_name, $this->_worksheet); } $this->_name = $value; - if ($this->_worksheet !== NULL) { + if ($this->_worksheet !== null) { $this->_worksheet->getParent()->addNamedRange($this); } @@ -130,7 +132,8 @@ class PHPExcel_NamedRange * * @return PHPExcel_Worksheet */ - public function getWorksheet() { + public function getWorksheet() + { return $this->_worksheet; } @@ -140,8 +143,9 @@ class PHPExcel_NamedRange * @param PHPExcel_Worksheet $value * @return PHPExcel_NamedRange */ - public function setWorksheet(PHPExcel_Worksheet $value = null) { - if ($value !== NULL) { + public function setWorksheet(PHPExcel_Worksheet $value = null) + { + if ($value !== null) { $this->_worksheet = $value; } return $this; @@ -152,7 +156,8 @@ class PHPExcel_NamedRange * * @return string */ - public function getRange() { + public function getRange() + { return $this->_range; } @@ -162,8 +167,9 @@ class PHPExcel_NamedRange * @param string $value * @return PHPExcel_NamedRange */ - public function setRange($value = null) { - if ($value !== NULL) { + public function setRange($value = null) + { + if ($value !== null) { $this->_range = $value; } return $this; @@ -174,7 +180,8 @@ class PHPExcel_NamedRange * * @return bool */ - public function getLocalOnly() { + public function getLocalOnly() + { return $this->_localOnly; } @@ -184,7 +191,8 @@ class PHPExcel_NamedRange * @param bool $value * @return PHPExcel_NamedRange */ - public function setLocalOnly($value = false) { + public function setLocalOnly($value = false) + { $this->_localOnly = $value; $this->_scope = $value ? $this->_worksheet : null; return $this; @@ -195,7 +203,8 @@ class PHPExcel_NamedRange * * @return PHPExcel_Worksheet|null */ - public function getScope() { + public function getScope() + { return $this->_scope; } @@ -205,7 +214,8 @@ class PHPExcel_NamedRange * @param PHPExcel_Worksheet|null $value * @return PHPExcel_NamedRange */ - public function setScope(PHPExcel_Worksheet $value = null) { + public function setScope(PHPExcel_Worksheet $value = null) + { $this->_scope = $value; $this->_localOnly = ($value == null) ? false : true; return $this; @@ -218,14 +228,16 @@ class PHPExcel_NamedRange * @param PHPExcel_Worksheet|null $pSheet Scope. Use null for global scope * @return PHPExcel_NamedRange */ - public static function resolveRange($pNamedRange = '', PHPExcel_Worksheet $pSheet) { + public static function resolveRange($pNamedRange = '', PHPExcel_Worksheet $pSheet) + { return $pSheet->getParent()->getNamedRange($pNamedRange, $pSheet); } /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ - public function __clone() { + public function __clone() + { $vars = get_object_vars($this); foreach ($vars as $key => $value) { if (is_object($value)) { diff --git a/Classes/PHPExcel/ReferenceHelper.php b/Classes/PHPExcel/ReferenceHelper.php index 5854629f..90c782f8 100644 --- a/Classes/PHPExcel/ReferenceHelper.php +++ b/Classes/PHPExcel/ReferenceHelper.php @@ -46,8 +46,9 @@ class PHPExcel_ReferenceHelper * * @return PHPExcel_ReferenceHelper */ - public static function getInstance() { - if (!isset(self::$_instance) || (self::$_instance === NULL)) { + public static function getInstance() + { + if (!isset(self::$_instance) || (self::$_instance === null)) { self::$_instance = new PHPExcel_ReferenceHelper(); } @@ -57,7 +58,8 @@ class PHPExcel_ReferenceHelper /** * Create a new PHPExcel_ReferenceHelper */ - protected function __construct() { + protected function __construct() + { } /** @@ -68,7 +70,8 @@ class PHPExcel_ReferenceHelper * @param string $b Second column to test (e.g. 'Z') * @return integer */ - public static function columnSort($a, $b) { + public static function columnSort($a, $b) + { return strcasecmp(strlen($a) . $a, strlen($b) . $b); } @@ -80,7 +83,8 @@ class PHPExcel_ReferenceHelper * @param string $b Second column to test (e.g. 'Z') * @return integer */ - public static function columnReverseSort($a, $b) { + public static function columnReverseSort($a, $b) + { return 1 - strcasecmp(strlen($a) . $a, strlen($b) . $b); } @@ -92,9 +96,10 @@ class PHPExcel_ReferenceHelper * @param string $b Second cell to test (e.g. 'Z1') * @return integer */ - public static function cellSort($a, $b) { - sscanf($a,'%[A-Z]%d', $ac, $ar); - sscanf($b,'%[A-Z]%d', $bc, $br); + public static function cellSort($a, $b) + { + sscanf($a, '%[A-Z]%d', $ac, $ar); + sscanf($b, '%[A-Z]%d', $bc, $br); if ($ar == $br) { return strcasecmp(strlen($ac) . $ac, strlen($bc) . $bc); @@ -110,9 +115,10 @@ class PHPExcel_ReferenceHelper * @param string $b Second cell to test (e.g. 'Z1') * @return integer */ - public static function cellReverseSort($a, $b) { - sscanf($a,'%[A-Z]%d', $ac, $ar); - sscanf($b,'%[A-Z]%d', $bc, $br); + public static function cellReverseSort($a, $b) + { + sscanf($a, '%[A-Z]%d', $ac, $ar); + sscanf($b, '%[A-Z]%d', $bc, $br); if ($ar == $br) { return 1 - strcasecmp(strlen($ac) . $ac, strlen($bc) . $bc); @@ -130,20 +136,21 @@ class PHPExcel_ReferenceHelper * @param integer $pNumCols Number of columns to insert/delete (negative values indicate deletion) * @return boolean */ - private static function cellAddressInDeleteRange($cellAddress, $beforeRow, $pNumRows, $beforeColumnIndex, $pNumCols) { + private static function cellAddressInDeleteRange($cellAddress, $beforeRow, $pNumRows, $beforeColumnIndex, $pNumCols) + { list($cellColumn, $cellRow) = PHPExcel_Cell::coordinateFromString($cellAddress); $cellColumnIndex = PHPExcel_Cell::columnIndexFromString($cellColumn); // Is cell within the range of rows/columns if we're deleting if ($pNumRows < 0 && ($cellRow >= ($beforeRow + $pNumRows)) && ($cellRow < $beforeRow)) { - return TRUE; + return true; } elseif ($pNumCols < 0 && ($cellColumnIndex >= ($beforeColumnIndex + $pNumCols)) && ($cellColumnIndex < $beforeColumnIndex)) { - return TRUE; + return true; } - return FALSE; + return false; } /** @@ -198,7 +205,7 @@ class PHPExcel_ReferenceHelper foreach ($aComments as $key => &$value) { // Any comments inside a deleted range will be ignored if (!self::cellAddressInDeleteRange($key, $beforeRow, $pNumRows, $beforeColumnIndex, $pNumCols)) { - // Otherwise build a new array of comments indexed by the adjusted cell reference + // Otherwise build a new array of comments indexed by the adjusted cell reference $newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows); $aNewComments[$newReference] = $value; } @@ -220,15 +227,13 @@ class PHPExcel_ReferenceHelper protected function _adjustHyperlinks($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows) { $aHyperlinkCollection = $pSheet->getHyperlinkCollection(); - ($pNumCols > 0 || $pNumRows > 0) ? - uksort($aHyperlinkCollection, array('PHPExcel_ReferenceHelper','cellReverseSort')) : - uksort($aHyperlinkCollection, array('PHPExcel_ReferenceHelper','cellSort')); + ($pNumCols > 0 || $pNumRows > 0) ? uksort($aHyperlinkCollection, array('PHPExcel_ReferenceHelper','cellReverseSort')) : uksort($aHyperlinkCollection, array('PHPExcel_ReferenceHelper','cellSort')); foreach ($aHyperlinkCollection as $key => $value) { $newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows); if ($key != $newReference) { - $pSheet->setHyperlink( $newReference, $value ); - $pSheet->setHyperlink( $key, null ); + $pSheet->setHyperlink($newReference, $value); + $pSheet->setHyperlink($key, null); } } } @@ -246,14 +251,13 @@ class PHPExcel_ReferenceHelper protected function _adjustDataValidations($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows) { $aDataValidationCollection = $pSheet->getDataValidationCollection(); - ($pNumCols > 0 || $pNumRows > 0) ? - uksort($aDataValidationCollection, array('PHPExcel_ReferenceHelper','cellReverseSort')) : - uksort($aDataValidationCollection, array('PHPExcel_ReferenceHelper','cellSort')); + ($pNumCols > 0 || $pNumRows > 0) ? uksort($aDataValidationCollection, array('PHPExcel_ReferenceHelper','cellReverseSort')) : uksort($aDataValidationCollection, array('PHPExcel_ReferenceHelper','cellSort')); + foreach ($aDataValidationCollection as $key => $value) { $newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows); if ($key != $newReference) { - $pSheet->setDataValidation( $newReference, $value ); - $pSheet->setDataValidation( $key, null ); + $pSheet->setDataValidation($newReference, $value); + $pSheet->setDataValidation($key, null); } } } @@ -298,8 +302,8 @@ class PHPExcel_ReferenceHelper foreach ($aProtectedCells as $key => $value) { $newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows); if ($key != $newReference) { - $pSheet->protectCells( $newReference, $value, true ); - $pSheet->unprotectCells( $key ); + $pSheet->protectCells($newReference, $value, true); + $pSheet->unprotectCells($key); } } } @@ -372,7 +376,7 @@ class PHPExcel_ReferenceHelper * @param PHPExcel_Worksheet $pSheet The worksheet that we're editing * @throws PHPExcel_Exception */ - public function insertNewBefore($pBefore = 'A1', $pNumCols = 0, $pNumRows = 0, PHPExcel_Worksheet $pSheet = NULL) + public function insertNewBefore($pBefore = 'A1', $pNumCols = 0, $pNumRows = 0, PHPExcel_Worksheet $pSheet = null) { $remove = ($pNumCols < 0 || $pNumRows < 0); $aCellCollection = $pSheet->getCellCollection(); @@ -442,8 +446,7 @@ class PHPExcel_ReferenceHelper if ($cell->getDataType() == PHPExcel_Cell_DataType::TYPE_FORMULA) { // Formula should be adjusted $pSheet->getCell($newCoordinates) - ->setValue($this->updateFormulaReferences($cell->getValue(), - $pBefore, $pNumCols, $pNumRows, $pSheet->getTitle())); + ->setValue($this->updateFormulaReferences($cell->getValue(), $pBefore, $pNumCols, $pNumRows, $pSheet->getTitle())); } else { // Formula should not be adjusted $pSheet->getCell($newCoordinates)->setValue($cell->getValue()); @@ -451,14 +454,12 @@ class PHPExcel_ReferenceHelper // Clear the original cell $pSheet->getCellCacheController()->deleteCacheData($cellID); - } else { /* We don't need to update styles for rows/columns before our insertion position, but we do still need to adjust any formulae in those cells */ if ($cell->getDataType() == PHPExcel_Cell_DataType::TYPE_FORMULA) { // Formula should be adjusted - $cell->setValue($this->updateFormulaReferences($cell->getValue(), - $pBefore, $pNumCols, $pNumRows, $pSheet->getTitle())); + $cell->setValue($this->updateFormulaReferences($cell->getValue(), $pBefore, $pNumCols, $pNumRows, $pSheet->getTitle())); } } @@ -472,7 +473,7 @@ class PHPExcel_ReferenceHelper for ($i = $beforeRow; $i <= $highestRow - 1; ++$i) { // Style - $coordinate = PHPExcel_Cell::stringFromColumnIndex( $beforeColumnIndex - 2 ) . $i; + $coordinate = PHPExcel_Cell::stringFromColumnIndex($beforeColumnIndex - 2) . $i; if ($pSheet->cellExists($coordinate)) { $xfIndex = $pSheet->getCell($coordinate)->getXfIndex(); $conditionalStyles = $pSheet->conditionalStylesExists($coordinate) ? @@ -594,17 +595,17 @@ class PHPExcel_ReferenceHelper } } } - $pSheet->setAutoFilter( $this->updateCellReference($autoFilterRange, $pBefore, $pNumCols, $pNumRows) ); + $pSheet->setAutoFilter($this->updateCellReference($autoFilterRange, $pBefore, $pNumCols, $pNumRows)); } // Update worksheet: freeze pane if ($pSheet->getFreezePane() != '') { - $pSheet->freezePane( $this->updateCellReference($pSheet->getFreezePane(), $pBefore, $pNumCols, $pNumRows) ); + $pSheet->freezePane($this->updateCellReference($pSheet->getFreezePane(), $pBefore, $pNumCols, $pNumRows)); } // Page setup if ($pSheet->getPageSetup()->isPrintAreaSet()) { - $pSheet->getPageSetup()->setPrintArea( $this->updateCellReference($pSheet->getPageSetup()->getPrintArea(), $pBefore, $pNumCols, $pNumRows) ); + $pSheet->getPageSetup()->setPrintArea($this->updateCellReference($pSheet->getPageSetup()->getPrintArea(), $pBefore, $pNumCols, $pNumRows)); } // Update worksheet: drawings @@ -620,9 +621,7 @@ class PHPExcel_ReferenceHelper if (count($pSheet->getParent()->getNamedRanges()) > 0) { foreach ($pSheet->getParent()->getNamedRanges() as $namedRange) { if ($namedRange->getWorksheet()->getHashCode() == $pSheet->getHashCode()) { - $namedRange->setRange( - $this->updateCellReference($namedRange->getRange(), $pBefore, $pNumCols, $pNumRows) - ); + $namedRange->setRange($this->updateCellReference($namedRange->getRange(), $pBefore, $pNumCols, $pNumRows)); } } } @@ -642,7 +641,8 @@ class PHPExcel_ReferenceHelper * @return string Updated formula * @throws PHPExcel_Exception */ - public function updateFormulaReferences($pFormula = '', $pBefore = 'A1', $pNumCols = 0, $pNumRows = 0, $sheetName = '') { + public function updateFormulaReferences($pFormula = '', $pBefore = 'A1', $pNumCols = 0, $pNumRows = 0, $sheetName = '') + { // Update cell references in the formula $formulaBlocks = explode('"', $pFormula); $i = false; @@ -657,8 +657,8 @@ class PHPExcel_ReferenceHelper foreach ($matches as $match) { $fromString = ($match[2] > '') ? $match[2].'!' : ''; $fromString .= $match[3].':'.$match[4]; - $modified3 = substr($this->updateCellReference('$A'.$match[3], $pBefore, $pNumCols, $pNumRows),2); - $modified4 = substr($this->updateCellReference('$A'.$match[4], $pBefore, $pNumCols, $pNumRows),2); + $modified3 = substr($this->updateCellReference('$A'.$match[3], $pBefore, $pNumCols, $pNumRows), 2); + $modified4 = substr($this->updateCellReference('$A'.$match[4], $pBefore, $pNumCols, $pNumRows), 2); if ($match[3].':'.$match[4] !== $modified3.':'.$modified4) { if (($match[2] == '') || (trim($match[2],"'") == $sheetName)) { @@ -682,8 +682,8 @@ class PHPExcel_ReferenceHelper foreach ($matches as $match) { $fromString = ($match[2] > '') ? $match[2].'!' : ''; $fromString .= $match[3].':'.$match[4]; - $modified3 = substr($this->updateCellReference($match[3].'$1', $pBefore, $pNumCols, $pNumRows),0,-2); - $modified4 = substr($this->updateCellReference($match[4].'$1', $pBefore, $pNumCols, $pNumRows),0,-2); + $modified3 = substr($this->updateCellReference($match[3].'$1', $pBefore, $pNumCols, $pNumRows), 0, -2); + $modified4 = substr($this->updateCellReference($match[4].'$1', $pBefore, $pNumCols, $pNumRows), 0, -2); if ($match[3].':'.$match[4] !== $modified3.':'.$modified4) { if (($match[2] == '') || (trim($match[2],"'") == $sheetName)) { @@ -781,7 +781,8 @@ class PHPExcel_ReferenceHelper * @return string Updated cell range * @throws PHPExcel_Exception */ - public function updateCellReference($pCellRange = 'A1', $pBefore = 'A1', $pNumCols = 0, $pNumRows = 0) { + public function updateCellReference($pCellRange = 'A1', $pBefore = 'A1', $pNumCols = 0, $pNumRows = 0) + { // Is it in another worksheet? Will not have to update anything. if (strpos($pCellRange, "!") !== false) { return $pCellRange; @@ -805,7 +806,8 @@ class PHPExcel_ReferenceHelper * @param string $oldName Old name (name to replace) * @param string $newName New name */ - public function updateNamedFormulas(PHPExcel $pPhpExcel, $oldName = '', $newName = '') { + public function updateNamedFormulas(PHPExcel $pPhpExcel, $oldName = '', $newName = '') + { if ($oldName == '') { return; } @@ -813,7 +815,7 @@ class PHPExcel_ReferenceHelper foreach ($pPhpExcel->getWorksheetIterator() as $sheet) { foreach ($sheet->getCellCollection(false) as $cellID) { $cell = $sheet->getCell($cellID); - if (($cell !== NULL) && ($cell->getDataType() == PHPExcel_Cell_DataType::TYPE_FORMULA)) { + if (($cell !== null) && ($cell->getDataType() == PHPExcel_Cell_DataType::TYPE_FORMULA)) { $formula = $cell->getValue(); if (strpos($formula, $oldName) !== false) { $formula = str_replace("'" . $oldName . "'!", "'" . $newName . "'!", $formula); @@ -835,7 +837,8 @@ class PHPExcel_ReferenceHelper * @return string Updated cell range * @throws PHPExcel_Exception */ - private function _updateCellRange($pCellRange = 'A1:A1', $pBefore = 'A1', $pNumCols = 0, $pNumRows = 0) { + private function _updateCellRange($pCellRange = 'A1:A1', $pBefore = 'A1', $pNumCols = 0, $pNumRows = 0) + { if (strpos($pCellRange,':') !== false || strpos($pCellRange, ',') !== false) { // Update range $range = PHPExcel_Cell::splitRange($pCellRange); @@ -872,23 +875,22 @@ class PHPExcel_ReferenceHelper * @return string Updated cell reference * @throws PHPExcel_Exception */ - private function _updateSingleCellReference($pCellReference = 'A1', $pBefore = 'A1', $pNumCols = 0, $pNumRows = 0) { + private function _updateSingleCellReference($pCellReference = 'A1', $pBefore = 'A1', $pNumCols = 0, $pNumRows = 0) + { if (strpos($pCellReference, ':') === false && strpos($pCellReference, ',') === false) { // Get coordinates of $pBefore - list($beforeColumn, $beforeRow) = PHPExcel_Cell::coordinateFromString( $pBefore ); + list($beforeColumn, $beforeRow) = PHPExcel_Cell::coordinateFromString($pBefore); // Get coordinates of $pCellReference - list($newColumn, $newRow) = PHPExcel_Cell::coordinateFromString( $pCellReference ); + list($newColumn, $newRow) = PHPExcel_Cell::coordinateFromString($pCellReference); // Verify which parts should be updated - $updateColumn = (($newColumn{0} != '$') && ($beforeColumn{0} != '$') && - PHPExcel_Cell::columnIndexFromString($newColumn) >= PHPExcel_Cell::columnIndexFromString($beforeColumn)); - $updateRow = (($newRow{0} != '$') && ($beforeRow{0} != '$') && - $newRow >= $beforeRow); + $updateColumn = (($newColumn{0} != '$') && ($beforeColumn{0} != '$') && (PHPExcel_Cell::columnIndexFromString($newColumn) >= PHPExcel_Cell::columnIndexFromString($beforeColumn))); + $updateRow = (($newRow{0} != '$') && ($beforeRow{0} != '$') && $newRow >= $beforeRow); // Create new column reference if ($updateColumn) { - $newColumn = PHPExcel_Cell::stringFromColumnIndex( PHPExcel_Cell::columnIndexFromString($newColumn) - 1 + $pNumCols ); + $newColumn = PHPExcel_Cell::stringFromColumnIndex(PHPExcel_Cell::columnIndexFromString($newColumn) - 1 + $pNumCols); } // Create new row reference @@ -908,7 +910,8 @@ class PHPExcel_ReferenceHelper * * @throws PHPExcel_Exception */ - public final function __clone() { + final public function __clone() + { throw new PHPExcel_Exception("Cloning a Singleton is not allowed!"); } } diff --git a/Classes/PHPExcel/Shared/Drawing.php b/Classes/PHPExcel/Shared/Drawing.php index 90d0911b..4125815d 100644 --- a/Classes/PHPExcel/Shared/Drawing.php +++ b/Classes/PHPExcel/Shared/Drawing.php @@ -41,7 +41,8 @@ class PHPExcel_Shared_Drawing * @param int $pValue Value in pixels * @return int Value in EMU */ - public static function pixelsToEMU($pValue = 0) { + public static function pixelsToEMU($pValue = 0) + { return round($pValue * 9525); } @@ -51,7 +52,8 @@ class PHPExcel_Shared_Drawing * @param int $pValue Value in EMU * @return int Value in pixels */ - public static function EMUToPixels($pValue = 0) { + public static function EMUToPixels($pValue = 0) + { if ($pValue != 0) { return round($pValue / 9525); } else { @@ -68,22 +70,19 @@ class PHPExcel_Shared_Drawing * @param PHPExcel_Style_Font $pDefaultFont Default font of the workbook * @return int Value in cell dimension */ - public static function pixelsToCellDimension($pValue = 0, PHPExcel_Style_Font $pDefaultFont) { + public static function pixelsToCellDimension($pValue = 0, PHPExcel_Style_Font $pDefaultFont) + { // Font name and size $name = $pDefaultFont->getName(); $size = $pDefaultFont->getSize(); if (isset(PHPExcel_Shared_Font::$defaultColumnWidths[$name][$size])) { // Exact width can be determined - $colWidth = $pValue - * PHPExcel_Shared_Font::$defaultColumnWidths[$name][$size]['width'] - / PHPExcel_Shared_Font::$defaultColumnWidths[$name][$size]['px']; + $colWidth = $pValue * PHPExcel_Shared_Font::$defaultColumnWidths[$name][$size]['width'] / PHPExcel_Shared_Font::$defaultColumnWidths[$name][$size]['px']; } else { // We don't have data for this particular font and size, use approximation by // extrapolating from Calibri 11 - $colWidth = $pValue * 11 - * PHPExcel_Shared_Font::$defaultColumnWidths['Calibri'][11]['width'] - / PHPExcel_Shared_Font::$defaultColumnWidths['Calibri'][11]['px'] / $size; + $colWidth = $pValue * 11 * PHPExcel_Shared_Font::$defaultColumnWidths['Calibri'][11]['width'] / PHPExcel_Shared_Font::$defaultColumnWidths['Calibri'][11]['px'] / $size; } return $colWidth; @@ -96,23 +95,19 @@ class PHPExcel_Shared_Drawing * @param PHPExcel_Style_Font $pDefaultFont Default font of the workbook * @return int Value in pixels */ - public static function cellDimensionToPixels($pValue = 0, PHPExcel_Style_Font $pDefaultFont) { + public static function cellDimensionToPixels($pValue = 0, PHPExcel_Style_Font $pDefaultFont) + { // Font name and size $name = $pDefaultFont->getName(); $size = $pDefaultFont->getSize(); if (isset(PHPExcel_Shared_Font::$defaultColumnWidths[$name][$size])) { // Exact width can be determined - $colWidth = $pValue - * PHPExcel_Shared_Font::$defaultColumnWidths[$name][$size]['px'] - / PHPExcel_Shared_Font::$defaultColumnWidths[$name][$size]['width']; - + $colWidth = $pValue * PHPExcel_Shared_Font::$defaultColumnWidths[$name][$size]['px'] / PHPExcel_Shared_Font::$defaultColumnWidths[$name][$size]['width']; } else { // We don't have data for this particular font and size, use approximation by // extrapolating from Calibri 11 - $colWidth = $pValue * $size - * PHPExcel_Shared_Font::$defaultColumnWidths['Calibri'][11]['px'] - / PHPExcel_Shared_Font::$defaultColumnWidths['Calibri'][11]['width'] / 11; + $colWidth = $pValue * $size * PHPExcel_Shared_Font::$defaultColumnWidths['Calibri'][11]['px'] / PHPExcel_Shared_Font::$defaultColumnWidths['Calibri'][11]['width'] / 11; } // Round pixels to closest integer @@ -127,7 +122,8 @@ class PHPExcel_Shared_Drawing * @param int $pValue Value in pixels * @return int Value in points */ - public static function pixelsToPoints($pValue = 0) { + public static function pixelsToPoints($pValue = 0) + { return $pValue * 0.67777777; } @@ -137,7 +133,8 @@ class PHPExcel_Shared_Drawing * @param int $pValue Value in points * @return int Value in pixels */ - public static function pointsToPixels($pValue = 0) { + public static function pointsToPixels($pValue = 0) + { if ($pValue != 0) { return (int) ceil($pValue * 1.333333333); } else { @@ -151,7 +148,8 @@ class PHPExcel_Shared_Drawing * @param int $pValue Degrees * @return int Angle */ - public static function degreesToAngle($pValue = 0) { + public static function degreesToAngle($pValue = 0) + { return (int)round($pValue * 60000); } @@ -161,7 +159,8 @@ class PHPExcel_Shared_Drawing * @param int $pValue Angle * @return int Degrees */ - public static function angleToDegrees($pValue = 0) { + public static function angleToDegrees($pValue = 0) + { if ($pValue != 0) { return round($pValue / 60000); } else { @@ -179,94 +178,93 @@ class PHPExcel_Shared_Drawing public static function imagecreatefrombmp($p_sFile) { // Load the image into a string - $file = fopen($p_sFile,"rb"); - $read = fread($file,10); - while (!feof($file)&&($read<>"")) - $read .= fread($file,1024); + $file = fopen($p_sFile, "rb"); + $read = fread($file, 10); + while (!feof($file) && ($read<>"")) { + $read .= fread($file, 1024); + } - $temp = unpack("H*", $read); - $hex = $temp[1]; - $header = substr($hex,0,108); + $temp = unpack("H*", $read); + $hex = $temp[1]; + $header = substr($hex, 0, 108); // Process the header // Structure: http://www.fastgraph.com/help/bmp_header_format.html - if (substr($header,0,4)=="424d") - { + if (substr($header, 0, 4)=="424d") { // Cut it in parts of 2 bytes - $header_parts = str_split($header,2); + $header_parts = str_split($header, 2); // Get the width 4 bytes - $width = hexdec($header_parts[19].$header_parts[18]); + $width = hexdec($header_parts[19].$header_parts[18]); // Get the height 4 bytes - $height = hexdec($header_parts[23].$header_parts[22]); + $height = hexdec($header_parts[23].$header_parts[22]); // Unset the header params unset($header_parts); } // Define starting X and Y - $x = 0; - $y = 1; + $x = 0; + $y = 1; // Create newimage - $image = imagecreatetruecolor($width, $height); + $image = imagecreatetruecolor($width, $height); // Grab the body from the image - $body = substr($hex,108); + $body = substr($hex, 108); // Calculate if padding at the end-line is needed // Divided by two to keep overview. // 1 byte = 2 HEX-chars - $body_size = (strlen($body)/2); - $header_size = ($width*$height); + $body_size = (strlen($body)/2); + $header_size = ($width*$height); // Use end-line padding? Only when needed - $usePadding = ($body_size>($header_size*3)+4); + $usePadding = ($body_size>($header_size*3)+4); // Using a for-loop with index-calculation instaid of str_split to avoid large memory consumption // Calculate the next DWORD-position in the body - for ($i=0;$i<$body_size;$i+=3) - { + for ($i = 0 ; $i < $body_size ; $i += 3) { // Calculate line-ending and padding - if ($x>=$width) - { - // If padding needed, ignore image-padding - // Shift i to the ending of the current 32-bit-block - if ($usePadding) - $i += $width%4; + if ($x >= $width) { + // If padding needed, ignore image-padding + // Shift i to the ending of the current 32-bit-block + if ($usePadding) { + $i += $width%4; + } // Reset horizontal position - $x = 0; + $x = 0; // Raise the height-position (bottom-up) $y++; // Reached the image-height? Break the for-loop - if ($y>$height) + if ($y > $height) { break; + } } - // Calculation of the RGB-pixel (defined as BGR in image-data) - // Define $i_pos as absolute position in the body - $i_pos = $i*2; - $r = hexdec($body[$i_pos+4].$body[$i_pos+5]); - $g = hexdec($body[$i_pos+2].$body[$i_pos+3]); - $b = hexdec($body[$i_pos].$body[$i_pos+1]); + // Calculation of the RGB-pixel (defined as BGR in image-data) + // Define $i_pos as absolute position in the body + $i_pos = $i * 2; + $r = hexdec($body[$i_pos+4].$body[$i_pos+5]); + $g = hexdec($body[$i_pos+2].$body[$i_pos+3]); + $b = hexdec($body[$i_pos].$body[$i_pos+1]); - // Calculate and draw the pixel - $color = imagecolorallocate($image, $r, $g, $b); + // Calculate and draw the pixel + $color = imagecolorallocate($image, $r, $g, $b); imagesetpixel($image, $x, $height-$y, $color); - // Raise the horizontal position + // Raise the horizontal position $x++; } - // Unset the body / free the memory + // Unset the body / free the memory unset($body); // Return image-object return $image; } - } diff --git a/Classes/PHPExcel/Shared/Escher.php b/Classes/PHPExcel/Shared/Escher.php index 67b346ee..948d409b 100644 --- a/Classes/PHPExcel/Shared/Escher.php +++ b/Classes/PHPExcel/Shared/Escher.php @@ -87,5 +87,4 @@ class PHPExcel_Shared_Escher { return $this->_dgContainer = $dgContainer; } - } diff --git a/Classes/PHPExcel/Shared/File.php b/Classes/PHPExcel/Shared/File.php index f1de3242..e2af00ee 100644 --- a/Classes/PHPExcel/Shared/File.php +++ b/Classes/PHPExcel/Shared/File.php @@ -41,7 +41,7 @@ class PHPExcel_Shared_File * @protected * @var boolean */ - protected static $_useUploadTempDirectory = FALSE; + protected static $_useUploadTempDirectory = false; /** @@ -49,9 +49,10 @@ class PHPExcel_Shared_File * * @param boolean $useUploadTempDir Use File Upload Temporary directory (true or false) */ - public static function setUseUploadTempDirectory($useUploadTempDir = FALSE) { + public static function setUseUploadTempDirectory($useUploadTempDir = false) + { self::$_useUploadTempDirectory = (boolean) $useUploadTempDir; - } // function setUseUploadTempDirectory() + } /** @@ -59,9 +60,10 @@ class PHPExcel_Shared_File * * @return boolean Use File Upload Temporary directory (true or false) */ - public static function getUseUploadTempDirectory() { + public static function getUseUploadTempDirectory() + { return self::$_useUploadTempDirectory; - } // function getUseUploadTempDirectory() + } /** @@ -70,11 +72,12 @@ class PHPExcel_Shared_File * @param string $pFilename Filename * @return bool */ - public static function file_exists($pFilename) { + public static function file_exists($pFilename) + { // Sick construction, but it seems that // file_exists returns strange values when // doing the original file_exists on ZIP archives... - if ( strtolower(substr($pFilename, 0, 3)) == 'zip' ) { + if (strtolower(substr($pFilename, 0, 3)) == 'zip') { // Open ZIP file and verify if the file exists $zipFile = substr($pFilename, 6, strpos($pFilename, '#') - 6); $archiveFile = substr($pFilename, strpos($pFilename, '#') + 1); @@ -99,7 +102,8 @@ class PHPExcel_Shared_File * @param string $pFilename * @return string */ - public static function realpath($pFilename) { + public static function realpath($pFilename) + { // Returnvalue $returnValue = ''; @@ -109,8 +113,8 @@ class PHPExcel_Shared_File } // Found something? - if ($returnValue == '' || ($returnValue === NULL)) { - $pathArray = explode('/' , $pFilename); + if ($returnValue == '' || ($returnValue === null)) { + $pathArray = explode('/', $pFilename); while (in_array('..', $pathArray) && $pathArray[0] != '..') { for ($i = 0; $i < count($pathArray); ++$i) { if ($pathArray[$i] == '..' && $i > 0) { @@ -137,10 +141,11 @@ class PHPExcel_Shared_File if (self::$_useUploadTempDirectory) { // use upload-directory when defined to allow running on environments having very restricted // open_basedir configs - if (ini_get('upload_tmp_dir') !== FALSE) { + if (ini_get('upload_tmp_dir') !== false) { if ($temp = ini_get('upload_tmp_dir')) { - if (file_exists($temp)) + if (file_exists($temp)) { return realpath($temp); + } } } } @@ -149,13 +154,19 @@ class PHPExcel_Shared_File // http://php.net/manual/en/function.sys-get-temp-dir.php#94119 if ( !function_exists('sys_get_temp_dir')) { if ($temp = getenv('TMP') ) { - if ((!empty($temp)) && (file_exists($temp))) { return realpath($temp); } + if ((!empty($temp)) && (file_exists($temp))) { + return realpath($temp); + } } if ($temp = getenv('TEMP') ) { - if ((!empty($temp)) && (file_exists($temp))) { return realpath($temp); } + if ((!empty($temp)) && (file_exists($temp))) { + return realpath($temp); + } } if ($temp = getenv('TMPDIR') ) { - if ((!empty($temp)) && (file_exists($temp))) { return realpath($temp); } + if ((!empty($temp)) && (file_exists($temp))) { + return realpath($temp); + } } // trick for creating a file in system's temporary dir @@ -174,5 +185,4 @@ class PHPExcel_Shared_File // be called if we're running 5.2.1 or earlier return realpath(sys_get_temp_dir()); } - } diff --git a/Classes/PHPExcel/Shared/OLE.php b/Classes/PHPExcel/Shared/OLE.php index 581e96bb..42a3c529 100644 --- a/Classes/PHPExcel/Shared/OLE.php +++ b/Classes/PHPExcel/Shared/OLE.php @@ -159,7 +159,7 @@ class PHPExcel_Shared_OLE for ($i = 0; $i < $bbatBlockCount; ++$i) { $pos = $this->_getBlockOffset($mbatBlocks[$i]); fseek($fh, $pos); - for ($j = 0 ; $j < $this->bigBlockSize / 4; ++$j) { + for ($j = 0; $j < $this->bigBlockSize / 4; ++$j) { $this->bbat[] = self::_readInt4($fh); } } @@ -198,8 +198,7 @@ class PHPExcel_Shared_OLE { static $isRegistered = false; if (!$isRegistered) { - stream_wrapper_register('ole-chainedblockstream', - 'PHPExcel_Shared_OLE_ChainedBlockStream'); + stream_wrapper_register('ole-chainedblockstream', 'PHPExcel_Shared_OLE_ChainedBlockStream'); $isRegistered = true; } @@ -266,7 +265,7 @@ class PHPExcel_Shared_OLE public function _readPpsWks($blockId) { $fh = $this->getStream($blockId); - for ($pos = 0; ; $pos += 128) { + for ($pos = 0;; $pos += 128) { fseek($fh, $pos, SEEK_SET); $nameUtf16 = fread($fh, 64); $nameLength = self::_readInt2($fh); @@ -275,19 +274,18 @@ class PHPExcel_Shared_OLE $name = str_replace("\x00", "", $nameUtf16); $type = self::_readInt1($fh); switch ($type) { - case self::OLE_PPS_TYPE_ROOT: - $pps = new PHPExcel_Shared_OLE_PPS_Root(null, null, array()); - $this->root = $pps; - break; - case self::OLE_PPS_TYPE_DIR: - $pps = new PHPExcel_Shared_OLE_PPS(null, null, null, null, null, - null, null, null, null, array()); - break; - case self::OLE_PPS_TYPE_FILE: - $pps = new PHPExcel_Shared_OLE_PPS_File($name); - break; - default: - continue; + case self::OLE_PPS_TYPE_ROOT: + $pps = new PHPExcel_Shared_OLE_PPS_Root(null, null, array()); + $this->root = $pps; + break; + case self::OLE_PPS_TYPE_DIR: + $pps = new PHPExcel_Shared_OLE_PPS(null, null, null, null, null, null, null, null, null, array()); + break; + case self::OLE_PPS_TYPE_FILE: + $pps = new PHPExcel_Shared_OLE_PPS_File($name); + break; + default: + continue; } fseek($fh, 1, SEEK_CUR); $pps->Type = $type; @@ -304,9 +302,7 @@ class PHPExcel_Shared_OLE $this->_list[] = $pps; // check if the PPS tree (starting from root) is complete - if (isset($this->root) && - $this->_ppsTreeComplete($this->root->No)) { - + if (isset($this->root) && $this->_ppsTreeComplete($this->root->No)) { break; } } @@ -473,8 +469,7 @@ class PHPExcel_Shared_OLE // days from 1-1-1601 until the beggining of UNIX era $days = 134774; // calculate seconds - $big_date = $days*24*3600 + gmmktime(date("H", $date),date("i", $date),date("s", $date), - date("m", $date),date("d", $date),date("Y", $date)); + $big_date = $days*24*3600 + gmmktime(date("H", $date), date("i", $date), date("s", $date), date("m", $date), date("d", $date), date("Y", $date)); // multiply just to make MS happy $big_date *= 10000000; @@ -513,7 +508,7 @@ class PHPExcel_Shared_OLE } // factor used for separating numbers into 4 bytes parts - $factor = pow(2,32); + $factor = pow(2, 32); list(, $high_part) = unpack('V', substr($string, 4, 4)); list(, $low_part) = unpack('V', substr($string, 0, 4)); diff --git a/Classes/PHPExcel/Shared/PCLZip/pclzip.lib.php b/Classes/PHPExcel/Shared/PCLZip/pclzip.lib.php index 36cc902b..effb8dd7 100644 --- a/Classes/PHPExcel/Shared/PCLZip/pclzip.lib.php +++ b/Classes/PHPExcel/Shared/PCLZip/pclzip.lib.php @@ -25,170 +25,170 @@ // $Id: pclzip.lib.php,v 1.60 2009/09/30 21:01:04 vblavet Exp $ // -------------------------------------------------------------------------------- - // ----- Constants - if (!defined('PCLZIP_READ_BLOCK_SIZE')) { - define( 'PCLZIP_READ_BLOCK_SIZE', 2048 ); - } - - // ----- File list separator - // In version 1.x of PclZip, the separator for file list is a space - // (which is not a very smart choice, specifically for windows paths !). - // A better separator should be a comma (,). This constant gives you the - // abilty to change that. - // However notice that changing this value, may have impact on existing - // scripts, using space separated filenames. - // Recommanded values for compatibility with older versions : - //define( 'PCLZIP_SEPARATOR', ' ' ); - // Recommanded values for smart separation of filenames. - if (!defined('PCLZIP_SEPARATOR')) { - define( 'PCLZIP_SEPARATOR', ',' ); - } +// ----- Constants +if (!defined('PCLZIP_READ_BLOCK_SIZE')) { + define('PCLZIP_READ_BLOCK_SIZE', 2048); +} - // ----- Error configuration - // 0 : PclZip Class integrated error handling - // 1 : PclError external library error handling. By enabling this - // you must ensure that you have included PclError library. - // [2,...] : reserved for futur use - if (!defined('PCLZIP_ERROR_EXTERNAL')) { - define( 'PCLZIP_ERROR_EXTERNAL', 0 ); - } +// ----- File list separator +// In version 1.x of PclZip, the separator for file list is a space +// (which is not a very smart choice, specifically for windows paths !). +// A better separator should be a comma (,). This constant gives you the +// abilty to change that. +// However notice that changing this value, may have impact on existing +// scripts, using space separated filenames. +// Recommanded values for compatibility with older versions : +//define('PCLZIP_SEPARATOR', ' '); +// Recommanded values for smart separation of filenames. +if (!defined('PCLZIP_SEPARATOR')) { + define('PCLZIP_SEPARATOR', ','); +} - // ----- Optional static temporary directory - // By default temporary files are generated in the script current - // path. - // If defined : - // - MUST BE terminated by a '/'. - // - MUST be a valid, already created directory - // Samples : - // define( 'PCLZIP_TEMPORARY_DIR', '/temp/' ); - // define( 'PCLZIP_TEMPORARY_DIR', 'C:/Temp/' ); - if (!defined('PCLZIP_TEMPORARY_DIR')) { - define( 'PCLZIP_TEMPORARY_DIR', '' ); - } +// ----- Error configuration +// 0 : PclZip Class integrated error handling +// 1 : PclError external library error handling. By enabling this +// you must ensure that you have included PclError library. +// [2,...] : reserved for futur use +if (!defined('PCLZIP_ERROR_EXTERNAL')) { + define('PCLZIP_ERROR_EXTERNAL', 0); +} - // ----- Optional threshold ratio for use of temporary files - // Pclzip sense the size of the file to add/extract and decide to - // use or not temporary file. The algorythm is looking for - // memory_limit of PHP and apply a ratio. - // threshold = memory_limit * ratio. - // Recommended values are under 0.5. Default 0.47. - // Samples : - // define( 'PCLZIP_TEMPORARY_FILE_RATIO', 0.5 ); - if (!defined('PCLZIP_TEMPORARY_FILE_RATIO')) { - define( 'PCLZIP_TEMPORARY_FILE_RATIO', 0.47 ); - } +// ----- Optional static temporary directory +// By default temporary files are generated in the script current +// path. +// If defined : +// - MUST BE terminated by a '/'. +// - MUST be a valid, already created directory +// Samples : +// define('PCLZIP_TEMPORARY_DIR', '/temp/'); +// define('PCLZIP_TEMPORARY_DIR', 'C:/Temp/'); +if (!defined('PCLZIP_TEMPORARY_DIR')) { + define('PCLZIP_TEMPORARY_DIR', ''); +} + +// ----- Optional threshold ratio for use of temporary files +// Pclzip sense the size of the file to add/extract and decide to +// use or not temporary file. The algorythm is looking for +// memory_limit of PHP and apply a ratio. +// threshold = memory_limit * ratio. +// Recommended values are under 0.5. Default 0.47. +// Samples : +// define('PCLZIP_TEMPORARY_FILE_RATIO', 0.5); +if (!defined('PCLZIP_TEMPORARY_FILE_RATIO')) { + define('PCLZIP_TEMPORARY_FILE_RATIO', 0.47); +} // -------------------------------------------------------------------------------- // ***** UNDER THIS LINE NOTHING NEEDS TO BE MODIFIED ***** // -------------------------------------------------------------------------------- - // ----- Global variables - $g_pclzip_version = "2.8.2"; +// ----- Global variables +$g_pclzip_version = "2.8.2"; - // ----- Error codes - // -1 : Unable to open file in binary write mode - // -2 : Unable to open file in binary read mode - // -3 : Invalid parameters - // -4 : File does not exist - // -5 : Filename is too long (max. 255) - // -6 : Not a valid zip file - // -7 : Invalid extracted file size - // -8 : Unable to create directory - // -9 : Invalid archive extension - // -10 : Invalid archive format - // -11 : Unable to delete file (unlink) - // -12 : Unable to rename file (rename) - // -13 : Invalid header checksum - // -14 : Invalid archive size - define( 'PCLZIP_ERR_USER_ABORTED', 2 ); - define( 'PCLZIP_ERR_NO_ERROR', 0 ); - define( 'PCLZIP_ERR_WRITE_OPEN_FAIL', -1 ); - define( 'PCLZIP_ERR_READ_OPEN_FAIL', -2 ); - define( 'PCLZIP_ERR_INVALID_PARAMETER', -3 ); - define( 'PCLZIP_ERR_MISSING_FILE', -4 ); - define( 'PCLZIP_ERR_FILENAME_TOO_LONG', -5 ); - define( 'PCLZIP_ERR_INVALID_ZIP', -6 ); - define( 'PCLZIP_ERR_BAD_EXTRACTED_FILE', -7 ); - define( 'PCLZIP_ERR_DIR_CREATE_FAIL', -8 ); - define( 'PCLZIP_ERR_BAD_EXTENSION', -9 ); - define( 'PCLZIP_ERR_BAD_FORMAT', -10 ); - define( 'PCLZIP_ERR_DELETE_FILE_FAIL', -11 ); - define( 'PCLZIP_ERR_RENAME_FILE_FAIL', -12 ); - define( 'PCLZIP_ERR_BAD_CHECKSUM', -13 ); - define( 'PCLZIP_ERR_INVALID_ARCHIVE_ZIP', -14 ); - define( 'PCLZIP_ERR_MISSING_OPTION_VALUE', -15 ); - define( 'PCLZIP_ERR_INVALID_OPTION_VALUE', -16 ); - define( 'PCLZIP_ERR_ALREADY_A_DIRECTORY', -17 ); - define( 'PCLZIP_ERR_UNSUPPORTED_COMPRESSION', -18 ); - define( 'PCLZIP_ERR_UNSUPPORTED_ENCRYPTION', -19 ); - define( 'PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE', -20 ); - define( 'PCLZIP_ERR_DIRECTORY_RESTRICTION', -21 ); +// ----- Error codes +// -1 : Unable to open file in binary write mode +// -2 : Unable to open file in binary read mode +// -3 : Invalid parameters +// -4 : File does not exist +// -5 : Filename is too long (max. 255) +// -6 : Not a valid zip file +// -7 : Invalid extracted file size +// -8 : Unable to create directory +// -9 : Invalid archive extension +// -10 : Invalid archive format +// -11 : Unable to delete file (unlink) +// -12 : Unable to rename file (rename) +// -13 : Invalid header checksum +// -14 : Invalid archive size +define('PCLZIP_ERR_USER_ABORTED', 2); +define('PCLZIP_ERR_NO_ERROR', 0); +define('PCLZIP_ERR_WRITE_OPEN_FAIL', -1); +define('PCLZIP_ERR_READ_OPEN_FAIL', -2); +define('PCLZIP_ERR_INVALID_PARAMETER', -3); +define('PCLZIP_ERR_MISSING_FILE', -4); +define('PCLZIP_ERR_FILENAME_TOO_LONG', -5); +define('PCLZIP_ERR_INVALID_ZIP', -6); +define('PCLZIP_ERR_BAD_EXTRACTED_FILE', -7); +define('PCLZIP_ERR_DIR_CREATE_FAIL', -8); +define('PCLZIP_ERR_BAD_EXTENSION', -9); +define('PCLZIP_ERR_BAD_FORMAT', -10); +define('PCLZIP_ERR_DELETE_FILE_FAIL', -11); +define('PCLZIP_ERR_RENAME_FILE_FAIL', -12); +define('PCLZIP_ERR_BAD_CHECKSUM', -13); +define('PCLZIP_ERR_INVALID_ARCHIVE_ZIP', -14); +define('PCLZIP_ERR_MISSING_OPTION_VALUE', -15); +define('PCLZIP_ERR_INVALID_OPTION_VALUE', -16); +define('PCLZIP_ERR_ALREADY_A_DIRECTORY', -17); +define('PCLZIP_ERR_UNSUPPORTED_COMPRESSION', -18); +define('PCLZIP_ERR_UNSUPPORTED_ENCRYPTION', -19); +define('PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE', -20); +define('PCLZIP_ERR_DIRECTORY_RESTRICTION', -21); - // ----- Options values - define( 'PCLZIP_OPT_PATH', 77001 ); - define( 'PCLZIP_OPT_ADD_PATH', 77002 ); - define( 'PCLZIP_OPT_REMOVE_PATH', 77003 ); - define( 'PCLZIP_OPT_REMOVE_ALL_PATH', 77004 ); - define( 'PCLZIP_OPT_SET_CHMOD', 77005 ); - define( 'PCLZIP_OPT_EXTRACT_AS_STRING', 77006 ); - define( 'PCLZIP_OPT_NO_COMPRESSION', 77007 ); - define( 'PCLZIP_OPT_BY_NAME', 77008 ); - define( 'PCLZIP_OPT_BY_INDEX', 77009 ); - define( 'PCLZIP_OPT_BY_EREG', 77010 ); - define( 'PCLZIP_OPT_BY_PREG', 77011 ); - define( 'PCLZIP_OPT_COMMENT', 77012 ); - define( 'PCLZIP_OPT_ADD_COMMENT', 77013 ); - define( 'PCLZIP_OPT_PREPEND_COMMENT', 77014 ); - define( 'PCLZIP_OPT_EXTRACT_IN_OUTPUT', 77015 ); - define( 'PCLZIP_OPT_REPLACE_NEWER', 77016 ); - define( 'PCLZIP_OPT_STOP_ON_ERROR', 77017 ); - // Having big trouble with crypt. Need to multiply 2 long int - // which is not correctly supported by PHP ... - //define( 'PCLZIP_OPT_CRYPT', 77018 ); - define( 'PCLZIP_OPT_EXTRACT_DIR_RESTRICTION', 77019 ); - define( 'PCLZIP_OPT_TEMP_FILE_THRESHOLD', 77020 ); - define( 'PCLZIP_OPT_ADD_TEMP_FILE_THRESHOLD', 77020 ); // alias - define( 'PCLZIP_OPT_TEMP_FILE_ON', 77021 ); - define( 'PCLZIP_OPT_ADD_TEMP_FILE_ON', 77021 ); // alias - define( 'PCLZIP_OPT_TEMP_FILE_OFF', 77022 ); - define( 'PCLZIP_OPT_ADD_TEMP_FILE_OFF', 77022 ); // alias - - // ----- File description attributes - define( 'PCLZIP_ATT_FILE_NAME', 79001 ); - define( 'PCLZIP_ATT_FILE_NEW_SHORT_NAME', 79002 ); - define( 'PCLZIP_ATT_FILE_NEW_FULL_NAME', 79003 ); - define( 'PCLZIP_ATT_FILE_MTIME', 79004 ); - define( 'PCLZIP_ATT_FILE_CONTENT', 79005 ); - define( 'PCLZIP_ATT_FILE_COMMENT', 79006 ); +// ----- Options values +define('PCLZIP_OPT_PATH', 77001); +define('PCLZIP_OPT_ADD_PATH', 77002); +define('PCLZIP_OPT_REMOVE_PATH', 77003); +define('PCLZIP_OPT_REMOVE_ALL_PATH', 77004); +define('PCLZIP_OPT_SET_CHMOD', 77005); +define('PCLZIP_OPT_EXTRACT_AS_STRING', 77006); +define('PCLZIP_OPT_NO_COMPRESSION', 77007); +define('PCLZIP_OPT_BY_NAME', 77008); +define('PCLZIP_OPT_BY_INDEX', 77009); +define('PCLZIP_OPT_BY_EREG', 77010); +define('PCLZIP_OPT_BY_PREG', 77011); +define('PCLZIP_OPT_COMMENT', 77012); +define('PCLZIP_OPT_ADD_COMMENT', 77013); +define('PCLZIP_OPT_PREPEND_COMMENT', 77014); +define('PCLZIP_OPT_EXTRACT_IN_OUTPUT', 77015); +define('PCLZIP_OPT_REPLACE_NEWER', 77016); +define('PCLZIP_OPT_STOP_ON_ERROR', 77017); +// Having big trouble with crypt. Need to multiply 2 long int +// which is not correctly supported by PHP ... +//define('PCLZIP_OPT_CRYPT', 77018); +define('PCLZIP_OPT_EXTRACT_DIR_RESTRICTION', 77019); +define('PCLZIP_OPT_TEMP_FILE_THRESHOLD', 77020); +define('PCLZIP_OPT_ADD_TEMP_FILE_THRESHOLD', 77020); // alias +define('PCLZIP_OPT_TEMP_FILE_ON', 77021); +define('PCLZIP_OPT_ADD_TEMP_FILE_ON', 77021); // alias +define('PCLZIP_OPT_TEMP_FILE_OFF', 77022); +define('PCLZIP_OPT_ADD_TEMP_FILE_OFF', 77022); // alias - // ----- Call backs values - define( 'PCLZIP_CB_PRE_EXTRACT', 78001 ); - define( 'PCLZIP_CB_POST_EXTRACT', 78002 ); - define( 'PCLZIP_CB_PRE_ADD', 78003 ); - define( 'PCLZIP_CB_POST_ADD', 78004 ); - /* For futur use - define( 'PCLZIP_CB_PRE_LIST', 78005 ); - define( 'PCLZIP_CB_POST_LIST', 78006 ); - define( 'PCLZIP_CB_PRE_DELETE', 78007 ); - define( 'PCLZIP_CB_POST_DELETE', 78008 ); - */ +// ----- File description attributes +define('PCLZIP_ATT_FILE_NAME', 79001); +define('PCLZIP_ATT_FILE_NEW_SHORT_NAME', 79002); +define('PCLZIP_ATT_FILE_NEW_FULL_NAME', 79003); +define('PCLZIP_ATT_FILE_MTIME', 79004); +define('PCLZIP_ATT_FILE_CONTENT', 79005); +define('PCLZIP_ATT_FILE_COMMENT', 79006); - // -------------------------------------------------------------------------------- - // Class : PclZip - // Description : - // PclZip is the class that represent a Zip archive. - // The public methods allow the manipulation of the archive. - // Attributes : - // Attributes must not be accessed directly. - // Methods : - // PclZip() : Object creator - // create() : Creates the Zip archive - // listContent() : List the content of the Zip archive - // extract() : Extract the content of the archive - // properties() : List the properties of the archive - // -------------------------------------------------------------------------------- - class PclZip - { +// ----- Call backs values +define('PCLZIP_CB_PRE_EXTRACT', 78001); +define('PCLZIP_CB_POST_EXTRACT', 78002); +define('PCLZIP_CB_PRE_ADD', 78003); +define('PCLZIP_CB_POST_ADD', 78004); +/* For futur use +define('PCLZIP_CB_PRE_LIST', 78005); +define('PCLZIP_CB_POST_LIST', 78006); +define('PCLZIP_CB_PRE_DELETE', 78007); +define('PCLZIP_CB_POST_DELETE', 78008); +*/ + +// -------------------------------------------------------------------------------- +// Class : PclZip +// Description : +// PclZip is the class that represent a Zip archive. +// The public methods allow the manipulation of the archive. +// Attributes : +// Attributes must not be accessed directly. +// Methods : +// PclZip() : Object creator +// create() : Creates the Zip archive +// listContent() : List the content of the Zip archive +// extract() : Extract the content of the archive +// properties() : List the properties of the archive +// -------------------------------------------------------------------------------- +class PclZip +{ // ----- Filename of the zip file var $zipname = ''; @@ -198,1154 +198,1101 @@ // ----- Internal error handling var $error_code = 1; var $error_string = ''; - + // ----- Current status of the magic_quotes_runtime // This value store the php configuration for magic_quotes // The class can then disable the magic_quotes and reset it after var $magic_quotes_status; - // -------------------------------------------------------------------------------- - // Function : PclZip() - // Description : - // Creates a PclZip object and set the name of the associated Zip archive - // filename. - // Note that no real action is taken, if the archive does not exist it is not - // created. Use create() for that. - // -------------------------------------------------------------------------------- - function PclZip($p_zipname) - { - - // ----- Tests the zlib - if (!function_exists('gzopen')) + // -------------------------------------------------------------------------------- + // Function : PclZip() + // Description : + // Creates a PclZip object and set the name of the associated Zip archive + // filename. + // Note that no real action is taken, if the archive does not exist it is not + // created. Use create() for that. + // -------------------------------------------------------------------------------- + function PclZip($p_zipname) { - die('Abort '.basename(__FILE__).' : Missing zlib extensions'); - } - - // ----- Set the attributes - $this->zipname = $p_zipname; - $this->zip_fd = 0; - $this->magic_quotes_status = -1; - - // ----- Return - return; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : - // create($p_filelist, $p_add_dir="", $p_remove_dir="") - // create($p_filelist, $p_option, $p_option_value, ...) - // Description : - // This method supports two different synopsis. The first one is historical. - // This method creates a Zip Archive. The Zip file is created in the - // filesystem. The files and directories indicated in $p_filelist - // are added in the archive. See the parameters description for the - // supported format of $p_filelist. - // When a directory is in the list, the directory and its content is added - // in the archive. - // In this synopsis, the function takes an optional variable list of - // options. See bellow the supported options. - // Parameters : - // $p_filelist : An array containing file or directory names, or - // a string containing one filename or one directory name, or - // a string containing a list of filenames and/or directory - // names separated by spaces. - // $p_add_dir : A path to add before the real path of the archived file, - // in order to have it memorized in the archive. - // $p_remove_dir : A path to remove from the real path of the file to archive, - // in order to have a shorter path memorized in the archive. - // When $p_add_dir and $p_remove_dir are set, $p_remove_dir - // is removed first, before $p_add_dir is added. - // Options : - // PCLZIP_OPT_ADD_PATH : - // PCLZIP_OPT_REMOVE_PATH : - // PCLZIP_OPT_REMOVE_ALL_PATH : - // PCLZIP_OPT_COMMENT : - // PCLZIP_CB_PRE_ADD : - // PCLZIP_CB_POST_ADD : - // Return Values : - // 0 on failure, - // The list of the added files, with a status of the add action. - // (see PclZip::listContent() for list entry format) - // -------------------------------------------------------------------------------- - function create($p_filelist) - { - $v_result=1; - - // ----- Reset the error handler - $this->privErrorReset(); - - // ----- Set default values - $v_options = array(); - $v_options[PCLZIP_OPT_NO_COMPRESSION] = FALSE; - - // ----- Look for variable options arguments - $v_size = func_num_args(); - - // ----- Look for arguments - if ($v_size > 1) { - // ----- Get the arguments - $v_arg_list = func_get_args(); - - // ----- Remove from the options list the first argument - array_shift($v_arg_list); - $v_size--; - - // ----- Look for first arg - if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) { - - // ----- Parse the options - $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, - array (PCLZIP_OPT_REMOVE_PATH => 'optional', - PCLZIP_OPT_REMOVE_ALL_PATH => 'optional', - PCLZIP_OPT_ADD_PATH => 'optional', - PCLZIP_CB_PRE_ADD => 'optional', - PCLZIP_CB_POST_ADD => 'optional', - PCLZIP_OPT_NO_COMPRESSION => 'optional', - PCLZIP_OPT_COMMENT => 'optional', - PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional', - PCLZIP_OPT_TEMP_FILE_ON => 'optional', - PCLZIP_OPT_TEMP_FILE_OFF => 'optional' - //, PCLZIP_OPT_CRYPT => 'optional' - )); - if ($v_result != 1) { - return 0; - } - } - - // ----- Look for 2 args - // Here we need to support the first historic synopsis of the - // method. - else { - - // ----- Get the first argument - $v_options[PCLZIP_OPT_ADD_PATH] = $v_arg_list[0]; - - // ----- Look for the optional second argument - if ($v_size == 2) { - $v_options[PCLZIP_OPT_REMOVE_PATH] = $v_arg_list[1]; - } - else if ($v_size > 2) { - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, - "Invalid number / type of arguments"); - return 0; - } - } - } - - // ----- Look for default option values - $this->privOptionDefaultThreshold($v_options); - - // ----- Init - $v_string_list = array(); - $v_att_list = array(); - $v_filedescr_list = array(); - $p_result_list = array(); - - // ----- Look if the $p_filelist is really an array - if (is_array($p_filelist)) { - - // ----- Look if the first element is also an array - // This will mean that this is a file description entry - if (isset($p_filelist[0]) && is_array($p_filelist[0])) { - $v_att_list = $p_filelist; - } - - // ----- The list is a list of string names - else { - $v_string_list = $p_filelist; - } - } - - // ----- Look if the $p_filelist is a string - else if (is_string($p_filelist)) { - // ----- Create a list from the string - $v_string_list = explode(PCLZIP_SEPARATOR, $p_filelist); - } - - // ----- Invalid variable type for $p_filelist - else { - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_filelist"); - return 0; - } - - // ----- Reformat the string list - if (sizeof($v_string_list) != 0) { - foreach ($v_string_list as $v_string) { - if ($v_string != '') { - $v_att_list[][PCLZIP_ATT_FILE_NAME] = $v_string; - } - else { - } - } - } - - // ----- For each file in the list check the attributes - $v_supported_attributes - = array ( PCLZIP_ATT_FILE_NAME => 'mandatory' - ,PCLZIP_ATT_FILE_NEW_SHORT_NAME => 'optional' - ,PCLZIP_ATT_FILE_NEW_FULL_NAME => 'optional' - ,PCLZIP_ATT_FILE_MTIME => 'optional' - ,PCLZIP_ATT_FILE_CONTENT => 'optional' - ,PCLZIP_ATT_FILE_COMMENT => 'optional' - ); - foreach ($v_att_list as $v_entry) { - $v_result = $this->privFileDescrParseAtt($v_entry, - $v_filedescr_list[], - $v_options, - $v_supported_attributes); - if ($v_result != 1) { - return 0; - } - } - - // ----- Expand the filelist (expand directories) - $v_result = $this->privFileDescrExpand($v_filedescr_list, $v_options); - if ($v_result != 1) { - return 0; - } - - // ----- Call the create fct - $v_result = $this->privCreate($v_filedescr_list, $p_result_list, $v_options); - if ($v_result != 1) { - return 0; - } - - // ----- Return - return $p_result_list; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : - // add($p_filelist, $p_add_dir="", $p_remove_dir="") - // add($p_filelist, $p_option, $p_option_value, ...) - // Description : - // This method supports two synopsis. The first one is historical. - // This methods add the list of files in an existing archive. - // If a file with the same name already exists, it is added at the end of the - // archive, the first one is still present. - // If the archive does not exist, it is created. - // Parameters : - // $p_filelist : An array containing file or directory names, or - // a string containing one filename or one directory name, or - // a string containing a list of filenames and/or directory - // names separated by spaces. - // $p_add_dir : A path to add before the real path of the archived file, - // in order to have it memorized in the archive. - // $p_remove_dir : A path to remove from the real path of the file to archive, - // in order to have a shorter path memorized in the archive. - // When $p_add_dir and $p_remove_dir are set, $p_remove_dir - // is removed first, before $p_add_dir is added. - // Options : - // PCLZIP_OPT_ADD_PATH : - // PCLZIP_OPT_REMOVE_PATH : - // PCLZIP_OPT_REMOVE_ALL_PATH : - // PCLZIP_OPT_COMMENT : - // PCLZIP_OPT_ADD_COMMENT : - // PCLZIP_OPT_PREPEND_COMMENT : - // PCLZIP_CB_PRE_ADD : - // PCLZIP_CB_POST_ADD : - // Return Values : - // 0 on failure, - // The list of the added files, with a status of the add action. - // (see PclZip::listContent() for list entry format) - // -------------------------------------------------------------------------------- - function add($p_filelist) - { - $v_result=1; - - // ----- Reset the error handler - $this->privErrorReset(); - - // ----- Set default values - $v_options = array(); - $v_options[PCLZIP_OPT_NO_COMPRESSION] = FALSE; - - // ----- Look for variable options arguments - $v_size = func_num_args(); - - // ----- Look for arguments - if ($v_size > 1) { - // ----- Get the arguments - $v_arg_list = func_get_args(); - - // ----- Remove form the options list the first argument - array_shift($v_arg_list); - $v_size--; - - // ----- Look for first arg - if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) { - - // ----- Parse the options - $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, - array (PCLZIP_OPT_REMOVE_PATH => 'optional', - PCLZIP_OPT_REMOVE_ALL_PATH => 'optional', - PCLZIP_OPT_ADD_PATH => 'optional', - PCLZIP_CB_PRE_ADD => 'optional', - PCLZIP_CB_POST_ADD => 'optional', - PCLZIP_OPT_NO_COMPRESSION => 'optional', - PCLZIP_OPT_COMMENT => 'optional', - PCLZIP_OPT_ADD_COMMENT => 'optional', - PCLZIP_OPT_PREPEND_COMMENT => 'optional', - PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional', - PCLZIP_OPT_TEMP_FILE_ON => 'optional', - PCLZIP_OPT_TEMP_FILE_OFF => 'optional' - //, PCLZIP_OPT_CRYPT => 'optional' - )); - if ($v_result != 1) { - return 0; - } - } - - // ----- Look for 2 args - // Here we need to support the first historic synopsis of the - // method. - else { - - // ----- Get the first argument - $v_options[PCLZIP_OPT_ADD_PATH] = $v_add_path = $v_arg_list[0]; - - // ----- Look for the optional second argument - if ($v_size == 2) { - $v_options[PCLZIP_OPT_REMOVE_PATH] = $v_arg_list[1]; - } - else if ($v_size > 2) { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments"); - - // ----- Return - return 0; - } - } - } - - // ----- Look for default option values - $this->privOptionDefaultThreshold($v_options); - - // ----- Init - $v_string_list = array(); - $v_att_list = array(); - $v_filedescr_list = array(); - $p_result_list = array(); - - // ----- Look if the $p_filelist is really an array - if (is_array($p_filelist)) { - - // ----- Look if the first element is also an array - // This will mean that this is a file description entry - if (isset($p_filelist[0]) && is_array($p_filelist[0])) { - $v_att_list = $p_filelist; - } - - // ----- The list is a list of string names - else { - $v_string_list = $p_filelist; - } - } - - // ----- Look if the $p_filelist is a string - else if (is_string($p_filelist)) { - // ----- Create a list from the string - $v_string_list = explode(PCLZIP_SEPARATOR, $p_filelist); - } - - // ----- Invalid variable type for $p_filelist - else { - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type '".gettype($p_filelist)."' for p_filelist"); - return 0; - } - - // ----- Reformat the string list - if (sizeof($v_string_list) != 0) { - foreach ($v_string_list as $v_string) { - $v_att_list[][PCLZIP_ATT_FILE_NAME] = $v_string; - } - } - - // ----- For each file in the list check the attributes - $v_supported_attributes - = array ( PCLZIP_ATT_FILE_NAME => 'mandatory' - ,PCLZIP_ATT_FILE_NEW_SHORT_NAME => 'optional' - ,PCLZIP_ATT_FILE_NEW_FULL_NAME => 'optional' - ,PCLZIP_ATT_FILE_MTIME => 'optional' - ,PCLZIP_ATT_FILE_CONTENT => 'optional' - ,PCLZIP_ATT_FILE_COMMENT => 'optional' - ); - foreach ($v_att_list as $v_entry) { - $v_result = $this->privFileDescrParseAtt($v_entry, - $v_filedescr_list[], - $v_options, - $v_supported_attributes); - if ($v_result != 1) { - return 0; - } - } - - // ----- Expand the filelist (expand directories) - $v_result = $this->privFileDescrExpand($v_filedescr_list, $v_options); - if ($v_result != 1) { - return 0; - } - - // ----- Call the create fct - $v_result = $this->privAdd($v_filedescr_list, $p_result_list, $v_options); - if ($v_result != 1) { - return 0; - } - - // ----- Return - return $p_result_list; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : listContent() - // Description : - // This public method, gives the list of the files and directories, with their - // properties. - // The properties of each entries in the list are (used also in other functions) : - // filename : Name of the file. For a create or add action it is the filename - // given by the user. For an extract function it is the filename - // of the extracted file. - // stored_filename : Name of the file / directory stored in the archive. - // size : Size of the stored file. - // compressed_size : Size of the file's data compressed in the archive - // (without the headers overhead) - // mtime : Last known modification date of the file (UNIX timestamp) - // comment : Comment associated with the file - // folder : true | false - // index : index of the file in the archive - // status : status of the action (depending of the action) : - // Values are : - // ok : OK ! - // filtered : the file / dir is not extracted (filtered by user) - // already_a_directory : the file can not be extracted because a - // directory with the same name already exists - // write_protected : the file can not be extracted because a file - // with the same name already exists and is - // write protected - // newer_exist : the file was not extracted because a newer file exists - // path_creation_fail : the file is not extracted because the folder - // does not exist and can not be created - // write_error : the file was not extracted because there was a - // error while writing the file - // read_error : the file was not extracted because there was a error - // while reading the file - // invalid_header : the file was not extracted because of an archive - // format error (bad file header) - // Note that each time a method can continue operating when there - // is an action error on a file, the error is only logged in the file status. - // Return Values : - // 0 on an unrecoverable failure, - // The list of the files in the archive. - // -------------------------------------------------------------------------------- - function listContent() - { - $v_result=1; - - // ----- Reset the error handler - $this->privErrorReset(); - - // ----- Check archive - if (!$this->privCheckFormat()) { - return(0); - } - - // ----- Call the extracting fct - $p_list = array(); - if (($v_result = $this->privList($p_list)) != 1) - { - unset($p_list); - return(0); - } - - // ----- Return - return $p_list; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : - // extract($p_path="./", $p_remove_path="") - // extract([$p_option, $p_option_value, ...]) - // Description : - // This method supports two synopsis. The first one is historical. - // This method extract all the files / directories from the archive to the - // folder indicated in $p_path. - // If you want to ignore the 'root' part of path of the memorized files - // you can indicate this in the optional $p_remove_path parameter. - // By default, if a newer file with the same name already exists, the - // file is not extracted. - // - // If both PCLZIP_OPT_PATH and PCLZIP_OPT_ADD_PATH aoptions - // are used, the path indicated in PCLZIP_OPT_ADD_PATH is append - // at the end of the path value of PCLZIP_OPT_PATH. - // Parameters : - // $p_path : Path where the files and directories are to be extracted - // $p_remove_path : First part ('root' part) of the memorized path - // (if any similar) to remove while extracting. - // Options : - // PCLZIP_OPT_PATH : - // PCLZIP_OPT_ADD_PATH : - // PCLZIP_OPT_REMOVE_PATH : - // PCLZIP_OPT_REMOVE_ALL_PATH : - // PCLZIP_CB_PRE_EXTRACT : - // PCLZIP_CB_POST_EXTRACT : - // Return Values : - // 0 or a negative value on failure, - // The list of the extracted files, with a status of the action. - // (see PclZip::listContent() for list entry format) - // -------------------------------------------------------------------------------- - function extract() - { - $v_result=1; - - // ----- Reset the error handler - $this->privErrorReset(); - - // ----- Check archive - if (!$this->privCheckFormat()) { - return(0); - } - - // ----- Set default values - $v_options = array(); -// $v_path = "./"; - $v_path = ''; - $v_remove_path = ""; - $v_remove_all_path = false; - - // ----- Look for variable options arguments - $v_size = func_num_args(); - - // ----- Default values for option - $v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = FALSE; - - // ----- Look for arguments - if ($v_size > 0) { - // ----- Get the arguments - $v_arg_list = func_get_args(); - - // ----- Look for first arg - if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) { - - // ----- Parse the options - $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, - array (PCLZIP_OPT_PATH => 'optional', - PCLZIP_OPT_REMOVE_PATH => 'optional', - PCLZIP_OPT_REMOVE_ALL_PATH => 'optional', - PCLZIP_OPT_ADD_PATH => 'optional', - PCLZIP_CB_PRE_EXTRACT => 'optional', - PCLZIP_CB_POST_EXTRACT => 'optional', - PCLZIP_OPT_SET_CHMOD => 'optional', - PCLZIP_OPT_BY_NAME => 'optional', - PCLZIP_OPT_BY_EREG => 'optional', - PCLZIP_OPT_BY_PREG => 'optional', - PCLZIP_OPT_BY_INDEX => 'optional', - PCLZIP_OPT_EXTRACT_AS_STRING => 'optional', - PCLZIP_OPT_EXTRACT_IN_OUTPUT => 'optional', - PCLZIP_OPT_REPLACE_NEWER => 'optional' - ,PCLZIP_OPT_STOP_ON_ERROR => 'optional' - ,PCLZIP_OPT_EXTRACT_DIR_RESTRICTION => 'optional', - PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional', - PCLZIP_OPT_TEMP_FILE_ON => 'optional', - PCLZIP_OPT_TEMP_FILE_OFF => 'optional' - )); - if ($v_result != 1) { - return 0; + // ----- Tests the zlib + if (!function_exists('gzopen')) { + die('Abort '.basename(__FILE__).' : Missing zlib extensions'); } - // ----- Set the arguments - if (isset($v_options[PCLZIP_OPT_PATH])) { - $v_path = $v_options[PCLZIP_OPT_PATH]; - } - if (isset($v_options[PCLZIP_OPT_REMOVE_PATH])) { - $v_remove_path = $v_options[PCLZIP_OPT_REMOVE_PATH]; - } - if (isset($v_options[PCLZIP_OPT_REMOVE_ALL_PATH])) { - $v_remove_all_path = $v_options[PCLZIP_OPT_REMOVE_ALL_PATH]; - } - if (isset($v_options[PCLZIP_OPT_ADD_PATH])) { - // ----- Check for '/' in last path char - if ((strlen($v_path) > 0) && (substr($v_path, -1) != '/')) { - $v_path .= '/'; - } - $v_path .= $v_options[PCLZIP_OPT_ADD_PATH]; - } - } - - // ----- Look for 2 args - // Here we need to support the first historic synopsis of the - // method. - else { - - // ----- Get the first argument - $v_path = $v_arg_list[0]; - - // ----- Look for the optional second argument - if ($v_size == 2) { - $v_remove_path = $v_arg_list[1]; - } - else if ($v_size > 2) { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments"); - - // ----- Return - return 0; - } - } - } - - // ----- Look for default option values - $this->privOptionDefaultThreshold($v_options); - - // ----- Trace - - // ----- Call the extracting fct - $p_list = array(); - $v_result = $this->privExtractByRule($p_list, $v_path, $v_remove_path, - $v_remove_all_path, $v_options); - if ($v_result < 1) { - unset($p_list); - return(0); - } - - // ----- Return - return $p_list; - } - // -------------------------------------------------------------------------------- - - - // -------------------------------------------------------------------------------- - // Function : - // extractByIndex($p_index, $p_path="./", $p_remove_path="") - // extractByIndex($p_index, [$p_option, $p_option_value, ...]) - // Description : - // This method supports two synopsis. The first one is historical. - // This method is doing a partial extract of the archive. - // The extracted files or folders are identified by their index in the - // archive (from 0 to n). - // Note that if the index identify a folder, only the folder entry is - // extracted, not all the files included in the archive. - // Parameters : - // $p_index : A single index (integer) or a string of indexes of files to - // extract. The form of the string is "0,4-6,8-12" with only numbers - // and '-' for range or ',' to separate ranges. No spaces or ';' - // are allowed. - // $p_path : Path where the files and directories are to be extracted - // $p_remove_path : First part ('root' part) of the memorized path - // (if any similar) to remove while extracting. - // Options : - // PCLZIP_OPT_PATH : - // PCLZIP_OPT_ADD_PATH : - // PCLZIP_OPT_REMOVE_PATH : - // PCLZIP_OPT_REMOVE_ALL_PATH : - // PCLZIP_OPT_EXTRACT_AS_STRING : The files are extracted as strings and - // not as files. - // The resulting content is in a new field 'content' in the file - // structure. - // This option must be used alone (any other options are ignored). - // PCLZIP_CB_PRE_EXTRACT : - // PCLZIP_CB_POST_EXTRACT : - // Return Values : - // 0 on failure, - // The list of the extracted files, with a status of the action. - // (see PclZip::listContent() for list entry format) - // -------------------------------------------------------------------------------- - //function extractByIndex($p_index, options...) - function extractByIndex($p_index) - { - $v_result=1; - - // ----- Reset the error handler - $this->privErrorReset(); - - // ----- Check archive - if (!$this->privCheckFormat()) { - return(0); - } - - // ----- Set default values - $v_options = array(); -// $v_path = "./"; - $v_path = ''; - $v_remove_path = ""; - $v_remove_all_path = false; - - // ----- Look for variable options arguments - $v_size = func_num_args(); - - // ----- Default values for option - $v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = FALSE; - - // ----- Look for arguments - if ($v_size > 1) { - // ----- Get the arguments - $v_arg_list = func_get_args(); - - // ----- Remove form the options list the first argument - array_shift($v_arg_list); - $v_size--; - - // ----- Look for first arg - if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) { - - // ----- Parse the options - $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, - array (PCLZIP_OPT_PATH => 'optional', - PCLZIP_OPT_REMOVE_PATH => 'optional', - PCLZIP_OPT_REMOVE_ALL_PATH => 'optional', - PCLZIP_OPT_EXTRACT_AS_STRING => 'optional', - PCLZIP_OPT_ADD_PATH => 'optional', - PCLZIP_CB_PRE_EXTRACT => 'optional', - PCLZIP_CB_POST_EXTRACT => 'optional', - PCLZIP_OPT_SET_CHMOD => 'optional', - PCLZIP_OPT_REPLACE_NEWER => 'optional' - ,PCLZIP_OPT_STOP_ON_ERROR => 'optional' - ,PCLZIP_OPT_EXTRACT_DIR_RESTRICTION => 'optional', - PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional', - PCLZIP_OPT_TEMP_FILE_ON => 'optional', - PCLZIP_OPT_TEMP_FILE_OFF => 'optional' - )); - if ($v_result != 1) { - return 0; - } - - // ----- Set the arguments - if (isset($v_options[PCLZIP_OPT_PATH])) { - $v_path = $v_options[PCLZIP_OPT_PATH]; - } - if (isset($v_options[PCLZIP_OPT_REMOVE_PATH])) { - $v_remove_path = $v_options[PCLZIP_OPT_REMOVE_PATH]; - } - if (isset($v_options[PCLZIP_OPT_REMOVE_ALL_PATH])) { - $v_remove_all_path = $v_options[PCLZIP_OPT_REMOVE_ALL_PATH]; - } - if (isset($v_options[PCLZIP_OPT_ADD_PATH])) { - // ----- Check for '/' in last path char - if ((strlen($v_path) > 0) && (substr($v_path, -1) != '/')) { - $v_path .= '/'; - } - $v_path .= $v_options[PCLZIP_OPT_ADD_PATH]; - } - if (!isset($v_options[PCLZIP_OPT_EXTRACT_AS_STRING])) { - $v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = FALSE; - } - else { - } - } - - // ----- Look for 2 args - // Here we need to support the first historic synopsis of the - // method. - else { - - // ----- Get the first argument - $v_path = $v_arg_list[0]; - - // ----- Look for the optional second argument - if ($v_size == 2) { - $v_remove_path = $v_arg_list[1]; - } - else if ($v_size > 2) { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments"); - - // ----- Return - return 0; - } - } - } - - // ----- Trace - - // ----- Trick - // Here I want to reuse extractByRule(), so I need to parse the $p_index - // with privParseOptions() - $v_arg_trick = array (PCLZIP_OPT_BY_INDEX, $p_index); - $v_options_trick = array(); - $v_result = $this->privParseOptions($v_arg_trick, sizeof($v_arg_trick), $v_options_trick, - array (PCLZIP_OPT_BY_INDEX => 'optional' )); - if ($v_result != 1) { - return 0; - } - $v_options[PCLZIP_OPT_BY_INDEX] = $v_options_trick[PCLZIP_OPT_BY_INDEX]; - - // ----- Look for default option values - $this->privOptionDefaultThreshold($v_options); - - // ----- Call the extracting fct - if (($v_result = $this->privExtractByRule($p_list, $v_path, $v_remove_path, $v_remove_all_path, $v_options)) < 1) { - return(0); - } - - // ----- Return - return $p_list; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : - // delete([$p_option, $p_option_value, ...]) - // Description : - // This method removes files from the archive. - // If no parameters are given, then all the archive is emptied. - // Parameters : - // None or optional arguments. - // Options : - // PCLZIP_OPT_BY_INDEX : - // PCLZIP_OPT_BY_NAME : - // PCLZIP_OPT_BY_EREG : - // PCLZIP_OPT_BY_PREG : - // Return Values : - // 0 on failure, - // The list of the files which are still present in the archive. - // (see PclZip::listContent() for list entry format) - // -------------------------------------------------------------------------------- - function delete() - { - $v_result=1; - - // ----- Reset the error handler - $this->privErrorReset(); - - // ----- Check archive - if (!$this->privCheckFormat()) { - return(0); - } - - // ----- Set default values - $v_options = array(); - - // ----- Look for variable options arguments - $v_size = func_num_args(); - - // ----- Look for arguments - if ($v_size > 0) { - // ----- Get the arguments - $v_arg_list = func_get_args(); - - // ----- Parse the options - $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, - array (PCLZIP_OPT_BY_NAME => 'optional', - PCLZIP_OPT_BY_EREG => 'optional', - PCLZIP_OPT_BY_PREG => 'optional', - PCLZIP_OPT_BY_INDEX => 'optional' )); - if ($v_result != 1) { - return 0; - } - } - - // ----- Magic quotes trick - $this->privDisableMagicQuotes(); - - // ----- Call the delete fct - $v_list = array(); - if (($v_result = $this->privDeleteByRule($v_list, $v_options)) != 1) { - $this->privSwapBackMagicQuotes(); - unset($v_list); - return(0); - } - - // ----- Magic quotes trick - $this->privSwapBackMagicQuotes(); - - // ----- Return - return $v_list; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : deleteByIndex() - // Description : - // ***** Deprecated ***** - // delete(PCLZIP_OPT_BY_INDEX, $p_index) should be prefered. - // -------------------------------------------------------------------------------- - function deleteByIndex($p_index) - { - - $p_list = $this->delete(PCLZIP_OPT_BY_INDEX, $p_index); - - // ----- Return - return $p_list; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : properties() - // Description : - // This method gives the properties of the archive. - // The properties are : - // nb : Number of files in the archive - // comment : Comment associated with the archive file - // status : not_exist, ok - // Parameters : - // None - // Return Values : - // 0 on failure, - // An array with the archive properties. - // -------------------------------------------------------------------------------- - function properties() - { - - // ----- Reset the error handler - $this->privErrorReset(); - - // ----- Magic quotes trick - $this->privDisableMagicQuotes(); - - // ----- Check archive - if (!$this->privCheckFormat()) { - $this->privSwapBackMagicQuotes(); - return(0); - } - - // ----- Default properties - $v_prop = array(); - $v_prop['comment'] = ''; - $v_prop['nb'] = 0; - $v_prop['status'] = 'not_exist'; - - // ----- Look if file exists - if (@is_file($this->zipname)) - { - // ----- Open the zip file - if (($this->zip_fd = @fopen($this->zipname, 'rb')) == 0) - { - $this->privSwapBackMagicQuotes(); - - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \''.$this->zipname.'\' in binary read mode'); + // ----- Set the attributes + $this->zipname = $p_zipname; + $this->zip_fd = 0; + $this->magic_quotes_status = -1; // ----- Return - return 0; - } - - // ----- Read the central directory informations - $v_central_dir = array(); - if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) - { - $this->privSwapBackMagicQuotes(); - return 0; - } - - // ----- Close the zip file - $this->privCloseFd(); - - // ----- Set the user attributes - $v_prop['comment'] = $v_central_dir['comment']; - $v_prop['nb'] = $v_central_dir['entries']; - $v_prop['status'] = 'ok'; + return; } + // -------------------------------------------------------------------------------- - // ----- Magic quotes trick + // -------------------------------------------------------------------------------- + // Function : + // create($p_filelist, $p_add_dir="", $p_remove_dir="") + // create($p_filelist, $p_option, $p_option_value, ...) + // Description : + // This method supports two different synopsis. The first one is historical. + // This method creates a Zip Archive. The Zip file is created in the + // filesystem. The files and directories indicated in $p_filelist + // are added in the archive. See the parameters description for the + // supported format of $p_filelist. + // When a directory is in the list, the directory and its content is added + // in the archive. + // In this synopsis, the function takes an optional variable list of + // options. See bellow the supported options. + // Parameters : + // $p_filelist : An array containing file or directory names, or + // a string containing one filename or one directory name, or + // a string containing a list of filenames and/or directory + // names separated by spaces. + // $p_add_dir : A path to add before the real path of the archived file, + // in order to have it memorized in the archive. + // $p_remove_dir : A path to remove from the real path of the file to archive, + // in order to have a shorter path memorized in the archive. + // When $p_add_dir and $p_remove_dir are set, $p_remove_dir + // is removed first, before $p_add_dir is added. + // Options : + // PCLZIP_OPT_ADD_PATH : + // PCLZIP_OPT_REMOVE_PATH : + // PCLZIP_OPT_REMOVE_ALL_PATH : + // PCLZIP_OPT_COMMENT : + // PCLZIP_CB_PRE_ADD : + // PCLZIP_CB_POST_ADD : + // Return Values : + // 0 on failure, + // The list of the added files, with a status of the add action. + // (see PclZip::listContent() for list entry format) + // -------------------------------------------------------------------------------- + function create($p_filelist) { + $v_result=1; + + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Set default values + $v_options = array(); + $v_options[PCLZIP_OPT_NO_COMPRESSION] = false; + + // ----- Look for variable options arguments + $v_size = func_num_args(); + + // ----- Look for arguments + if ($v_size > 1) { + // ----- Get the arguments + $v_arg_list = func_get_args(); + + // ----- Remove from the options list the first argument + array_shift($v_arg_list); + $v_size--; + + // ----- Look for first arg + if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) { + // ----- Parse the options + $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, array( + PCLZIP_OPT_REMOVE_PATH => 'optional', + PCLZIP_OPT_REMOVE_ALL_PATH => 'optional', + PCLZIP_OPT_ADD_PATH => 'optional', + PCLZIP_CB_PRE_ADD => 'optional', + PCLZIP_CB_POST_ADD => 'optional', + PCLZIP_OPT_NO_COMPRESSION => 'optional', + PCLZIP_OPT_COMMENT => 'optional', + PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional', + PCLZIP_OPT_TEMP_FILE_ON => 'optional', + PCLZIP_OPT_TEMP_FILE_OFF => 'optional' + //, PCLZIP_OPT_CRYPT => 'optional' + ))); + if ($v_result != 1) { + return 0; + } + } else { + // ----- Look for 2 args + // Here we need to support the first historic synopsis of the + // method. + + // ----- Get the first argument + $v_options[PCLZIP_OPT_ADD_PATH] = $v_arg_list[0]; + + // ----- Look for the optional second argument + if ($v_size == 2) { + $v_options[PCLZIP_OPT_REMOVE_PATH] = $v_arg_list[1]; + } else if ($v_size > 2) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments"); + return 0; + } + } + } + + // ----- Look for default option values + $this->privOptionDefaultThreshold($v_options); + + // ----- Init + $v_string_list = array(); + $v_att_list = array(); + $v_filedescr_list = array(); + $p_result_list = array(); + + // ----- Look if the $p_filelist is really an array + if (is_array($p_filelist)) { + // ----- Look if the first element is also an array + // This will mean that this is a file description entry + if (isset($p_filelist[0]) && is_array($p_filelist[0])) { + $v_att_list = $p_filelist; + } else { + // ----- The list is a list of string names + $v_string_list = $p_filelist; + } + } else if (is_string($p_filelist)) { + // ----- Look if the $p_filelist is a string + // ----- Create a list from the string + $v_string_list = explode(PCLZIP_SEPARATOR, $p_filelist); + } else { + // ----- Invalid variable type for $p_filelist + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_filelist"); + return 0; + } + // ----- Reformat the string list + if (sizeof($v_string_list) != 0) { + foreach ($v_string_list as $v_string) { + if ($v_string != '') { + $v_att_list[][PCLZIP_ATT_FILE_NAME] = $v_string; + } + } + } + + // ----- For each file in the list check the attributes + $v_supported_attributes = array( + PCLZIP_ATT_FILE_NAME => 'mandatory', + PCLZIP_ATT_FILE_NEW_SHORT_NAME => 'optional', + PCLZIP_ATT_FILE_NEW_FULL_NAME => 'optional', + PCLZIP_ATT_FILE_MTIME => 'optional', + PCLZIP_ATT_FILE_CONTENT => 'optional', + PCLZIP_ATT_FILE_COMMENT => 'optional', + )); + foreach ($v_att_list as $v_entry) { + $v_result = $this->privFileDescrParseAtt($v_entry, $v_filedescr_list[], $v_options, $v_supported_attributes); + if ($v_result != 1) { + return 0; + } + } + // ----- Expand the filelist (expand directories) + $v_result = $this->privFileDescrExpand($v_filedescr_list, $v_options); + if ($v_result != 1) { + return 0; + } + + // ----- Call the create fct + $v_result = $this->privCreate($v_filedescr_list, $p_result_list, $v_options); + if ($v_result != 1) { + return 0; + } + + // ----- Return + return $p_result_list; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : + // add($p_filelist, $p_add_dir="", $p_remove_dir="") + // add($p_filelist, $p_option, $p_option_value, ...) + // Description : + // This method supports two synopsis. The first one is historical. + // This methods add the list of files in an existing archive. + // If a file with the same name already exists, it is added at the end of the + // archive, the first one is still present. + // If the archive does not exist, it is created. + // Parameters : + // $p_filelist : An array containing file or directory names, or + // a string containing one filename or one directory name, or + // a string containing a list of filenames and/or directory + // names separated by spaces. + // $p_add_dir : A path to add before the real path of the archived file, + // in order to have it memorized in the archive. + // $p_remove_dir : A path to remove from the real path of the file to archive, + // in order to have a shorter path memorized in the archive. + // When $p_add_dir and $p_remove_dir are set, $p_remove_dir + // is removed first, before $p_add_dir is added. + // Options : + // PCLZIP_OPT_ADD_PATH : + // PCLZIP_OPT_REMOVE_PATH : + // PCLZIP_OPT_REMOVE_ALL_PATH : + // PCLZIP_OPT_COMMENT : + // PCLZIP_OPT_ADD_COMMENT : + // PCLZIP_OPT_PREPEND_COMMENT : + // PCLZIP_CB_PRE_ADD : + // PCLZIP_CB_POST_ADD : + // Return Values : + // 0 on failure, + // The list of the added files, with a status of the add action. + // (see PclZip::listContent() for list entry format) + // -------------------------------------------------------------------------------- + function add($p_filelist) + { + $v_result=1; + + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Set default values + $v_options = array(); + $v_options[PCLZIP_OPT_NO_COMPRESSION] = false; + + // ----- Look for variable options arguments + $v_size = func_num_args(); + + // ----- Look for arguments + if ($v_size > 1) { + // ----- Get the arguments + $v_arg_list = func_get_args(); + + // ----- Remove form the options list the first argument + array_shift($v_arg_list); + $v_size--; + + // ----- Look for first arg + if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) { + // ----- Parse the options + $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, array( + PCLZIP_OPT_REMOVE_PATH => 'optional', + PCLZIP_OPT_REMOVE_ALL_PATH => 'optional', + PCLZIP_OPT_ADD_PATH => 'optional', + PCLZIP_CB_PRE_ADD => 'optional', + PCLZIP_CB_POST_ADD => 'optional', + PCLZIP_OPT_NO_COMPRESSION => 'optional', + PCLZIP_OPT_COMMENT => 'optional', + PCLZIP_OPT_ADD_COMMENT => 'optional', + PCLZIP_OPT_PREPEND_COMMENT => 'optional', + PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional', + PCLZIP_OPT_TEMP_FILE_ON => 'optional', + PCLZIP_OPT_TEMP_FILE_OFF => 'optional' + //, PCLZIP_OPT_CRYPT => 'optional' + ))); + if ($v_result != 1) { + return 0; + } + } else { + // ----- Look for 2 args + // Here we need to support the first historic synopsis of the method. + + // ----- Get the first argument + $v_options[PCLZIP_OPT_ADD_PATH] = $v_add_path = $v_arg_list[0]; + + // ----- Look for the optional second argument + if ($v_size == 2) { + $v_options[PCLZIP_OPT_REMOVE_PATH] = $v_arg_list[1]; + } else if ($v_size > 2) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments"); + // ----- Return + return 0; + } + } + } + + // ----- Look for default option values + $this->privOptionDefaultThreshold($v_options); + + // ----- Init + $v_string_list = array(); + $v_att_list = array(); + $v_filedescr_list = array(); + $p_result_list = array(); + + // ----- Look if the $p_filelist is really an array + if (is_array($p_filelist)) { + // ----- Look if the first element is also an array + // This will mean that this is a file description entry + if (isset($p_filelist[0]) && is_array($p_filelist[0])) { + $v_att_list = $p_filelist; + } else { + // ----- The list is a list of string names + $v_string_list = $p_filelist; + } + } else if (is_string($p_filelist)) { + // ----- Look if the $p_filelist is a string + // ----- Create a list from the string + $v_string_list = explode(PCLZIP_SEPARATOR, $p_filelist); + } else { + // ----- Invalid variable type for $p_filelist + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type '".gettype($p_filelist)."' for p_filelist"); + return 0; + } + + // ----- Reformat the string list + if (sizeof($v_string_list) != 0) { + foreach ($v_string_list as $v_string) { + $v_att_list[][PCLZIP_ATT_FILE_NAME] = $v_string; + } + } + + // ----- For each file in the list check the attributes + $v_supported_attributes = array( + PCLZIP_ATT_FILE_NAME => 'mandatory', + PCLZIP_ATT_FILE_NEW_SHORT_NAME => 'optional', + PCLZIP_ATT_FILE_NEW_FULL_NAME => 'optional', + PCLZIP_ATT_FILE_MTIME => 'optional', + PCLZIP_ATT_FILE_CONTENT => 'optional', + PCLZIP_ATT_FILE_COMMENT => 'optional', + )); + foreach ($v_att_list as $v_entry) { + $v_result = $this->privFileDescrParseAtt($v_entry, $v_filedescr_list[], $v_options, $v_supported_attributes); + if ($v_result != 1) { + return 0; + } + } + + // ----- Expand the filelist (expand directories) + $v_result = $this->privFileDescrExpand($v_filedescr_list, $v_options); + if ($v_result != 1) { + return 0; + } + + // ----- Call the create fct + $v_result = $this->privAdd($v_filedescr_list, $p_result_list, $v_options); + if ($v_result != 1) { + return 0; + } + + // ----- Return + return $p_result_list; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : listContent() + // Description : + // This public method, gives the list of the files and directories, with their + // properties. + // The properties of each entries in the list are (used also in other functions) : + // filename : Name of the file. For a create or add action it is the filename + // given by the user. For an extract function it is the filename + // of the extracted file. + // stored_filename : Name of the file / directory stored in the archive. + // size : Size of the stored file. + // compressed_size : Size of the file's data compressed in the archive + // (without the headers overhead) + // mtime : Last known modification date of the file (UNIX timestamp) + // comment : Comment associated with the file + // folder : true | false + // index : index of the file in the archive + // status : status of the action (depending of the action) : + // Values are : + // ok : OK ! + // filtered : the file / dir is not extracted (filtered by user) + // already_a_directory : the file can not be extracted because a + // directory with the same name already exists + // write_protected : the file can not be extracted because a file + // with the same name already exists and is + // write protected + // newer_exist : the file was not extracted because a newer file exists + // path_creation_fail : the file is not extracted because the folder + // does not exist and can not be created + // write_error : the file was not extracted because there was a + // error while writing the file + // read_error : the file was not extracted because there was a error + // while reading the file + // invalid_header : the file was not extracted because of an archive + // format error (bad file header) + // Note that each time a method can continue operating when there + // is an action error on a file, the error is only logged in the file status. + // Return Values : + // 0 on an unrecoverable failure, + // The list of the files in the archive. + // -------------------------------------------------------------------------------- + function listContent() + { + $v_result=1; + + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Check archive + if (!$this->privCheckFormat()) { + return(0); + } + + // ----- Call the extracting fct + $p_list = array(); + if (($v_result = $this->privList($p_list)) != 1) { + unset($p_list); + return(0); + } + + // ----- Return + return $p_list; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : + // extract($p_path="./", $p_remove_path="") + // extract([$p_option, $p_option_value, ...]) + // Description : + // This method supports two synopsis. The first one is historical. + // This method extract all the files / directories from the archive to the + // folder indicated in $p_path. + // If you want to ignore the 'root' part of path of the memorized files + // you can indicate this in the optional $p_remove_path parameter. + // By default, if a newer file with the same name already exists, the + // file is not extracted. + // + // If both PCLZIP_OPT_PATH and PCLZIP_OPT_ADD_PATH aoptions + // are used, the path indicated in PCLZIP_OPT_ADD_PATH is append + // at the end of the path value of PCLZIP_OPT_PATH. + // Parameters : + // $p_path : Path where the files and directories are to be extracted + // $p_remove_path : First part ('root' part) of the memorized path + // (if any similar) to remove while extracting. + // Options : + // PCLZIP_OPT_PATH : + // PCLZIP_OPT_ADD_PATH : + // PCLZIP_OPT_REMOVE_PATH : + // PCLZIP_OPT_REMOVE_ALL_PATH : + // PCLZIP_CB_PRE_EXTRACT : + // PCLZIP_CB_POST_EXTRACT : + // Return Values : + // 0 or a negative value on failure, + // The list of the extracted files, with a status of the action. + // (see PclZip::listContent() for list entry format) + // -------------------------------------------------------------------------------- + function extract() + { + $v_result=1; + + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Check archive + if (!$this->privCheckFormat()) { + return(0); + } + + // ----- Set default values + $v_options = array(); + // $v_path = "./"; + $v_path = ''; + $v_remove_path = ""; + $v_remove_all_path = false; + + // ----- Look for variable options arguments + $v_size = func_num_args(); + + // ----- Default values for option + $v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = false; + + // ----- Look for arguments + if ($v_size > 0) { + // ----- Get the arguments + $v_arg_list = func_get_args(); + + // ----- Look for first arg + if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) { + // ----- Parse the options + $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, array( + PCLZIP_OPT_PATH => 'optional', + PCLZIP_OPT_REMOVE_PATH => 'optional', + PCLZIP_OPT_REMOVE_ALL_PATH => 'optional', + PCLZIP_OPT_ADD_PATH => 'optional', + PCLZIP_CB_PRE_EXTRACT => 'optional', + PCLZIP_CB_POST_EXTRACT => 'optional', + PCLZIP_OPT_SET_CHMOD => 'optional', + PCLZIP_OPT_BY_NAME => 'optional', + PCLZIP_OPT_BY_EREG => 'optional', + PCLZIP_OPT_BY_PREG => 'optional', + PCLZIP_OPT_BY_INDEX => 'optional', + PCLZIP_OPT_EXTRACT_AS_STRING => 'optional', + PCLZIP_OPT_EXTRACT_IN_OUTPUT => 'optional', + PCLZIP_OPT_REPLACE_NEWER => 'optional', + PCLZIP_OPT_STOP_ON_ERROR => 'optional', + PCLZIP_OPT_EXTRACT_DIR_RESTRICTION => 'optional', + PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional', + PCLZIP_OPT_TEMP_FILE_ON => 'optional', + PCLZIP_OPT_TEMP_FILE_OFF => 'optional' + ))); + if ($v_result != 1) { + return 0; + } + + // ----- Set the arguments + if (isset($v_options[PCLZIP_OPT_PATH])) { + $v_path = $v_options[PCLZIP_OPT_PATH]; + } + if (isset($v_options[PCLZIP_OPT_REMOVE_PATH])) { + $v_remove_path = $v_options[PCLZIP_OPT_REMOVE_PATH]; + } + if (isset($v_options[PCLZIP_OPT_REMOVE_ALL_PATH])) { + $v_remove_all_path = $v_options[PCLZIP_OPT_REMOVE_ALL_PATH]; + } + if (isset($v_options[PCLZIP_OPT_ADD_PATH])) { + // ----- Check for '/' in last path char + if ((strlen($v_path) > 0) && (substr($v_path, -1) != '/')) { + $v_path .= '/'; + } + $v_path .= $v_options[PCLZIP_OPT_ADD_PATH]; + } + } else { + // ----- Look for 2 args + // Here we need to support the first historic synopsis of the method. + // ----- Get the first argument + $v_path = $v_arg_list[0]; + + // ----- Look for the optional second argument + if ($v_size == 2) { + $v_remove_path = $v_arg_list[1]; + } else if ($v_size > 2) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments"); + // ----- Return + return 0; + } + } + } + + // ----- Look for default option values + $this->privOptionDefaultThreshold($v_options); + + // ----- Trace + + // ----- Call the extracting fct + $p_list = array(); + $v_result = $this->privExtractByRule($p_list, $v_path, $v_remove_path, + $v_remove_all_path, $v_options); + if ($v_result < 1) { + unset($p_list); + return(0); + } + + // ----- Return + return $p_list; + } + // -------------------------------------------------------------------------------- + + + // -------------------------------------------------------------------------------- + // Function : + // extractByIndex($p_index, $p_path="./", $p_remove_path="") + // extractByIndex($p_index, [$p_option, $p_option_value, ...]) + // Description : + // This method supports two synopsis. The first one is historical. + // This method is doing a partial extract of the archive. + // The extracted files or folders are identified by their index in the + // archive (from 0 to n). + // Note that if the index identify a folder, only the folder entry is + // extracted, not all the files included in the archive. + // Parameters : + // $p_index : A single index (integer) or a string of indexes of files to + // extract. The form of the string is "0,4-6,8-12" with only numbers + // and '-' for range or ',' to separate ranges. No spaces or ';' + // are allowed. + // $p_path : Path where the files and directories are to be extracted + // $p_remove_path : First part ('root' part) of the memorized path + // (if any similar) to remove while extracting. + // Options : + // PCLZIP_OPT_PATH : + // PCLZIP_OPT_ADD_PATH : + // PCLZIP_OPT_REMOVE_PATH : + // PCLZIP_OPT_REMOVE_ALL_PATH : + // PCLZIP_OPT_EXTRACT_AS_STRING : The files are extracted as strings and + // not as files. + // The resulting content is in a new field 'content' in the file + // structure. + // This option must be used alone (any other options are ignored). + // PCLZIP_CB_PRE_EXTRACT : + // PCLZIP_CB_POST_EXTRACT : + // Return Values : + // 0 on failure, + // The list of the extracted files, with a status of the action. + // (see PclZip::listContent() for list entry format) + // -------------------------------------------------------------------------------- + //function extractByIndex($p_index, options...) + function extractByIndex($p_index) + { + $v_result=1; + + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Check archive + if (!$this->privCheckFormat()) { + return(0); + } + + // ----- Set default values + $v_options = array(); + // $v_path = "./"; + $v_path = ''; + $v_remove_path = ""; + $v_remove_all_path = false; + + // ----- Look for variable options arguments + $v_size = func_num_args(); + + // ----- Default values for option + $v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = false; + + // ----- Look for arguments + if ($v_size > 1) { + // ----- Get the arguments + $v_arg_list = func_get_args(); + + // ----- Remove form the options list the first argument + array_shift($v_arg_list); + $v_size--; + + // ----- Look for first arg + if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) { + // ----- Parse the options + $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, array( + PCLZIP_OPT_PATH => 'optional', + PCLZIP_OPT_REMOVE_PATH => 'optional', + PCLZIP_OPT_REMOVE_ALL_PATH => 'optional', + PCLZIP_OPT_EXTRACT_AS_STRING => 'optional', + PCLZIP_OPT_ADD_PATH => 'optional', + PCLZIP_CB_PRE_EXTRACT => 'optional', + PCLZIP_CB_POST_EXTRACT => 'optional', + PCLZIP_OPT_SET_CHMOD => 'optional', + PCLZIP_OPT_REPLACE_NEWER => 'optional', + PCLZIP_OPT_STOP_ON_ERROR => 'optional', + PCLZIP_OPT_EXTRACT_DIR_RESTRICTION => 'optional', + PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional', + PCLZIP_OPT_TEMP_FILE_ON => 'optional', + PCLZIP_OPT_TEMP_FILE_OFF => 'optional' + ))); + if ($v_result != 1) { + return 0; + } + + // ----- Set the arguments + if (isset($v_options[PCLZIP_OPT_PATH])) { + $v_path = $v_options[PCLZIP_OPT_PATH]; + } + if (isset($v_options[PCLZIP_OPT_REMOVE_PATH])) { + $v_remove_path = $v_options[PCLZIP_OPT_REMOVE_PATH]; + } + if (isset($v_options[PCLZIP_OPT_REMOVE_ALL_PATH])) { + $v_remove_all_path = $v_options[PCLZIP_OPT_REMOVE_ALL_PATH]; + } + if (isset($v_options[PCLZIP_OPT_ADD_PATH])) { + // ----- Check for '/' in last path char + if ((strlen($v_path) > 0) && (substr($v_path, -1) != '/')) { + $v_path .= '/'; + } + $v_path .= $v_options[PCLZIP_OPT_ADD_PATH]; + } + if (!isset($v_options[PCLZIP_OPT_EXTRACT_AS_STRING])) { + $v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = false; + } + } else { + // ----- Look for 2 args + // Here we need to support the first historic synopsis of the method. + + // ----- Get the first argument + $v_path = $v_arg_list[0]; + + // ----- Look for the optional second argument + if ($v_size == 2) { + $v_remove_path = $v_arg_list[1]; + } else if ($v_size > 2) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments"); + + // ----- Return + return 0; + } + } + } + + // ----- Trace + + // ----- Trick + // Here I want to reuse extractByRule(), so I need to parse the $p_index + // with privParseOptions() + $v_arg_trick = array (PCLZIP_OPT_BY_INDEX, $p_index); + $v_options_trick = array(); + $v_result = $this->privParseOptions($v_arg_trick, sizeof($v_arg_trick), $v_options_trick, + array (PCLZIP_OPT_BY_INDEX => 'optional')); + if ($v_result != 1) { + return 0; + } + $v_options[PCLZIP_OPT_BY_INDEX] = $v_options_trick[PCLZIP_OPT_BY_INDEX]; + + // ----- Look for default option values + $this->privOptionDefaultThreshold($v_options); + + // ----- Call the extracting fct + if (($v_result = $this->privExtractByRule($p_list, $v_path, $v_remove_path, $v_remove_all_path, $v_options)) < 1) { + return(0); + } + + // ----- Return + return $p_list; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : + // delete([$p_option, $p_option_value, ...]) + // Description : + // This method removes files from the archive. + // If no parameters are given, then all the archive is emptied. + // Parameters : + // None or optional arguments. + // Options : + // PCLZIP_OPT_BY_INDEX : + // PCLZIP_OPT_BY_NAME : + // PCLZIP_OPT_BY_EREG : + // PCLZIP_OPT_BY_PREG : + // Return Values : + // 0 on failure, + // The list of the files which are still present in the archive. + // (see PclZip::listContent() for list entry format) + // -------------------------------------------------------------------------------- + function delete() +{ +$v_result=1; + +// ----- Reset the error handler +$this->privErrorReset(); + +// ----- Check archive +if (!$this->privCheckFormat()) { + return(0); +} + +// ----- Set default values +$v_options = array(); + +// ----- Look for variable options arguments +$v_size = func_num_args(); + +// ----- Look for arguments +if ($v_size > 0) { + // ----- Get the arguments + $v_arg_list = func_get_args(); + + // ----- Parse the options + $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, + array (PCLZIP_OPT_BY_NAME => 'optional', + PCLZIP_OPT_BY_EREG => 'optional', + PCLZIP_OPT_BY_PREG => 'optional', + PCLZIP_OPT_BY_INDEX => 'optional')); + if ($v_result != 1) { + return 0; + } +} + +// ----- Magic quotes trick +$this->privDisableMagicQuotes(); + +// ----- Call the delete fct +$v_list = array(); +if (($v_result = $this->privDeleteByRule($v_list, $v_options)) != 1) { + $this->privSwapBackMagicQuotes(); + unset($v_list); + return(0); +} + +// ----- Magic quotes trick +$this->privSwapBackMagicQuotes(); + +// ----- Return +return $v_list; +} +// -------------------------------------------------------------------------------- + +// -------------------------------------------------------------------------------- +// Function : deleteByIndex() +// Description : +// ***** Deprecated ***** +// delete(PCLZIP_OPT_BY_INDEX, $p_index) should be prefered. +// -------------------------------------------------------------------------------- +function deleteByIndex($p_index) +{ + +$p_list = $this->delete(PCLZIP_OPT_BY_INDEX, $p_index); + +// ----- Return +return $p_list; +} +// -------------------------------------------------------------------------------- + +// -------------------------------------------------------------------------------- +// Function : properties() +// Description : +// This method gives the properties of the archive. +// The properties are : +// nb : Number of files in the archive +// comment : Comment associated with the archive file +// status : not_exist, ok +// Parameters : +// None +// Return Values : +// 0 on failure, +// An array with the archive properties. +// -------------------------------------------------------------------------------- +function properties() +{ + +// ----- Reset the error handler +$this->privErrorReset(); + +// ----- Magic quotes trick +$this->privDisableMagicQuotes(); + +// ----- Check archive +if (!$this->privCheckFormat()) { + $this->privSwapBackMagicQuotes(); + return(0); +} + +// ----- Default properties +$v_prop = array(); +$v_prop['comment'] = ''; +$v_prop['nb'] = 0; +$v_prop['status'] = 'not_exist'; + +// ----- Look if file exists +if (@is_file($this->zipname)) +{ + // ----- Open the zip file + if (($this->zip_fd = @fopen($this->zipname, 'rb')) == 0) + { $this->privSwapBackMagicQuotes(); + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \''.$this->zipname.'\' in binary read mode'); // ----- Return - return $v_prop; + return 0; } - // -------------------------------------------------------------------------------- - // -------------------------------------------------------------------------------- - // Function : duplicate() - // Description : - // This method creates an archive by copying the content of an other one. If - // the archive already exist, it is replaced by the new one without any warning. - // Parameters : - // $p_archive : The filename of a valid archive, or - // a valid PclZip object. - // Return Values : - // 1 on success. - // 0 or a negative value on error (error code). - // -------------------------------------------------------------------------------- - function duplicate($p_archive) + // ----- Read the central directory informations + $v_central_dir = array(); + if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) { - $v_result = 1; - - // ----- Reset the error handler - $this->privErrorReset(); - - // ----- Look if the $p_archive is a PclZip object - if ((is_object($p_archive)) && (get_class($p_archive) == 'pclzip')) - { - - // ----- Duplicate the archive - $v_result = $this->privDuplicate($p_archive->zipname); - } - - // ----- Look if the $p_archive is a string (so a filename) - else if (is_string($p_archive)) - { - - // ----- Check that $p_archive is a valid zip file - // TBC : Should also check the archive format - if (!is_file($p_archive)) { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_MISSING_FILE, "No file with filename '".$p_archive."'"); - $v_result = PCLZIP_ERR_MISSING_FILE; - } - else { - // ----- Duplicate the archive - $v_result = $this->privDuplicate($p_archive); - } - } - - // ----- Invalid variable - else - { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_archive_to_add"); - $v_result = PCLZIP_ERR_INVALID_PARAMETER; - } - - // ----- Return - return $v_result; + $this->privSwapBackMagicQuotes(); + return 0; } - // -------------------------------------------------------------------------------- - // -------------------------------------------------------------------------------- - // Function : merge() - // Description : - // This method merge the $p_archive_to_add archive at the end of the current - // one ($this). - // If the archive ($this) does not exist, the merge becomes a duplicate. - // If the $p_archive_to_add archive does not exist, the merge is a success. - // Parameters : - // $p_archive_to_add : It can be directly the filename of a valid zip archive, - // or a PclZip object archive. - // Return Values : - // 1 on success, - // 0 or negative values on error (see below). - // -------------------------------------------------------------------------------- - function merge($p_archive_to_add) - { - $v_result = 1; + // ----- Close the zip file + $this->privCloseFd(); - // ----- Reset the error handler - $this->privErrorReset(); + // ----- Set the user attributes + $v_prop['comment'] = $v_central_dir['comment']; + $v_prop['nb'] = $v_central_dir['entries']; + $v_prop['status'] = 'ok'; +} - // ----- Check archive - if (!$this->privCheckFormat()) { - return(0); - } +// ----- Magic quotes trick +$this->privSwapBackMagicQuotes(); - // ----- Look if the $p_archive_to_add is a PclZip object - if ((is_object($p_archive_to_add)) && (get_class($p_archive_to_add) == 'pclzip')) - { +// ----- Return +return $v_prop; +} +// -------------------------------------------------------------------------------- - // ----- Merge the archive - $v_result = $this->privMerge($p_archive_to_add); - } +// -------------------------------------------------------------------------------- +// Function : duplicate() +// Description : +// This method creates an archive by copying the content of an other one. If +// the archive already exist, it is replaced by the new one without any warning. +// Parameters : +// $p_archive : The filename of a valid archive, or +// a valid PclZip object. +// Return Values : +// 1 on success. +// 0 or a negative value on error (error code). +// -------------------------------------------------------------------------------- +function duplicate($p_archive) +{ +$v_result = 1; - // ----- Look if the $p_archive_to_add is a string (so a filename) - else if (is_string($p_archive_to_add)) - { +// ----- Reset the error handler +$this->privErrorReset(); - // ----- Create a temporary archive - $v_object_archive = new PclZip($p_archive_to_add); +// ----- Look if the $p_archive is a PclZip object +if ((is_object($p_archive)) && (get_class($p_archive) == 'pclzip')) +{ - // ----- Merge the archive - $v_result = $this->privMerge($v_object_archive); - } + // ----- Duplicate the archive + $v_result = $this->privDuplicate($p_archive->zipname); +} - // ----- Invalid variable - else - { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_archive_to_add"); - $v_result = PCLZIP_ERR_INVALID_PARAMETER; - } +// ----- Look if the $p_archive is a string (so a filename) +else if (is_string($p_archive)) +{ - // ----- Return - return $v_result; + // ----- Check that $p_archive is a valid zip file + // TBC : Should also check the archive format + if (!is_file($p_archive)) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_FILE, "No file with filename '".$p_archive."'"); + $v_result = PCLZIP_ERR_MISSING_FILE; } - // -------------------------------------------------------------------------------- - - - - // -------------------------------------------------------------------------------- - // Function : errorCode() - // Description : - // Parameters : - // -------------------------------------------------------------------------------- - function errorCode() - { - if (PCLZIP_ERROR_EXTERNAL == 1) { - return(PclErrorCode()); - } - else { - return($this->error_code); - } + else { + // ----- Duplicate the archive + $v_result = $this->privDuplicate($p_archive); } - // -------------------------------------------------------------------------------- +} - // -------------------------------------------------------------------------------- - // Function : errorName() - // Description : - // Parameters : - // -------------------------------------------------------------------------------- - function errorName($p_with_code=false) - { - $v_name = array ( PCLZIP_ERR_NO_ERROR => 'PCLZIP_ERR_NO_ERROR', - PCLZIP_ERR_WRITE_OPEN_FAIL => 'PCLZIP_ERR_WRITE_OPEN_FAIL', - PCLZIP_ERR_READ_OPEN_FAIL => 'PCLZIP_ERR_READ_OPEN_FAIL', - PCLZIP_ERR_INVALID_PARAMETER => 'PCLZIP_ERR_INVALID_PARAMETER', - PCLZIP_ERR_MISSING_FILE => 'PCLZIP_ERR_MISSING_FILE', - PCLZIP_ERR_FILENAME_TOO_LONG => 'PCLZIP_ERR_FILENAME_TOO_LONG', - PCLZIP_ERR_INVALID_ZIP => 'PCLZIP_ERR_INVALID_ZIP', - PCLZIP_ERR_BAD_EXTRACTED_FILE => 'PCLZIP_ERR_BAD_EXTRACTED_FILE', - PCLZIP_ERR_DIR_CREATE_FAIL => 'PCLZIP_ERR_DIR_CREATE_FAIL', - PCLZIP_ERR_BAD_EXTENSION => 'PCLZIP_ERR_BAD_EXTENSION', - PCLZIP_ERR_BAD_FORMAT => 'PCLZIP_ERR_BAD_FORMAT', - PCLZIP_ERR_DELETE_FILE_FAIL => 'PCLZIP_ERR_DELETE_FILE_FAIL', - PCLZIP_ERR_RENAME_FILE_FAIL => 'PCLZIP_ERR_RENAME_FILE_FAIL', - PCLZIP_ERR_BAD_CHECKSUM => 'PCLZIP_ERR_BAD_CHECKSUM', - PCLZIP_ERR_INVALID_ARCHIVE_ZIP => 'PCLZIP_ERR_INVALID_ARCHIVE_ZIP', - PCLZIP_ERR_MISSING_OPTION_VALUE => 'PCLZIP_ERR_MISSING_OPTION_VALUE', - PCLZIP_ERR_INVALID_OPTION_VALUE => 'PCLZIP_ERR_INVALID_OPTION_VALUE', - PCLZIP_ERR_UNSUPPORTED_COMPRESSION => 'PCLZIP_ERR_UNSUPPORTED_COMPRESSION', - PCLZIP_ERR_UNSUPPORTED_ENCRYPTION => 'PCLZIP_ERR_UNSUPPORTED_ENCRYPTION' - ,PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE => 'PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE' - ,PCLZIP_ERR_DIRECTORY_RESTRICTION => 'PCLZIP_ERR_DIRECTORY_RESTRICTION' - ); +// ----- Invalid variable +else +{ + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_archive_to_add"); + $v_result = PCLZIP_ERR_INVALID_PARAMETER; +} - if (isset($v_name[$this->error_code])) { - $v_value = $v_name[$this->error_code]; - } - else { - $v_value = 'NoName'; - } +// ----- Return +return $v_result; +} +// -------------------------------------------------------------------------------- - if ($p_with_code) { - return($v_value.' ('.$this->error_code.')'); - } - else { - return($v_value); - } +// -------------------------------------------------------------------------------- +// Function : merge() +// Description : +// This method merge the $p_archive_to_add archive at the end of the current +// one ($this). +// If the archive ($this) does not exist, the merge becomes a duplicate. +// If the $p_archive_to_add archive does not exist, the merge is a success. +// Parameters : +// $p_archive_to_add : It can be directly the filename of a valid zip archive, +// or a PclZip object archive. +// Return Values : +// 1 on success, +// 0 or negative values on error (see below). +// -------------------------------------------------------------------------------- +function merge($p_archive_to_add) +{ +$v_result = 1; + +// ----- Reset the error handler +$this->privErrorReset(); + +// ----- Check archive +if (!$this->privCheckFormat()) { + return(0); +} + +// ----- Look if the $p_archive_to_add is a PclZip object +if ((is_object($p_archive_to_add)) && (get_class($p_archive_to_add) == 'pclzip')) +{ + + // ----- Merge the archive + $v_result = $this->privMerge($p_archive_to_add); +} + +// ----- Look if the $p_archive_to_add is a string (so a filename) +else if (is_string($p_archive_to_add)) +{ + + // ----- Create a temporary archive + $v_object_archive = new PclZip($p_archive_to_add); + + // ----- Merge the archive + $v_result = $this->privMerge($v_object_archive); +} + +// ----- Invalid variable +else +{ + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_archive_to_add"); + $v_result = PCLZIP_ERR_INVALID_PARAMETER; +} + +// ----- Return +return $v_result; +} +// -------------------------------------------------------------------------------- + + + +// -------------------------------------------------------------------------------- +// Function : errorCode() +// Description : +// Parameters : +// -------------------------------------------------------------------------------- +function errorCode() +{ +if (PCLZIP_ERROR_EXTERNAL == 1) { + return(PclErrorCode()); +} +else { + return($this->error_code); +} +} +// -------------------------------------------------------------------------------- + +// -------------------------------------------------------------------------------- +// Function : errorName() +// Description : +// Parameters : +// -------------------------------------------------------------------------------- +function errorName($p_with_code=false) +{ +$v_name = array (PCLZIP_ERR_NO_ERROR => 'PCLZIP_ERR_NO_ERROR', + PCLZIP_ERR_WRITE_OPEN_FAIL => 'PCLZIP_ERR_WRITE_OPEN_FAIL', + PCLZIP_ERR_READ_OPEN_FAIL => 'PCLZIP_ERR_READ_OPEN_FAIL', + PCLZIP_ERR_INVALID_PARAMETER => 'PCLZIP_ERR_INVALID_PARAMETER', + PCLZIP_ERR_MISSING_FILE => 'PCLZIP_ERR_MISSING_FILE', + PCLZIP_ERR_FILENAME_TOO_LONG => 'PCLZIP_ERR_FILENAME_TOO_LONG', + PCLZIP_ERR_INVALID_ZIP => 'PCLZIP_ERR_INVALID_ZIP', + PCLZIP_ERR_BAD_EXTRACTED_FILE => 'PCLZIP_ERR_BAD_EXTRACTED_FILE', + PCLZIP_ERR_DIR_CREATE_FAIL => 'PCLZIP_ERR_DIR_CREATE_FAIL', + PCLZIP_ERR_BAD_EXTENSION => 'PCLZIP_ERR_BAD_EXTENSION', + PCLZIP_ERR_BAD_FORMAT => 'PCLZIP_ERR_BAD_FORMAT', + PCLZIP_ERR_DELETE_FILE_FAIL => 'PCLZIP_ERR_DELETE_FILE_FAIL', + PCLZIP_ERR_RENAME_FILE_FAIL => 'PCLZIP_ERR_RENAME_FILE_FAIL', + PCLZIP_ERR_BAD_CHECKSUM => 'PCLZIP_ERR_BAD_CHECKSUM', + PCLZIP_ERR_INVALID_ARCHIVE_ZIP => 'PCLZIP_ERR_INVALID_ARCHIVE_ZIP', + PCLZIP_ERR_MISSING_OPTION_VALUE => 'PCLZIP_ERR_MISSING_OPTION_VALUE', + PCLZIP_ERR_INVALID_OPTION_VALUE => 'PCLZIP_ERR_INVALID_OPTION_VALUE', + PCLZIP_ERR_UNSUPPORTED_COMPRESSION => 'PCLZIP_ERR_UNSUPPORTED_COMPRESSION', + PCLZIP_ERR_UNSUPPORTED_ENCRYPTION => 'PCLZIP_ERR_UNSUPPORTED_ENCRYPTION' + ,PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE => 'PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE' + ,PCLZIP_ERR_DIRECTORY_RESTRICTION => 'PCLZIP_ERR_DIRECTORY_RESTRICTION' + ) ); + +if (isset($v_name[$this->error_code])) { + $v_value = $v_name[$this->error_code]; +} +else { + $v_value = 'NoName'; +} + +if ($p_with_code) { + return($v_value.' ('.$this->error_code.')'); +} +else { + return($v_value); +} +} +// -------------------------------------------------------------------------------- + +// -------------------------------------------------------------------------------- +// Function : errorInfo() +// Description : +// Parameters : +// -------------------------------------------------------------------------------- +function errorInfo($p_full=false) +{ +if (PCLZIP_ERROR_EXTERNAL == 1) { + return(PclErrorString()); +} +else { + if ($p_full) { + return($this->errorName(true)." : ".$this->error_string); } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : errorInfo() - // Description : - // Parameters : - // -------------------------------------------------------------------------------- - function errorInfo($p_full=false) - { - if (PCLZIP_ERROR_EXTERNAL == 1) { - return(PclErrorString()); - } - else { - if ($p_full) { - return($this->errorName(true)." : ".$this->error_string); - } - else { - return($this->error_string." [code ".$this->error_code."]"); - } - } + else { + return($this->error_string." [code ".$this->error_code."]"); } - // -------------------------------------------------------------------------------- +} +} +// -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- @@ -1356,3583 +1303,3453 @@ - // -------------------------------------------------------------------------------- - // Function : privCheckFormat() - // Description : - // This method check that the archive exists and is a valid zip archive. - // Several level of check exists. (futur) - // Parameters : - // $p_level : Level of check. Default 0. - // 0 : Check the first bytes (magic codes) (default value)) - // 1 : 0 + Check the central directory (futur) - // 2 : 1 + Check each file header (futur) - // Return Values : - // true on success, - // false on error, the error code is set. - // -------------------------------------------------------------------------------- - function privCheckFormat($p_level=0) - { - $v_result = true; +// -------------------------------------------------------------------------------- +// Function : privCheckFormat() +// Description : +// This method check that the archive exists and is a valid zip archive. +// Several level of check exists. (futur) +// Parameters : +// $p_level : Level of check. Default 0. +// 0 : Check the first bytes (magic codes) (default value)) +// 1 : 0 + Check the central directory (futur) +// 2 : 1 + Check each file header (futur) +// Return Values : +// true on success, +// false on error, the error code is set. +// -------------------------------------------------------------------------------- +function privCheckFormat($p_level=0) +{ +$v_result = true; - // ----- Reset the file system cache - clearstatcache(); +// ----- Reset the file system cache +clearstatcache(); - // ----- Reset the error handler - $this->privErrorReset(); +// ----- Reset the error handler +$this->privErrorReset(); - // ----- Look if the file exits - if (!is_file($this->zipname)) { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_MISSING_FILE, "Missing archive file '".$this->zipname."'"); - return(false); - } +// ----- Look if the file exits +if (!is_file($this->zipname)) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_FILE, "Missing archive file '".$this->zipname."'"); + return(false); +} - // ----- Check that the file is readeable - if (!is_readable($this->zipname)) { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, "Unable to read archive '".$this->zipname."'"); - return(false); - } +// ----- Check that the file is readeable +if (!is_readable($this->zipname)) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, "Unable to read archive '".$this->zipname."'"); + return(false); +} - // ----- Check the magic code - // TBC +// ----- Check the magic code +// TBC - // ----- Check the central header - // TBC +// ----- Check the central header +// TBC - // ----- Check each file header - // TBC +// ----- Check each file header +// TBC + +// ----- Return +return $v_result; +} +// -------------------------------------------------------------------------------- + +// -------------------------------------------------------------------------------- +// Function : privParseOptions() +// Description : +// This internal methods reads the variable list of arguments ($p_options_list, +// $p_size) and generate an array with the options and values ($v_result_list). +// $v_requested_options contains the options that can be present and those that +// must be present. +// $v_requested_options is an array, with the option value as key, and 'optional', +// or 'mandatory' as value. +// Parameters : +// See above. +// Return Values : +// 1 on success. +// 0 on failure. +// -------------------------------------------------------------------------------- +function privParseOptions(&$p_options_list, $p_size, &$v_result_list, $v_requested_options=false) +{ +$v_result=1; + +// ----- Read the options +$i=0; +while ($i<$p_size) { + + // ----- Check if the option is supported + if (!isset($v_requested_options[$p_options_list[$i]])) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid optional parameter '".$p_options_list[$i]."' for this method"); // ----- Return - return $v_result; + return PclZip::errorCode(); } - // -------------------------------------------------------------------------------- - // -------------------------------------------------------------------------------- - // Function : privParseOptions() - // Description : - // This internal methods reads the variable list of arguments ($p_options_list, - // $p_size) and generate an array with the options and values ($v_result_list). - // $v_requested_options contains the options that can be present and those that - // must be present. - // $v_requested_options is an array, with the option value as key, and 'optional', - // or 'mandatory' as value. - // Parameters : - // See above. - // Return Values : - // 1 on success. - // 0 on failure. - // -------------------------------------------------------------------------------- - function privParseOptions(&$p_options_list, $p_size, &$v_result_list, $v_requested_options=false) - { - $v_result=1; - - // ----- Read the options - $i=0; - while ($i<$p_size) { - - // ----- Check if the option is supported - if (!isset($v_requested_options[$p_options_list[$i]])) { + // ----- Look for next option + switch ($p_options_list[$i]) { + // ----- Look for options that request a path value + case PCLZIP_OPT_PATH : + case PCLZIP_OPT_REMOVE_PATH : + case PCLZIP_OPT_ADD_PATH : + // ----- Check the number of parameters + if (($i+1) >= $p_size) { // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid optional parameter '".$p_options_list[$i]."' for this method"); + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); // ----- Return return PclZip::errorCode(); } - // ----- Look for next option - switch ($p_options_list[$i]) { - // ----- Look for options that request a path value - case PCLZIP_OPT_PATH : - case PCLZIP_OPT_REMOVE_PATH : - case PCLZIP_OPT_ADD_PATH : - // ----- Check the number of parameters - if (($i+1) >= $p_size) { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); - - // ----- Return - return PclZip::errorCode(); - } - - // ----- Get the value - $v_result_list[$p_options_list[$i]] = PclZipUtilTranslateWinPath($p_options_list[$i+1], FALSE); - $i++; - break; - - case PCLZIP_OPT_TEMP_FILE_THRESHOLD : - // ----- Check the number of parameters - if (($i+1) >= $p_size) { - PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); - return PclZip::errorCode(); - } - - // ----- Check for incompatible options - if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_OFF])) { - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_OFF'"); - return PclZip::errorCode(); - } - - // ----- Check the value - $v_value = $p_options_list[$i+1]; - if ((!is_integer($v_value)) || ($v_value<0)) { - PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Integer expected for option '".PclZipUtilOptionText($p_options_list[$i])."'"); - return PclZip::errorCode(); - } - - // ----- Get the value (and convert it in bytes) - $v_result_list[$p_options_list[$i]] = $v_value*1048576; - $i++; - break; - - case PCLZIP_OPT_TEMP_FILE_ON : - // ----- Check for incompatible options - if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_OFF])) { - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_OFF'"); - return PclZip::errorCode(); - } - - $v_result_list[$p_options_list[$i]] = true; - break; - - case PCLZIP_OPT_TEMP_FILE_OFF : - // ----- Check for incompatible options - if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_ON])) { - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_ON'"); - return PclZip::errorCode(); - } - // ----- Check for incompatible options - if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_THRESHOLD])) { - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_THRESHOLD'"); - return PclZip::errorCode(); - } - - $v_result_list[$p_options_list[$i]] = true; - break; - - case PCLZIP_OPT_EXTRACT_DIR_RESTRICTION : - // ----- Check the number of parameters - if (($i+1) >= $p_size) { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); - - // ----- Return - return PclZip::errorCode(); - } - - // ----- Get the value - if ( is_string($p_options_list[$i+1]) - && ($p_options_list[$i+1] != '')) { - $v_result_list[$p_options_list[$i]] = PclZipUtilTranslateWinPath($p_options_list[$i+1], FALSE); - $i++; - } - else { - } - break; - - // ----- Look for options that request an array of string for value - case PCLZIP_OPT_BY_NAME : - // ----- Check the number of parameters - if (($i+1) >= $p_size) { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); - - // ----- Return - return PclZip::errorCode(); - } - - // ----- Get the value - if (is_string($p_options_list[$i+1])) { - $v_result_list[$p_options_list[$i]][0] = $p_options_list[$i+1]; - } - else if (is_array($p_options_list[$i+1])) { - $v_result_list[$p_options_list[$i]] = $p_options_list[$i+1]; - } - else { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Wrong parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); - - // ----- Return - return PclZip::errorCode(); - } - $i++; - break; - - // ----- Look for options that request an EREG or PREG expression - case PCLZIP_OPT_BY_EREG : - // ereg() is deprecated starting with PHP 5.3. Move PCLZIP_OPT_BY_EREG - // to PCLZIP_OPT_BY_PREG - $p_options_list[$i] = PCLZIP_OPT_BY_PREG; - case PCLZIP_OPT_BY_PREG : - //case PCLZIP_OPT_CRYPT : - // ----- Check the number of parameters - if (($i+1) >= $p_size) { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); - - // ----- Return - return PclZip::errorCode(); - } - - // ----- Get the value - if (is_string($p_options_list[$i+1])) { - $v_result_list[$p_options_list[$i]] = $p_options_list[$i+1]; - } - else { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Wrong parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); - - // ----- Return - return PclZip::errorCode(); - } - $i++; - break; - - // ----- Look for options that takes a string - case PCLZIP_OPT_COMMENT : - case PCLZIP_OPT_ADD_COMMENT : - case PCLZIP_OPT_PREPEND_COMMENT : - // ----- Check the number of parameters - if (($i+1) >= $p_size) { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, - "Missing parameter value for option '" - .PclZipUtilOptionText($p_options_list[$i]) - ."'"); - - // ----- Return - return PclZip::errorCode(); - } - - // ----- Get the value - if (is_string($p_options_list[$i+1])) { - $v_result_list[$p_options_list[$i]] = $p_options_list[$i+1]; - } - else { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, - "Wrong parameter value for option '" - .PclZipUtilOptionText($p_options_list[$i]) - ."'"); - - // ----- Return - return PclZip::errorCode(); - } - $i++; - break; - - // ----- Look for options that request an array of index - case PCLZIP_OPT_BY_INDEX : - // ----- Check the number of parameters - if (($i+1) >= $p_size) { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); - - // ----- Return - return PclZip::errorCode(); - } - - // ----- Get the value - $v_work_list = array(); - if (is_string($p_options_list[$i+1])) { - - // ----- Remove spaces - $p_options_list[$i+1] = strtr($p_options_list[$i+1], ' ', ''); - - // ----- Parse items - $v_work_list = explode(",", $p_options_list[$i+1]); - } - else if (is_integer($p_options_list[$i+1])) { - $v_work_list[0] = $p_options_list[$i+1].'-'.$p_options_list[$i+1]; - } - else if (is_array($p_options_list[$i+1])) { - $v_work_list = $p_options_list[$i+1]; - } - else { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Value must be integer, string or array for option '".PclZipUtilOptionText($p_options_list[$i])."'"); - - // ----- Return - return PclZip::errorCode(); - } - - // ----- Reduce the index list - // each index item in the list must be a couple with a start and - // an end value : [0,3], [5-5], [8-10], ... - // ----- Check the format of each item - $v_sort_flag=false; - $v_sort_value=0; - for ($j=0; $j= $p_size) { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); - - // ----- Return - return PclZip::errorCode(); - } - - // ----- Get the value - $v_result_list[$p_options_list[$i]] = $p_options_list[$i+1]; - $i++; - break; - - // ----- Look for options that request a call-back - case PCLZIP_CB_PRE_EXTRACT : - case PCLZIP_CB_POST_EXTRACT : - case PCLZIP_CB_PRE_ADD : - case PCLZIP_CB_POST_ADD : - /* for futur use - case PCLZIP_CB_PRE_DELETE : - case PCLZIP_CB_POST_DELETE : - case PCLZIP_CB_PRE_LIST : - case PCLZIP_CB_POST_LIST : - */ - // ----- Check the number of parameters - if (($i+1) >= $p_size) { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); - - // ----- Return - return PclZip::errorCode(); - } - - // ----- Get the value - $v_function_name = $p_options_list[$i+1]; - - // ----- Check that the value is a valid existing function - if (!function_exists($v_function_name)) { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Function '".$v_function_name."()' is not an existing function for option '".PclZipUtilOptionText($p_options_list[$i])."'"); - - // ----- Return - return PclZip::errorCode(); - } - - // ----- Set the attribute - $v_result_list[$p_options_list[$i]] = $v_function_name; - $i++; - break; - - default : - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, - "Unknown parameter '" - .$p_options_list[$i]."'"); - - // ----- Return - return PclZip::errorCode(); - } - - // ----- Next options + // ----- Get the value + $v_result_list[$p_options_list[$i]] = PclZipUtilTranslateWinPath($p_options_list[$i+1], false); $i++; - } + break; - // ----- Look for mandatory options - if ($v_requested_options !== false) { - for ($key=reset($v_requested_options); $key=key($v_requested_options); $key=next($v_requested_options)) { - // ----- Look for mandatory option - if ($v_requested_options[$key] == 'mandatory') { - // ----- Look if present - if (!isset($v_result_list[$key])) { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Missing mandatory parameter ".PclZipUtilOptionText($key)."(".$key.")"); - - // ----- Return - return PclZip::errorCode(); - } - } + case PCLZIP_OPT_TEMP_FILE_THRESHOLD : + // ----- Check the number of parameters + if (($i+1) >= $p_size) { + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + return PclZip::errorCode(); } - } - - // ----- Look for default values - if (!isset($v_result_list[PCLZIP_OPT_TEMP_FILE_THRESHOLD])) { - } + // ----- Check for incompatible options + if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_OFF])) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_OFF'"); + return PclZip::errorCode(); + } + + // ----- Check the value + $v_value = $p_options_list[$i+1]; + if ((!is_integer($v_value)) || ($v_value<0)) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Integer expected for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + return PclZip::errorCode(); + } - // ----- Return - return $v_result; - } - // -------------------------------------------------------------------------------- + // ----- Get the value (and convert it in bytes) + $v_result_list[$p_options_list[$i]] = $v_value*1048576; + $i++; + break; - // -------------------------------------------------------------------------------- - // Function : privOptionDefaultThreshold() - // Description : - // Parameters : - // Return Values : - // -------------------------------------------------------------------------------- - function privOptionDefaultThreshold(&$p_options) - { - $v_result=1; - - if (isset($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD]) - || isset($p_options[PCLZIP_OPT_TEMP_FILE_OFF])) { - return $v_result; - } - - // ----- Get 'memory_limit' configuration value - $v_memory_limit = ini_get('memory_limit'); - $v_memory_limit = trim($v_memory_limit); - $last = strtolower(substr($v_memory_limit, -1)); - - if ($last == 'g') - //$v_memory_limit = $v_memory_limit*1024*1024*1024; - $v_memory_limit = $v_memory_limit*1073741824; - if ($last == 'm') - //$v_memory_limit = $v_memory_limit*1024*1024; - $v_memory_limit = $v_memory_limit*1048576; - if ($last == 'k') - $v_memory_limit = $v_memory_limit*1024; - - $p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD] = floor($v_memory_limit*PCLZIP_TEMPORARY_FILE_RATIO); - + case PCLZIP_OPT_TEMP_FILE_ON : + // ----- Check for incompatible options + if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_OFF])) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_OFF'"); + return PclZip::errorCode(); + } + + $v_result_list[$p_options_list[$i]] = true; + break; - // ----- Sanity check : No threshold if value lower than 1M - if ($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD] < 1048576) { - unset($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD]); - } - - // ----- Return - return $v_result; - } - // -------------------------------------------------------------------------------- + case PCLZIP_OPT_TEMP_FILE_OFF : + // ----- Check for incompatible options + if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_ON])) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_ON'"); + return PclZip::errorCode(); + } + // ----- Check for incompatible options + if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_THRESHOLD])) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_THRESHOLD'"); + return PclZip::errorCode(); + } + + $v_result_list[$p_options_list[$i]] = true; + break; - // -------------------------------------------------------------------------------- - // Function : privFileDescrParseAtt() - // Description : - // Parameters : - // Return Values : - // 1 on success. - // 0 on failure. - // -------------------------------------------------------------------------------- - function privFileDescrParseAtt(&$p_file_list, &$p_filedescr, $v_options, $v_requested_options=false) - { - $v_result=1; - - // ----- For each file in the list check the attributes - foreach ($p_file_list as $v_key => $v_value) { - - // ----- Check if the option is supported - if (!isset($v_requested_options[$v_key])) { + case PCLZIP_OPT_EXTRACT_DIR_RESTRICTION : + // ----- Check the number of parameters + if (($i+1) >= $p_size) { // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid file attribute '".$v_key."' for this file"); + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); // ----- Return return PclZip::errorCode(); } - // ----- Look for attribute - switch ($v_key) { - case PCLZIP_ATT_FILE_NAME : - if (!is_string($v_value)) { - PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".PclZipUtilOptionText($v_key)."'"); - return PclZip::errorCode(); - } + // ----- Get the value + if (is_string($p_options_list[$i+1]) + && ($p_options_list[$i+1] != '')) { + $v_result_list[$p_options_list[$i]] = PclZipUtilTranslateWinPath($p_options_list[$i+1], false); + $i++; + } + else { + } + break; - $p_filedescr['filename'] = PclZipUtilPathReduction($v_value); - - if ($p_filedescr['filename'] == '') { - PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid empty filename for attribute '".PclZipUtilOptionText($v_key)."'"); - return PclZip::errorCode(); - } + // ----- Look for options that request an array of string for value + case PCLZIP_OPT_BY_NAME : + // ----- Check the number of parameters + if (($i+1) >= $p_size) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); - break; - - case PCLZIP_ATT_FILE_NEW_SHORT_NAME : - if (!is_string($v_value)) { - PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".PclZipUtilOptionText($v_key)."'"); - return PclZip::errorCode(); - } - - $p_filedescr['new_short_name'] = PclZipUtilPathReduction($v_value); - - if ($p_filedescr['new_short_name'] == '') { - PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid empty short filename for attribute '".PclZipUtilOptionText($v_key)."'"); - return PclZip::errorCode(); - } - break; - - case PCLZIP_ATT_FILE_NEW_FULL_NAME : - if (!is_string($v_value)) { - PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".PclZipUtilOptionText($v_key)."'"); - return PclZip::errorCode(); - } - - $p_filedescr['new_full_name'] = PclZipUtilPathReduction($v_value); - - if ($p_filedescr['new_full_name'] == '') { - PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid empty full filename for attribute '".PclZipUtilOptionText($v_key)."'"); - return PclZip::errorCode(); - } - break; - - // ----- Look for options that takes a string - case PCLZIP_ATT_FILE_COMMENT : - if (!is_string($v_value)) { - PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".PclZipUtilOptionText($v_key)."'"); - return PclZip::errorCode(); - } - - $p_filedescr['comment'] = $v_value; - break; - - case PCLZIP_ATT_FILE_MTIME : - if (!is_integer($v_value)) { - PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". Integer expected for attribute '".PclZipUtilOptionText($v_key)."'"); - return PclZip::errorCode(); - } - - $p_filedescr['mtime'] = $v_value; - break; - - case PCLZIP_ATT_FILE_CONTENT : - $p_filedescr['content'] = $v_value; - break; - - default : - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, - "Unknown parameter '".$v_key."'"); - - // ----- Return - return PclZip::errorCode(); + // ----- Return + return PclZip::errorCode(); } - // ----- Look for mandatory options - if ($v_requested_options !== false) { - for ($key=reset($v_requested_options); $key=key($v_requested_options); $key=next($v_requested_options)) { - // ----- Look for mandatory option - if ($v_requested_options[$key] == 'mandatory') { - // ----- Look if present - if (!isset($p_file_list[$key])) { - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Missing mandatory parameter ".PclZipUtilOptionText($key)."(".$key.")"); - return PclZip::errorCode(); - } - } - } + // ----- Get the value + if (is_string($p_options_list[$i+1])) { + $v_result_list[$p_options_list[$i]][0] = $p_options_list[$i+1]; } - - // end foreach - } - - // ----- Return - return $v_result; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : privFileDescrExpand() - // Description : - // This method look for each item of the list to see if its a file, a folder - // or a string to be added as file. For any other type of files (link, other) - // just ignore the item. - // Then prepare the information that will be stored for that file. - // When its a folder, expand the folder with all the files that are in that - // folder (recursively). - // Parameters : - // Return Values : - // 1 on success. - // 0 on failure. - // -------------------------------------------------------------------------------- - function privFileDescrExpand(&$p_filedescr_list, &$p_options) - { - $v_result=1; - - // ----- Create a result list - $v_result_list = array(); - - // ----- Look each entry - for ($i=0; $i= $p_size) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Get the value + if (is_string($p_options_list[$i+1])) { + $v_result_list[$p_options_list[$i]] = $p_options_list[$i+1]; + } + else { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Wrong parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + + // ----- Return + return PclZip::errorCode(); + } + $i++; + break; + + // ----- Look for options that takes a string + case PCLZIP_OPT_COMMENT : + case PCLZIP_OPT_ADD_COMMENT : + case PCLZIP_OPT_PREPEND_COMMENT : + // ----- Check the number of parameters + if (($i+1) >= $p_size) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, + "Missing parameter value for option '" + .PclZipUtilOptionText($p_options_list[$i]) + ."'"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Get the value + if (is_string($p_options_list[$i+1])) { + $v_result_list[$p_options_list[$i]] = $p_options_list[$i+1]; + } + else { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, + "Wrong parameter value for option '" + .PclZipUtilOptionText($p_options_list[$i]) + ."'"); + + // ----- Return + return PclZip::errorCode(); + } + $i++; + break; + + // ----- Look for options that request an array of index + case PCLZIP_OPT_BY_INDEX : + // ----- Check the number of parameters + if (($i+1) >= $p_size) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Get the value + $v_work_list = array(); + if (is_string($p_options_list[$i+1])) { + + // ----- Remove spaces + $p_options_list[$i+1] = strtr($p_options_list[$i+1], ' ', ''); + + // ----- Parse items + $v_work_list = explode(",", $p_options_list[$i+1]); + } + else if (is_integer($p_options_list[$i+1])) { + $v_work_list[0] = $p_options_list[$i+1].'-'.$p_options_list[$i+1]; + } + else if (is_array($p_options_list[$i+1])) { + $v_work_list = $p_options_list[$i+1]; + } + else { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Value must be integer, string or array for option '".PclZipUtilOptionText($p_options_list[$i])."'"); // ----- Return return PclZip::errorCode(); } - // ----- Calculate the stored filename - $this->privCalculateStoredFilename($v_descr, $p_options); - - // ----- Add the descriptor in result list - $v_result_list[sizeof($v_result_list)] = $v_descr; - - // ----- Look for folder - if ($v_descr['type'] == 'folder') { - // ----- List of items in folder - $v_dirlist_descr = array(); - $v_dirlist_nb = 0; - if ($v_folder_handler = @opendir($v_descr['filename'])) { - while (($v_item_handler = @readdir($v_folder_handler)) !== false) { + // ----- Reduce the index list + // each index item in the list must be a couple with a start and + // an end value : [0,3], [5-5], [8-10], ... + // ----- Check the format of each item + $v_sort_flag=false; + $v_sort_value=0; + for ($j=0; $j= $p_size) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Get the value + $v_result_list[$p_options_list[$i]] = $p_options_list[$i+1]; + $i++; + break; + + // ----- Look for options that request a call-back + case PCLZIP_CB_PRE_EXTRACT : + case PCLZIP_CB_POST_EXTRACT : + case PCLZIP_CB_PRE_ADD : + case PCLZIP_CB_POST_ADD : + /* for futur use + case PCLZIP_CB_PRE_DELETE : + case PCLZIP_CB_POST_DELETE : + case PCLZIP_CB_PRE_LIST : + case PCLZIP_CB_POST_LIST : + */ + // ----- Check the number of parameters + if (($i+1) >= $p_size) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Get the value + $v_function_name = $p_options_list[$i+1]; + + // ----- Check that the value is a valid existing function + if (!function_exists($v_function_name)) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VA )); + if ($v_result != 1) { + return 0; + } + } + + // ----- Look for 2 args + // Here we need to support the first historic synopsis of the + // method. + else { + + // ----- Get the first argument + $v_options[PCLZIP_OPT_ADD_PATH] = $v_arg_list[0]; + + // ----- Look for the optional second argument + if ($v_size == 2) { + $v_options[PCLZIP_OPT_REMOVE_PATH] = $v_arg_list[1]; + } + else if ($v_size > 2) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, + "Invalid number / type of arguments"); + return 0; + } + } +} + +// ----- Look for default option values +$this->privOptionDefaultThreshold($v_options); + +// ----- Init +$v_string_list = array(); +$v_att_list = array(); +$v_filedescr_list = array(); +$p_result_list = array(); + +// ----- Look if the $p_filelist is really an array +if (is_array($p_filelist)) { + + // ----- Look if the first element is also an array + // This will mean that this is a file description entry + if (isset($p_filelist[0]) && is_array($p_filelist[0])) { + $v_att_list = $p_filelist; + } + + // ----- The list is a list of string names + else { + $v_string_list = $p_filelist; + } +} + +// ----- Look if the $p_filelist is a string +else if (is_string($p_filelist)) { + // ----- Create a list from the string + $v_string_list = explode(PCLZIP_SEPARATOR, $p_filelist); +} + +// ----- Invalid variable type for $p_filelist +else { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_filelist"); + return 0; +} + +// ----- Reformat the string list +if (sizeof($v_string_list) != 0) { + foreach ($v_string_list as $v_string) { + if ($v_string != '') { + $v_att_list[][PCLZIP_ATT_FILE_NAME] = $v_string; + } + else { + } + } +} + +// ----- For each file in the list check the attributes +$v_supported_attributes += array (PCLZIP_ATT_FILE_NAME => 'mandatory' + ,PCLZIP_ATT_FILE_NEW_SHORT_NAME => 'optional' + ,PCLZIP_ATT_FILE_NEW_FULL_NAME => 'optional' + ,PCLZIP_ATT_FILE_MTIME => 'optional' + ,PCLZIP_ATT_FILE_CONTENT => 'optional' + ,PCLZIP_ATT_FILE_COMMENT => 'optional' + ); +foreach ($v_att_list as $v_entry) { + $v_result = $this->privFileDescrParseAtt($v_entry, + $v_filedescr_list[], + $v_options, + $v_supported_attributes); + if ($v_result != 1) { + return 0; + } +} + +// ----- Expand the filelist (expand directories) +$v_result = $this->privFileDescrExpand($v_filedescr_list, $v_options); +if ($v_result != 1) { + return 0; +} + +// ----- Call the create fct +$v_result = $this->privCreate($v_filedescr_list, $p_result_list, $v_options); +if ($v_result != 1) { + return 0; +} + +// ----- Return +return $p_result_list; +} +// -------------------------------------------------------------------------------- + +// -------------------------------------------------------------------------------- +// Function : +// add($p_filelist, $p_add_dir="", $p_remove_dir="") +// add($p_filelist, $p_option, $p_option_value, ...) +// Description : +// This method supports two synopsis. The first one is historical. +// This methods add the list of files in an existing archive. +// If a file with the same name already exists, it is added at the end of the +// archive, the first one is still present. +// If the archive does not exist, it is created. +// Parameters : +// $p_filelist : An array containing file or directory names, or +// a string containing one filename or one directory name, or +// a string containing a list of filenames and/or directory +// names separated by spaces. +// $p_add_dir : A path to add before the real path of the archived file, +// in order to have it memorized in the archive. +// $p_remove_dir : A path to remove from the real path of the file to archive, +// in order to have a shorter path memorized in the archive. +// When $p_add_dir and $p_remove_dir are set, $p_remove_dir +// is removed first, before $p_add_dir is added. +// Options : +// PCLZIP_OPT_ADD_PATH : +// PCLZIP_OPT_REMOVE_PATH : +// PCLZIP_OPT_REMOVE_ALL_PATH : +// PCLZIP_OPT_COMMENT : +// PCLZIP_OPT_ADD_COMMENT : +// PCLZIP_OPT_PREPEND_COMMENT : +// PCLZIP_CB_PRE_ADD : +// PCLZIP_CB_POST_ADD : +// Return Values : +// 0 on failure, +// The list of the added files, with a status of the add action. +// (see PclZip::listContent() for list entry format) +// -------------------------------------------------------------------------------- +function add($p_filelist) +{ +$v_result=1; + +// ----- Reset the error handler +$this->privErrorReset(); + +// ----- Set default values +$v_options = array(); +$v_options[PCLZIP_OPT_NO_COMPRESSION] = false; + +// ----- Look for variable options arguments +$v_size = func_num_args(); + +// ----- Look for arguments +if ($v_size > 1) { + // ----- Get the arguments + $v_arg_list = func_get_args(); + + // ----- Remove form the options list the first argument + array_shift($v_arg_list); + $v_size--; + + // ----- Look for first arg + if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) { + + // ----- Parse the options + $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, + array (PCLZIP_OPT_REMOVE_PATH => 'optional', + PCLZIP_OPT_REMOVE_ALL_PATH => 'optional', + PCLZIP_OPT_ADD_PATH => 'optional', + PCLZIP_CB_PRE_ADD => 'optional', + PCLZIP_CB_POST_ADD => 'optional', + PCLZIP_OPT_NO_COMPRESSION => 'optional', + PCLZIP_OPT_COMMENT => 'optional', + PCLZIP_OPT_ADD_COMMENT => 'optional', + PCLZIP_OPT_PREPEND_COMMENT => 'optional', + PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional', + PCLZIP_OPT_TEMP_FILE_ON => 'optional', + PCLZIP_OPT_TEMP_FILE_OFF => 'optional' + //, PCLZIP_OPT_CRYPT => 'optional' + )); + if ($v_result != 1) { + return 0; + } + } + + // ----- Look for 2 args + // Here we need to support the first historic synopsis of the + // method. + else { + + // ----- Get the first argument + $v_options[PCLZIP_OPT_ADD_PATH] = $v_add_path = $v_arg_list[0]; + + // ----- Look for the optional second argument + if ($v_size == 2) { + $v_options[PCLZIP_OPT_REMOVE_PATH] = $v_arg_list[1]; + } + else if ($v_size > 2) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments"); + + // ----- Return + return 0; + } + } +} + +// ----- Look for default option values +$this->privOptionDefaultThreshold($v_options); + +// ----- Init +$v_string_list = array(); +$v_att_list = array(); +$v_filedescr_list = array(); +$p_result_list = array(); + +// ----- Look if the $p_filelist is really an array +if (is_array($p_filelist)) { + + // ----- Look if the first element is also an array + // This will mean that this is a file description entry + if (isset($p_filelist[0]) && is_array($p_filelist[0])) { + $v_att_list = $p_filelist; + } + + // ----- The list is a list of string names + else { + $v_string_list = $p_filelist; + } +} + +// ----- Look if the $p_filelist is a string +else if (is_string($p_filelist)) { + // ----- Create a list from the string + $v_string_list = explode(PCLZIP_SEPARATOR, $p_filelist); +} + +// ----- Invalid variable type for $p_filelist +else { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type '".gettype($p_filelist)."' for p_filelist"); + return 0; +} + +// ----- Reformat the string list +if (sizeof($v_string_list) != 0) { + foreach ($v_string_list as $v_string) { + $v_att_list[][PCLZIP_ATT_FILE_NAME] = $v_string; + } +} + +// ----- For each file in the list check the attributes +$v_supported_attributes += array (PCLZIP_ATT_FILE_NAME => 'mandatory' + ,PCLZIP_ATT_FILE_NEW_SHORT_NAME => 'optional' + ,PCLZIP_ATT_FILE_NEW_FULL_NAME => 'optional' + ,PCLZIP_ATT_FILE_MTIME => 'optional' + ,PCLZIP_ATT_FILE_CONTENT => 'optional' + ,PCLZIP_ATT_FILE_COMMENT => 'optional' + ); +foreach ($v_att_list as $v_entry) { + $v_result = $this->privFileDescrParseAtt($v_entry, + $v_filedescr_list[], + $v_options, + $v_supported_attributes); + if ($v_result != 1) { + return 0; + } +} + +// ----- Expand the filelist (expand directories) +$v_result = $this->privFileDescrExpand($v_filedescr_list, $v_options); +if ($v_result != 1) { + return 0; +} + +// ----- Call the create fct +$v_result = $this->privAdd($v_filedescr_list, $p_result_list, $v_options); +if ($v_result != 1) { + return 0; +} + +// ----- Return +return $p_result_list; +} +// -------------------------------------------------------------------------------- + +// -------------------------------------------------------------------------------- +// Function : listContent() +// Description : +// This public method, gives the list of the files and directories, with their +// properties. +// The properties of each entries in the list are (used also in other functions) : +// filename : Name of the file. For a create or add action it is the filename +// given by the user. For an extract function it is the filename +// of the extracted file. +// stored_filename : Name of the file / directory stored in the archive. +// size : Size of the stored file. +// compressed_size : Size of the file's data compressed in the archive +// (without the headers overhead) +// mtime : Last known modification date of the file (UNIX timestamp) +// comment : Comment associated with the file +// folder : true | false +// index : index of the file in the archive +// status : status of the action (depending of the action) : +// Values are : +// ok : OK ! +// filtered : the file / dir is not extracted (filtered by user) +// already_a_directory : the file can not be extracted because a +// directory with the same name already exists +// write_protected : the file can not be extracted because a file +// with the same name already exists and is +// write protected +// newer_exist : the file was not extracted because a newer file exists +// path_creation_fail : the file is not extracted because the folder +// does not exist and can not be created +// write_error : the file was not extracted because there was a +// error while writing the file +// read_error : the file was not extracted because there was a error +// while reading the file +// invalid_header : the file was not extracted because of an archive +// format error (bad file header) +// Note that each time a method can continue operating when there +// is an action error on a file, the error is only logged in the file status. +// Return Values : +// 0 on an unrecoverable failure, +// The list of the files in the archive. +// -------------------------------------------------------------------------------- +function listContent() +{ +$v_result=1; + +// ----- Reset the error handler +$this->privErrorReset(); + +// ----- Check archive +if (!$this->privCheckFormat()) { + return(0); +} + +// ----- Call the extracting fct +$p_list = array(); +if (($v_result = $this->privList($p_list)) != 1) +{ + unset($p_list); + return(0); +} + +// ----- Return +return $p_list; +} +// -------------------------------------------------------------------------------- + +// -------------------------------------------------------------------------------- +// Function : +// extract($p_path="./", $p_remove_path="") +// extract([$p_option, $p_option_value, ...]) +// Description : +// This method supports two synopsis. The first one is historical. +// This method extract all the files / directories from the archive to the +// folder indicated in $p_path. +// If you want to ignore the 'root' part of path of the memorized files +// you can indicate this in the optional $p_remove_path parameter. +// By default, if a newer file with the same name already exists, the +// file is not extracted. +// +// If both PCLZIP_OPT_PATH and PCLZIP_OPT_ADD_PATH aoptions +// are used, the path indicated in PCLZIP_OPT_ADD_PATH is append +// at the end of the path value of PCLZIP_OPT_PATH. +// Parameters : +// $p_path : Path where the files and directories are to be extracted +// $p_remove_path : First part ('root' part) of the memorized path +// (if any similar) to remove while extracting. +// Options : +// PCLZIP_OPT_PATH : +// PCLZIP_OPT_ADD_PATH : +// PCLZIP_OPT_REMOVE_PATH : +// PCLZIP_OPT_REMOVE_ALL_PATH : +// PCLZIP_CB_PRE_EXTRACT : +// PCLZIP_CB_POST_EXTRACT : +// Return Values : +// 0 or a negative value on failure, +// The list of the extracted files, with a status of the action. +// (see PclZip::listContent() for list entry format) +// -------------------------------------------------------------------------------- +function extract() +{ +$v_result=1; + +// ----- Reset the error handler +$this->privErrorReset(); + +// ----- Check archive +if (!$this->privCheckFormat()) { + return(0); +} + +// ----- Set default values +$v_options = array(); +// $v_path = "./"; +$v_path = ''; +$v_remove_path = ""; +$v_remove_all_path = false; + +// ----- Look for variable options arguments +$v_size = func_num_args(); + +// ----- Default values for option +$v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = false; + +// ----- Look for arguments +if ($v_size > 0) { + // ----- Get the arguments + $v_arg_list = func_get_args(); + + // ----- Look for first arg + if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) { + + // ----- Parse the options + $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, + array (PCLZIP_OPT_PATH => 'optional', + PCLZIP_OPT_REMOVE_PATH => 'optional', + PCLZIP_OPT_REMOVE_ALL_PATH => 'optional', + PCLZIP_OPT_ADD_PATH => 'optional', + PCLZIP_CB_PRE_EXTRACT => 'optional', + PCLZIP_CB_POST_EXTRACT => 'optional', + PCLZIP_OPT_SET_CHMOD => 'optional', + PCLZIP_OPT_BY_NAME => 'optional', + PCLZIP_OPT_BY_EREG => 'optional', + PCLZIP_OPT_BY_PREG => 'optional', + PCLZIP_OPT_BY_INDEX => 'optional', + PCLZIP_OPT_EXTRACT_AS_STRING => 'optional', + PCLZIP_OPT_EXTRACT_IN_OUTPUT => 'optional', + PCLZIP_OPT_REPLACE_NEWER => 'optional' + ,PCLZIP_OPT_STOP_ON_ERROR => 'optional' + ,PCLZIP_OPT_EXTRACT_DIR_RESTRICTION => 'optional', + PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional', + PCLZIP_OPT_TEMP_FILE_ON => 'optional', + PCLZIP_OPT_TEMP_FILE_OFF => 'optional' + )); + if ($v_result != 1) { + return 0; + } + + // ----- Set the arguments + if (isset($v_options[PCLZIP_OPT_PATH])) { + $v_path = $v_options[PCLZIP_OPT_PATH]; + } + if (isset($v_options[PCLZIP_OPT_REMOVE_PATH])) { + $v_remove_path = $v_options[PCLZIP_OPT_REMOVE_PATH]; + } + if (isset($v_options[PCLZIP_OPT_REMOVE_ALL_PATH])) { + $v_remove_all_path = $v_options[PCLZIP_OPT_REMOVE_ALL_PATH]; + } + if (isset($v_options[PCLZIP_OPT_ADD_PATH])) { + // ----- Check for '/' in last path char + if ((strlen($v_path) > 0) && (substr($v_path, -1) != '/')) { + $v_path .= '/'; + } + $v_path .= $v_options[PCLZIP_OPT_ADD_PATH]; + } + } + + // ----- Look for 2 args + // Here we need to support the first historic synopsis of the + // method. + else { + + // ----- Get the first argument + $v_path = $v_arg_list[0]; + + // ----- Look for the optional second argument + if ($v_size == 2) { + $v_remove_path = $v_arg_list[1]; + } + else if ($v_size > 2) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments"); + + // ----- Return + return 0; + } + } +} + +// ----- Look for default option values +$this->privOptionDefaultThreshold($v_options); + +// ----- Trace + +// ----- Call the extracting fct +$p_list = array(); +$v_result = $this->privExtractByRule($p_list, $v_path, $v_remove_path, + $v_remove_all_path, $v_options); +if ($v_result < 1) { + unset($p_list); + return(0); +} + +// ----- Return +return $p_list; +} +// -------------------------------------------------------------------------------- + + +// -------------------------------------------------------------------------------- +// Function : +// extractByIndex($p_index, $p_path="./", $p_remove_path="") +// extractByIndex($p_index, [$p_option, $p_option_value, ...]) +// Description : +// This method supports two synopsis. The first one is historical. +// This method is doing a partial extract of the archive. +// The extracted files or folders are identified by their index in the +// archive (from 0 to n). +// Note that if the index identify a folder, only the folder entry is +// extracted, not all the files included in the archive. +// Parameters : +// $p_index : A single index (integer) or a string of indexes of files to +// extract. The form of the string is "0,4-6,8-12" with only numbers +// and '-' for range or ',' to separate ranges. No spaces or ';' +// are allowed. +// $p_path : Path where the files and directories are to be extracted +// $p_remove_path : First part ('root' part) of the memorized path +// (if any similar) to remove while extracting. +// Options : +// PCLZIP_OPT_PATH : +// PCLZIP_OPT_ADD_PATH : +// PCLZIP_OPT_REMOVE_PATH : +// PCLZIP_OPT_REMOVE_ALL_PATH : +// PCLZIP_OPT_EXTRACT_AS_STRING : The files are extracted as strings and +// not as files. +// The resulting content is in a new field 'content' in the file +// structure. +// This option must be used alone (any other options are ignored). +// PCLZIP_CB_PRE_EXTRACT : +// PCLZIP_CB_POST_EXTRACT : +// Return Values : +// 0 on failure, +// The list of the extracted files, with a status of the action. +// (see PclZip::listContent() for list entry format) +// -------------------------------------------------------------------------------- +//function extractByIndex($p_index, options...) +function extractByIndex($p_index) +{ +$v_result=1; + +// ----- Reset the error handler +$this->privErrorReset(); + +// ----- Check archive +if (!$this->privCheckFormat()) { + return(0); +} + +// ----- Set default values +$v_options = array(); +// $v_path = "./"; +$v_path = ''; +$v_remove_path = ""; +$v_remove_all_path = false; + +// ----- Look for variable options arguments +$v_size = func_num_args(); + +// ----- Default values for option +$v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = false; + +// ----- Look for arguments +if ($v_size > 1) { + // ----- Get the arguments + $v_arg_list = func_get_args(); + + // ----- Remove form the options list the first argument + array_shift($v_arg_list); + $v_size--; + + // ----- Look for first arg + if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) { + + // ----- Parse the options + $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, + array (PCLZIP_OPT_PATH => 'optional', + PCLZIP_OPT_REMOVE_PATH => 'optional', + PCLZIP_OPT_REMOVE_ALL_PATH => 'optional', + PCLZIP_OPT_EXTRACT_AS_STRING => 'optional', + PCLZIP_OPT_ADD_PATH => 'optional', + PCLZIP_CB_PRE_EXTRACT => 'optional', + PCLZIP_CB_POST_EXTRACT => 'optional', + PCLZIP_OPT_SET_CHMOD => 'optional', + PCLZIP_OPT_REPLACE_NEWER => 'optional' + ,PCLZIP_OPT_STOP_ON_ERROR => 'optional' + ,PCLZIP_OPT_EXTRACT_DIR_RESTRICTION => 'optional', + PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional', + PCLZIP_OPT_TEMP_FILE_ON => 'optional', + PCLZIP_OPT_TEMP_FILE_OFF => 'optional' + )); + if ($v_result != 1) { + return 0; + } + + // ----- Set the arguments + if (isset($v_options[PCLZIP_OPT_PATH])) { + $v_path = $v_options[PCLZIP_OPT_PATH]; + } + if (isset($v_options[PCLZIP_OPT_REMOVE_PATH])) { + $v_remove_path = $v_options[PCLZIP_OPT_REMOVE_PATH]; + } + if (isset($v_options[PCLZIP_OPT_REMOVE_ALL_PATH])) { + $v_remove_all_path = $v_options[PCLZIP_OPT_REMOVE_ALL_PATH]; + } + if (isset($v_options[PCLZIP_OPT_ADD_PATH])) { + // ----- Check for '/' in last path char + if ((strlen($v_path) > 0) && (substr($v_path, -1) != '/')) { + $v_path .= '/'; + } + $v_path .= $v_options[PCLZIP_OPT_ADD_PATH]; + } + if (!isset($v_options[PCLZIP_OPT_EXTRACT_AS_STRING])) { + $v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = false; + } + else { + } + } + + // ----- Look for 2 args + // Here we need to support the first historic synopsis of the + // method. + else ){ + + // ----- Get the first argument + $v_path = $v_arg_list[0]; + + // ----- Look for the optional second argument + if ($v_size == 2) { + $v_remove_path = $v_arg_list[1]; + } + else if ($v_size > 2) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments"); + + // ----- Return + return 0; + } + } +} + +// ----- Trace + +// ----- Trick +// Here I want to reuse extractByRule(), so I need to parse the $p_index +// with privParseOptions() +$v_arg_trick = array (PCLZIP_OPT_BY_INDEX, $p_index); +$v_options_trick = array(); +$v_result = $this->privParseOptions($v_arg_trick, sizeof($v_arg_trick), $v_options_trick, + array (PCLZIP_OPT_BY_INDEX => 'optional')); +if ($v_result != 1) { + return 0; +} +$v_options[PCLZIP_OPT_BY_INDEX] = $v_options_trick[PCLZIP_OPT_BY_INDEX]; + +// ----- Look for default option values +$this->privOptionDefaultThreshold($v_options); + +// ----- Call the extracting fct +if (($v_result = $this->privExtractByRule($p_list, $v_path, $v_remove_path, $v_remove_all_path, $v_options)) < 1) { + return(0); +} + +// ----- Return +return $p_list; +} +// -------------------------------------------------------------------------------- + +// -------------------------------------------------------------------------------- +// Function : +// delete([$p_option, $p_option_value, ...]) +// Description : +// This method removes files from the archive. +// If no parameters are given, then all the archive is emptied. +// Parameters : +// None or optional arguments. +// Options : +// PCLZIP_OPT_BY_INDEX : +// PCLZIP_OPT_BY_NAME : +// PCLZIP_OPT_BY_EREG : +// PCLZIP_OPT_BY_PREG : +// Return Values : +// 0 on failure, +// The list of the files which are still present in the archive. +// (see PclZip::listContent() for list entry format) +// -------------------------------------------------------------------------------- +function delete() +{ +$v_result=1; + +// ----- Reset the error handler +$this->privErrorReset(); + +// ----- Check archive +if (!$this->privCheckFormat()) { + return(0); +} + +// ----- Set default values +$v_options = array(); + +// ----- Look for variable options arguments +$v_size = func_num_args(); + +// ----- Look for arguments +if ($v_size > 0) { + // ----- Get the arguments + $v_arg_list = func_get_args(); + + // ----- Parse the options + $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, + array (PCLZIP_OPT_BY_NAME => 'optional', + PCLZIP_OPT_BY_EREG => 'optional', + PCLZIP_OPT_BY_PREG => 'optional', + PCLZIP_OPT_BY_INDEX => 'optional')); + if ($v_result != 1) { + return 0; + } +} + +// ----- Magic quotes trick +$this->privDisableMagicQuotes(); + +// ----- Call the delete fct +$v_list = array(); +if (($v_result = $this->privDeleteByRule($v_list, $v_options)) != 1) { + $this->privSwapBackMagicQuotes(); + unset($v_list); + return(0); +} + +// ----- Magic quotes trick +$this->privSwapBackMagicQuotes(); + +// ----- Return +return $v_list; +} +// -------------------------------------------------------------------------------- + +// -------------------------------------------------------------------------------- +// Function : deleteByIndex() +// Description : +// ***** Deprecated ***** +// delete(PCLZIP_OPT_BY_INDEX, $p_index) should be prefered. +// -------------------------------------------------------------------------------- +function deleteByIndex($p_index) +{ + +$p_list = $this->delete(PCLZIP_OPT_BY_INDEX, $p_index); + +// ----- Return +return $p_list; +} +// -------------------------------------------------------------------------------- + +// -------------------------------------------------------------------------------- +// Function : properties() +// Description : +// This method gives the properties of the archive. +// The properties are : +// nb : Number of files in the archive +// comment : Comment associated with the archive file +// status : not_exist, ok +// Parameters : +// None +// Return Values : +// 0 on failure, +// An array with the archive properties. +// -------------------------------------------------------------------------------- +function properties() +{ + +// ----- Reset the error handler +$this->privErrorReset(); + +// ----- Magic quotes trick +$this->privDisableMagicQuotes(); + +// ----- Check archive +if (!$this->privCheckFormat()) { + $this->privSwapBackMagicQuotes(); + return(0); +} + +// ----- Default properties +$v_prop = array(); +$v_prop['comment'] = ''; +$v_prop['nb'] = 0; +$v_prop['status'] = 'not_exist'; + +// ----- Look if file exists +if (@is_file($this->zipname)) +{ + // ----- Open the zip file + if (($this->zip_fd = @fopen($this->zipname, 'rb')) == 0) + { + $this->privSwapBackMagicQuotes(); + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \''.$this->zipname.'\' in binary read mode'); + + // ----- Return + return 0; + } + + // ----- Read the central directory informations + $v_central_dir = array(); + if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) + { + $this->privSwapBackMagicQuotes(); + return 0; + } + + // ----- Close the zip file + $this->privCloseFd(); + + // ----- Set the user attributes + $v_prop['comment'] = $v_central_dir['comment']; + $v_prop['nb'] = $v_central_dir['entries']; + $v_prop['status'] = 'ok'; +} + +// ----- Magic quotes trick +$this->privSwapBackMagicQuotes(); + +// ----- Return +return $v_prop; +} +// -------------------------------------------------------------------------------- + +// -------------------------------------------------------------------------------- +// Function : duplicate() +// Description : +// This method creates an archive by copying the content of an other one. If +// the archive already exist, it is replaced by the new one without any warning. +// Parameters : +// $p_archive : The filename of a valid archive, or +// a valid PclZip object. +// Return Values : +// 1 on success. +// 0 or a negative value on error (error code). +// -------------------------------------------------------------------------------- +function duplicate($p_archive) +{ +$v_result = 1; + +// ----- Reset the error handler +$this->privErrorReset(); + +// ----- Look if the $p_archive is a PclZip object +if ((is_object($p_archive)) && (get_class($p_archive) == 'pclzip')) +{ + + // ----- Duplicate the archive + $v_result = $this->privDuplicate($p_archive->zipname); +} + +// ----- Look if the $p_archive is a string (so a filename) +else if (is_string($p_archive)) +{ + + // ----- Check that $p_archive is a valid zip file + // TBC : Should also check the archive format + if (!is_file($p_archive)) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_FILE, "No file with filename '".$p_archive."'"); + $v_result = PCLZIP_ERR_MISSING_FILE; + } + else { + // ----- Duplicate the archive + $v_result = $this->privDuplicate($p_archive); + } +} + +// ----- Invalid variable +else +{ + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_archive_to_add"); + $v_result = PCLZIP_ERR_INVALID_PARAMETER; +} + +// ----- Return +return $v_result; +} +// -------------------------------------------------------------------------------- + +// -------------------------------------------------------------------------------- +// Function : merge() +// Description : +// This method merge the $p_archive_to_add archive at the end of the current +// one ($this). +// If the archive ($this) does not exist, the merge becomes a duplicate. +// If the $p_archive_to_add archive does not exist, the merge is a success. +// Parameters : +// $p_archive_to_add : It can be directly the filename of a valid zip archive, +// or a PclZip object archive. +// Return Values : +// 1 on success, +// 0 or negative values on error (see below). +// -------------------------------------------------------------------------------- +function merge($p_archive_to_add) +{ +$v_result = 1; + +// ----- Reset the error handler +$this->privErrorReset(); + +// ----- Check archive +if (!$this->privCheckFormat()) { + return(0); +} + +// ----- Look if the $p_archive_to_add is a PclZip object +if ((is_object($p_archive_to_add)) && (get_class($p_archive_to_add) == 'pclzip')) +{ + + // ----- Merge the archive + $v_result = $this->privMerge($p_archive_to_add); +} + +// ----- Look if the $p_archive_to_add is a string (so a filename) +else if (is_string($p_archive_to_add)) +{ + + // ----- Create a temporary archive + $v_object_archive = new PclZip($p_archive_to_add); + + // ----- Merge the archive + $v_result = $this->privMerge($v_object_archive); +} + +// ----- Invalid variable +else +{ + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_archive_to_add"); + $v_result = PCLZIP_ERR_INVALID_PARAMETER; +} + +// ----- Return +return $v_result; +} +// -------------------------------------------------------------------------------- + + + +// -------------------------------------------------------------------------------- +// Function : errorCode() +// Description : +// Parameters : +// -------------------------------------------------------------------------------- +function errorCode() +{ +if (PCLZIP_ERROR_EXTERNAL == 1) { + return(PclErrorCode()); +} +else { + return($this->error_code); +} +} +// -------------------------------------------------------------------------------- + +// -------------------------------------------------------------------------------- +// Function : errorName() +// Description : +// Parameters : +// -------------------------------------------------------------------------------- +function errorName($p_with_code=false) +{ +$v_name = array (PCLZIP_ERR_NO_ERROR => 'PCLZIP_ERR_NO_ERROR', + PCLZIP_ERR_WRITE_OPEN_FAIL => 'PCLZIP_ERR_WRITE_OPEN_FAIL', + PCLZIP_ERR_READ_OPEN_FAIL => 'PCLZIP_ERR_READ_OPEN_FAIL', + PCLZIP_ERR_INVALID_PARAMETER => 'PCLZIP_ERR_INVALID_PARAMETER', + PCLZIP_ERR_MISSING_FILE => 'PCLZIP_ERR_MISSING_FILE', + PCLZIP_ERR_FILENAME_TOO_LONG => 'PCLZIP_ERR_FILENAME_TOO_LONG', + PCLZIP_ERR_INVALID_ZIP => 'PCLZIP_ERR_INVALID_ZIP', + PCLZIP_ERR_BAD_EXTRACTED_FILE => 'PCLZIP_ERR_BAD_EXTRACTED_FILE', + PCLZIP_ERR_DIR_CREATE_FAIL => 'PCLZIP_ERR_DIR_CREATE_FAIL', + PCLZIP_ERR_BAD_EXTENSION => 'PCLZIP_ERR_BAD_EXTENSION', + PCLZIP_ERR_BAD_FORMAT => 'PCLZIP_ERR_BAD_FORMAT', + PCLZIP_ERR_DELETE_FILE_FAIL => 'PCLZIP_ERR_DELETE_FILE_FAIL', + PCLZIP_ERR_RENAME_FILE_FAIL => 'PCLZIP_ERR_RENAME_FILE_FAIL', + PCLZIP_ERR_BAD_CHECKSUM => 'PCLZIP_ERR_BAD_CHECKSUM', + PCLZIP_ERR_INVALID_ARCHIVE_ZIP => 'PCLZIP_ERR_INVALID_ARCHIVE_ZIP', + PCLZIP_ERR_MISSING_OPTION_VALUE => 'PCLZIP_ERR_MISSING_OPTION_VALUE', + PCLZIP_ERR_INVALID_OPTION_VALUE => 'PCLZIP_ERR_INVALID_OPTION_VALUE', + PCLZIP_ERR_UNSUPPORTED_COMPRESSION => 'PCLZIP_ERR_UNSUPPORTED_COMPRESSION', + PCLZIP_ERR_UNSUPPORTED_ENCRYPTION => 'PCLZIP_ERR_UNSUPPORTED_ENCRYPTION' + ,PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE => 'PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE' + ,PCLZIP_ERR_DIRECTORY_RESTRICTION => 'PCLZIP_ERR_DIRECTORY_RESTRICTION' + ) == 0) +{ + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary read mode'); + return PclZip::errorCode(); +} + +// ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks +fseek($v_file_compressed, 10); +$v_size = $p_header['compressed_size']; +while ($v_size != 0) +{ + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @fread($v_file_compressed, $v_read_size); + //$v_binary_data = pack('a'.$v_read_size, $v_buffer); + @fwrite($this->zip_fd, $v_buffer, $v_read_size); + $v_size -= $v_read_size; +} + +// ----- Close the file +@fclose($v_file_compressed); + +// ----- Unlink the temporary file +@unlink($v_gzip_temp_name); + +// ----- Return +return $v_result; +} +// -------------------------------------------------------------------------------- + +// -------------------------------------------------------------------------------- +// Function : privCalculateStoredFilename() +// Description : +// Based on file descriptor properties and global options, this method +// calculate the filename that will be stored in the archive. +// Parameters : +// Return Values : +// -------------------------------------------------------------------------------- +function privCalculateStoredFilename(&$p_filedescr, &$p_options) +{ +$v_result=1; + +// ----- Working variables +$p_filename = $p_filedescr['filename']; +if (isset($p_options[PCLZIP_OPT_ADD_PATH])) { + $p_add_dir = $p_options[PCLZIP_OPT_ADD_PATH]; +} +else { + $p_add_dir = ''; +} +if (isset($p_options[PCLZIP_OPT_REMOVE_PATH])) { + $p_remove_dir = $p_options[PCLZIP_OPT_REMOVE_PATH]; +} +else { + $p_remove_dir = ''; +} +if (isset($p_options[PCLZIP_OPT_REMOVE_ALL_PATH])) { + $p_remove_all_dir = $p_options[PCLZIP_OPT_REMOVE_ALL_PATH]; +} +else { + $p_remove_all_dir = 0; +} + + +// ----- Look for full name change +if (isset($p_filedescr['new_full_name'])) { + // ----- Remove drive letter if any + $v_stored_filename = PclZipUtilTranslateWinPath($p_filedescr['new_full_name']); +} + +// ----- Look for path and/or short name change +else { + + // ----- Look for short name change + // Its when we cahnge just the filename but not the path + if (isset($p_filedescr['new_short_name'])) { + $v_path_info = pathinfo($p_filename); + $v_dir = ''; + if ($v_path_info['dirname'] != '') { + $v_dir = $v_path_info['dirname'].'/'; + } + $v_stored_filename = $v_dir.$p_filedescr['new_short_name']; + } + else { + // ----- Calculate the stored filename + $v_stored_filename = $p_filename; + } + + // ----- Look for all path to remove + if ($p_remove_all_dir) { + $v_stored_filename = basename($p_filename); + } + // ----- Look for partial path remove + else if ($p_remove_dir != "") { + if (substr($p_remove_dir, -1) != '/') + $p_remove_dir .= "/"; + + if ((substr($p_filename, 0, 2) == "./") + || (substr($p_remove_dir, 0, 2) == "./")) { - // ----- Expand each element of the list - if ($v_dirlist_nb != 0) { - // ----- Expand - if (($v_result = $this->privFileDescrExpand($v_dirlist_descr, $p_options)) != 1) { - return $v_result; - } - - // ----- Concat the resulting list - $v_result_list = array_merge($v_result_list, $v_dirlist_descr); - } - else { - } - - // ----- Free local array - unset($v_dirlist_descr); + if ((substr($p_filename, 0, 2) == "./") + && (substr($p_remove_dir, 0, 2) != "./")) { + $p_remove_dir = "./".$p_remove_dir; + } + if ((substr($p_filename, 0, 2) != "./") + && (substr($p_remove_dir, 0, 2) == "./")) { + $p_remove_dir = substr($p_remove_dir, 2); } } - - // ----- Get the result list - $p_filedescr_list = $v_result_list; - // ----- Return + $v_compare = PclZipUtilPathInclusion($p_remove_dir, + $v_stored_filename); + if ($v_compare > 0) { + if ($v_compare == 2) { + $v_stored_filename = ""; + } + else { + $v_stored_filename = substr($v_stored_filename, + strlen($p_remove_dir)); + } + } + } + + // ----- Remove drive letter if any + $v_stored_filename = PclZipUtilTranslateWinPath($v_stored_filename); + + // ----- Look for path to add + if ($p_add_dir != "") { + if (substr($p_add_dir, -1) == "/") + $v_stored_filename = $p_add_dir.$v_stored_filename; + else + $v_stored_filename = $p_add_dir."/".$v_stored_filename; + } +} + +// ----- Filename (reduce the path of stored name) +$v_stored_filename = PclZipUtilPathReduction($v_stored_filename); +$p_filedescr['stored_filename'] = $v_stored_filename; + +// ----- Return +return $v_result; +} +// -------------------------------------------------------------------------------- + +// -------------------------------------------------------------------------------- +// Function : privWriteFileHeader() +// Description : +// Parameters : +// Return Values : +// -------------------------------------------------------------------------------- +function privWriteFileHeader(&$p_header) +{ +$v_result=1; + +// ----- Store the offset position of the file +$p_header['offset'] = ftell($this->zip_fd); + +// ----- Transform UNIX mtime to DOS format mdate/mtime +$v_date = getdate($p_header['mtime']); +$v_mtime = ($v_date['hours']<<11) + ($v_date['minutes']<<5) + $v_date['seconds']/2; +$v_mdate = (($v_date['year']-1980)<<9) + ($v_date['mon']<<5) + $v_date['mday']; + +// ----- Packed data +$v_binary_data = pack("VvvvvvVVVvv", 0x04034b50, + $p_header['version_extracted'], $p_header['flag'], + $p_header['compression'], $v_mtime, $v_mdate, + $p_header['crc'], $p_header['compressed_size'], + $p_header['size'], + strlen($p_header['stored_filename']), + $p_header['extra_len']); + +// ----- Write the first 148 bytes of the header in the archive +fputs($this->zip_fd, $v_binary_data, 30); + +// ----- Write the variable fields +if (strlen($p_header['stored_filename']) != 0) +{ + fputs($this->zip_fd, $p_header['stored_filename'], strlen($p_header['stored_filename'])); +} +if ($p_header['extra_len'] != 0) +{ + fputs($this->zip_fd, $p_header['extra'], $p_header['extra_len']); +} + +// ----- Return +return $v_result; +} +// -------------------------------------------------------------------------------- + +// -------------------------------------------------------------------------------- +// Function : privWriteCentralFileHeader() +// Description : +// Parameters : +// Return Values : +// -------------------------------------------------------------------------------- +function privWriteCentralFileHeader(&$p_header) +{ +$v_result=1; + +// TBC +//for(reset($p_header); $key = key($p_header); next($p_header)) { +//} + +// ----- Transform UNIX mtime to DOS format mdate/mtime +$v_date = getdate($p_header['mtime']); +$v_mtime = ($v_date['hours']<<11) + ($v_date['minutes']<<5) + $v_date['seconds']/2; +$v_mdate = (($v_date['year']-1980)<<9) + ($v_date['mon']<<5) + $v_date['mday']; + + +// ----- Packed data +$v_binary_data = pack("VvvvvvvVVVvvvvvVV", 0x02014b50, + $p_header['version'], $p_header['version_extracted'], + $p_header['flag'], $p_header['compression'], + $v_mtime, $v_mdate, $p_header['crc'], + $p_header['compressed_size'], $p_header['size'], + strlen($p_header['stored_filename']), + $p_header['extra_len'], $p_header['comment_len'], + $p_header['disk'], $p_header['internal'], + $p_header['external'], $p_header['offset']); + +// ----- Write the 42 bytes of the header in the zip file +fputs($this->zip_fd, $v_binary_data, 46); + +// ----- Write the variable fields +if (strlen($p_header['stored_filename']) != 0) +{ + fputs($this->zip_fd, $p_header['stored_filename'], strlen($p_header['stored_filename'])); +} +if ($p_header['extra_len'] != 0) +{ + fputs($this->zip_fd, $p_header['extra'], $p_header['extra_len']); +} +if ($p_header['comment_len'] != 0) +{ + fputs($this->zip_fd, $p_header['comment'], $p_header['comment_len']); +} + +// ----- Return +return $v_result; +} +// -------------------------------------------------------------------------------- + +// -------------------------------------------------------------------------------- +// Function : privWriteCentralHeader() +// Description : +// Parameters : +// Return Values : +// -------------------------------------------------------------------------------- +function privWriteCentralHeader($p_nb_entries, $p_size, $p_offset, $p_comment) +{ +$v_result=1; + +// ----- Packed data +$v_binary_data = pack("VvvvvVVv", 0x06054b50, 0, 0, $p_nb_entries, + $p_nb_entries, $p_size, + $p_offset, strlen($p_comment)); + +// ----- Write the 22 bytes of the header in the zip file +fputs($this->zip_fd, $v_binary_data, 22); + +// ----- Write the variable fields +if (strlen($p_comment) != 0) +{ + fputs($this->zip_fd, $p_comment, strlen($p_comment)); +} + +// ----- Return +return $v_result; +} +// -------------------------------------------------------------------------------- + +// -------------------------------------------------------------------------------- +// Function : privList() +// Description : +// Parameters : +// Return Values : +// -------------------------------------------------------------------------------- +function privList(&$p_list) +{ +$v_result=1; + +// ----- Magic quotes trick +$this->privDisableMagicQuotes(); + +// ----- Open the zip file +if (($this->zip_fd = @fopen($this->zipname, 'rb')) == 0) +{ + // ----- Magic quotes trick + $this->privSwapBackMagicQuotes(); + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \''.$this->zipname.'\' in binary read mode'); + + // ----- Return + return PclZip::errorCode(); +} + +// ----- Read the central directory informations +$v_central_dir = array(); +if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) +{ + $this->privSwapBackMagicQuotes(); + return $v_result; +} + +// ----- Go to beginning of Central Dir +@rewind($this->zip_fd); +if (@fseek($this->zip_fd, $v_central_dir['offset'])) +{ + $this->privSwapBackMagicQuotes(); + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); + + // ----- Return + return PclZip::errorCode(); +} + +// ----- Read each entry +for ($i=0; $i<$v_central_dir['entries']; $i++) +{ + // ----- Read the file header + if (($v_result = $this->privReadCentralFileHeader($v_header)) != 1) + { + $this->privSwapBackMagicQuotes(); return $v_result; } - // -------------------------------------------------------------------------------- + $v_header['index'] = $i; - // -------------------------------------------------------------------------------- - // Function : privCreate() - // Description : - // Parameters : - // Return Values : - // -------------------------------------------------------------------------------- - function privCreate($p_filedescr_list, &$p_result_list, &$p_options) + // ----- Get the only interesting attributes + $this->privConvertHeader2FileInfo($v_header, $p_list[$i]); + unset($v_header); +} + +// ----- Close the zip file +$this->privCloseFd(); + +// ----- Magic quotes trick +$this->privSwapBackMagicQuotes(); + +// ----- Return +return $v_result; +} +// -------------------------------------------------------------------------------- + +// -------------------------------------------------------------------------------- +// Function : privConvertHeader2FileInfo() +// Description : +// This function takes the file informations from the central directory +// entries and extract the interesting parameters that will be given back. +// The resulting file infos are set in the array $p_info +// $p_info['filename'] : Filename with full path. Given by user (add), +// extracted in the filesystem (extract). +// $p_info['stored_filename'] : Stored filename in the archive. +// $p_info['size'] = Size of the file. +// $p_info['compressed_size'] = Compressed size of the file. +// $p_info['mtime'] = Last modification date of the file. +// $p_info['comment'] = Comment associated with the file. +// $p_info['folder'] = true/false : indicates if the entry is a folder or not. +// $p_info['status'] = status of the action on the file. +// $p_info['crc'] = CRC of the file content. +// Parameters : +// Return Values : +// -------------------------------------------------------------------------------- +function privConvertHeader2FileInfo($p_header, &$p_info) +{ +$v_result=1; + +// ----- Get the interesting attributes +$v_temp_path = PclZipUtilPathReduction($p_header['filename']); +$p_info['filename'] = $v_temp_path; +$v_temp_path = PclZipUtilPathReduction($p_header['stored_filename']); +$p_info['stored_filename'] = $v_temp_path; +$p_info['size'] = $p_header['size']; +$p_info['compressed_size'] = $p_header['compressed_size']; +$p_info['mtime'] = $p_header['mtime']; +$p_info['comment'] = $p_header['comment']; +$p_info['folder'] = (($p_header['external']&0x00000010)==0x00000010); +$p_info['index'] = $p_header['index']; +$p_info['status'] = $p_header['status']; +$p_info['crc'] = $p_header['crc']; + +// ----- Return +return $v_result; +} +// -------------------------------------------------------------------------------- + +// -------------------------------------------------------------------------------- +// Function : privExtractByRule() +// Description : +// Extract a file or directory depending of rules (by index, by name, ...) +// Parameters : +// $p_file_list : An array where will be placed the properties of each +// extracted file +// $p_path : Path to add while writing the extracted files +// $p_remove_path : Path to remove (from the file memorized path) while writing the +// extracted files. If the path does not match the file path, +// the file is extracted with its memorized path. +// $p_remove_path does not apply to 'list' mode. +// $p_path and $p_remove_path are commulative. +// Return Values : +// 1 on success,0 or less on error (see error code list) +// -------------------------------------------------------------------------------- +function privExtractByRule(&$p_file_list, $p_path, $p_remove_path, $p_remove_all_path, &$p_options) +{ +$v_result=1; + +// ----- Magic quotes trick +$this->privDisableMagicQuotes(); + +// ----- Check the path +if (($p_path == "") + || ((substr($p_path, 0, 1) != "/") + && (substr($p_path, 0, 3) != "../") + && (substr($p_path,1,2)!=":/"))) + $p_path = "./".$p_path; + +// ----- Reduce the path last (and duplicated) '/' +if (($p_path != "./") && ($p_path != "/")) +{ + // ----- Look for the path end '/' + while (substr($p_path, -1) == "/") { - $v_result=1; - $v_list_detail = array(); - - // ----- Magic quotes trick - $this->privDisableMagicQuotes(); + $p_path = substr($p_path, 0, strlen($p_path)-1); + } +} - // ----- Open the file in write mode - if (($v_result = $this->privOpenFd('wb')) != 1) - { - // ----- Return - return $v_result; - } +// ----- Look for path to remove format (should end by /) +if (($p_remove_path != "") && (substr($p_remove_path, -1) != '/')) +{ + $p_remove_path .= '/'; +} +$p_remove_path_size = strlen($p_remove_path); - // ----- Add the list of files - $v_result = $this->privAddList($p_filedescr_list, $p_result_list, $p_options); +// ----- Open the zip file +if (($v_result = $this->privOpenFd('rb')) != 1) +{ + $this->privSwapBackMagicQuotes(); + return $v_result; +} - // ----- Close +// ----- Read the central directory informations +$v_central_dir = array(); +if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) +{ + // ----- Close the zip file + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + + return $v_result; +} + +// ----- Start at beginning of Central Dir +$v_pos_entry = $v_central_dir['offset']; + +// ----- Read each entry +$j_start = 0; +for ($i=0, $v_nb_extracted=0; $i<$v_central_dir['entries']; $i++) +{ + + // ----- Read next Central dir entry + @rewind($this->zip_fd); + if (@fseek($this->zip_fd, $v_pos_entry)) + { + // ----- Close the zip file $this->privCloseFd(); - - // ----- Magic quotes trick $this->privSwapBackMagicQuotes(); + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Read the file header + $v_header = array(); + if (($v_result = $this->privReadCentralFileHeader($v_header)) != 1) + { + // ----- Close the zip file + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + + return $v_result; + } + + // ----- Store the index + $v_header['index'] = $i; + + // ----- Store the file position + $v_pos_entry = ftell($this->zip_fd); + + // ----- Look for the specific extract rules + $v_extract = false; + + // ----- Look for extract by name rule + if ((isset($p_options[PCLZIP_OPT_BY_NAME])) + && ($p_options[PCLZIP_OPT_BY_NAME] != 0)) { + + // ----- Look if the filename is in the list + for ($j=0; ($j strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) + && (substr($v_header['stored_filename'], 0, strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) == $p_options[PCLZIP_OPT_BY_NAME][$j])) { + $v_extract = true; + } + } + // ----- Look for a filename + elseif ($v_header['stored_filename'] == $p_options[PCLZIP_OPT_BY_NAME][$j]) { + $v_extract = true; + } + } + } + + // ----- Look for extract by ereg rule + // ereg() is deprecated with PHP 5.3 + /* + else if ((isset($p_options[PCLZIP_OPT_BY_EREG])) + && ($p_options[PCLZIP_OPT_BY_EREG] != "")) { + + if (ereg($p_options[PCLZIP_OPT_BY_EREG], $v_header['stored_filename'])) { + $v_extract = true; + } + } + */ + + // ----- Look for extract by preg rule + else if ((isset($p_options[PCLZIP_OPT_BY_PREG])) + && ($p_options[PCLZIP_OPT_BY_PREG] != "")) { + + if (preg_match($p_options[PCLZIP_OPT_BY_PREG], $v_header['stored_filename'])) { + $v_extract = true; + } + } + + // ----- Look for extract by index rule + else if ((isset($p_options[PCLZIP_OPT_BY_INDEX])) + && ($p_options[PCLZIP_OPT_BY_INDEX] != 0)) { + + // ----- Look if the index is in the list + for ($j=$j_start; ($j=$p_options[PCLZIP_OPT_BY_INDEX][$j]['start']) && ($i<=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end'])) { + $v_extract = true; + } + if ($i>=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end']) { + $j_start = $j+1; + } + + if ($p_options[PCLZIP_OPT_BY_INDEX][$j]['start']>$i) { + break; + } + } + } + + // ----- Look for no rule, which means extract all the archive + else { + $v_extract = true; + } + + // ----- Check compression method + if (($v_extract) + && (($v_header['compression'] != 8) + && ($v_header['compression'] != 0))) { + $v_header['status'] = 'unsupported_compression'; + + // ----- Look for PCLZIP_OPT_STOP_ON_ERROR + if ((isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) + && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) { + + $this->privSwapBackMagicQuotes(); + + PclZip::privErrorLog(PCLZIP_ERR_UNSUPPORTED_COMPRESSION, + "Filename '".$v_header['stored_filename']."' is " + ."compressed by an unsupported compression " + ."method (".$v_header['compression'].") "); + + return PclZip::errorCode(); + } + } + + // ----- Check encrypted files + if (($v_extract) && (($v_header['flag'] & 1) == 1)) { + $v_header['status'] = 'unsupported_encryption'; + + // ----- Look for PCLZIP_OPT_STOP_ON_ERROR + if ((isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) + && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) { + + $this->privSwapBackMagicQuotes(); + + PclZip::privErrorLog(PCLZIP_ERR_UNSUPPORTED_ENCRYPTION, + "Unsupported encryption for " + ." filename '".$v_header['stored_filename'] + ."'"); + + return PclZip::errorCode(); + } +} + + // ----- Look for real extraction + if (($v_extract) && ($v_header['status'] != 'ok')) { + $v_result = $this->privConvertHeader2FileInfo($v_header, + $p_file_list[$v_nb_extracted++]); + if ($v_result != 1) { + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + return $v_result; + } + + $v_extract = false; + } + + // ----- Look for real extraction + if ($v_extract) + { + + // ----- Go to the file position + @rewind($this->zip_fd); + if (@fseek($this->zip_fd, $v_header['offset'])) + { + // ----- Close the zip file + $this->privCloseFd(); + + $this->privSwapBackMagicQuotes(); + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Look for extraction as string + if ($p_options[PCLZIP_OPT_EXTRACT_AS_STRING]) { + + $v_string = ''; + + // ----- Extracting the file + $v_result1 = $this->privExtractFileAsString($v_header, $v_string, $p_options); + if ($v_result1 < 1) { + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + return $v_result1; + } + + // ----- Get the only interesting attributes + if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted])) != 1) + { + // ----- Close the zip file + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + + return $v_result; + } + + // ----- Set the file content + $p_file_list[$v_nb_extracted]['content'] = $v_string; + + // ----- Next extracted file + $v_nb_extracted++; + + // ----- Look for user callback abort + if ($v_result1 == 2) { + break; + } + } + // ----- Look for extraction in standard output + elseif ((isset($p_options[PCLZIP_OPT_EXTRACT_IN_OUTPUT])) + && ($p_options[PCLZIP_OPT_EXTRACT_IN_OUTPUT])) { + // ----- Extracting the file in standard output + $v_result1 = $this->privExtractFileInOutput($v_header, $p_options); + if ($v_result1 < 1) { + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + return $v_result1; + } + + // ----- Get the only interesting attributes + if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted++])) != 1) { + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + return $v_result; + } + + // ----- Look for user callback abort + if ($v_result1 == 2) { + break; + } + } + // ----- Look for normal extraction + else { + // ----- Extracting the file + $v_result1 = $this->privExtractFile($v_header, + $p_path, $p_remove_path, + $p_remove_all_path, + $p_options); + if ($v_result1 < 1) { + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + return $v_result1; + } + + // ----- Get the only interesting attributes + if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted++])) != 1) + { + // ----- Close the zip file + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + + return $v_result; + } + + // ----- Look for user callback abort + if ($v_result1 == 2) { + break; + } + } + } +} + +// ----- Close the zip file +$this->privCloseFd(); +$this->privSwapBackMagicQuotes(); + +// ----- Return +return $v_result; +} +// -------------------------------------------------------------------------------- + +// -------------------------------------------------------------------------------- +// Function : privExtractFile() +// Description : +// Parameters : +// Return Values : +// +// 1 : ... ? +// PCLZIP_ERR_USER_ABORTED(2) : User ask for extraction stop in callback +// -------------------------------------------------------------------------------- +function privExtractFile(&$p_entry, $p_path, $p_remove_path, $p_remove_all_path, &$p_options) +{ +$v_result=1; + +// ----- Read the file header +if (($v_result = $this->privReadFileHeader($v_header)) != 1) +{ + // ----- Return + return $v_result; +} + + +// ----- Check that the file header is coherent with $p_entry info +if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) { + // TBC +} + +// ----- Look for all path to remove +if ($p_remove_all_path == true) { + // ----- Look for folder entry that not need to be extracted + if (($p_entry['external']&0x00000010)==0x00000010) { + + $p_entry['status'] = "filtered"; + + return $v_result; + } + + // ----- Get the basename of the path + $p_entry['filename'] = basename($p_entry['filename']); +} + +// ----- Look for path to remove +else if ($p_remove_path != "") +{ + if (PclZipUtilPathInclusion($p_remove_path, $p_entry['filename']) == 2) + { + + // ----- Change the file status + $p_entry['status'] = "filtered"; + // ----- Return return $v_result; } - // -------------------------------------------------------------------------------- - // -------------------------------------------------------------------------------- - // Function : privAdd() - // Description : - // Parameters : - // Return Values : - // -------------------------------------------------------------------------------- - function privAdd($p_filedescr_list, &$p_result_list, &$p_options) + $p_remove_path_size = strlen($p_remove_path); + if (substr($p_entry['filename'], 0, $p_remove_path_size) == $p_remove_path) { - $v_result=1; - $v_list_detail = array(); - // ----- Look if the archive exists or is empty - if ((!is_file($this->zipname)) || (filesize($this->zipname) == 0)) - { + // ----- Remove the path + $p_entry['filename'] = substr($p_entry['filename'], $p_remove_path_size); - // ----- Do a create - $v_result = $this->privCreate($p_filedescr_list, $p_result_list, $p_options); + } +} + +// ----- Add the path +if ($p_path != '') { + $p_entry['filename'] = $p_path."/".$p_entry['filename']; +} + +// ----- Check a base_dir_restriction +if (isset($p_options[PCLZIP_OPT_EXTRACT_DIR_RESTRICTION])) { + $v_inclusion + = PclZipUtilPathInclusion($p_options[PCLZIP_OPT_EXTRACT_DIR_RESTRICTION], + $p_entry['filename']); + if ($v_inclusion == 0) { + + PclZip::privErrorLog(PCLZIP_ERR_DIRECTORY_RESTRICTION, + "Filename '".$p_entry['filename']."' is " + ."outside PCLZIP_OPT_EXTRACT_DIR_RESTRICTION"); + + return PclZip::errorCode(); + } +} + +// ----- Look for pre-extract callback +if (isset($p_options[PCLZIP_CB_PRE_EXTRACT])) { + + // ----- Generate a local information + $v_local_header = array(); + $this->privConvertHeader2FileInfo($p_entry, $v_local_header); + + // ----- Call the callback + // Here I do not use call_user_func() because I need to send a reference to the + // header. +// eval('$v_result = '.$p_options[PCLZIP_CB_PRE_EXTRACT].'(PCLZIP_CB_PRE_EXTRACT, $v_local_header);'); + $v_result = $p_options[PCLZIP_CB_PRE_EXTRACT](PCLZIP_CB_PRE_EXTRACT, $v_local_header); + if ($v_result == 0) { + // ----- Change the file status + $p_entry['status'] = "skipped"; + $v_result = 1; + } + + // ----- Look for abort result + if ($v_result == 2) { + // ----- This status is internal and will be changed in 'skipped' + $p_entry['status'] = "aborted"; + $v_result = PCLZIP_ERR_USER_ABORTED; + } + + // ----- Update the informations + // Only some fields can be modified + $p_entry['filename'] = $v_local_header['filename']; +} + + +// ----- Look if extraction should be done +if ($p_entry['status'] == 'ok') { + +// ----- Look for specific actions while the file exist +if (file_exists($p_entry['filename'])) +{ + + // ----- Look if file is a directory + if (is_dir($p_entry['filename'])) + { + + // ----- Change the file status + $p_entry['status'] = "already_a_directory"; + + // ----- Look for PCLZIP_OPT_STOP_ON_ERROR + // For historical reason first PclZip implementation does not stop + // when this kind of error occurs. + if ((isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) + && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) { + + PclZip::privErrorLog(PCLZIP_ERR_ALREADY_A_DIRECTORY, + "Filename '".$p_entry['filename']."' is " + ."already used by an existing directory"); + + return PclZip::errorCode(); + } + } + // ----- Look if file is write protected + else if (!is_writeable($p_entry['filename'])) + { + + // ----- Change the file status + $p_entry['status'] = "write_protected"; + + // ----- Look for PCLZIP_OPT_STOP_ON_ERROR + // For historical reason first PclZip implementation does not stop + // when this kind of error occurs. + if ((isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) + && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) { + + PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, + "Filename '".$p_entry['filename']."' exists " + ."and is write protected"); + + return PclZip::errorCode(); + } + } + + // ----- Look if the extracted file is older + else if (filemtime($p_entry['filename']) > $p_entry['mtime']) + { + // ----- Change the file status + if ((isset($p_options[PCLZIP_OPT_REPLACE_NEWER])) + && ($p_options[PCLZIP_OPT_REPLACE_NEWER]===true)) { + } + else { + $p_entry['status'] = "newer_exist"; + + // ----- Look for PCLZIP_OPT_STOP_ON_ERROR + // For historical reason first PclZip implementation does not stop + // when this kind of error occurs. + if ((isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) + && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) { + + PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, + "Newer version of '".$p_entry['filename']."' exists " + ."and option PCLZIP_OPT_REPLACE_NEWER is not selected"); + + return PclZip::errorCode(); + } + } + } + else { + } +} + +// ----- Check the directory availability and create it if necessary +else { + if ((($p_entry['external']&0x00000010)==0x00000010) || (substr($p_entry['filename'], -1) == '/')) + $v_dir_to_check = $p_entry['filename']; + else if (!strstr($p_entry['filename'], "/")) + $v_dir_to_check = ""; + else + $v_dir_to_check = dirname($p_entry['filename']); + + if (($v_result = $this->privDirCheck($v_dir_to_check, (($p_entry['external']&0x00000010)==0x00000010))) != 1) { + + // ----- Change the file status + $p_entry['status'] = "path_creation_fail"; // ----- Return - return $v_result; + //return $v_result; + $v_result = 1; } - // ----- Magic quotes trick - $this->privDisableMagicQuotes(); + } +} - // ----- Open the zip file - if (($v_result=$this->privOpenFd('rb')) != 1) +// ----- Look if extraction should be done +if ($p_entry['status'] == 'ok') { + + // ----- Do the extraction (if not a folder) + if (!(($p_entry['external']&0x00000010)==0x00000010)) + { + // ----- Look for not compressed file + if ($p_entry['compression'] == 0) { + + // ----- Opening destination file + if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0) + { + + // ----- Change the file status + $p_entry['status'] = "write_error"; + + // ----- Return + return $v_result; + } + + + // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks + $v_size = $p_entry['compressed_size']; + while ($v_size != 0) + { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @fread($this->zip_fd, $v_read_size); + /* Try to speed up the code + $v_binary_data = pack('a'.$v_read_size, $v_buffer); + @fwrite($v_dest_file, $v_binary_data, $v_read_size); + */ + @fwrite($v_dest_file, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + + // ----- Closing the destination file + fclose($v_dest_file); + + // ----- Change the file mtime + touch($p_entry['filename'], $p_entry['mtime']); + + + } + else { + // ----- TBC + // Need to be finished + if (($p_entry['flag'] & 1) == 1) { + PclZip::privErrorLog(PCLZIP_ERR_UNSUPPORTED_ENCRYPTION, 'File \''.$p_entry['filename'].'\' is encrypted. Encrypted files are not supported.'); + return PclZip::errorCode(); + } + + + // ----- Look for using temporary file to unzip + if ((!isset($p_options[PCLZIP_OPT_TEMP_FILE_OFF])) + && (isset($p_options[PCLZIP_OPT_TEMP_FILE_ON]) + || (isset($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD]) + && ($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD] <= $p_entry['size'])))) { + $v_result = $this->privExtractFileUsingTempFile($p_entry, $p_options); + if ($v_result < PCLZIP_ERR_NO_ERROR) { + return $v_result; + } + } + + // ----- Look for extract in memory + else { + + + // ----- Read the compressed file in a buffer (one shot) + $v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']); + + // ----- Decompress the file + $v_file_content = @gzinflate($v_buffer); + unset($v_buffer); + if ($v_file_content === false) { + + // ----- Change the file status + // TBC + $p_entry['status'] = "error"; + + return $v_result; + } + + // ----- Opening destination file + if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0) { + + // ----- Change the file status + $p_entry['status'] = "write_error"; + + return $v_result; + } + + // ----- Write the uncompressed data + @fwrite($v_dest_file, $v_file_content, $p_entry['size']); + unset($v_file_content); + + // ----- Closing the destination file + @fclose($v_dest_file); + + } + + // ----- Change the file mtime + @touch($p_entry['filename'], $p_entry['mtime']); + } + + // ----- Look for chmod option + if (isset($p_options[PCLZIP_OPT_SET_CHMOD])) { + + // ----- Change the mode of the file + @chmod($p_entry['filename'], $p_options[PCLZIP_OPT_SET_CHMOD]); + } + + } +} + + // ----- Change abort status + if ($p_entry['status'] == "aborted") { + $p_entry['status'] = "skipped"; + } + +// ----- Look for post-extract callback +elseif (isset($p_options[PCLZIP_CB_POST_EXTRACT])) { + + // ----- Generate a local information + $v_local_header = array(); + $this->privConvertHeader2FileInfo($p_entry, $v_local_header); + + // ----- Call the callback + // Here I do not use call_user_func() because I need to send a reference to the + // header. +// eval('$v_result = '.$p_options[PCLZIP_CB_POST_EXTRACT].'(PCLZIP_CB_POST_EXTRACT, $v_local_header);'); + $v_result = $p_options[PCLZIP_CB_POST_EXTRACT](PCLZIP_CB_POST_EXTRACT, $v_local_header); + + // ----- Look for abort result + if ($v_result == 2) { + $v_result = PCLZIP_ERR_USER_ABORTED; + } +} + +// ----- Return +return $v_result; +} +// -------------------------------------------------------------------------------- + +// -------------------------------------------------------------------------------- +// Function : privExtractFileUsingTempFile() +// Description : +// Parameters : +// Return Values : +// -------------------------------------------------------------------------------- +function privExtractFileUsingTempFile(&$p_entry, &$p_options) +{ +$v_result=1; + +// ----- Creates a temporary file +$v_gzip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.gz'; +if (($v_dest_file = @fopen($v_gzip_temp_name, "wb")) == 0) { + fclose($v_file); + PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary write mode'); + return PclZip::errorCode(); +} + + +// ----- Write gz file format header +$v_binary_data = pack('va1a1Va1a1', 0x8b1f, Chr($p_entry['compression']), Chr(0x00), time(), Chr(0x00), Chr(3)); +@fwrite($v_dest_file, $v_binary_data, 10); + +// ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks +$v_size = $p_entry['compressed_size']; +while ($v_size != 0) +{ + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @fread($this->zip_fd, $v_read_size); + //$v_binary_data = pack('a'.$v_read_size, $v_buffer); + @fwrite($v_dest_file, $v_buffer, $v_read_size); + $v_size -= $v_read_size; +} + +// ----- Write gz file format footer +$v_binary_data = pack('VV', $p_entry['crc'], $p_entry['size']); +@fwrite($v_dest_file, $v_binary_data, 8); + +// ----- Close the temporary file +@fclose($v_dest_file); + +// ----- Opening destination file +if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0) { + $p_entry['status'] = "write_error"; + return $v_result; +} + +// ----- Open the temporary gz file +if (($v_src_file = @gzopen($v_gzip_temp_name, 'rb')) == 0) { + @fclose($v_dest_file); + $p_entry['status'] = "read_error"; + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary read mode'); + return PclZip::errorCode(); +} + + +// ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks +$v_size = $p_entry['size']; +while ($v_size != 0) { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @gzread($v_src_file, $v_read_size); + //$v_binary_data = pack('a'.$v_read_size, $v_buffer); + @fwrite($v_dest_file, $v_buffer, $v_read_size); + $v_size -= $v_read_size; +} +@fclose($v_dest_file); +@gzclose($v_src_file); + +// ----- Delete the temporary file +@unlink($v_gzip_temp_name); + +// ----- Return +return $v_result; +} +// -------------------------------------------------------------------------------- + +// -------------------------------------------------------------------------------- +// Function : privExtractFileInOutput() +// Description : +// Parameters : +// Return Values : +// -------------------------------------------------------------------------------- +function privExtractFileInOutput(&$p_entry, &$p_options) +{ +$v_result=1; + +// ----- Read the file header +if (($v_result = $this->privReadFileHeader($v_header)) != 1) { + return $v_result; +} + + +// ----- Check that the file header is coherent with $p_entry info +if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) { + // TBC +} + +// ----- Look for pre-extract callback +if (isset($p_options[PCLZIP_CB_PRE_EXTRACT])) { + + // ----- Generate a local information + $v_local_header = array(); + $this->privConvertHeader2FileInfo($p_entry, $v_local_header); + + // ----- Call the callback + // Here I do not use call_user_func() because I need to send a reference to the + // header. +// eval('$v_result = '.$p_options[PCLZIP_CB_PRE_EXTRACT].'(PCLZIP_CB_PRE_EXTRACT, $v_local_header);'); + $v_result = $p_options[PCLZIP_CB_PRE_EXTRACT](PCLZIP_CB_PRE_EXTRACT, $v_local_header); + if ($v_result == 0) { + // ----- Change the file status + $p_entry['status'] = "skipped"; + $v_result = 1; + } + + // ----- Look for abort result + if ($v_result == 2) { + // ----- This status is internal and will be changed in 'skipped' + $p_entry['status'] = "aborted"; + $v_result = PCLZIP_ERR_USER_ABORTED; + } + + // ----- Update the informations + // Only some fields can be modified + $p_entry['filename'] = $v_local_header['filename']; +} + +// ----- Trace + +// ----- Look if extraction should be done +if ($p_entry['status'] == 'ok') { + + // ----- Do the extraction (if not a folder) + if (!(($p_entry['external']&0x00000010)==0x00000010)) { + // ----- Look for not compressed file + if ($p_entry['compressed_size'] == $p_entry['size']) { + + // ----- Read the file in a buffer (one shot) + $v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']); + + // ----- Send the file to the output + echo $v_buffer; + unset($v_buffer); + } + else { + + // ----- Read the compressed file in a buffer (one shot) + $v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']); + + // ----- Decompress the file + $v_file_content = gzinflate($v_buffer); + unset($v_buffer); + + // ----- Send the file to the output + echo $v_file_content; + unset($v_file_content); + } + } +} + +// ----- Change abort status +if ($p_entry['status'] == "aborted") { + $p_entry['status'] = "skipped"; +} + +// ----- Look for post-extract callback +elseif (isset($p_options[PCLZIP_CB_POST_EXTRACT])) { + + // ----- Generate a local information + $v_local_header = array(); + $this->privConvertHeader2FileInfo($p_entry, $v_local_header); + + // ----- Call the callback + // Here I do not use call_user_func() because I need to send a reference to the + // header. +// eval('$v_result = '.$p_options[PCLZIP_CB_POST_EXTRACT].'(PCLZIP_CB_POST_EXTRACT, $v_local_header);'); + $v_result = $p_options[PCLZIP_CB_POST_EXTRACT](PCLZIP_CB_POST_EXTRACT, $v_local_header); + + // ----- Look for abort result + if ($v_result == 2) { + $v_result = PCLZIP_ERR_USER_ABORTED; + } +} + +return $v_result; +} +// -------------------------------------------------------------------------------- + +// -------------------------------------------------------------------------------- +// Function : privExtractFileAsString() +// Description : +// Parameters : +// Return Values : +// -------------------------------------------------------------------------------- +function privExtractFileAsString(&$p_entry, &$p_string, &$p_options) +{ +$v_result=1; + +// ----- Read the file header +$v_header = array(); +if (($v_result = $this->privReadFileHeader($v_header)) != 1) +{ + // ----- Return + return $v_result; +} + + +// ----- Check that the file header is coherent with $p_entry info +if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) { + // TBC +} + +// ----- Look for pre-extract callback +if (isset($p_options[PCLZIP_CB_PRE_EXTRACT])) { + + // ----- Generate a local information + $v_local_header = array(); + $this->privConvertHeader2FileInfo($p_entry, $v_local_header); + + // ----- Call the callback + // Here I do not use call_user_func() because I need to send a reference to the + // header. +// eval('$v_result = '.$p_options[PCLZIP_CB_PRE_EXTRACT].'(PCLZIP_CB_PRE_EXTRACT, $v_local_header);'); + $v_result = $p_options[PCLZIP_CB_PRE_EXTRACT](PCLZIP_CB_PRE_EXTRACT, $v_local_header); + if ($v_result == 0) { + // ----- Change the file status + $p_entry['status'] = "skipped"; + $v_result = 1; + } + + // ----- Look for abort result + if ($v_result == 2) { + // ----- This status is internal and will be changed in 'skipped' + $p_entry['status'] = "aborted"; + $v_result = PCLZIP_ERR_USER_ABORTED; + } + + // ----- Update the informations + // Only some fields can be modified + $p_entry['filename'] = $v_local_header['filename']; +} + + +// ----- Look if extraction should be done +if ($p_entry['status'] == 'ok') { + + // ----- Do the extraction (if not a folder) + if (!(($p_entry['external']&0x00000010)==0x00000010)) { + // ----- Look for not compressed file +// if ($p_entry['compressed_size'] == $p_entry['size']) + if ($p_entry['compression'] == 0) { + + // ----- Reading the file + $p_string = @fread($this->zip_fd, $p_entry['compressed_size']); + } + else { + + // ----- Reading the file + $v_data = @fread($this->zip_fd, $p_entry['compressed_size']); + + // ----- Decompress the file + if (($p_string = @gzinflate($v_data)) === false) { + // TBC + } + } + + // ----- Trace + } + else { + // TBC : error : can not extract a folder in a string + } + +} + + // ----- Change abort status + if ($p_entry['status'] == "aborted") { + $p_entry['status'] = "skipped"; + } + +// ----- Look for post-extract callback +elseif (isset($p_options[PCLZIP_CB_POST_EXTRACT])) { + + // ----- Generate a local information + $v_local_header = array(); + $this->privConvertHeader2FileInfo($p_entry, $v_local_header); + + // ----- Swap the content to header + $v_local_header['content'] = $p_string; + $p_string = ''; + + // ----- Call the callback + // Here I do not use call_user_func() because I need to send a reference to the + // header. +// eval('$v_result = '.$p_options[PCLZIP_CB_POST_EXTRACT].'(PCLZIP_CB_POST_EXTRACT, $v_local_header);'); + $v_result = $p_options[PCLZIP_CB_POST_EXTRACT](PCLZIP_CB_POST_EXTRACT, $v_local_header); + + // ----- Swap back the content to header + $p_string = $v_local_header['content']; + unset($v_local_header['content']); + + // ----- Look for abort result + if ($v_result == 2) { + $v_result = PCLZIP_ERR_USER_ABORTED; + } +} + +// ----- Return +return $v_result; +} +// -------------------------------------------------------------------------------- + +// -------------------------------------------------------------------------------- +// Function : privReadFileHeader() +// Description : +// Parameters : +// Return Values : +// -------------------------------------------------------------------------------- +function privReadFileHeader(&$p_header) +{ +$v_result=1; + +// ----- Read the 4 bytes signature +$v_binary_data = @fread($this->zip_fd, 4); +$v_data = unpack('Vid', $v_binary_data); + +// ----- Check signature +if ($v_data['id'] != 0x04034b50) +{ + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Invalid archive structure'); + + // ----- Return + return PclZip::errorCode(); +} + +// ----- Read the first 42 bytes of the header +$v_binary_data = fread($this->zip_fd, 26); + +// ----- Look for invalid block size +if (strlen($v_binary_data) != 26) +{ + $p_header['filename'] = ""; + $p_header['status'] = "invalid_header"; + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Invalid block size : ".strlen($v_binary_data)); + + // ----- Return + return PclZip::errorCode(); +} + +// ----- Extract the values +$v_data = unpack('vversion/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len', $v_binary_data); + +// ----- Get filename +$p_header['filename'] = fread($this->zip_fd, $v_data['filename_len']); + +// ----- Get extra_fields +if ($v_data['extra_len'] != 0) { + $p_header['extra'] = fread($this->zip_fd, $v_data['extra_len']); +} +else { + $p_header['extra'] = ''; +} + +// ----- Extract properties +$p_header['version_extracted'] = $v_data['version']; +$p_header['compression'] = $v_data['compression']; +$p_header['size'] = $v_data['size']; +$p_header['compressed_size'] = $v_data['compressed_size']; +$p_header['crc'] = $v_data['crc']; +$p_header['flag'] = $v_data['flag']; +$p_header['filename_len'] = $v_data['filename_len']; + +// ----- Recuperate date in UNIX format +$p_header['mdate'] = $v_data['mdate']; +$p_header['mtime'] = $v_data['mtime']; +if ($p_header['mdate'] && $p_header['mtime']) +{ + // ----- Extract time + $v_hour = ($p_header['mtime'] & 0xF800) >> 11; + $v_minute = ($p_header['mtime'] & 0x07E0) >> 5; + $v_seconde = ($p_header['mtime'] & 0x001F)*2; + + // ----- Extract date + $v_year = (($p_header['mdate'] & 0xFE00) >> 9) + 1980; + $v_month = ($p_header['mdate'] & 0x01E0) >> 5; + $v_day = $p_header['mdate'] & 0x001F; + + // ----- Get UNIX date format + $p_header['mtime'] = @mktime($v_hour, $v_minute, $v_seconde, $v_month, $v_day, $v_year); + +} +else +{ + $p_header['mtime'] = time(); +} + +// TBC +//for(reset($v_data); $key = key($v_data); next($v_data)) { +//} + +// ----- Set the stored filename +$p_header['stored_filename'] = $p_header['filename']; + +// ----- Set the status field +$p_header['status'] = "ok"; + +// ----- Return +return $v_result; +} +// -------------------------------------------------------------------------------- + +// -------------------------------------------------------------------------------- +// Function : privReadCentralFileHeader() +// Description : +// Parameters : +// Return Values : +// -------------------------------------------------------------------------------- +function privReadCentralFileHeader(&$p_header) +{ +$v_result=1; + +// ----- Read the 4 bytes signature +$v_binary_data = @fread($this->zip_fd, 4); +$v_data = unpack('Vid', $v_binary_data); + +// ----- Check signature +if ($v_data['id'] != 0x02014b50) +{ + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Invalid archive structure'); + + // ----- Return + return PclZip::errorCode(); +} + +// ----- Read the first 42 bytes of the header +$v_binary_data = fread($this->zip_fd, 42); + +// ----- Look for invalid block size +if (strlen($v_binary_data) != 42) +{ + $p_header['filename'] = ""; + $p_header['status'] = "invalid_header"; + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Invalid block size : ".strlen($v_binary_data)); + + // ----- Return + return PclZip::errorCode(); +} + +// ----- Extract the values +$p_header = unpack('vversion/vversion_extracted/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len/vcomment_len/vdisk/vinternal/Vexternal/Voffset', $v_binary_data); + +// ----- Get filename +if ($p_header['filename_len'] != 0) + $p_header['filename'] = fread($this->zip_fd, $p_header['filename_len']); +else + $p_header['filename'] = ''; + +// ----- Get extra +if ($p_header['extra_len'] != 0) + $p_header['extra'] = fread($this->zip_fd, $p_header['extra_len']); +else + $p_header['extra'] = ''; + +// ----- Get comment +if ($p_header['comment_len'] != 0) + $p_header['comment'] = fread($this->zip_fd, $p_header['comment_len']); +else + $p_header['comment'] = ''; + +// ----- Extract properties + +// ----- Recuperate date in UNIX format +//if ($p_header['mdate'] && $p_header['mtime']) +// TBC : bug : this was ignoring time with 0/0/0 +if (1) +{ + // ----- Extract time + $v_hour = ($p_header['mtime'] & 0xF800) >> 11; + $v_minute = ($p_header['mtime'] & 0x07E0) >> 5; + $v_seconde = ($p_header['mtime'] & 0x001F)*2; + + // ----- Extract date + $v_year = (($p_header['mdate'] & 0xFE00) >> 9) + 1980; + $v_month = ($p_header['mdate'] & 0x01E0) >> 5; + $v_day = $p_header['mdate'] & 0x001F; + + // ----- Get UNIX date format + $p_header['mtime'] = @mktime($v_hour, $v_minute, $v_seconde, $v_month, $v_day, $v_year); + +} +else +{ + $p_header['mtime'] = time(); +} + +// ----- Set the stored filename +$p_header['stored_filename'] = $p_header['filename']; + +// ----- Set default status to ok +$p_header['status'] = 'ok'; + +// ----- Look if it is a directory +if (substr($p_header['filename'], -1) == '/') { + //$p_header['external'] = 0x41FF0010; + $p_header['external'] = 0x00000010; +} + + +// ----- Return +return $v_result; +} +// -------------------------------------------------------------------------------- + +// -------------------------------------------------------------------------------- +// Function : privCheckFileHeaders() +// Description : +// Parameters : +// Return Values : +// 1 on success, +// 0 on error; +// -------------------------------------------------------------------------------- +function privCheckFileHeaders(&$p_local_header, &$p_central_header) +{ +$v_result=1; + + // ----- Check the static values + // TBC + if ($p_local_header['filename'] != $p_central_header['filename']) { + } + if ($p_local_header['version_extracted'] != $p_central_header['version_extracted']) { + } + if ($p_local_header['flag'] != $p_central_header['flag']) { + } + if ($p_local_header['compression'] != $p_central_header['compression']) { + } + if ($p_local_header['mtime'] != $p_central_header['mtime']) { + } + if ($p_local_header['filename_len'] != $p_central_header['filename_len']) { + } + + // ----- Look for flag bit 3 + if (($p_local_header['flag'] & 8) == 8) { + $p_local_header['size'] = $p_central_header['size']; + $p_local_header['compressed_size'] = $p_central_header['compressed_size']; + $p_local_header['crc'] = $p_central_header['crc']; + } + +// ----- Return +return $v_result; +} +// -------------------------------------------------------------------------------- + +// -------------------------------------------------------------------------------- +// Function : privReadEndCentralDir() +// Description : +// Parameters : +// Return Values : +// -------------------------------------------------------------------------------- +function privReadEndCentralDir(&$p_central_dir) +{ +$v_result=1; + +// ----- Go to the end of the zip file +$v_size = filesize($this->zipname); +@fseek($this->zip_fd, $v_size); +if (@ftell($this->zip_fd) != $v_size) +{ + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to go to the end of the archive \''.$this->zipname.'\''); + + // ----- Return + return PclZip::errorCode(); +} + +// ----- First try : look if this is an archive with no commentaries (most of the time) +// in this case the end of central dir is at 22 bytes of the file end +$v_found = 0; +if ($v_size > 26) { + @fseek($this->zip_fd, $v_size-22); + if (($v_pos = @ftell($this->zip_fd)) != ($v_size-22)) + { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to seek back to the middle of the archive \''.$this->zipname.'\''); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Read for bytes + $v_binary_data = @fread($this->zip_fd, 4); + $v_data = @unpack('Vid', $v_binary_data); + + // ----- Check signature + if ($v_data['id'] == 0x06054b50) { + $v_found = 1; + } + + $v_pos = ftell($this->zip_fd); +} + +// ----- Go back to the maximum possible size of the Central Dir End Record +if (!$v_found) { + $v_maximum_size = 65557; // 0xFFFF + 22; + if ($v_maximum_size > $v_size) + $v_maximum_size = $v_size; + @fseek($this->zip_fd, $v_size-$v_maximum_size); + if (@ftell($this->zip_fd) != ($v_size-$v_maximum_size)) + { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to seek back to the middle of the archive \''.$this->zipname.'\''); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Read byte per byte in order to find the signature + $v_pos = ftell($this->zip_fd); + $v_bytes = 0x00000000; + while ($v_pos < $v_size) + { + // ----- Read a byte + $v_byte = @fread($this->zip_fd, 1); + + // ----- Add the byte + //$v_bytes = ($v_bytes << 8) | Ord($v_byte); + // Note we mask the old value down such that once shifted we can never end up with more than a 32bit number + // Otherwise on systems where we have 64bit integers the check below for the magic number will fail. + $v_bytes = (($v_bytes & 0xFFFFFF) << 8) | Ord($v_byte); + + // ----- Compare the bytes + if ($v_bytes == 0x504b0506) { - // ----- Magic quotes trick - $this->privSwapBackMagicQuotes(); - - // ----- Return - return $v_result; + $v_pos++; + break; } - // ----- Read the central directory informations - $v_central_dir = array(); - if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) - { - $this->privCloseFd(); - $this->privSwapBackMagicQuotes(); - return $v_result; - } + $v_pos++; + } - // ----- Go to beginning of File - @rewind($this->zip_fd); + // ----- Look if not found end of central dir + if ($v_pos == $v_size) + { + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Unable to find End of Central Dir Record signature"); + + // ----- Return + return PclZip::errorCode(); + } +} + +// ----- Read the first 18 bytes of the header +$v_binary_data = fread($this->zip_fd, 18); + +// ----- Look for invalid block size +if (strlen($v_binary_data) != 18) +{ + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Invalid End of Central Dir Record size : ".strlen($v_binary_data)); + + // ----- Return + return PclZip::errorCode(); +} + +// ----- Extract the values +$v_data = unpack('vdisk/vdisk_start/vdisk_entries/ventries/Vsize/Voffset/vcomment_size', $v_binary_data); + +// ----- Check the global size +if (($v_pos + $v_data['comment_size'] + 18) != $v_size) { + + // ----- Removed in release 2.2 see readme file + // The check of the file size is a little too strict. + // Some bugs where found when a zip is encrypted/decrypted with 'crypt'. + // While decrypted, zip has training 0 bytes + if (0) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, + 'The central dir is not at the end of the archive.' + .' Some trailing bytes exists after the archive.'); + + // ----- Return + return PclZip::errorCode(); + } +} + +// ----- Get comment +if ($v_data['comment_size'] != 0) { + $p_central_dir['comment'] = fread($this->zip_fd, $v_data['comment_size']); +} +else + $p_central_dir['comment'] = ''; + +$p_central_dir['entries'] = $v_data['entries']; +$p_central_dir['disk_entries'] = $v_data['disk_entries']; +$p_central_dir['offset'] = $v_data['offset']; +$p_central_dir['size'] = $v_data['size']; +$p_central_dir['disk'] = $v_data['disk']; +$p_central_dir['disk_start'] = $v_data['disk_start']; + +// TBC +//for(reset($p_central_dir); $key = key($p_central_dir); next($p_central_dir)) { +//} + +// ----- Return +return $v_result; +} +// -------------------------------------------------------------------------------- + +// -------------------------------------------------------------------------------- +// Function : privDeleteByRule() +// Description : +// Parameters : +// Return Values : +// -------------------------------------------------------------------------------- +function privDeleteByRule(&$p_result_list, &$p_options) +{ +$v_result=1; +$v_list_detail = array(); + +// ----- Open the zip file +if (($v_result=$this->privOpenFd('rb')) != 1) +{ + // ----- Return + return $v_result; +} + +// ----- Read the central directory informations +$v_central_dir = array(); +if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) +{ + $this->privCloseFd(); + return $v_result; +} + +// ----- Go to beginning of File +@rewind($this->zip_fd); + +// ----- Scan all the files +// ----- Start at beginning of Central Dir +$v_pos_entry = $v_central_dir['offset']; +@rewind($this->zip_fd); +if (@fseek($this->zip_fd, $v_pos_entry)) +{ + // ----- Close the zip file + $this->privCloseFd(); + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); + + // ----- Return + return PclZip::errorCode(); +} + +// ----- Read each entry +$v_header_list = array(); +$j_start = 0; +for ($i=0, $v_nb_extracted=0; $i<$v_central_dir['entries']; $i++) +{ + + // ----- Read the file header + $v_header_list[$v_nb_extracted] = array(); + if (($v_result = $this->privReadCentralFileHeader($v_header_list[$v_nb_extracted])) != 1) + { + // ----- Close the zip file + $this->privCloseFd(); + + return $v_result; + } + + + // ----- Store the index + $v_header_list[$v_nb_extracted]['index'] = $i; + + // ----- Look for the specific extract rules + $v_found = false; + + // ----- Look for extract by name rule + if ((isset($p_options[PCLZIP_OPT_BY_NAME])) + && ($p_options[PCLZIP_OPT_BY_NAME] != 0)) { + + // ----- Look if the filename is in the list + for ($j=0; ($j strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) + && (substr($v_header_list[$v_nb_extracted]['stored_filename'], 0, strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) == $p_options[PCLZIP_OPT_BY_NAME][$j])) { + $v_found = true; + } + elseif ((($v_header_list[$v_nb_extracted]['external']&0x00000010)==0x00000010) /* Indicates a folder */ + && ($v_header_list[$v_nb_extracted]['stored_filename'].'/' == $p_options[PCLZIP_OPT_BY_NAME][$j])) { + $v_found = true; + } + } + // ----- Look for a filename + elseif ($v_header_list[$v_nb_extracted]['stored_filename'] == $p_options[PCLZIP_OPT_BY_NAME][$j]) { + $v_found = true; + } + } + } + + // ----- Look for extract by ereg rule + // ereg() is deprecated with PHP 5.3 + /* + else if ((isset($p_options[PCLZIP_OPT_BY_EREG])) + && ($p_options[PCLZIP_OPT_BY_EREG] != "")) { + + if (ereg($p_options[PCLZIP_OPT_BY_EREG], $v_header_list[$v_nb_extracted]['stored_filename'])) { + $v_found = true; + } + } + */ + + // ----- Look for extract by preg rule + else if ((isset($p_options[PCLZIP_OPT_BY_PREG])) + && ($p_options[PCLZIP_OPT_BY_PREG] != "")) { + + if (preg_match($p_options[PCLZIP_OPT_BY_PREG], $v_header_list[$v_nb_extracted]['stored_filename'])) { + $v_found = true; + } + } + + // ----- Look for extract by index rule + else if ((isset($p_options[PCLZIP_OPT_BY_INDEX])) + && ($p_options[PCLZIP_OPT_BY_INDEX] != 0)) { + + // ----- Look if the index is in the list + for ($j=$j_start; ($j=$p_options[PCLZIP_OPT_BY_INDEX][$j]['start']) && ($i<=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end'])) { + $v_found = true; + } + if ($i>=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end']) { + $j_start = $j+1; + } + + if ($p_options[PCLZIP_OPT_BY_INDEX][$j]['start']>$i) { + break; + } + } + } + else { + $v_found = true; + } + + // ----- Look for deletion + if ($v_found) + { + unset($v_header_list[$v_nb_extracted]); + } + else + { + $v_nb_extracted++; + } +} + +// ----- Look if something need to be deleted +if ($v_nb_extracted > 0) { // ----- Creates a temporay file $v_zip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.tmp'; - // ----- Open the temporary file in write mode - if (($v_zip_temp_fd = @fopen($v_zip_temp_name, 'wb')) == 0) - { - $this->privCloseFd(); - $this->privSwapBackMagicQuotes(); + // ----- Creates a temporary zip archive + $v_temp_zip = new PclZip($v_zip_temp_name); - PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_zip_temp_name.'\' in binary write mode'); - - // ----- Return - return PclZip::errorCode(); - } - - // ----- Copy the files from the archive to the temporary file - // TBC : Here I should better append the file and go back to erase the central dir - $v_size = $v_central_dir['offset']; - while ($v_size != 0) - { - $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); - $v_buffer = fread($this->zip_fd, $v_read_size); - @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); - $v_size -= $v_read_size; - } - - // ----- Swap the file descriptor - // Here is a trick : I swap the temporary fd with the zip fd, in order to use - // the following methods on the temporary fil and not the real archive - $v_swap = $this->zip_fd; - $this->zip_fd = $v_zip_temp_fd; - $v_zip_temp_fd = $v_swap; - - // ----- Add the files - $v_header_list = array(); - if (($v_result = $this->privAddFileList($p_filedescr_list, $v_header_list, $p_options)) != 1) - { - fclose($v_zip_temp_fd); - $this->privCloseFd(); - @unlink($v_zip_temp_name); - $this->privSwapBackMagicQuotes(); - - // ----- Return - return $v_result; - } - - // ----- Store the offset of the central dir - $v_offset = @ftell($this->zip_fd); - - // ----- Copy the block of file headers from the old archive - $v_size = $v_central_dir['size']; - while ($v_size != 0) - { - $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); - $v_buffer = @fread($v_zip_temp_fd, $v_read_size); - @fwrite($this->zip_fd, $v_buffer, $v_read_size); - $v_size -= $v_read_size; - } - - // ----- Create the Central Dir files header - for ($i=0, $v_count=0; $iprivWriteCentralFileHeader($v_header_list[$i])) != 1) { - fclose($v_zip_temp_fd); - $this->privCloseFd(); - @unlink($v_zip_temp_name); - $this->privSwapBackMagicQuotes(); - - // ----- Return - return $v_result; - } - $v_count++; - } - - // ----- Transform the header to a 'usable' info - $this->privConvertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]); - } - - // ----- Zip file comment - $v_comment = $v_central_dir['comment']; - if (isset($p_options[PCLZIP_OPT_COMMENT])) { - $v_comment = $p_options[PCLZIP_OPT_COMMENT]; - } - if (isset($p_options[PCLZIP_OPT_ADD_COMMENT])) { - $v_comment = $v_comment.$p_options[PCLZIP_OPT_ADD_COMMENT]; - } - if (isset($p_options[PCLZIP_OPT_PREPEND_COMMENT])) { - $v_comment = $p_options[PCLZIP_OPT_PREPEND_COMMENT].$v_comment; - } - - // ----- Calculate the size of the central header - $v_size = @ftell($this->zip_fd)-$v_offset; - - // ----- Create the central dir footer - if (($v_result = $this->privWriteCentralHeader($v_count+$v_central_dir['entries'], $v_size, $v_offset, $v_comment)) != 1) - { - // ----- Reset the file list - unset($v_header_list); - $this->privSwapBackMagicQuotes(); - - // ----- Return - return $v_result; - } - - // ----- Swap back the file descriptor - $v_swap = $this->zip_fd; - $this->zip_fd = $v_zip_temp_fd; - $v_zip_temp_fd = $v_swap; - - // ----- Close - $this->privCloseFd(); - - // ----- Close the temporary file - @fclose($v_zip_temp_fd); - - // ----- Magic quotes trick - $this->privSwapBackMagicQuotes(); - - // ----- Delete the zip file - // TBC : I should test the result ... - @unlink($this->zipname); - - // ----- Rename the temporary file - // TBC : I should test the result ... - //@rename($v_zip_temp_name, $this->zipname); - PclZipUtilRename($v_zip_temp_name, $this->zipname); - - // ----- Return - return $v_result; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : privOpenFd() - // Description : - // Parameters : - // -------------------------------------------------------------------------------- - function privOpenFd($p_mode) - { - $v_result=1; - - // ----- Look if already open - if ($this->zip_fd != 0) - { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Zip file \''.$this->zipname.'\' already open'); - - // ----- Return - return PclZip::errorCode(); - } - - // ----- Open the zip file - if (($this->zip_fd = @fopen($this->zipname, $p_mode)) == 0) - { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \''.$this->zipname.'\' in '.$p_mode.' mode'); - - // ----- Return - return PclZip::errorCode(); - } - - // ----- Return - return $v_result; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : privCloseFd() - // Description : - // Parameters : - // -------------------------------------------------------------------------------- - function privCloseFd() - { - $v_result=1; - - if ($this->zip_fd != 0) - @fclose($this->zip_fd); - $this->zip_fd = 0; - - // ----- Return - return $v_result; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : privAddList() - // Description : - // $p_add_dir and $p_remove_dir will give the ability to memorize a path which is - // different from the real path of the file. This is usefull if you want to have PclTar - // running in any directory, and memorize relative path from an other directory. - // Parameters : - // $p_list : An array containing the file or directory names to add in the tar - // $p_result_list : list of added files with their properties (specially the status field) - // $p_add_dir : Path to add in the filename path archived - // $p_remove_dir : Path to remove in the filename path archived - // Return Values : - // -------------------------------------------------------------------------------- -// function privAddList($p_list, &$p_result_list, $p_add_dir, $p_remove_dir, $p_remove_all_dir, &$p_options) - function privAddList($p_filedescr_list, &$p_result_list, &$p_options) - { - $v_result=1; - - // ----- Add the files - $v_header_list = array(); - if (($v_result = $this->privAddFileList($p_filedescr_list, $v_header_list, $p_options)) != 1) - { - // ----- Return - return $v_result; - } - - // ----- Store the offset of the central dir - $v_offset = @ftell($this->zip_fd); - - // ----- Create the Central Dir files header - for ($i=0, $v_count=0; $iprivWriteCentralFileHeader($v_header_list[$i])) != 1) { - // ----- Return - return $v_result; - } - $v_count++; - } - - // ----- Transform the header to a 'usable' info - $this->privConvertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]); - } - - // ----- Zip file comment - $v_comment = ''; - if (isset($p_options[PCLZIP_OPT_COMMENT])) { - $v_comment = $p_options[PCLZIP_OPT_COMMENT]; - } - - // ----- Calculate the size of the central header - $v_size = @ftell($this->zip_fd)-$v_offset; - - // ----- Create the central dir footer - if (($v_result = $this->privWriteCentralHeader($v_count, $v_size, $v_offset, $v_comment)) != 1) - { - // ----- Reset the file list - unset($v_header_list); - - // ----- Return - return $v_result; - } - - // ----- Return - return $v_result; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : privAddFileList() - // Description : - // Parameters : - // $p_filedescr_list : An array containing the file description - // or directory names to add in the zip - // $p_result_list : list of added files with their properties (specially the status field) - // Return Values : - // -------------------------------------------------------------------------------- - function privAddFileList($p_filedescr_list, &$p_result_list, &$p_options) - { - $v_result=1; - $v_header = array(); - - // ----- Recuperate the current number of elt in list - $v_nb = sizeof($p_result_list); - - // ----- Loop on the files - for ($j=0; ($jprivAddFile($p_filedescr_list[$j], $v_header, - $p_options); - if ($v_result != 1) { - return $v_result; - } - - // ----- Store the file infos - $p_result_list[$v_nb++] = $v_header; - } - } - - // ----- Return - return $v_result; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : privAddFile() - // Description : - // Parameters : - // Return Values : - // -------------------------------------------------------------------------------- - function privAddFile($p_filedescr, &$p_header, &$p_options) - { - $v_result=1; - - // ----- Working variable - $p_filename = $p_filedescr['filename']; - - // TBC : Already done in the fileAtt check ... ? - if ($p_filename == "") { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid file list parameter (invalid or empty list)"); - - // ----- Return - return PclZip::errorCode(); - } - - // ----- Look for a stored different filename - /* TBC : Removed - if (isset($p_filedescr['stored_filename'])) { - $v_stored_filename = $p_filedescr['stored_filename']; - } - else { - $v_stored_filename = $p_filedescr['stored_filename']; - } - */ - - // ----- Set the file properties - clearstatcache(); - $p_header['version'] = 20; - $p_header['version_extracted'] = 10; - $p_header['flag'] = 0; - $p_header['compression'] = 0; - $p_header['crc'] = 0; - $p_header['compressed_size'] = 0; - $p_header['filename_len'] = strlen($p_filename); - $p_header['extra_len'] = 0; - $p_header['disk'] = 0; - $p_header['internal'] = 0; - $p_header['offset'] = 0; - $p_header['filename'] = $p_filename; -// TBC : Removed $p_header['stored_filename'] = $v_stored_filename; - $p_header['stored_filename'] = $p_filedescr['stored_filename']; - $p_header['extra'] = ''; - $p_header['status'] = 'ok'; - $p_header['index'] = -1; - - // ----- Look for regular file - if ($p_filedescr['type']=='file') { - $p_header['external'] = 0x00000000; - $p_header['size'] = filesize($p_filename); - } - - // ----- Look for regular folder - else if ($p_filedescr['type']=='folder') { - $p_header['external'] = 0x00000010; - $p_header['mtime'] = filemtime($p_filename); - $p_header['size'] = filesize($p_filename); - } - - // ----- Look for virtual file - else if ($p_filedescr['type'] == 'virtual_file') { - $p_header['external'] = 0x00000000; - $p_header['size'] = strlen($p_filedescr['content']); - } - - - // ----- Look for filetime - if (isset($p_filedescr['mtime'])) { - $p_header['mtime'] = $p_filedescr['mtime']; - } - else if ($p_filedescr['type'] == 'virtual_file') { - $p_header['mtime'] = time(); - } - else { - $p_header['mtime'] = filemtime($p_filename); - } - - // ------ Look for file comment - if (isset($p_filedescr['comment'])) { - $p_header['comment_len'] = strlen($p_filedescr['comment']); - $p_header['comment'] = $p_filedescr['comment']; - } - else { - $p_header['comment_len'] = 0; - $p_header['comment'] = ''; - } - - // ----- Look for pre-add callback - if (isset($p_options[PCLZIP_CB_PRE_ADD])) { - - // ----- Generate a local information - $v_local_header = array(); - $this->privConvertHeader2FileInfo($p_header, $v_local_header); - - // ----- Call the callback - // Here I do not use call_user_func() because I need to send a reference to the - // header. -// eval('$v_result = '.$p_options[PCLZIP_CB_PRE_ADD].'(PCLZIP_CB_PRE_ADD, $v_local_header);'); - $v_result = $p_options[PCLZIP_CB_PRE_ADD](PCLZIP_CB_PRE_ADD, $v_local_header); - if ($v_result == 0) { - // ----- Change the file status - $p_header['status'] = "skipped"; - $v_result = 1; - } - - // ----- Update the informations - // Only some fields can be modified - if ($p_header['stored_filename'] != $v_local_header['stored_filename']) { - $p_header['stored_filename'] = PclZipUtilPathReduction($v_local_header['stored_filename']); - } - } - - // ----- Look for empty stored filename - if ($p_header['stored_filename'] == "") { - $p_header['status'] = "filtered"; - } - - // ----- Check the path length - if (strlen($p_header['stored_filename']) > 0xFF) { - $p_header['status'] = 'filename_too_long'; - } - - // ----- Look if no error, or file not skipped - if ($p_header['status'] == 'ok') { - - // ----- Look for a file - if ($p_filedescr['type'] == 'file') { - // ----- Look for using temporary file to zip - if ( (!isset($p_options[PCLZIP_OPT_TEMP_FILE_OFF])) - && (isset($p_options[PCLZIP_OPT_TEMP_FILE_ON]) - || (isset($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD]) - && ($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD] <= $p_header['size'])) ) ) { - $v_result = $this->privAddFileUsingTempFile($p_filedescr, $p_header, $p_options); - if ($v_result < PCLZIP_ERR_NO_ERROR) { - return $v_result; - } - } - - // ----- Use "in memory" zip algo - else { - - // ----- Open the source file - if (($v_file = @fopen($p_filename, "rb")) == 0) { - PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, "Unable to open file '$p_filename' in binary read mode"); - return PclZip::errorCode(); - } - - // ----- Read the file content - $v_content = @fread($v_file, $p_header['size']); - - // ----- Close the file - @fclose($v_file); - - // ----- Calculate the CRC - $p_header['crc'] = @crc32($v_content); - - // ----- Look for no compression - if ($p_options[PCLZIP_OPT_NO_COMPRESSION]) { - // ----- Set header parameters - $p_header['compressed_size'] = $p_header['size']; - $p_header['compression'] = 0; - } - - // ----- Look for normal compression - else { - // ----- Compress the content - $v_content = @gzdeflate($v_content); - - // ----- Set header parameters - $p_header['compressed_size'] = strlen($v_content); - $p_header['compression'] = 8; - } - - // ----- Call the header generation - if (($v_result = $this->privWriteFileHeader($p_header)) != 1) { - @fclose($v_file); - return $v_result; - } - - // ----- Write the compressed (or not) content - @fwrite($this->zip_fd, $v_content, $p_header['compressed_size']); - - } - - } - - // ----- Look for a virtual file (a file from string) - else if ($p_filedescr['type'] == 'virtual_file') { - - $v_content = $p_filedescr['content']; - - // ----- Calculate the CRC - $p_header['crc'] = @crc32($v_content); - - // ----- Look for no compression - if ($p_options[PCLZIP_OPT_NO_COMPRESSION]) { - // ----- Set header parameters - $p_header['compressed_size'] = $p_header['size']; - $p_header['compression'] = 0; - } - - // ----- Look for normal compression - else { - // ----- Compress the content - $v_content = @gzdeflate($v_content); - - // ----- Set header parameters - $p_header['compressed_size'] = strlen($v_content); - $p_header['compression'] = 8; - } - - // ----- Call the header generation - if (($v_result = $this->privWriteFileHeader($p_header)) != 1) { - @fclose($v_file); - return $v_result; - } - - // ----- Write the compressed (or not) content - @fwrite($this->zip_fd, $v_content, $p_header['compressed_size']); - } - - // ----- Look for a directory - else if ($p_filedescr['type'] == 'folder') { - // ----- Look for directory last '/' - if (@substr($p_header['stored_filename'], -1) != '/') { - $p_header['stored_filename'] .= '/'; - } - - // ----- Set the file properties - $p_header['size'] = 0; - //$p_header['external'] = 0x41FF0010; // Value for a folder : to be checked - $p_header['external'] = 0x00000010; // Value for a folder : to be checked - - // ----- Call the header generation - if (($v_result = $this->privWriteFileHeader($p_header)) != 1) - { - return $v_result; - } - } - } - - // ----- Look for post-add callback - if (isset($p_options[PCLZIP_CB_POST_ADD])) { - - // ----- Generate a local information - $v_local_header = array(); - $this->privConvertHeader2FileInfo($p_header, $v_local_header); - - // ----- Call the callback - // Here I do not use call_user_func() because I need to send a reference to the - // header. -// eval('$v_result = '.$p_options[PCLZIP_CB_POST_ADD].'(PCLZIP_CB_POST_ADD, $v_local_header);'); - $v_result = $p_options[PCLZIP_CB_POST_ADD](PCLZIP_CB_POST_ADD, $v_local_header); - if ($v_result == 0) { - // ----- Ignored - $v_result = 1; - } - - // ----- Update the informations - // Nothing can be modified - } - - // ----- Return - return $v_result; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : privAddFileUsingTempFile() - // Description : - // Parameters : - // Return Values : - // -------------------------------------------------------------------------------- - function privAddFileUsingTempFile($p_filedescr, &$p_header, &$p_options) - { - $v_result=PCLZIP_ERR_NO_ERROR; - - // ----- Working variable - $p_filename = $p_filedescr['filename']; - - - // ----- Open the source file - if (($v_file = @fopen($p_filename, "rb")) == 0) { - PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, "Unable to open file '$p_filename' in binary read mode"); - return PclZip::errorCode(); - } - - // ----- Creates a compressed temporary file - $v_gzip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.gz'; - if (($v_file_compressed = @gzopen($v_gzip_temp_name, "wb")) == 0) { - fclose($v_file); - PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary write mode'); - return PclZip::errorCode(); - } - - // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks - $v_size = filesize($p_filename); - while ($v_size != 0) { - $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); - $v_buffer = @fread($v_file, $v_read_size); - //$v_binary_data = pack('a'.$v_read_size, $v_buffer); - @gzputs($v_file_compressed, $v_buffer, $v_read_size); - $v_size -= $v_read_size; - } - - // ----- Close the file - @fclose($v_file); - @gzclose($v_file_compressed); - - // ----- Check the minimum file size - if (filesize($v_gzip_temp_name) < 18) { - PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'gzip temporary file \''.$v_gzip_temp_name.'\' has invalid filesize - should be minimum 18 bytes'); - return PclZip::errorCode(); - } - - // ----- Extract the compressed attributes - if (($v_file_compressed = @fopen($v_gzip_temp_name, "rb")) == 0) { - PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary read mode'); - return PclZip::errorCode(); - } - - // ----- Read the gzip file header - $v_binary_data = @fread($v_file_compressed, 10); - $v_data_header = unpack('a1id1/a1id2/a1cm/a1flag/Vmtime/a1xfl/a1os', $v_binary_data); - - // ----- Check some parameters - $v_data_header['os'] = bin2hex($v_data_header['os']); - - // ----- Read the gzip file footer - @fseek($v_file_compressed, filesize($v_gzip_temp_name)-8); - $v_binary_data = @fread($v_file_compressed, 8); - $v_data_footer = unpack('Vcrc/Vcompressed_size', $v_binary_data); - - // ----- Set the attributes - $p_header['compression'] = ord($v_data_header['cm']); - //$p_header['mtime'] = $v_data_header['mtime']; - $p_header['crc'] = $v_data_footer['crc']; - $p_header['compressed_size'] = filesize($v_gzip_temp_name)-18; - - // ----- Close the file - @fclose($v_file_compressed); - - // ----- Call the header generation - if (($v_result = $this->privWriteFileHeader($p_header)) != 1) { - return $v_result; - } - - // ----- Add the compressed data - if (($v_file_compressed = @fopen($v_gzip_temp_name, "rb")) == 0) - { - PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary read mode'); - return PclZip::errorCode(); - } - - // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks - fseek($v_file_compressed, 10); - $v_size = $p_header['compressed_size']; - while ($v_size != 0) - { - $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); - $v_buffer = @fread($v_file_compressed, $v_read_size); - //$v_binary_data = pack('a'.$v_read_size, $v_buffer); - @fwrite($this->zip_fd, $v_buffer, $v_read_size); - $v_size -= $v_read_size; - } - - // ----- Close the file - @fclose($v_file_compressed); - - // ----- Unlink the temporary file - @unlink($v_gzip_temp_name); - - // ----- Return - return $v_result; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : privCalculateStoredFilename() - // Description : - // Based on file descriptor properties and global options, this method - // calculate the filename that will be stored in the archive. - // Parameters : - // Return Values : - // -------------------------------------------------------------------------------- - function privCalculateStoredFilename(&$p_filedescr, &$p_options) - { - $v_result=1; - - // ----- Working variables - $p_filename = $p_filedescr['filename']; - if (isset($p_options[PCLZIP_OPT_ADD_PATH])) { - $p_add_dir = $p_options[PCLZIP_OPT_ADD_PATH]; - } - else { - $p_add_dir = ''; - } - if (isset($p_options[PCLZIP_OPT_REMOVE_PATH])) { - $p_remove_dir = $p_options[PCLZIP_OPT_REMOVE_PATH]; - } - else { - $p_remove_dir = ''; - } - if (isset($p_options[PCLZIP_OPT_REMOVE_ALL_PATH])) { - $p_remove_all_dir = $p_options[PCLZIP_OPT_REMOVE_ALL_PATH]; - } - else { - $p_remove_all_dir = 0; - } - - - // ----- Look for full name change - if (isset($p_filedescr['new_full_name'])) { - // ----- Remove drive letter if any - $v_stored_filename = PclZipUtilTranslateWinPath($p_filedescr['new_full_name']); - } - - // ----- Look for path and/or short name change - else { - - // ----- Look for short name change - // Its when we cahnge just the filename but not the path - if (isset($p_filedescr['new_short_name'])) { - $v_path_info = pathinfo($p_filename); - $v_dir = ''; - if ($v_path_info['dirname'] != '') { - $v_dir = $v_path_info['dirname'].'/'; - } - $v_stored_filename = $v_dir.$p_filedescr['new_short_name']; - } - else { - // ----- Calculate the stored filename - $v_stored_filename = $p_filename; - } - - // ----- Look for all path to remove - if ($p_remove_all_dir) { - $v_stored_filename = basename($p_filename); - } - // ----- Look for partial path remove - else if ($p_remove_dir != "") { - if (substr($p_remove_dir, -1) != '/') - $p_remove_dir .= "/"; - - if ( (substr($p_filename, 0, 2) == "./") - || (substr($p_remove_dir, 0, 2) == "./")) { - - if ( (substr($p_filename, 0, 2) == "./") - && (substr($p_remove_dir, 0, 2) != "./")) { - $p_remove_dir = "./".$p_remove_dir; - } - if ( (substr($p_filename, 0, 2) != "./") - && (substr($p_remove_dir, 0, 2) == "./")) { - $p_remove_dir = substr($p_remove_dir, 2); - } - } - - $v_compare = PclZipUtilPathInclusion($p_remove_dir, - $v_stored_filename); - if ($v_compare > 0) { - if ($v_compare == 2) { - $v_stored_filename = ""; - } - else { - $v_stored_filename = substr($v_stored_filename, - strlen($p_remove_dir)); - } - } - } - - // ----- Remove drive letter if any - $v_stored_filename = PclZipUtilTranslateWinPath($v_stored_filename); - - // ----- Look for path to add - if ($p_add_dir != "") { - if (substr($p_add_dir, -1) == "/") - $v_stored_filename = $p_add_dir.$v_stored_filename; - else - $v_stored_filename = $p_add_dir."/".$v_stored_filename; - } - } - - // ----- Filename (reduce the path of stored name) - $v_stored_filename = PclZipUtilPathReduction($v_stored_filename); - $p_filedescr['stored_filename'] = $v_stored_filename; - - // ----- Return - return $v_result; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : privWriteFileHeader() - // Description : - // Parameters : - // Return Values : - // -------------------------------------------------------------------------------- - function privWriteFileHeader(&$p_header) - { - $v_result=1; - - // ----- Store the offset position of the file - $p_header['offset'] = ftell($this->zip_fd); - - // ----- Transform UNIX mtime to DOS format mdate/mtime - $v_date = getdate($p_header['mtime']); - $v_mtime = ($v_date['hours']<<11) + ($v_date['minutes']<<5) + $v_date['seconds']/2; - $v_mdate = (($v_date['year']-1980)<<9) + ($v_date['mon']<<5) + $v_date['mday']; - - // ----- Packed data - $v_binary_data = pack("VvvvvvVVVvv", 0x04034b50, - $p_header['version_extracted'], $p_header['flag'], - $p_header['compression'], $v_mtime, $v_mdate, - $p_header['crc'], $p_header['compressed_size'], - $p_header['size'], - strlen($p_header['stored_filename']), - $p_header['extra_len']); - - // ----- Write the first 148 bytes of the header in the archive - fputs($this->zip_fd, $v_binary_data, 30); - - // ----- Write the variable fields - if (strlen($p_header['stored_filename']) != 0) - { - fputs($this->zip_fd, $p_header['stored_filename'], strlen($p_header['stored_filename'])); - } - if ($p_header['extra_len'] != 0) - { - fputs($this->zip_fd, $p_header['extra'], $p_header['extra_len']); - } - - // ----- Return - return $v_result; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : privWriteCentralFileHeader() - // Description : - // Parameters : - // Return Values : - // -------------------------------------------------------------------------------- - function privWriteCentralFileHeader(&$p_header) - { - $v_result=1; - - // TBC - //for(reset($p_header); $key = key($p_header); next($p_header)) { - //} - - // ----- Transform UNIX mtime to DOS format mdate/mtime - $v_date = getdate($p_header['mtime']); - $v_mtime = ($v_date['hours']<<11) + ($v_date['minutes']<<5) + $v_date['seconds']/2; - $v_mdate = (($v_date['year']-1980)<<9) + ($v_date['mon']<<5) + $v_date['mday']; - - - // ----- Packed data - $v_binary_data = pack("VvvvvvvVVVvvvvvVV", 0x02014b50, - $p_header['version'], $p_header['version_extracted'], - $p_header['flag'], $p_header['compression'], - $v_mtime, $v_mdate, $p_header['crc'], - $p_header['compressed_size'], $p_header['size'], - strlen($p_header['stored_filename']), - $p_header['extra_len'], $p_header['comment_len'], - $p_header['disk'], $p_header['internal'], - $p_header['external'], $p_header['offset']); - - // ----- Write the 42 bytes of the header in the zip file - fputs($this->zip_fd, $v_binary_data, 46); - - // ----- Write the variable fields - if (strlen($p_header['stored_filename']) != 0) - { - fputs($this->zip_fd, $p_header['stored_filename'], strlen($p_header['stored_filename'])); - } - if ($p_header['extra_len'] != 0) - { - fputs($this->zip_fd, $p_header['extra'], $p_header['extra_len']); - } - if ($p_header['comment_len'] != 0) - { - fputs($this->zip_fd, $p_header['comment'], $p_header['comment_len']); - } - - // ----- Return - return $v_result; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : privWriteCentralHeader() - // Description : - // Parameters : - // Return Values : - // -------------------------------------------------------------------------------- - function privWriteCentralHeader($p_nb_entries, $p_size, $p_offset, $p_comment) - { - $v_result=1; - - // ----- Packed data - $v_binary_data = pack("VvvvvVVv", 0x06054b50, 0, 0, $p_nb_entries, - $p_nb_entries, $p_size, - $p_offset, strlen($p_comment)); - - // ----- Write the 22 bytes of the header in the zip file - fputs($this->zip_fd, $v_binary_data, 22); - - // ----- Write the variable fields - if (strlen($p_comment) != 0) - { - fputs($this->zip_fd, $p_comment, strlen($p_comment)); - } - - // ----- Return - return $v_result; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : privList() - // Description : - // Parameters : - // Return Values : - // -------------------------------------------------------------------------------- - function privList(&$p_list) - { - $v_result=1; - - // ----- Magic quotes trick - $this->privDisableMagicQuotes(); - - // ----- Open the zip file - if (($this->zip_fd = @fopen($this->zipname, 'rb')) == 0) - { - // ----- Magic quotes trick - $this->privSwapBackMagicQuotes(); - - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \''.$this->zipname.'\' in binary read mode'); - - // ----- Return - return PclZip::errorCode(); - } - - // ----- Read the central directory informations - $v_central_dir = array(); - if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) - { - $this->privSwapBackMagicQuotes(); - return $v_result; - } - - // ----- Go to beginning of Central Dir - @rewind($this->zip_fd); - if (@fseek($this->zip_fd, $v_central_dir['offset'])) - { - $this->privSwapBackMagicQuotes(); - - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); - - // ----- Return - return PclZip::errorCode(); - } - - // ----- Read each entry - for ($i=0; $i<$v_central_dir['entries']; $i++) - { - // ----- Read the file header - if (($v_result = $this->privReadCentralFileHeader($v_header)) != 1) - { - $this->privSwapBackMagicQuotes(); - return $v_result; - } - $v_header['index'] = $i; - - // ----- Get the only interesting attributes - $this->privConvertHeader2FileInfo($v_header, $p_list[$i]); - unset($v_header); - } - - // ----- Close the zip file - $this->privCloseFd(); - - // ----- Magic quotes trick - $this->privSwapBackMagicQuotes(); - - // ----- Return - return $v_result; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : privConvertHeader2FileInfo() - // Description : - // This function takes the file informations from the central directory - // entries and extract the interesting parameters that will be given back. - // The resulting file infos are set in the array $p_info - // $p_info['filename'] : Filename with full path. Given by user (add), - // extracted in the filesystem (extract). - // $p_info['stored_filename'] : Stored filename in the archive. - // $p_info['size'] = Size of the file. - // $p_info['compressed_size'] = Compressed size of the file. - // $p_info['mtime'] = Last modification date of the file. - // $p_info['comment'] = Comment associated with the file. - // $p_info['folder'] = true/false : indicates if the entry is a folder or not. - // $p_info['status'] = status of the action on the file. - // $p_info['crc'] = CRC of the file content. - // Parameters : - // Return Values : - // -------------------------------------------------------------------------------- - function privConvertHeader2FileInfo($p_header, &$p_info) - { - $v_result=1; - - // ----- Get the interesting attributes - $v_temp_path = PclZipUtilPathReduction($p_header['filename']); - $p_info['filename'] = $v_temp_path; - $v_temp_path = PclZipUtilPathReduction($p_header['stored_filename']); - $p_info['stored_filename'] = $v_temp_path; - $p_info['size'] = $p_header['size']; - $p_info['compressed_size'] = $p_header['compressed_size']; - $p_info['mtime'] = $p_header['mtime']; - $p_info['comment'] = $p_header['comment']; - $p_info['folder'] = (($p_header['external']&0x00000010)==0x00000010); - $p_info['index'] = $p_header['index']; - $p_info['status'] = $p_header['status']; - $p_info['crc'] = $p_header['crc']; - - // ----- Return - return $v_result; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : privExtractByRule() - // Description : - // Extract a file or directory depending of rules (by index, by name, ...) - // Parameters : - // $p_file_list : An array where will be placed the properties of each - // extracted file - // $p_path : Path to add while writing the extracted files - // $p_remove_path : Path to remove (from the file memorized path) while writing the - // extracted files. If the path does not match the file path, - // the file is extracted with its memorized path. - // $p_remove_path does not apply to 'list' mode. - // $p_path and $p_remove_path are commulative. - // Return Values : - // 1 on success,0 or less on error (see error code list) - // -------------------------------------------------------------------------------- - function privExtractByRule(&$p_file_list, $p_path, $p_remove_path, $p_remove_all_path, &$p_options) - { - $v_result=1; - - // ----- Magic quotes trick - $this->privDisableMagicQuotes(); - - // ----- Check the path - if ( ($p_path == "") - || ( (substr($p_path, 0, 1) != "/") - && (substr($p_path, 0, 3) != "../") - && (substr($p_path,1,2)!=":/"))) - $p_path = "./".$p_path; - - // ----- Reduce the path last (and duplicated) '/' - if (($p_path != "./") && ($p_path != "/")) - { - // ----- Look for the path end '/' - while (substr($p_path, -1) == "/") - { - $p_path = substr($p_path, 0, strlen($p_path)-1); - } - } - - // ----- Look for path to remove format (should end by /) - if (($p_remove_path != "") && (substr($p_remove_path, -1) != '/')) - { - $p_remove_path .= '/'; - } - $p_remove_path_size = strlen($p_remove_path); - - // ----- Open the zip file - if (($v_result = $this->privOpenFd('rb')) != 1) - { - $this->privSwapBackMagicQuotes(); - return $v_result; - } - - // ----- Read the central directory informations - $v_central_dir = array(); - if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) - { - // ----- Close the zip file - $this->privCloseFd(); - $this->privSwapBackMagicQuotes(); - - return $v_result; - } - - // ----- Start at beginning of Central Dir - $v_pos_entry = $v_central_dir['offset']; - - // ----- Read each entry - $j_start = 0; - for ($i=0, $v_nb_extracted=0; $i<$v_central_dir['entries']; $i++) - { - - // ----- Read next Central dir entry - @rewind($this->zip_fd); - if (@fseek($this->zip_fd, $v_pos_entry)) - { - // ----- Close the zip file + // ----- Open the temporary zip file in write mode + if (($v_result = $v_temp_zip->privOpenFd('wb')) != 1) { $this->privCloseFd(); - $this->privSwapBackMagicQuotes(); - - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); // ----- Return - return PclZip::errorCode(); - } - - // ----- Read the file header - $v_header = array(); - if (($v_result = $this->privReadCentralFileHeader($v_header)) != 1) - { - // ----- Close the zip file - $this->privCloseFd(); - $this->privSwapBackMagicQuotes(); - return $v_result; - } - - // ----- Store the index - $v_header['index'] = $i; - - // ----- Store the file position - $v_pos_entry = ftell($this->zip_fd); - - // ----- Look for the specific extract rules - $v_extract = false; - - // ----- Look for extract by name rule - if ( (isset($p_options[PCLZIP_OPT_BY_NAME])) - && ($p_options[PCLZIP_OPT_BY_NAME] != 0)) { - - // ----- Look if the filename is in the list - for ($j=0; ($j strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) - && (substr($v_header['stored_filename'], 0, strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) == $p_options[PCLZIP_OPT_BY_NAME][$j])) { - $v_extract = true; - } - } - // ----- Look for a filename - elseif ($v_header['stored_filename'] == $p_options[PCLZIP_OPT_BY_NAME][$j]) { - $v_extract = true; - } - } - } - - // ----- Look for extract by ereg rule - // ereg() is deprecated with PHP 5.3 - /* - else if ( (isset($p_options[PCLZIP_OPT_BY_EREG])) - && ($p_options[PCLZIP_OPT_BY_EREG] != "")) { - - if (ereg($p_options[PCLZIP_OPT_BY_EREG], $v_header['stored_filename'])) { - $v_extract = true; - } - } - */ - - // ----- Look for extract by preg rule - else if ( (isset($p_options[PCLZIP_OPT_BY_PREG])) - && ($p_options[PCLZIP_OPT_BY_PREG] != "")) { - - if (preg_match($p_options[PCLZIP_OPT_BY_PREG], $v_header['stored_filename'])) { - $v_extract = true; - } - } - - // ----- Look for extract by index rule - else if ( (isset($p_options[PCLZIP_OPT_BY_INDEX])) - && ($p_options[PCLZIP_OPT_BY_INDEX] != 0)) { - - // ----- Look if the index is in the list - for ($j=$j_start; ($j=$p_options[PCLZIP_OPT_BY_INDEX][$j]['start']) && ($i<=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end'])) { - $v_extract = true; - } - if ($i>=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end']) { - $j_start = $j+1; - } - - if ($p_options[PCLZIP_OPT_BY_INDEX][$j]['start']>$i) { - break; - } - } - } - - // ----- Look for no rule, which means extract all the archive - else { - $v_extract = true; - } - - // ----- Check compression method - if ( ($v_extract) - && ( ($v_header['compression'] != 8) - && ($v_header['compression'] != 0))) { - $v_header['status'] = 'unsupported_compression'; - - // ----- Look for PCLZIP_OPT_STOP_ON_ERROR - if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) - && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) { - - $this->privSwapBackMagicQuotes(); - - PclZip::privErrorLog(PCLZIP_ERR_UNSUPPORTED_COMPRESSION, - "Filename '".$v_header['stored_filename']."' is " - ."compressed by an unsupported compression " - ."method (".$v_header['compression'].") "); - - return PclZip::errorCode(); - } - } - - // ----- Check encrypted files - if (($v_extract) && (($v_header['flag'] & 1) == 1)) { - $v_header['status'] = 'unsupported_encryption'; - - // ----- Look for PCLZIP_OPT_STOP_ON_ERROR - if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) - && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) { - - $this->privSwapBackMagicQuotes(); - - PclZip::privErrorLog(PCLZIP_ERR_UNSUPPORTED_ENCRYPTION, - "Unsupported encryption for " - ." filename '".$v_header['stored_filename'] - ."'"); - - return PclZip::errorCode(); - } } - // ----- Look for real extraction - if (($v_extract) && ($v_header['status'] != 'ok')) { - $v_result = $this->privConvertHeader2FileInfo($v_header, - $p_file_list[$v_nb_extracted++]); - if ($v_result != 1) { - $this->privCloseFd(); - $this->privSwapBackMagicQuotes(); - return $v_result; - } + // ----- Look which file need to be kept + for ($i=0; $izip_fd); - if (@fseek($this->zip_fd, $v_header['offset'])) - { - // ----- Close the zip file - $this->privCloseFd(); - - $this->privSwapBackMagicQuotes(); - - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); - - // ----- Return - return PclZip::errorCode(); - } - - // ----- Look for extraction as string - if ($p_options[PCLZIP_OPT_EXTRACT_AS_STRING]) { - - $v_string = ''; - - // ----- Extracting the file - $v_result1 = $this->privExtractFileAsString($v_header, $v_string, $p_options); - if ($v_result1 < 1) { - $this->privCloseFd(); - $this->privSwapBackMagicQuotes(); - return $v_result1; - } - - // ----- Get the only interesting attributes - if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted])) != 1) - { + if (@fseek($this->zip_fd, $v_header_list[$i]['offset'])) { // ----- Close the zip file $this->privCloseFd(); - $this->privSwapBackMagicQuotes(); + $v_temp_zip->privCloseFd(); + @unlink($v_zip_temp_name); - return $v_result; - } + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); - // ----- Set the file content - $p_file_list[$v_nb_extracted]['content'] = $v_string; - - // ----- Next extracted file - $v_nb_extracted++; - - // ----- Look for user callback abort - if ($v_result1 == 2) { - break; - } + // ----- Return + return PclZip::errorCode(); } - // ----- Look for extraction in standard output - elseif ( (isset($p_options[PCLZIP_OPT_EXTRACT_IN_OUTPUT])) - && ($p_options[PCLZIP_OPT_EXTRACT_IN_OUTPUT])) { - // ----- Extracting the file in standard output - $v_result1 = $this->privExtractFileInOutput($v_header, $p_options); - if ($v_result1 < 1) { - $this->privCloseFd(); - $this->privSwapBackMagicQuotes(); - return $v_result1; - } - // ----- Get the only interesting attributes - if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted++])) != 1) { - $this->privCloseFd(); - $this->privSwapBackMagicQuotes(); - return $v_result; - } - - // ----- Look for user callback abort - if ($v_result1 == 2) { - break; - } - } - // ----- Look for normal extraction - else { - // ----- Extracting the file - $v_result1 = $this->privExtractFile($v_header, - $p_path, $p_remove_path, - $p_remove_all_path, - $p_options); - if ($v_result1 < 1) { - $this->privCloseFd(); - $this->privSwapBackMagicQuotes(); - return $v_result1; - } - - // ----- Get the only interesting attributes - if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted++])) != 1) - { + // ----- Read the file header + $v_local_header = array(); + if (($v_result = $this->privReadFileHeader($v_local_header)) != 1) { // ----- Close the zip file $this->privCloseFd(); - $this->privSwapBackMagicQuotes(); - - return $v_result; - } - - // ----- Look for user callback abort - if ($v_result1 == 2) { - break; - } - } - } - } - - // ----- Close the zip file - $this->privCloseFd(); - $this->privSwapBackMagicQuotes(); - - // ----- Return - return $v_result; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : privExtractFile() - // Description : - // Parameters : - // Return Values : - // - // 1 : ... ? - // PCLZIP_ERR_USER_ABORTED(2) : User ask for extraction stop in callback - // -------------------------------------------------------------------------------- - function privExtractFile(&$p_entry, $p_path, $p_remove_path, $p_remove_all_path, &$p_options) - { - $v_result=1; - - // ----- Read the file header - if (($v_result = $this->privReadFileHeader($v_header)) != 1) - { - // ----- Return - return $v_result; - } - - - // ----- Check that the file header is coherent with $p_entry info - if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) { - // TBC - } - - // ----- Look for all path to remove - if ($p_remove_all_path == true) { - // ----- Look for folder entry that not need to be extracted - if (($p_entry['external']&0x00000010)==0x00000010) { - - $p_entry['status'] = "filtered"; - - return $v_result; - } - - // ----- Get the basename of the path - $p_entry['filename'] = basename($p_entry['filename']); - } - - // ----- Look for path to remove - else if ($p_remove_path != "") - { - if (PclZipUtilPathInclusion($p_remove_path, $p_entry['filename']) == 2) - { - - // ----- Change the file status - $p_entry['status'] = "filtered"; - - // ----- Return - return $v_result; - } - - $p_remove_path_size = strlen($p_remove_path); - if (substr($p_entry['filename'], 0, $p_remove_path_size) == $p_remove_path) - { - - // ----- Remove the path - $p_entry['filename'] = substr($p_entry['filename'], $p_remove_path_size); - - } - } - - // ----- Add the path - if ($p_path != '') { - $p_entry['filename'] = $p_path."/".$p_entry['filename']; - } - - // ----- Check a base_dir_restriction - if (isset($p_options[PCLZIP_OPT_EXTRACT_DIR_RESTRICTION])) { - $v_inclusion - = PclZipUtilPathInclusion($p_options[PCLZIP_OPT_EXTRACT_DIR_RESTRICTION], - $p_entry['filename']); - if ($v_inclusion == 0) { - - PclZip::privErrorLog(PCLZIP_ERR_DIRECTORY_RESTRICTION, - "Filename '".$p_entry['filename']."' is " - ."outside PCLZIP_OPT_EXTRACT_DIR_RESTRICTION"); - - return PclZip::errorCode(); - } - } - - // ----- Look for pre-extract callback - if (isset($p_options[PCLZIP_CB_PRE_EXTRACT])) { - - // ----- Generate a local information - $v_local_header = array(); - $this->privConvertHeader2FileInfo($p_entry, $v_local_header); - - // ----- Call the callback - // Here I do not use call_user_func() because I need to send a reference to the - // header. -// eval('$v_result = '.$p_options[PCLZIP_CB_PRE_EXTRACT].'(PCLZIP_CB_PRE_EXTRACT, $v_local_header);'); - $v_result = $p_options[PCLZIP_CB_PRE_EXTRACT](PCLZIP_CB_PRE_EXTRACT, $v_local_header); - if ($v_result == 0) { - // ----- Change the file status - $p_entry['status'] = "skipped"; - $v_result = 1; - } - - // ----- Look for abort result - if ($v_result == 2) { - // ----- This status is internal and will be changed in 'skipped' - $p_entry['status'] = "aborted"; - $v_result = PCLZIP_ERR_USER_ABORTED; - } - - // ----- Update the informations - // Only some fields can be modified - $p_entry['filename'] = $v_local_header['filename']; - } - - - // ----- Look if extraction should be done - if ($p_entry['status'] == 'ok') { - - // ----- Look for specific actions while the file exist - if (file_exists($p_entry['filename'])) - { - - // ----- Look if file is a directory - if (is_dir($p_entry['filename'])) - { - - // ----- Change the file status - $p_entry['status'] = "already_a_directory"; - - // ----- Look for PCLZIP_OPT_STOP_ON_ERROR - // For historical reason first PclZip implementation does not stop - // when this kind of error occurs. - if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) - && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) { - - PclZip::privErrorLog(PCLZIP_ERR_ALREADY_A_DIRECTORY, - "Filename '".$p_entry['filename']."' is " - ."already used by an existing directory"); - - return PclZip::errorCode(); - } - } - // ----- Look if file is write protected - else if (!is_writeable($p_entry['filename'])) - { - - // ----- Change the file status - $p_entry['status'] = "write_protected"; - - // ----- Look for PCLZIP_OPT_STOP_ON_ERROR - // For historical reason first PclZip implementation does not stop - // when this kind of error occurs. - if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) - && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) { - - PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, - "Filename '".$p_entry['filename']."' exists " - ."and is write protected"); - - return PclZip::errorCode(); - } - } - - // ----- Look if the extracted file is older - else if (filemtime($p_entry['filename']) > $p_entry['mtime']) - { - // ----- Change the file status - if ( (isset($p_options[PCLZIP_OPT_REPLACE_NEWER])) - && ($p_options[PCLZIP_OPT_REPLACE_NEWER]===true)) { - } - else { - $p_entry['status'] = "newer_exist"; - - // ----- Look for PCLZIP_OPT_STOP_ON_ERROR - // For historical reason first PclZip implementation does not stop - // when this kind of error occurs. - if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) - && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) { - - PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, - "Newer version of '".$p_entry['filename']."' exists " - ."and option PCLZIP_OPT_REPLACE_NEWER is not selected"); - - return PclZip::errorCode(); - } - } - } - else { - } - } - - // ----- Check the directory availability and create it if necessary - else { - if ((($p_entry['external']&0x00000010)==0x00000010) || (substr($p_entry['filename'], -1) == '/')) - $v_dir_to_check = $p_entry['filename']; - else if (!strstr($p_entry['filename'], "/")) - $v_dir_to_check = ""; - else - $v_dir_to_check = dirname($p_entry['filename']); - - if (($v_result = $this->privDirCheck($v_dir_to_check, (($p_entry['external']&0x00000010)==0x00000010))) != 1) { - - // ----- Change the file status - $p_entry['status'] = "path_creation_fail"; - - // ----- Return - //return $v_result; - $v_result = 1; - } - } - } - - // ----- Look if extraction should be done - if ($p_entry['status'] == 'ok') { - - // ----- Do the extraction (if not a folder) - if (!(($p_entry['external']&0x00000010)==0x00000010)) - { - // ----- Look for not compressed file - if ($p_entry['compression'] == 0) { - - // ----- Opening destination file - if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0) - { - - // ----- Change the file status - $p_entry['status'] = "write_error"; + $v_temp_zip->privCloseFd(); + @unlink($v_zip_temp_name); // ----- Return return $v_result; - } - - - // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks - $v_size = $p_entry['compressed_size']; - while ($v_size != 0) - { - $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); - $v_buffer = @fread($this->zip_fd, $v_read_size); - /* Try to speed up the code - $v_binary_data = pack('a'.$v_read_size, $v_buffer); - @fwrite($v_dest_file, $v_binary_data, $v_read_size); - */ - @fwrite($v_dest_file, $v_buffer, $v_read_size); - $v_size -= $v_read_size; - } - - // ----- Closing the destination file - fclose($v_dest_file); - - // ----- Change the file mtime - touch($p_entry['filename'], $p_entry['mtime']); - - } - else { - // ----- TBC - // Need to be finished - if (($p_entry['flag'] & 1) == 1) { - PclZip::privErrorLog(PCLZIP_ERR_UNSUPPORTED_ENCRYPTION, 'File \''.$p_entry['filename'].'\' is encrypted. Encrypted files are not supported.'); - return PclZip::errorCode(); - } - - - // ----- Look for using temporary file to unzip - if ( (!isset($p_options[PCLZIP_OPT_TEMP_FILE_OFF])) - && (isset($p_options[PCLZIP_OPT_TEMP_FILE_ON]) - || (isset($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD]) - && ($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD] <= $p_entry['size'])) ) ) { - $v_result = $this->privExtractFileUsingTempFile($p_entry, $p_options); - if ($v_result < PCLZIP_ERR_NO_ERROR) { - return $v_result; - } - } - - // ----- Look for extract in memory - else { - - - // ----- Read the compressed file in a buffer (one shot) - $v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']); - - // ----- Decompress the file - $v_file_content = @gzinflate($v_buffer); - unset($v_buffer); - if ($v_file_content === FALSE) { - - // ----- Change the file status - // TBC - $p_entry['status'] = "error"; - - return $v_result; - } - - // ----- Opening destination file - if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0) { - - // ----- Change the file status - $p_entry['status'] = "write_error"; - - return $v_result; - } - - // ----- Write the uncompressed data - @fwrite($v_dest_file, $v_file_content, $p_entry['size']); - unset($v_file_content); - - // ----- Closing the destination file - @fclose($v_dest_file); - - } - - // ----- Change the file mtime - @touch($p_entry['filename'], $p_entry['mtime']); - } - - // ----- Look for chmod option - if (isset($p_options[PCLZIP_OPT_SET_CHMOD])) { - - // ----- Change the mode of the file - @chmod($p_entry['filename'], $p_options[PCLZIP_OPT_SET_CHMOD]); - } - - } - } - - // ----- Change abort status - if ($p_entry['status'] == "aborted") { - $p_entry['status'] = "skipped"; - } - - // ----- Look for post-extract callback - elseif (isset($p_options[PCLZIP_CB_POST_EXTRACT])) { - - // ----- Generate a local information - $v_local_header = array(); - $this->privConvertHeader2FileInfo($p_entry, $v_local_header); - - // ----- Call the callback - // Here I do not use call_user_func() because I need to send a reference to the - // header. -// eval('$v_result = '.$p_options[PCLZIP_CB_POST_EXTRACT].'(PCLZIP_CB_POST_EXTRACT, $v_local_header);'); - $v_result = $p_options[PCLZIP_CB_POST_EXTRACT](PCLZIP_CB_POST_EXTRACT, $v_local_header); - - // ----- Look for abort result - if ($v_result == 2) { - $v_result = PCLZIP_ERR_USER_ABORTED; - } - } - - // ----- Return - return $v_result; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : privExtractFileUsingTempFile() - // Description : - // Parameters : - // Return Values : - // -------------------------------------------------------------------------------- - function privExtractFileUsingTempFile(&$p_entry, &$p_options) - { - $v_result=1; - // ----- Creates a temporary file - $v_gzip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.gz'; - if (($v_dest_file = @fopen($v_gzip_temp_name, "wb")) == 0) { - fclose($v_file); - PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary write mode'); - return PclZip::errorCode(); - } - - - // ----- Write gz file format header - $v_binary_data = pack('va1a1Va1a1', 0x8b1f, Chr($p_entry['compression']), Chr(0x00), time(), Chr(0x00), Chr(3)); - @fwrite($v_dest_file, $v_binary_data, 10); - - // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks - $v_size = $p_entry['compressed_size']; - while ($v_size != 0) - { - $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); - $v_buffer = @fread($this->zip_fd, $v_read_size); - //$v_binary_data = pack('a'.$v_read_size, $v_buffer); - @fwrite($v_dest_file, $v_buffer, $v_read_size); - $v_size -= $v_read_size; - } - - // ----- Write gz file format footer - $v_binary_data = pack('VV', $p_entry['crc'], $p_entry['size']); - @fwrite($v_dest_file, $v_binary_data, 8); - - // ----- Close the temporary file - @fclose($v_dest_file); - - // ----- Opening destination file - if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0) { - $p_entry['status'] = "write_error"; - return $v_result; - } - - // ----- Open the temporary gz file - if (($v_src_file = @gzopen($v_gzip_temp_name, 'rb')) == 0) { - @fclose($v_dest_file); - $p_entry['status'] = "read_error"; - PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary read mode'); - return PclZip::errorCode(); - } - - - // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks - $v_size = $p_entry['size']; - while ($v_size != 0) { - $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); - $v_buffer = @gzread($v_src_file, $v_read_size); - //$v_binary_data = pack('a'.$v_read_size, $v_buffer); - @fwrite($v_dest_file, $v_buffer, $v_read_size); - $v_size -= $v_read_size; - } - @fclose($v_dest_file); - @gzclose($v_src_file); - - // ----- Delete the temporary file - @unlink($v_gzip_temp_name); - - // ----- Return - return $v_result; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : privExtractFileInOutput() - // Description : - // Parameters : - // Return Values : - // -------------------------------------------------------------------------------- - function privExtractFileInOutput(&$p_entry, &$p_options) - { - $v_result=1; - - // ----- Read the file header - if (($v_result = $this->privReadFileHeader($v_header)) != 1) { - return $v_result; - } - - - // ----- Check that the file header is coherent with $p_entry info - if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) { - // TBC - } - - // ----- Look for pre-extract callback - if (isset($p_options[PCLZIP_CB_PRE_EXTRACT])) { - - // ----- Generate a local information - $v_local_header = array(); - $this->privConvertHeader2FileInfo($p_entry, $v_local_header); - - // ----- Call the callback - // Here I do not use call_user_func() because I need to send a reference to the - // header. -// eval('$v_result = '.$p_options[PCLZIP_CB_PRE_EXTRACT].'(PCLZIP_CB_PRE_EXTRACT, $v_local_header);'); - $v_result = $p_options[PCLZIP_CB_PRE_EXTRACT](PCLZIP_CB_PRE_EXTRACT, $v_local_header); - if ($v_result == 0) { - // ----- Change the file status - $p_entry['status'] = "skipped"; - $v_result = 1; - } - - // ----- Look for abort result - if ($v_result == 2) { - // ----- This status is internal and will be changed in 'skipped' - $p_entry['status'] = "aborted"; - $v_result = PCLZIP_ERR_USER_ABORTED; - } - - // ----- Update the informations - // Only some fields can be modified - $p_entry['filename'] = $v_local_header['filename']; - } - - // ----- Trace - - // ----- Look if extraction should be done - if ($p_entry['status'] == 'ok') { - - // ----- Do the extraction (if not a folder) - if (!(($p_entry['external']&0x00000010)==0x00000010)) { - // ----- Look for not compressed file - if ($p_entry['compressed_size'] == $p_entry['size']) { - - // ----- Read the file in a buffer (one shot) - $v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']); - - // ----- Send the file to the output - echo $v_buffer; - unset($v_buffer); + // ----- Check that local file header is same as central file header + if ($this->privCheckFileHeaders($v_local_header, + $v_header_list[$i]) != 1) { + // TBC } - else { + unset($v_local_header); - // ----- Read the compressed file in a buffer (one shot) - $v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']); - - // ----- Decompress the file - $v_file_content = gzinflate($v_buffer); - unset($v_buffer); - - // ----- Send the file to the output - echo $v_file_content; - unset($v_file_content); - } - } - } - - // ----- Change abort status - if ($p_entry['status'] == "aborted") { - $p_entry['status'] = "skipped"; - } - - // ----- Look for post-extract callback - elseif (isset($p_options[PCLZIP_CB_POST_EXTRACT])) { - - // ----- Generate a local information - $v_local_header = array(); - $this->privConvertHeader2FileInfo($p_entry, $v_local_header); - - // ----- Call the callback - // Here I do not use call_user_func() because I need to send a reference to the - // header. -// eval('$v_result = '.$p_options[PCLZIP_CB_POST_EXTRACT].'(PCLZIP_CB_POST_EXTRACT, $v_local_header);'); - $v_result = $p_options[PCLZIP_CB_POST_EXTRACT](PCLZIP_CB_POST_EXTRACT, $v_local_header); - - // ----- Look for abort result - if ($v_result == 2) { - $v_result = PCLZIP_ERR_USER_ABORTED; - } - } - - return $v_result; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : privExtractFileAsString() - // Description : - // Parameters : - // Return Values : - // -------------------------------------------------------------------------------- - function privExtractFileAsString(&$p_entry, &$p_string, &$p_options) - { - $v_result=1; - - // ----- Read the file header - $v_header = array(); - if (($v_result = $this->privReadFileHeader($v_header)) != 1) - { - // ----- Return - return $v_result; - } - - - // ----- Check that the file header is coherent with $p_entry info - if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) { - // TBC - } - - // ----- Look for pre-extract callback - if (isset($p_options[PCLZIP_CB_PRE_EXTRACT])) { - - // ----- Generate a local information - $v_local_header = array(); - $this->privConvertHeader2FileInfo($p_entry, $v_local_header); - - // ----- Call the callback - // Here I do not use call_user_func() because I need to send a reference to the - // header. -// eval('$v_result = '.$p_options[PCLZIP_CB_PRE_EXTRACT].'(PCLZIP_CB_PRE_EXTRACT, $v_local_header);'); - $v_result = $p_options[PCLZIP_CB_PRE_EXTRACT](PCLZIP_CB_PRE_EXTRACT, $v_local_header); - if ($v_result == 0) { - // ----- Change the file status - $p_entry['status'] = "skipped"; - $v_result = 1; - } - - // ----- Look for abort result - if ($v_result == 2) { - // ----- This status is internal and will be changed in 'skipped' - $p_entry['status'] = "aborted"; - $v_result = PCLZIP_ERR_USER_ABORTED; - } - - // ----- Update the informations - // Only some fields can be modified - $p_entry['filename'] = $v_local_header['filename']; - } - - - // ----- Look if extraction should be done - if ($p_entry['status'] == 'ok') { - - // ----- Do the extraction (if not a folder) - if (!(($p_entry['external']&0x00000010)==0x00000010)) { - // ----- Look for not compressed file - // if ($p_entry['compressed_size'] == $p_entry['size']) - if ($p_entry['compression'] == 0) { - - // ----- Reading the file - $p_string = @fread($this->zip_fd, $p_entry['compressed_size']); - } - else { - - // ----- Reading the file - $v_data = @fread($this->zip_fd, $p_entry['compressed_size']); - - // ----- Decompress the file - if (($p_string = @gzinflate($v_data)) === FALSE) { - // TBC - } - } - - // ----- Trace - } - else { - // TBC : error : can not extract a folder in a string - } - - } - - // ----- Change abort status - if ($p_entry['status'] == "aborted") { - $p_entry['status'] = "skipped"; - } - - // ----- Look for post-extract callback - elseif (isset($p_options[PCLZIP_CB_POST_EXTRACT])) { - - // ----- Generate a local information - $v_local_header = array(); - $this->privConvertHeader2FileInfo($p_entry, $v_local_header); - - // ----- Swap the content to header - $v_local_header['content'] = $p_string; - $p_string = ''; - - // ----- Call the callback - // Here I do not use call_user_func() because I need to send a reference to the - // header. -// eval('$v_result = '.$p_options[PCLZIP_CB_POST_EXTRACT].'(PCLZIP_CB_POST_EXTRACT, $v_local_header);'); - $v_result = $p_options[PCLZIP_CB_POST_EXTRACT](PCLZIP_CB_POST_EXTRACT, $v_local_header); - - // ----- Swap back the content to header - $p_string = $v_local_header['content']; - unset($v_local_header['content']); - - // ----- Look for abort result - if ($v_result == 2) { - $v_result = PCLZIP_ERR_USER_ABORTED; - } - } - - // ----- Return - return $v_result; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : privReadFileHeader() - // Description : - // Parameters : - // Return Values : - // -------------------------------------------------------------------------------- - function privReadFileHeader(&$p_header) - { - $v_result=1; - - // ----- Read the 4 bytes signature - $v_binary_data = @fread($this->zip_fd, 4); - $v_data = unpack('Vid', $v_binary_data); - - // ----- Check signature - if ($v_data['id'] != 0x04034b50) - { - - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Invalid archive structure'); - - // ----- Return - return PclZip::errorCode(); - } - - // ----- Read the first 42 bytes of the header - $v_binary_data = fread($this->zip_fd, 26); - - // ----- Look for invalid block size - if (strlen($v_binary_data) != 26) - { - $p_header['filename'] = ""; - $p_header['status'] = "invalid_header"; - - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Invalid block size : ".strlen($v_binary_data)); - - // ----- Return - return PclZip::errorCode(); - } - - // ----- Extract the values - $v_data = unpack('vversion/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len', $v_binary_data); - - // ----- Get filename - $p_header['filename'] = fread($this->zip_fd, $v_data['filename_len']); - - // ----- Get extra_fields - if ($v_data['extra_len'] != 0) { - $p_header['extra'] = fread($this->zip_fd, $v_data['extra_len']); - } - else { - $p_header['extra'] = ''; - } - - // ----- Extract properties - $p_header['version_extracted'] = $v_data['version']; - $p_header['compression'] = $v_data['compression']; - $p_header['size'] = $v_data['size']; - $p_header['compressed_size'] = $v_data['compressed_size']; - $p_header['crc'] = $v_data['crc']; - $p_header['flag'] = $v_data['flag']; - $p_header['filename_len'] = $v_data['filename_len']; - - // ----- Recuperate date in UNIX format - $p_header['mdate'] = $v_data['mdate']; - $p_header['mtime'] = $v_data['mtime']; - if ($p_header['mdate'] && $p_header['mtime']) - { - // ----- Extract time - $v_hour = ($p_header['mtime'] & 0xF800) >> 11; - $v_minute = ($p_header['mtime'] & 0x07E0) >> 5; - $v_seconde = ($p_header['mtime'] & 0x001F)*2; - - // ----- Extract date - $v_year = (($p_header['mdate'] & 0xFE00) >> 9) + 1980; - $v_month = ($p_header['mdate'] & 0x01E0) >> 5; - $v_day = $p_header['mdate'] & 0x001F; - - // ----- Get UNIX date format - $p_header['mtime'] = @mktime($v_hour, $v_minute, $v_seconde, $v_month, $v_day, $v_year); - - } - else - { - $p_header['mtime'] = time(); - } - - // TBC - //for(reset($v_data); $key = key($v_data); next($v_data)) { - //} - - // ----- Set the stored filename - $p_header['stored_filename'] = $p_header['filename']; - - // ----- Set the status field - $p_header['status'] = "ok"; - - // ----- Return - return $v_result; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : privReadCentralFileHeader() - // Description : - // Parameters : - // Return Values : - // -------------------------------------------------------------------------------- - function privReadCentralFileHeader(&$p_header) - { - $v_result=1; - - // ----- Read the 4 bytes signature - $v_binary_data = @fread($this->zip_fd, 4); - $v_data = unpack('Vid', $v_binary_data); - - // ----- Check signature - if ($v_data['id'] != 0x02014b50) - { - - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Invalid archive structure'); - - // ----- Return - return PclZip::errorCode(); - } - - // ----- Read the first 42 bytes of the header - $v_binary_data = fread($this->zip_fd, 42); - - // ----- Look for invalid block size - if (strlen($v_binary_data) != 42) - { - $p_header['filename'] = ""; - $p_header['status'] = "invalid_header"; - - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Invalid block size : ".strlen($v_binary_data)); - - // ----- Return - return PclZip::errorCode(); - } - - // ----- Extract the values - $p_header = unpack('vversion/vversion_extracted/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len/vcomment_len/vdisk/vinternal/Vexternal/Voffset', $v_binary_data); - - // ----- Get filename - if ($p_header['filename_len'] != 0) - $p_header['filename'] = fread($this->zip_fd, $p_header['filename_len']); - else - $p_header['filename'] = ''; - - // ----- Get extra - if ($p_header['extra_len'] != 0) - $p_header['extra'] = fread($this->zip_fd, $p_header['extra_len']); - else - $p_header['extra'] = ''; - - // ----- Get comment - if ($p_header['comment_len'] != 0) - $p_header['comment'] = fread($this->zip_fd, $p_header['comment_len']); - else - $p_header['comment'] = ''; - - // ----- Extract properties - - // ----- Recuperate date in UNIX format - //if ($p_header['mdate'] && $p_header['mtime']) - // TBC : bug : this was ignoring time with 0/0/0 - if (1) - { - // ----- Extract time - $v_hour = ($p_header['mtime'] & 0xF800) >> 11; - $v_minute = ($p_header['mtime'] & 0x07E0) >> 5; - $v_seconde = ($p_header['mtime'] & 0x001F)*2; - - // ----- Extract date - $v_year = (($p_header['mdate'] & 0xFE00) >> 9) + 1980; - $v_month = ($p_header['mdate'] & 0x01E0) >> 5; - $v_day = $p_header['mdate'] & 0x001F; - - // ----- Get UNIX date format - $p_header['mtime'] = @mktime($v_hour, $v_minute, $v_seconde, $v_month, $v_day, $v_year); - - } - else - { - $p_header['mtime'] = time(); - } - - // ----- Set the stored filename - $p_header['stored_filename'] = $p_header['filename']; - - // ----- Set default status to ok - $p_header['status'] = 'ok'; - - // ----- Look if it is a directory - if (substr($p_header['filename'], -1) == '/') { - //$p_header['external'] = 0x41FF0010; - $p_header['external'] = 0x00000010; - } - - - // ----- Return - return $v_result; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : privCheckFileHeaders() - // Description : - // Parameters : - // Return Values : - // 1 on success, - // 0 on error; - // -------------------------------------------------------------------------------- - function privCheckFileHeaders(&$p_local_header, &$p_central_header) - { - $v_result=1; - - // ----- Check the static values - // TBC - if ($p_local_header['filename'] != $p_central_header['filename']) { - } - if ($p_local_header['version_extracted'] != $p_central_header['version_extracted']) { - } - if ($p_local_header['flag'] != $p_central_header['flag']) { - } - if ($p_local_header['compression'] != $p_central_header['compression']) { - } - if ($p_local_header['mtime'] != $p_central_header['mtime']) { - } - if ($p_local_header['filename_len'] != $p_central_header['filename_len']) { - } - - // ----- Look for flag bit 3 - if (($p_local_header['flag'] & 8) == 8) { - $p_local_header['size'] = $p_central_header['size']; - $p_local_header['compressed_size'] = $p_central_header['compressed_size']; - $p_local_header['crc'] = $p_central_header['crc']; - } - - // ----- Return - return $v_result; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : privReadEndCentralDir() - // Description : - // Parameters : - // Return Values : - // -------------------------------------------------------------------------------- - function privReadEndCentralDir(&$p_central_dir) - { - $v_result=1; - - // ----- Go to the end of the zip file - $v_size = filesize($this->zipname); - @fseek($this->zip_fd, $v_size); - if (@ftell($this->zip_fd) != $v_size) - { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to go to the end of the archive \''.$this->zipname.'\''); - - // ----- Return - return PclZip::errorCode(); - } - - // ----- First try : look if this is an archive with no commentaries (most of the time) - // in this case the end of central dir is at 22 bytes of the file end - $v_found = 0; - if ($v_size > 26) { - @fseek($this->zip_fd, $v_size-22); - if (($v_pos = @ftell($this->zip_fd)) != ($v_size-22)) - { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to seek back to the middle of the archive \''.$this->zipname.'\''); - - // ----- Return - return PclZip::errorCode(); - } - - // ----- Read for bytes - $v_binary_data = @fread($this->zip_fd, 4); - $v_data = @unpack('Vid', $v_binary_data); - - // ----- Check signature - if ($v_data['id'] == 0x06054b50) { - $v_found = 1; - } - - $v_pos = ftell($this->zip_fd); - } - - // ----- Go back to the maximum possible size of the Central Dir End Record - if (!$v_found) { - $v_maximum_size = 65557; // 0xFFFF + 22; - if ($v_maximum_size > $v_size) - $v_maximum_size = $v_size; - @fseek($this->zip_fd, $v_size-$v_maximum_size); - if (@ftell($this->zip_fd) != ($v_size-$v_maximum_size)) - { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to seek back to the middle of the archive \''.$this->zipname.'\''); - - // ----- Return - return PclZip::errorCode(); - } - - // ----- Read byte per byte in order to find the signature - $v_pos = ftell($this->zip_fd); - $v_bytes = 0x00000000; - while ($v_pos < $v_size) - { - // ----- Read a byte - $v_byte = @fread($this->zip_fd, 1); - - // ----- Add the byte - //$v_bytes = ($v_bytes << 8) | Ord($v_byte); - // Note we mask the old value down such that once shifted we can never end up with more than a 32bit number - // Otherwise on systems where we have 64bit integers the check below for the magic number will fail. - $v_bytes = ( ($v_bytes & 0xFFFFFF) << 8) | Ord($v_byte); - - // ----- Compare the bytes - if ($v_bytes == 0x504b0506) - { - $v_pos++; - break; - } - - $v_pos++; - } - - // ----- Look if not found end of central dir - if ($v_pos == $v_size) - { - - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Unable to find End of Central Dir Record signature"); - - // ----- Return - return PclZip::errorCode(); - } - } - - // ----- Read the first 18 bytes of the header - $v_binary_data = fread($this->zip_fd, 18); - - // ----- Look for invalid block size - if (strlen($v_binary_data) != 18) - { - - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Invalid End of Central Dir Record size : ".strlen($v_binary_data)); - - // ----- Return - return PclZip::errorCode(); - } - - // ----- Extract the values - $v_data = unpack('vdisk/vdisk_start/vdisk_entries/ventries/Vsize/Voffset/vcomment_size', $v_binary_data); - - // ----- Check the global size - if (($v_pos + $v_data['comment_size'] + 18) != $v_size) { - - // ----- Removed in release 2.2 see readme file - // The check of the file size is a little too strict. - // Some bugs where found when a zip is encrypted/decrypted with 'crypt'. - // While decrypted, zip has training 0 bytes - if (0) { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, - 'The central dir is not at the end of the archive.' - .' Some trailing bytes exists after the archive.'); - - // ----- Return - return PclZip::errorCode(); - } - } - - // ----- Get comment - if ($v_data['comment_size'] != 0) { - $p_central_dir['comment'] = fread($this->zip_fd, $v_data['comment_size']); - } - else - $p_central_dir['comment'] = ''; - - $p_central_dir['entries'] = $v_data['entries']; - $p_central_dir['disk_entries'] = $v_data['disk_entries']; - $p_central_dir['offset'] = $v_data['offset']; - $p_central_dir['size'] = $v_data['size']; - $p_central_dir['disk'] = $v_data['disk']; - $p_central_dir['disk_start'] = $v_data['disk_start']; - - // TBC - //for(reset($p_central_dir); $key = key($p_central_dir); next($p_central_dir)) { - //} - - // ----- Return - return $v_result; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : privDeleteByRule() - // Description : - // Parameters : - // Return Values : - // -------------------------------------------------------------------------------- - function privDeleteByRule(&$p_result_list, &$p_options) - { - $v_result=1; - $v_list_detail = array(); - - // ----- Open the zip file - if (($v_result=$this->privOpenFd('rb')) != 1) - { - // ----- Return - return $v_result; - } - - // ----- Read the central directory informations - $v_central_dir = array(); - if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) - { - $this->privCloseFd(); - return $v_result; - } - - // ----- Go to beginning of File - @rewind($this->zip_fd); - - // ----- Scan all the files - // ----- Start at beginning of Central Dir - $v_pos_entry = $v_central_dir['offset']; - @rewind($this->zip_fd); - if (@fseek($this->zip_fd, $v_pos_entry)) - { - // ----- Close the zip file - $this->privCloseFd(); - - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); - - // ----- Return - return PclZip::errorCode(); - } - - // ----- Read each entry - $v_header_list = array(); - $j_start = 0; - for ($i=0, $v_nb_extracted=0; $i<$v_central_dir['entries']; $i++) - { - - // ----- Read the file header - $v_header_list[$v_nb_extracted] = array(); - if (($v_result = $this->privReadCentralFileHeader($v_header_list[$v_nb_extracted])) != 1) - { - // ----- Close the zip file - $this->privCloseFd(); - - return $v_result; - } - - - // ----- Store the index - $v_header_list[$v_nb_extracted]['index'] = $i; - - // ----- Look for the specific extract rules - $v_found = false; - - // ----- Look for extract by name rule - if ( (isset($p_options[PCLZIP_OPT_BY_NAME])) - && ($p_options[PCLZIP_OPT_BY_NAME] != 0)) { - - // ----- Look if the filename is in the list - for ($j=0; ($j strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) - && (substr($v_header_list[$v_nb_extracted]['stored_filename'], 0, strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) == $p_options[PCLZIP_OPT_BY_NAME][$j])) { - $v_found = true; - } - elseif ( (($v_header_list[$v_nb_extracted]['external']&0x00000010)==0x00000010) /* Indicates a folder */ - && ($v_header_list[$v_nb_extracted]['stored_filename'].'/' == $p_options[PCLZIP_OPT_BY_NAME][$j])) { - $v_found = true; - } - } - // ----- Look for a filename - elseif ($v_header_list[$v_nb_extracted]['stored_filename'] == $p_options[PCLZIP_OPT_BY_NAME][$j]) { - $v_found = true; - } - } - } - - // ----- Look for extract by ereg rule - // ereg() is deprecated with PHP 5.3 - /* - else if ( (isset($p_options[PCLZIP_OPT_BY_EREG])) - && ($p_options[PCLZIP_OPT_BY_EREG] != "")) { - - if (ereg($p_options[PCLZIP_OPT_BY_EREG], $v_header_list[$v_nb_extracted]['stored_filename'])) { - $v_found = true; - } - } - */ - - // ----- Look for extract by preg rule - else if ( (isset($p_options[PCLZIP_OPT_BY_PREG])) - && ($p_options[PCLZIP_OPT_BY_PREG] != "")) { - - if (preg_match($p_options[PCLZIP_OPT_BY_PREG], $v_header_list[$v_nb_extracted]['stored_filename'])) { - $v_found = true; - } - } - - // ----- Look for extract by index rule - else if ( (isset($p_options[PCLZIP_OPT_BY_INDEX])) - && ($p_options[PCLZIP_OPT_BY_INDEX] != 0)) { - - // ----- Look if the index is in the list - for ($j=$j_start; ($j=$p_options[PCLZIP_OPT_BY_INDEX][$j]['start']) && ($i<=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end'])) { - $v_found = true; - } - if ($i>=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end']) { - $j_start = $j+1; - } - - if ($p_options[PCLZIP_OPT_BY_INDEX][$j]['start']>$i) { - break; - } - } - } - else { - $v_found = true; - } - - // ----- Look for deletion - if ($v_found) - { - unset($v_header_list[$v_nb_extracted]); - } - else - { - $v_nb_extracted++; - } - } - - // ----- Look if something need to be deleted - if ($v_nb_extracted > 0) { - - // ----- Creates a temporay file - $v_zip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.tmp'; - - // ----- Creates a temporary zip archive - $v_temp_zip = new PclZip($v_zip_temp_name); - - // ----- Open the temporary zip file in write mode - if (($v_result = $v_temp_zip->privOpenFd('wb')) != 1) { + // ----- Write the file header + if (($v_result = $v_temp_zip->privWriteFileHeader($v_header_list[$i])) != 1) { + // ----- Close the zip file $this->privCloseFd(); + $v_temp_zip->privCloseFd(); + @unlink($v_zip_temp_name); // ----- Return return $v_result; } - // ----- Look which file need to be kept - for ($i=0; $izip_fd, $v_temp_zip->zip_fd, $v_header_list[$i]['compressed_size'])) != 1) { + // ----- Close the zip file + $this->privCloseFd(); + $v_temp_zip->privCloseFd(); + @unlink($v_zip_temp_name); - // ----- Calculate the position of the header - @rewind($this->zip_fd); - if (@fseek($this->zip_fd, $v_header_list[$i]['offset'])) { - // ----- Close the zip file - $this->privCloseFd(); - $v_temp_zip->privCloseFd(); - @unlink($v_zip_temp_name); - - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); - - // ----- Return - return PclZip::errorCode(); - } - - // ----- Read the file header - $v_local_header = array(); - if (($v_result = $this->privReadFileHeader($v_local_header)) != 1) { - // ----- Close the zip file - $this->privCloseFd(); - $v_temp_zip->privCloseFd(); - @unlink($v_zip_temp_name); - - // ----- Return - return $v_result; - } - - // ----- Check that local file header is same as central file header - if ($this->privCheckFileHeaders($v_local_header, - $v_header_list[$i]) != 1) { - // TBC - } - unset($v_local_header); - - // ----- Write the file header - if (($v_result = $v_temp_zip->privWriteFileHeader($v_header_list[$i])) != 1) { - // ----- Close the zip file - $this->privCloseFd(); - $v_temp_zip->privCloseFd(); - @unlink($v_zip_temp_name); - - // ----- Return - return $v_result; - } - - // ----- Read/write the data block - if (($v_result = PclZipUtilCopyBlock($this->zip_fd, $v_temp_zip->zip_fd, $v_header_list[$i]['compressed_size'])) != 1) { - // ----- Close the zip file - $this->privCloseFd(); - $v_temp_zip->privCloseFd(); - @unlink($v_zip_temp_name); - - // ----- Return - return $v_result; - } + // ----- Return + return $v_result; } + } - // ----- Store the offset of the central dir - $v_offset = @ftell($v_temp_zip->zip_fd); + // ----- Store the offset of the central dir + $v_offset = @ftell($v_temp_zip->zip_fd); - // ----- Re-Create the Central Dir files header - for ($i=0; $iprivWriteCentralFileHeader($v_header_list[$i])) != 1) { - $v_temp_zip->privCloseFd(); - $this->privCloseFd(); - @unlink($v_zip_temp_name); - - // ----- Return - return $v_result; - } - - // ----- Transform the header to a 'usable' info - $v_temp_zip->privConvertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]); - } - - - // ----- Zip file comment - $v_comment = ''; - if (isset($p_options[PCLZIP_OPT_COMMENT])) { - $v_comment = $p_options[PCLZIP_OPT_COMMENT]; - } - - // ----- Calculate the size of the central header - $v_size = @ftell($v_temp_zip->zip_fd)-$v_offset; - - // ----- Create the central dir footer - if (($v_result = $v_temp_zip->privWriteCentralHeader(sizeof($v_header_list), $v_size, $v_offset, $v_comment)) != 1) { - // ----- Reset the file list - unset($v_header_list); + // ----- Re-Create the Central Dir files header + for ($i=0; $iprivWriteCentralFileHeader($v_header_list[$i])) != 1) { $v_temp_zip->privCloseFd(); $this->privCloseFd(); @unlink($v_zip_temp_name); @@ -4941,273 +4758,35 @@ return $v_result; } - // ----- Close - $v_temp_zip->privCloseFd(); - $this->privCloseFd(); - - // ----- Delete the zip file - // TBC : I should test the result ... - @unlink($this->zipname); - - // ----- Rename the temporary file - // TBC : I should test the result ... - //@rename($v_zip_temp_name, $this->zipname); - PclZipUtilRename($v_zip_temp_name, $this->zipname); - - // ----- Destroy the temporary archive - unset($v_temp_zip); - } - - // ----- Remove every files : reset the file - else if ($v_central_dir['entries'] != 0) { - $this->privCloseFd(); - - if (($v_result = $this->privOpenFd('wb')) != 1) { - return $v_result; - } - - if (($v_result = $this->privWriteCentralHeader(0, 0, 0, '')) != 1) { - return $v_result; - } - - $this->privCloseFd(); + // ----- Transform the header to a 'usable' info + $v_temp_zip->privConvertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]); } - // ----- Return - return $v_result; - } - // -------------------------------------------------------------------------------- - // -------------------------------------------------------------------------------- - // Function : privDirCheck() - // Description : - // Check if a directory exists, if not it creates it and all the parents directory - // which may be useful. - // Parameters : - // $p_dir : Directory path to check. - // Return Values : - // 1 : OK - // -1 : Unable to create directory - // -------------------------------------------------------------------------------- - function privDirCheck($p_dir, $p_is_dir=false) - { - $v_result = 1; - - - // ----- Remove the final '/' - if (($p_is_dir) && (substr($p_dir, -1)=='/')) - { - $p_dir = substr($p_dir, 0, strlen($p_dir)-1); + // ----- Zip file comment + $v_comment = ''; + if (isset($p_options[PCLZIP_OPT_COMMENT])) { + $v_comment = $p_options[PCLZIP_OPT_COMMENT]; } - // ----- Check the directory availability - if ((is_dir($p_dir)) || ($p_dir == "")) - { - return 1; - } - - // ----- Extract parent directory - $p_parent_dir = dirname($p_dir); - - // ----- Just a check - if ($p_parent_dir != $p_dir) - { - // ----- Look for parent directory - if ($p_parent_dir != "") - { - if (($v_result = $this->privDirCheck($p_parent_dir)) != 1) - { - return $v_result; - } - } - } - - // ----- Create the directory - if (!@mkdir($p_dir, 0777)) - { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_DIR_CREATE_FAIL, "Unable to create directory '$p_dir'"); - - // ----- Return - return PclZip::errorCode(); - } - - // ----- Return - return $v_result; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : privMerge() - // Description : - // If $p_archive_to_add does not exist, the function exit with a success result. - // Parameters : - // Return Values : - // -------------------------------------------------------------------------------- - function privMerge(&$p_archive_to_add) - { - $v_result=1; - - // ----- Look if the archive_to_add exists - if (!is_file($p_archive_to_add->zipname)) - { - - // ----- Nothing to merge, so merge is a success - $v_result = 1; - - // ----- Return - return $v_result; - } - - // ----- Look if the archive exists - if (!is_file($this->zipname)) - { - - // ----- Do a duplicate - $v_result = $this->privDuplicate($p_archive_to_add->zipname); - - // ----- Return - return $v_result; - } - - // ----- Open the zip file - if (($v_result=$this->privOpenFd('rb')) != 1) - { - // ----- Return - return $v_result; - } - - // ----- Read the central directory informations - $v_central_dir = array(); - if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) - { - $this->privCloseFd(); - return $v_result; - } - - // ----- Go to beginning of File - @rewind($this->zip_fd); - - // ----- Open the archive_to_add file - if (($v_result=$p_archive_to_add->privOpenFd('rb')) != 1) - { - $this->privCloseFd(); - - // ----- Return - return $v_result; - } - - // ----- Read the central directory informations - $v_central_dir_to_add = array(); - if (($v_result = $p_archive_to_add->privReadEndCentralDir($v_central_dir_to_add)) != 1) - { - $this->privCloseFd(); - $p_archive_to_add->privCloseFd(); - - return $v_result; - } - - // ----- Go to beginning of File - @rewind($p_archive_to_add->zip_fd); - - // ----- Creates a temporay file - $v_zip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.tmp'; - - // ----- Open the temporary file in write mode - if (($v_zip_temp_fd = @fopen($v_zip_temp_name, 'wb')) == 0) - { - $this->privCloseFd(); - $p_archive_to_add->privCloseFd(); - - PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_zip_temp_name.'\' in binary write mode'); - - // ----- Return - return PclZip::errorCode(); - } - - // ----- Copy the files from the archive to the temporary file - // TBC : Here I should better append the file and go back to erase the central dir - $v_size = $v_central_dir['offset']; - while ($v_size != 0) - { - $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); - $v_buffer = fread($this->zip_fd, $v_read_size); - @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); - $v_size -= $v_read_size; - } - - // ----- Copy the files from the archive_to_add into the temporary file - $v_size = $v_central_dir_to_add['offset']; - while ($v_size != 0) - { - $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); - $v_buffer = fread($p_archive_to_add->zip_fd, $v_read_size); - @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); - $v_size -= $v_read_size; - } - - // ----- Store the offset of the central dir - $v_offset = @ftell($v_zip_temp_fd); - - // ----- Copy the block of file headers from the old archive - $v_size = $v_central_dir['size']; - while ($v_size != 0) - { - $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); - $v_buffer = @fread($this->zip_fd, $v_read_size); - @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); - $v_size -= $v_read_size; - } - - // ----- Copy the block of file headers from the archive_to_add - $v_size = $v_central_dir_to_add['size']; - while ($v_size != 0) - { - $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); - $v_buffer = @fread($p_archive_to_add->zip_fd, $v_read_size); - @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); - $v_size -= $v_read_size; - } - - // ----- Merge the file comments - $v_comment = $v_central_dir['comment'].' '.$v_central_dir_to_add['comment']; - - // ----- Calculate the size of the (new) central header - $v_size = @ftell($v_zip_temp_fd)-$v_offset; - - // ----- Swap the file descriptor - // Here is a trick : I swap the temporary fd with the zip fd, in order to use - // the following methods on the temporary fil and not the real archive fd - $v_swap = $this->zip_fd; - $this->zip_fd = $v_zip_temp_fd; - $v_zip_temp_fd = $v_swap; + // ----- Calculate the size of the central header + $v_size = @ftell($v_temp_zip->zip_fd)-$v_offset; // ----- Create the central dir footer - if (($v_result = $this->privWriteCentralHeader($v_central_dir['entries']+$v_central_dir_to_add['entries'], $v_size, $v_offset, $v_comment)) != 1) - { - $this->privCloseFd(); - $p_archive_to_add->privCloseFd(); - @fclose($v_zip_temp_fd); - $this->zip_fd = null; + if (($v_result = $v_temp_zip->privWriteCentralHeader(sizeof($v_header_list), $v_size, $v_offset, $v_comment)) != 1) { + // ----- Reset the file list + unset($v_header_list); + $v_temp_zip->privCloseFd(); + $this->privCloseFd(); + @unlink($v_zip_temp_name); - // ----- Reset the file list - unset($v_header_list); - - // ----- Return - return $v_result; + // ----- Return + return $v_result; } - // ----- Swap back the file descriptor - $v_swap = $this->zip_fd; - $this->zip_fd = $v_zip_temp_fd; - $v_zip_temp_fd = $v_swap; - // ----- Close + $v_temp_zip->privCloseFd(); $this->privCloseFd(); - $p_archive_to_add->privCloseFd(); - - // ----- Close the temporary file - @fclose($v_zip_temp_fd); // ----- Delete the zip file // TBC : I should test the result ... @@ -5218,474 +4797,738 @@ //@rename($v_zip_temp_name, $this->zipname); PclZipUtilRename($v_zip_temp_name, $this->zipname); - // ----- Return - return $v_result; - } - // -------------------------------------------------------------------------------- + // ----- Destroy the temporary archive + unset($v_temp_zip); +} - // -------------------------------------------------------------------------------- - // Function : privDuplicate() - // Description : - // Parameters : - // Return Values : - // -------------------------------------------------------------------------------- - function privDuplicate($p_archive_filename) - { - $v_result=1; - - // ----- Look if the $p_archive_filename exists - if (!is_file($p_archive_filename)) - { - - // ----- Nothing to duplicate, so duplicate is a success. - $v_result = 1; - - // ----- Return - return $v_result; - } - - // ----- Open the zip file - if (($v_result=$this->privOpenFd('wb')) != 1) - { - // ----- Return - return $v_result; - } - - // ----- Open the temporary file in write mode - if (($v_zip_temp_fd = @fopen($p_archive_filename, 'rb')) == 0) - { - $this->privCloseFd(); - - PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive file \''.$p_archive_filename.'\' in binary write mode'); - - // ----- Return - return PclZip::errorCode(); - } - - // ----- Copy the files from the archive to the temporary file - // TBC : Here I should better append the file and go back to erase the central dir - $v_size = filesize($p_archive_filename); - while ($v_size != 0) - { - $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); - $v_buffer = fread($v_zip_temp_fd, $v_read_size); - @fwrite($this->zip_fd, $v_buffer, $v_read_size); - $v_size -= $v_read_size; - } - - // ----- Close +// ----- Remove every files : reset the file +else if ($v_central_dir['entries'] != 0) { $this->privCloseFd(); - // ----- Close the temporary file - @fclose($v_zip_temp_fd); - - // ----- Return - return $v_result; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : privErrorLog() - // Description : - // Parameters : - // -------------------------------------------------------------------------------- - function privErrorLog($p_error_code=0, $p_error_string='') - { - if (PCLZIP_ERROR_EXTERNAL == 1) { - PclError($p_error_code, $p_error_string); - } - else { - $this->error_code = $p_error_code; - $this->error_string = $p_error_string; - } - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : privErrorReset() - // Description : - // Parameters : - // -------------------------------------------------------------------------------- - function privErrorReset() - { - if (PCLZIP_ERROR_EXTERNAL == 1) { - PclErrorReset(); - } - else { - $this->error_code = 0; - $this->error_string = ''; - } - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : privDisableMagicQuotes() - // Description : - // Parameters : - // Return Values : - // -------------------------------------------------------------------------------- - function privDisableMagicQuotes() - { - $v_result=1; - - // ----- Look if function exists - if ( (!function_exists("get_magic_quotes_runtime")) - || (!function_exists("set_magic_quotes_runtime"))) { + if (($v_result = $this->privOpenFd('wb')) != 1) { return $v_result; } - // ----- Look if already done - if ($this->magic_quotes_status != -1) { + if (($v_result = $this->privWriteCentralHeader(0, 0, 0, '')) != 1) { return $v_result; } - // ----- Get and memorize the magic_quote value - $this->magic_quotes_status = @get_magic_quotes_runtime(); + $this->privCloseFd(); +} - // ----- Disable magic_quotes - if ($this->magic_quotes_status == 1) { - @set_magic_quotes_runtime(0); - } +// ----- Return +return $v_result; +} +// -------------------------------------------------------------------------------- - // ----- Return - return $v_result; - } - // -------------------------------------------------------------------------------- +// -------------------------------------------------------------------------------- +// Function : privDirCheck() +// Description : +// Check if a directory exists, if not it creates it and all the parents directory +// which may be useful. +// Parameters : +// $p_dir : Directory path to check. +// Return Values : +// 1 : OK +// -1 : Unable to create directory +// -------------------------------------------------------------------------------- +function privDirCheck($p_dir, $p_is_dir=false) +{ +$v_result = 1; - // -------------------------------------------------------------------------------- - // Function : privSwapBackMagicQuotes() - // Description : - // Parameters : - // Return Values : - // -------------------------------------------------------------------------------- - function privSwapBackMagicQuotes() + +// ----- Remove the final '/' +if (($p_is_dir) && (substr($p_dir, -1)=='/')) +{ + $p_dir = substr($p_dir, 0, strlen($p_dir)-1); +} + +// ----- Check the directory availability +if ((is_dir($p_dir)) || ($p_dir == "")) +{ + return 1; +} + +// ----- Extract parent directory +$p_parent_dir = dirname($p_dir); + +// ----- Just a check +if ($p_parent_dir != $p_dir) +{ + // ----- Look for parent directory + if ($p_parent_dir != "") { - $v_result=1; - - // ----- Look if function exists - if ( (!function_exists("get_magic_quotes_runtime")) - || (!function_exists("set_magic_quotes_runtime"))) { + if (($v_result = $this->privDirCheck($p_parent_dir)) != 1) + { return $v_result; } - - // ----- Look if something to do - if ($this->magic_quotes_status != -1) { - return $v_result; - } - - // ----- Swap back magic_quotes - if ($this->magic_quotes_status == 1) { - @set_magic_quotes_runtime($this->magic_quotes_status); - } - - // ----- Return - return $v_result; } - // -------------------------------------------------------------------------------- +} - } - // End of class - // -------------------------------------------------------------------------------- +// ----- Create the directory +if (!@mkdir($p_dir, 0777)) +{ + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_DIR_CREATE_FAIL, "Unable to create directory '$p_dir'"); - // -------------------------------------------------------------------------------- - // Function : PclZipUtilPathReduction() - // Description : - // Parameters : - // Return Values : - // -------------------------------------------------------------------------------- - function PclZipUtilPathReduction($p_dir) - { - $v_result = ""; + // ----- Return + return PclZip::errorCode(); +} - // ----- Look for not empty path - if ($p_dir != "") { - // ----- Explode path by directory names - $v_list = explode("/", $p_dir); +// ----- Return +return $v_result; +} +// -------------------------------------------------------------------------------- - // ----- Study directories from last to first - $v_skip = 0; - for ($i=sizeof($v_list)-1; $i>=0; $i--) { - // ----- Look for current path - if ($v_list[$i] == ".") { - // ----- Ignore this directory - // Should be the first $i=0, but no check is done - } - else if ($v_list[$i] == "..") { - $v_skip++; - } - else if ($v_list[$i] == "") { - // ----- First '/' i.e. root slash - if ($i == 0) { - $v_result = "/".$v_result; - if ($v_skip > 0) { - // ----- It is an invalid path, so the path is not modified - // TBC - $v_result = $p_dir; - $v_skip = 0; - } - } - // ----- Last '/' i.e. indicates a directory - else if ($i == (sizeof($v_list)-1)) { - $v_result = $v_list[$i]; - } - // ----- Double '/' inside the path - else { - // ----- Ignore only the double '//' in path, - // but not the first and last '/' - } - } - else { - // ----- Look for item to skip - if ($v_skip > 0) { - $v_skip--; - } - else { - $v_result = $v_list[$i].($i!=(sizeof($v_list)-1)?"/".$v_result:""); - } +// -------------------------------------------------------------------------------- +// Function : privMerge() +// Description : +// If $p_archive_to_add does not exist, the function exit with a success result. +// Parameters : +// Return Values : +// -------------------------------------------------------------------------------- +function privMerge(&$p_archive_to_add) +{ +$v_result=1; + +// ----- Look if the archive_to_add exists +if (!is_file($p_archive_to_add->zipname)) +{ + + // ----- Nothing to merge, so merge is a success + $v_result = 1; + + // ----- Return + return $v_result; +} + +// ----- Look if the archive exists +if (!is_file($this->zipname)) +{ + + // ----- Do a duplicate + $v_result = $this->privDuplicate($p_archive_to_add->zipname); + + // ----- Return + return $v_result; +} + +// ----- Open the zip file +if (($v_result=$this->privOpenFd('rb')) != 1) +{ + // ----- Return + return $v_result; +} + +// ----- Read the central directory informations +$v_central_dir = array(); +if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) +{ + $this->privCloseFd(); + return $v_result; +} + +// ----- Go to beginning of File +@rewind($this->zip_fd); + +// ----- Open the archive_to_add file +if (($v_result=$p_archive_to_add->privOpenFd('rb')) != 1) +{ + $this->privCloseFd(); + + // ----- Return + return $v_result; +} + +// ----- Read the central directory informations +$v_central_dir_to_add = array(); +if (($v_result = $p_archive_to_add->privReadEndCentralDir($v_central_dir_to_add)) != 1) +{ + $this->privCloseFd(); + $p_archive_to_add->privCloseFd(); + + return $v_result; +} + +// ----- Go to beginning of File +@rewind($p_archive_to_add->zip_fd); + +// ----- Creates a temporay file +$v_zip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.tmp'; + +// ----- Open the temporary file in write mode +if (($v_zip_temp_fd = @fopen($v_zip_temp_name, 'wb')) == 0) +{ + $this->privCloseFd(); + $p_archive_to_add->privCloseFd(); + + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_zip_temp_name.'\' in binary write mode'); + + // ----- Return + return PclZip::errorCode(); +} + +// ----- Copy the files from the archive to the temporary file +// TBC : Here I should better append the file and go back to erase the central dir +$v_size = $v_central_dir['offset']; +while ($v_size != 0) +{ + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = fread($this->zip_fd, $v_read_size); + @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); + $v_size -= $v_read_size; +} + +// ----- Copy the files from the archive_to_add into the temporary file +$v_size = $v_central_dir_to_add['offset']; +while ($v_size != 0) +{ + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = fread($p_archive_to_add->zip_fd, $v_read_size); + @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); + $v_size -= $v_read_size; +} + +// ----- Store the offset of the central dir +$v_offset = @ftell($v_zip_temp_fd); + +// ----- Copy the block of file headers from the old archive +$v_size = $v_central_dir['size']; +while ($v_size != 0) +{ + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @fread($this->zip_fd, $v_read_size); + @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); + $v_size -= $v_read_size; +} + +// ----- Copy the block of file headers from the archive_to_add +$v_size = $v_central_dir_to_add['size']; +while ($v_size != 0) +{ + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @fread($p_archive_to_add->zip_fd, $v_read_size); + @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); + $v_size -= $v_read_size; +} + +// ----- Merge the file comments +$v_comment = $v_central_dir['comment'].' '.$v_central_dir_to_add['comment']; + +// ----- Calculate the size of the (new) central header +$v_size = @ftell($v_zip_temp_fd)-$v_offset; + +// ----- Swap the file descriptor +// Here is a trick : I swap the temporary fd with the zip fd, in order to use +// the following methods on the temporary fil and not the real archive fd +$v_swap = $this->zip_fd; +$this->zip_fd = $v_zip_temp_fd; +$v_zip_temp_fd = $v_swap; + +// ----- Create the central dir footer +if (($v_result = $this->privWriteCentralHeader($v_central_dir['entries']+$v_central_dir_to_add['entries'], $v_size, $v_offset, $v_comment)) != 1) +{ + $this->privCloseFd(); + $p_archive_to_add->privCloseFd(); + @fclose($v_zip_temp_fd); + $this->zip_fd = null; + + // ----- Reset the file list + unset($v_header_list); + + // ----- Return + return $v_result; +} + +// ----- Swap back the file descriptor +$v_swap = $this->zip_fd; +$this->zip_fd = $v_zip_temp_fd; +$v_zip_temp_fd = $v_swap; + +// ----- Close +$this->privCloseFd(); +$p_archive_to_add->privCloseFd(); + +// ----- Close the temporary file +@fclose($v_zip_temp_fd); + +// ----- Delete the zip file +// TBC : I should test the result ... +@unlink($this->zipname); + +// ----- Rename the temporary file +// TBC : I should test the result ... +//@rename($v_zip_temp_name, $this->zipname); +PclZipUtilRename($v_zip_temp_name, $this->zipname); + +// ----- Return +return $v_result; +} +// -------------------------------------------------------------------------------- + +// -------------------------------------------------------------------------------- +// Function : privDuplicate() +// Description : +// Parameters : +// Return Values : +// -------------------------------------------------------------------------------- +function privDuplicate($p_archive_filename) +{ +$v_result=1; + +// ----- Look if the $p_archive_filename exists +if (!is_file($p_archive_filename)) +{ + + // ----- Nothing to duplicate, so duplicate is a success. + $v_result = 1; + + // ----- Return + return $v_result; +} + +// ----- Open the zip file +if (($v_result=$this->privOpenFd('wb')) != 1) +{ + // ----- Return + return $v_result; +} + +// ----- Open the temporary file in write mode +if (($v_zip_temp_fd = @fopen($p_archive_filename, 'rb')) == 0) +{ + $this->privCloseFd(); + + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive file \''.$p_archive_filename.'\' in binary write mode'); + + // ----- Return + return PclZip::errorCode(); +} + +// ----- Copy the files from the archive to the temporary file +// TBC : Here I should better append the file and go back to erase the central dir +$v_size = filesize($p_archive_filename); +while ($v_size != 0) +{ + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = fread($v_zip_temp_fd, $v_read_size); + @fwrite($this->zip_fd, $v_buffer, $v_read_size); + $v_size -= $v_read_size; +} + +// ----- Close +$this->privCloseFd(); + +// ----- Close the temporary file +@fclose($v_zip_temp_fd); + +// ----- Return +return $v_result; +} +// -------------------------------------------------------------------------------- + +// -------------------------------------------------------------------------------- +// Function : privErrorLog() +// Description : +// Parameters : +// -------------------------------------------------------------------------------- +function privErrorLog($p_error_code=0, $p_error_string='') +{ +if (PCLZIP_ERROR_EXTERNAL == 1) { + PclError($p_error_code, $p_error_string); +} +else { + $this->error_code = $p_error_code; + $this->error_string = $p_error_string; +} +} +// -------------------------------------------------------------------------------- + +// -------------------------------------------------------------------------------- +// Function : privErrorReset() +// Description : +// Parameters : +// -------------------------------------------------------------------------------- +function privErrorReset() +{ +if (PCLZIP_ERROR_EXTERNAL == 1) { + PclErrorReset(); +} +else { + $this->error_code = 0; + $this->error_string = ''; +} +} +// -------------------------------------------------------------------------------- + +// -------------------------------------------------------------------------------- +// Function : privDisableMagicQuotes() +// Description : +// Parameters : +// Return Values : +// -------------------------------------------------------------------------------- +function privDisableMagicQuotes() +{ +$v_result=1; + +// ----- Look if function exists +if ((!function_exists("get_magic_quotes_runtime")) + || (!function_exists("set_magic_quotes_runtime"))) { + return $v_result; +} + +// ----- Look if already done +if ($this->magic_quotes_status != -1) { + return $v_result; +} + +// ----- Get and memorize the magic_quote value +$this->magic_quotes_status = @get_magic_quotes_runtime(); + +// ----- Disable magic_quotes +if ($this->magic_quotes_status == 1) { + @set_magic_quotes_runtime(0); +} + +// ----- Return +return $v_result; +} +// -------------------------------------------------------------------------------- + +// -------------------------------------------------------------------------------- +// Function : privSwapBackMagicQuotes() +// Description : +// Parameters : +// Return Values : +// -------------------------------------------------------------------------------- +function privSwapBackMagicQuotes() +{ +$v_result=1; + +// ----- Look if function exists +if ((!function_exists("get_magic_quotes_runtime")) + || (!function_exists("set_magic_quotes_runtime"))) { + return $v_result; +} + +// ----- Look if something to do +if ($this->magic_quotes_status != -1) { + return $v_result; +} + +// ----- Swap back magic_quotes +if ($this->magic_quotes_status == 1) { + @set_magic_quotes_runtime($this->magic_quotes_status); +} + +// ----- Return +return $v_result; +} +// -------------------------------------------------------------------------------- + +} +// End of class +// -------------------------------------------------------------------------------- + +// -------------------------------------------------------------------------------- +// Function : PclZipUtilPathReduction() +// Description : +// Parameters : +// Return Values : +// -------------------------------------------------------------------------------- +function PclZipUtilPathReduction($p_dir) +{ +$v_result = ""; + +// ----- Look for not empty path +if ($p_dir != "") { + // ----- Explode path by directory names + $v_list = explode("/", $p_dir); + + // ----- Study directories from last to first + $v_skip = 0; + for ($i=sizeof($v_list)-1; $i>=0; $i--) { + // ----- Look for current path + if ($v_list[$i] == ".") { + // ----- Ignore this directory + // Should be the first $i=0, but no check is done + } + else if ($v_list[$i] == "..") { + $v_skip++; + } + else if ($v_list[$i] == "") { + // ----- First '/' i.e. root slash + if ($i == 0) { + $v_result = "/".$v_result; + if ($v_skip > 0) { + // ----- It is an invalid path, so the path is not modified + // TBC + $v_result = $p_dir; + $v_skip = 0; } } - - // ----- Look for skip + // ----- Last '/' i.e. indicates a directory + else if ($i == (sizeof($v_list)-1)) { + $v_result = $v_list[$i]; + } + // ----- Double '/' inside the path + else { + // ----- Ignore only the double '//' in path, + // but not the first and last '/' + } + } + else { + // ----- Look for item to skip if ($v_skip > 0) { - while ($v_skip > 0) { - $v_result = '../'.$v_result; - $v_skip--; - } + $v_skip--; + } + else { + $v_result = $v_list[$i].($i!=(sizeof($v_list)-1)?"/".$v_result:""); } } - - // ----- Return - return $v_result; } - // -------------------------------------------------------------------------------- + + // ----- Look for skip + if ($v_skip > 0) { + while ($v_skip > 0) { + $v_result = '../'.$v_result; + $v_skip--; + } + } +} - // -------------------------------------------------------------------------------- - // Function : PclZipUtilPathInclusion() - // Description : - // This function indicates if the path $p_path is under the $p_dir tree. Or, - // said in an other way, if the file or sub-dir $p_path is inside the dir - // $p_dir. - // The function indicates also if the path is exactly the same as the dir. - // This function supports path with duplicated '/' like '//', but does not - // support '.' or '..' statements. - // Parameters : - // Return Values : - // 0 if $p_path is not inside directory $p_dir - // 1 if $p_path is inside directory $p_dir - // 2 if $p_path is exactly the same as $p_dir - // -------------------------------------------------------------------------------- - function PclZipUtilPathInclusion($p_dir, $p_path) +// ----- Return +return $v_result; +} +// -------------------------------------------------------------------------------- + +// -------------------------------------------------------------------------------- +// Function : PclZipUtilPathInclusion() +// Description : +// This function indicates if the path $p_path is under the $p_dir tree. Or, +// said in an other way, if the file or sub-dir $p_path is inside the dir +// $p_dir. +// The function indicates also if the path is exactly the same as the dir. +// This function supports path with duplicated '/' like '//', but does not +// support '.' or '..' statements. +// Parameters : +// Return Values : +// 0 if $p_path is not inside directory $p_dir +// 1 if $p_path is inside directory $p_dir +// 2 if $p_path is exactly the same as $p_dir +// -------------------------------------------------------------------------------- +function PclZipUtilPathInclusion($p_dir, $p_path) +{ +$v_result = 1; + +// ----- Look for path beginning by ./ +if (($p_dir == '.') + || ((strlen($p_dir) >=2) && (substr($p_dir, 0, 2) == './'))) { + $p_dir = PclZipUtilTranslateWinPath(getcwd(), false).'/'.substr($p_dir, 1); +} +if (($p_path == '.') + || ((strlen($p_path) >=2) && (substr($p_path, 0, 2) == './'))) { + $p_path = PclZipUtilTranslateWinPath(getcwd(), false).'/'.substr($p_path, 1); +} + +// ----- Explode dir and path by directory separator +$v_list_dir = explode("/", $p_dir); +$v_list_dir_size = sizeof($v_list_dir); +$v_list_path = explode("/", $p_path); +$v_list_path_size = sizeof($v_list_path); + +// ----- Study directories paths +$i = 0; +$j = 0; +while (($i < $v_list_dir_size) && ($j < $v_list_path_size) && ($v_result)) { + + // ----- Look for empty dir (path reduction) + if ($v_list_dir[$i] == '') { + $i++; + continue; + } + if ($v_list_path[$j] == '') { + $j++; + continue; + } + + // ----- Compare the items + if (($v_list_dir[$i] != $v_list_path[$j]) && ($v_list_dir[$i] != '') && ($v_list_path[$j] != '')) { + $v_result = 0; + } + + // ----- Next items + $i++; + $j++; +} + +// ----- Look if everything seems to be the same +if ($v_result) { + // ----- Skip all the empty items + while (($j < $v_list_path_size) && ($v_list_path[$j] == '')) $j++; + while (($i < $v_list_dir_size) && ($v_list_dir[$i] == '')) $i++; + + if (($i >= $v_list_dir_size) && ($j >= $v_list_path_size)) { + // ----- There are exactly the same + $v_result = 2; + } + else if ($i < $v_list_dir_size) { + // ----- The path is shorter than the dir + $v_result = 0; + } +} + +// ----- Return +return $v_result; +} +// -------------------------------------------------------------------------------- + +// -------------------------------------------------------------------------------- +// Function : PclZipUtilCopyBlock() +// Description : +// Parameters : +// $p_mode : read/write compression mode +// 0 : src & dest normal +// 1 : src gzip, dest normal +// 2 : src normal, dest gzip +// 3 : src & dest gzip +// Return Values : +// -------------------------------------------------------------------------------- +function PclZipUtilCopyBlock($p_src, $p_dest, $p_size, $p_mode=0) +{ +$v_result = 1; + +if ($p_mode==0) +{ + while ($p_size != 0) { - $v_result = 1; - - // ----- Look for path beginning by ./ - if ( ($p_dir == '.') - || ((strlen($p_dir) >=2) && (substr($p_dir, 0, 2) == './'))) { - $p_dir = PclZipUtilTranslateWinPath(getcwd(), FALSE).'/'.substr($p_dir, 1); - } - if ( ($p_path == '.') - || ((strlen($p_path) >=2) && (substr($p_path, 0, 2) == './'))) { - $p_path = PclZipUtilTranslateWinPath(getcwd(), FALSE).'/'.substr($p_path, 1); - } - - // ----- Explode dir and path by directory separator - $v_list_dir = explode("/", $p_dir); - $v_list_dir_size = sizeof($v_list_dir); - $v_list_path = explode("/", $p_path); - $v_list_path_size = sizeof($v_list_path); - - // ----- Study directories paths - $i = 0; - $j = 0; - while (($i < $v_list_dir_size) && ($j < $v_list_path_size) && ($v_result)) { - - // ----- Look for empty dir (path reduction) - if ($v_list_dir[$i] == '') { - $i++; - continue; - } - if ($v_list_path[$j] == '') { - $j++; - continue; - } - - // ----- Compare the items - if (($v_list_dir[$i] != $v_list_path[$j]) && ($v_list_dir[$i] != '') && ( $v_list_path[$j] != '')) { - $v_result = 0; - } - - // ----- Next items - $i++; - $j++; - } - - // ----- Look if everything seems to be the same - if ($v_result) { - // ----- Skip all the empty items - while (($j < $v_list_path_size) && ($v_list_path[$j] == '')) $j++; - while (($i < $v_list_dir_size) && ($v_list_dir[$i] == '')) $i++; - - if (($i >= $v_list_dir_size) && ($j >= $v_list_path_size)) { - // ----- There are exactly the same - $v_result = 2; - } - else if ($i < $v_list_dir_size) { - // ----- The path is shorter than the dir - $v_result = 0; - } - } - - // ----- Return - return $v_result; + $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @fread($p_src, $v_read_size); + @fwrite($p_dest, $v_buffer, $v_read_size); + $p_size -= $v_read_size; } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : PclZipUtilCopyBlock() - // Description : - // Parameters : - // $p_mode : read/write compression mode - // 0 : src & dest normal - // 1 : src gzip, dest normal - // 2 : src normal, dest gzip - // 3 : src & dest gzip - // Return Values : - // -------------------------------------------------------------------------------- - function PclZipUtilCopyBlock($p_src, $p_dest, $p_size, $p_mode=0) +} +else if ($p_mode==1) +{ + while ($p_size != 0) { - $v_result = 1; - - if ($p_mode==0) - { - while ($p_size != 0) - { - $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE); - $v_buffer = @fread($p_src, $v_read_size); - @fwrite($p_dest, $v_buffer, $v_read_size); - $p_size -= $v_read_size; - } - } - else if ($p_mode==1) - { - while ($p_size != 0) - { - $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE); - $v_buffer = @gzread($p_src, $v_read_size); - @fwrite($p_dest, $v_buffer, $v_read_size); - $p_size -= $v_read_size; - } - } - else if ($p_mode==2) - { - while ($p_size != 0) - { - $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE); - $v_buffer = @fread($p_src, $v_read_size); - @gzwrite($p_dest, $v_buffer, $v_read_size); - $p_size -= $v_read_size; - } - } - else if ($p_mode==3) - { - while ($p_size != 0) - { - $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE); - $v_buffer = @gzread($p_src, $v_read_size); - @gzwrite($p_dest, $v_buffer, $v_read_size); - $p_size -= $v_read_size; - } - } - - // ----- Return - return $v_result; + $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @gzread($p_src, $v_read_size); + @fwrite($p_dest, $v_buffer, $v_read_size); + $p_size -= $v_read_size; } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : PclZipUtilRename() - // Description : - // This function tries to do a simple rename() function. If it fails, it - // tries to copy the $p_src file in a new $p_dest file and then unlink the - // first one. - // Parameters : - // $p_src : Old filename - // $p_dest : New filename - // Return Values : - // 1 on success, 0 on failure. - // -------------------------------------------------------------------------------- - function PclZipUtilRename($p_src, $p_dest) +} +else if ($p_mode==2) +{ + while ($p_size != 0) { - $v_result = 1; - - // ----- Try to rename the files - if (!@rename($p_src, $p_dest)) { - - // ----- Try to copy & unlink the src - if (!@copy($p_src, $p_dest)) { - $v_result = 0; - } - else if (!@unlink($p_src)) { - $v_result = 0; - } - } - - // ----- Return - return $v_result; + $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @fread($p_src, $v_read_size); + @gzwrite($p_dest, $v_buffer, $v_read_size); + $p_size -= $v_read_size; } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : PclZipUtilOptionText() - // Description : - // Translate option value in text. Mainly for debug purpose. - // Parameters : - // $p_option : the option value. - // Return Values : - // The option text value. - // -------------------------------------------------------------------------------- - function PclZipUtilOptionText($p_option) +} +else if ($p_mode==3) +{ + while ($p_size != 0) { - - $v_list = get_defined_constants(); - for (reset($v_list); $v_key = key($v_list); next($v_list)) { - $v_prefix = substr($v_key, 0, 10); - if (( ($v_prefix == 'PCLZIP_OPT') - || ($v_prefix == 'PCLZIP_CB_') - || ($v_prefix == 'PCLZIP_ATT')) - && ($v_list[$v_key] == $p_option)) { - return $v_key; - } - } - - $v_result = 'Unknown'; - - return $v_result; + $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @gzread($p_src, $v_read_size); + @gzwrite($p_dest, $v_buffer, $v_read_size); + $p_size -= $v_read_size; } - // -------------------------------------------------------------------------------- +} - // -------------------------------------------------------------------------------- - // Function : PclZipUtilTranslateWinPath() - // Description : - // Translate windows path by replacing '\' by '/' and optionally removing - // drive letter. - // Parameters : - // $p_path : path to translate. - // $p_remove_disk_letter : true | false - // Return Values : - // The path translated. - // -------------------------------------------------------------------------------- - function PclZipUtilTranslateWinPath($p_path, $p_remove_disk_letter=true) - { - if (stristr(php_uname(), 'windows')) { - // ----- Look for potential disk letter - if (($p_remove_disk_letter) && (($v_position = strpos($p_path, ':')) != false)) { - $p_path = substr($p_path, $v_position+1); - } - // ----- Change potential windows directory separator - if ((strpos($p_path, '\\') > 0) || (substr($p_path, 0,1) == '\\')) { - $p_path = strtr($p_path, '\\', '/'); - } - } - return $p_path; +// ----- Return +return $v_result; +} +// -------------------------------------------------------------------------------- + +// -------------------------------------------------------------------------------- +// Function : PclZipUtilRename() +// Description : +// This function tries to do a simple rename() function. If it fails, it +// tries to copy the $p_src file in a new $p_dest file and then unlink the +// first one. +// Parameters : +// $p_src : Old filename +// $p_dest : New filename +// Return Values : +// 1 on success, 0 on failure. +// -------------------------------------------------------------------------------- +function PclZipUtilRename($p_src, $p_dest) +{ +$v_result = 1; + +// ----- Try to rename the files +if (!@rename($p_src, $p_dest)) { + + // ----- Try to copy & unlink the src + if (!@copy($p_src, $p_dest)) { + $v_result = 0; } - // -------------------------------------------------------------------------------- + else if (!@unlink($p_src)) { + $v_result = 0; + } +} + +// ----- Return +return $v_result; +} +// -------------------------------------------------------------------------------- + +// -------------------------------------------------------------------------------- +// Function : PclZipUtilOptionText() +// Description : +// Translate option value in text. Mainly for debug purpose. +// Parameters : +// $p_option : the option value. +// Return Values : +// The option text value. +// -------------------------------------------------------------------------------- +function PclZipUtilOptionText($p_option) +{ + +$v_list = get_defined_constants(); +for (reset($v_list); $v_key = key($v_list); next($v_list)) { + $v_prefix = substr($v_key, 0, 10); + if ((($v_prefix == 'PCLZIP_OPT') + || ($v_prefix == 'PCLZIP_CB_') + || ($v_prefix == 'PCLZIP_ATT')) + && ($v_list[$v_key] == $p_option)) { + return $v_key; + } +} + +$v_result = 'Unknown'; + +return $v_result; +} +// -------------------------------------------------------------------------------- + +// -------------------------------------------------------------------------------- +// Function : PclZipUtilTranslateWinPath() +// Description : +// Translate windows path by replacing '\' by '/' and optionally removing +// drive letter. +// Parameters : +// $p_path : path to translate. +// $p_remove_disk_letter : true | false +// Return Values : +// The path translated. +// -------------------------------------------------------------------------------- +function PclZipUtilTranslateWinPath($p_path, $p_remove_disk_letter=true) +{ +if (stristr(php_uname(), 'windows')) { + // ----- Look for potential disk letter + if (($p_remove_disk_letter) && (($v_position = strpos($p_path, ':')) != false)) { + $p_path = substr($p_path, $v_position+1); + } + // ----- Change potential windows directory separator + if ((strpos($p_path, '\\') > 0) || (substr($p_path, 0,1) == '\\')) { + $p_path = strtr($p_path, '\\', '/'); + } +} +return $p_path; +} +// -------------------------------------------------------------------------------- \ No newline at end of file diff --git a/Classes/PHPExcel/Shared/ZipStreamWrapper.php b/Classes/PHPExcel/Shared/ZipStreamWrapper.php index de31e247..254849df 100644 --- a/Classes/PHPExcel/Shared/ZipStreamWrapper.php +++ b/Classes/PHPExcel/Shared/ZipStreamWrapper.php @@ -57,9 +57,10 @@ class PHPExcel_Shared_ZipStreamWrapper { /** * Register wrapper */ - public static function register() { - @stream_wrapper_unregister("zip"); - @stream_wrapper_register("zip", __CLASS__); + public static function register() + { + @stream_wrapper_unregister('zip'); + @stream_wrapper_register('zip', __CLASS__); } /** @@ -71,7 +72,8 @@ class PHPExcel_Shared_ZipStreamWrapper { * @param string &$openedPath absolute path of the opened stream (out parameter) * @return bool true on success */ - public function stream_open($path, $mode, $options, &$opened_path) { + public function stream_open($path, $mode, $options, &$opened_path) + { // Check for mode if ($mode{0} != 'r') { throw new PHPExcel_Reader_Exception('Mode ' . $mode . ' is not supported. Only read mode is supported.'); @@ -87,7 +89,7 @@ class PHPExcel_Shared_ZipStreamWrapper { $this->_fileNameInArchive = $url['fragment']; $this->_position = 0; - $this->_data = $this->_archive->getFromName( $this->_fileNameInArchive ); + $this->_data = $this->_archive->getFromName($this->_fileNameInArchive); return true; } @@ -97,7 +99,8 @@ class PHPExcel_Shared_ZipStreamWrapper { * * @return boolean */ - public function statName() { + public function statName() + { return $this->_fileNameInArchive; } @@ -106,8 +109,9 @@ class PHPExcel_Shared_ZipStreamWrapper { * * @return boolean */ - public function url_stat() { - return $this->statName( $this->_fileNameInArchive ); + public function url_stat() + { + return $this->statName($this->_fileNameInArchive); } /** @@ -115,8 +119,9 @@ class PHPExcel_Shared_ZipStreamWrapper { * * @return boolean */ - public function stream_stat() { - return $this->_archive->statName( $this->_fileNameInArchive ); + public function stream_stat() + { + return $this->_archive->statName($this->_fileNameInArchive); } /** @@ -125,7 +130,8 @@ class PHPExcel_Shared_ZipStreamWrapper { * @param int $count maximum number of bytes to read * @return string */ - function stream_read($count) { + function stream_read($count) + { $ret = substr($this->_data, $this->_position, $count); $this->_position += strlen($ret); return $ret; @@ -137,7 +143,8 @@ class PHPExcel_Shared_ZipStreamWrapper { * * @return int */ - public function stream_tell() { + public function stream_tell() + { return $this->_position; } @@ -146,7 +153,8 @@ class PHPExcel_Shared_ZipStreamWrapper { * * @return bool */ - public function stream_eof() { + public function stream_eof() + { return $this->_position >= strlen($this->_data); } @@ -157,7 +165,8 @@ class PHPExcel_Shared_ZipStreamWrapper { * @param int $whence SEEK_SET, SEEK_CUR or SEEK_END * @return bool */ - public function stream_seek($offset, $whence) { + public function stream_seek($offset, $whence) + { switch ($whence) { case SEEK_SET: if ($offset < strlen($this->_data) && $offset >= 0) { @@ -167,7 +176,6 @@ class PHPExcel_Shared_ZipStreamWrapper { return false; } break; - case SEEK_CUR: if ($offset >= 0) { $this->_position += $offset; @@ -176,7 +184,6 @@ class PHPExcel_Shared_ZipStreamWrapper { return false; } break; - case SEEK_END: if (strlen($this->_data) + $offset >= 0) { $this->_position = strlen($this->_data) + $offset; @@ -185,7 +192,6 @@ class PHPExcel_Shared_ZipStreamWrapper { return false; } break; - default: return false; } diff --git a/Classes/PHPExcel/Style.php b/Classes/PHPExcel/Style.php index 33ad3caa..20f7236e 100644 --- a/Classes/PHPExcel/Style.php +++ b/Classes/PHPExcel/Style.php @@ -210,7 +210,6 @@ class PHPExcel_Style extends PHPExcel_Style_Supervisor implements PHPExcel_IComp { if (is_array($pStyles)) { if ($this->isSupervisor) { - $pRange = $this->getSelectedCells(); // Uppercase coordinate @@ -322,7 +321,7 @@ class PHPExcel_Style extends PHPExcel_Style_Supervisor implements PHPExcel_IComp unset($regionStyles['borders']['inside']); // what are the inner edges of the region when looking at the selection - $innerEdges = array_diff( array('top', 'right', 'bottom', 'left'), $edges ); + $innerEdges = array_diff(array('top', 'right', 'bottom', 'left'), $edges); // inner edges that are not touching the region should take the 'inside' border properties if they have been set foreach ($innerEdges as $innerEdge) { diff --git a/Classes/PHPExcel/Writer/Excel2007/DocProps.php b/Classes/PHPExcel/Writer/Excel2007/DocProps.php index 4573cc02..6ef50d3b 100644 --- a/Classes/PHPExcel/Writer/Excel2007/DocProps.php +++ b/Classes/PHPExcel/Writer/Excel2007/DocProps.php @@ -240,21 +240,21 @@ class PHPExcel_Writer_Excel2007_DocProps extends PHPExcel_Writer_Excel2007_Write $objWriter->writeAttribute('name', $customProperty); switch ($propertyType) { - case 'i' : + case 'i': $objWriter->writeElement('vt:i4', $propertyValue); break; - case 'f' : + case 'f': $objWriter->writeElement('vt:r8', $propertyValue); break; - case 'b' : + case 'b': $objWriter->writeElement('vt:bool', ($propertyValue) ? 'true' : 'false'); break; - case 'd' : + case 'd': $objWriter->startElement('vt:filetime'); $objWriter->writeRawData(date(DATE_W3C, $propertyValue)); $objWriter->endElement(); break; - default : + default: $objWriter->writeElement('vt:lpwstr', $propertyValue); break; } diff --git a/Classes/PHPExcel/Writer/Excel2007/Drawing.php b/Classes/PHPExcel/Writer/Excel2007/Drawing.php index 3d44ed35..794d6a4b 100644 --- a/Classes/PHPExcel/Writer/Excel2007/Drawing.php +++ b/Classes/PHPExcel/Writer/Excel2007/Drawing.php @@ -44,7 +44,7 @@ class PHPExcel_Writer_Excel2007_Drawing extends PHPExcel_Writer_Excel2007_Writer * @return string XML Output * @throws PHPExcel_Writer_Exception */ - public function writeDrawings(PHPExcel_Worksheet $pWorksheet = null, &$chartRef, $includeCharts = FALSE) + public function writeDrawings(PHPExcel_Worksheet $pWorksheet = null, &$chartRef, $includeCharts = false) { // Create XML writer $objWriter = null; @@ -62,26 +62,25 @@ class PHPExcel_Writer_Excel2007_Drawing extends PHPExcel_Writer_Excel2007_Writer $objWriter->writeAttribute('xmlns:xdr', 'http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing'); $objWriter->writeAttribute('xmlns:a', 'http://schemas.openxmlformats.org/drawingml/2006/main'); - // Loop through images and write drawings - $i = 1; - $iterator = $pWorksheet->getDrawingCollection()->getIterator(); - while ($iterator->valid()) { - $this->_writeDrawing($objWriter, $iterator->current(), $i); + // Loop through images and write drawings + $i = 1; + $iterator = $pWorksheet->getDrawingCollection()->getIterator(); + while ($iterator->valid()) { + $this->_writeDrawing($objWriter, $iterator->current(), $i); - $iterator->next(); - ++$i; - } + $iterator->next(); + ++$i; + } - if ($includeCharts) { - $chartCount = $pWorksheet->getChartCount(); - // Loop through charts and write the chart position - if ($chartCount > 0) { - for ($c = 0; $c < $chartCount; ++$c) { - $this->_writeChart($objWriter, $pWorksheet->getChartByIndex($c), $c+$i); - } + if ($includeCharts) { + $chartCount = $pWorksheet->getChartCount(); + // Loop through charts and write the chart position + if ($chartCount > 0) { + for ($c = 0; $c < $chartCount; ++$c) { + $this->_writeChart($objWriter, $pWorksheet->getChartByIndex($c), $c+$i); } } - + } $objWriter->endElement(); @@ -174,81 +173,81 @@ class PHPExcel_Writer_Excel2007_Drawing extends PHPExcel_Writer_Excel2007_Writer if ($pRelationId >= 0) { // xdr:oneCellAnchor $objWriter->startElement('xdr:oneCellAnchor'); - // Image location - $aCoordinates = PHPExcel_Cell::coordinateFromString($pDrawing->getCoordinates()); - $aCoordinates[0] = PHPExcel_Cell::columnIndexFromString($aCoordinates[0]); + // Image location + $aCoordinates = PHPExcel_Cell::coordinateFromString($pDrawing->getCoordinates()); + $aCoordinates[0] = PHPExcel_Cell::columnIndexFromString($aCoordinates[0]); - // xdr:from - $objWriter->startElement('xdr:from'); - $objWriter->writeElement('xdr:col', $aCoordinates[0] - 1); - $objWriter->writeElement('xdr:colOff', PHPExcel_Shared_Drawing::pixelsToEMU($pDrawing->getOffsetX())); - $objWriter->writeElement('xdr:row', $aCoordinates[1] - 1); - $objWriter->writeElement('xdr:rowOff', PHPExcel_Shared_Drawing::pixelsToEMU($pDrawing->getOffsetY())); - $objWriter->endElement(); + // xdr:from + $objWriter->startElement('xdr:from'); + $objWriter->writeElement('xdr:col', $aCoordinates[0] - 1); + $objWriter->writeElement('xdr:colOff', PHPExcel_Shared_Drawing::pixelsToEMU($pDrawing->getOffsetX())); + $objWriter->writeElement('xdr:row', $aCoordinates[1] - 1); + $objWriter->writeElement('xdr:rowOff', PHPExcel_Shared_Drawing::pixelsToEMU($pDrawing->getOffsetY())); + $objWriter->endElement(); - // xdr:ext - $objWriter->startElement('xdr:ext'); - $objWriter->writeAttribute('cx', PHPExcel_Shared_Drawing::pixelsToEMU($pDrawing->getWidth())); - $objWriter->writeAttribute('cy', PHPExcel_Shared_Drawing::pixelsToEMU($pDrawing->getHeight())); - $objWriter->endElement(); + // xdr:ext + $objWriter->startElement('xdr:ext'); + $objWriter->writeAttribute('cx', PHPExcel_Shared_Drawing::pixelsToEMU($pDrawing->getWidth())); + $objWriter->writeAttribute('cy', PHPExcel_Shared_Drawing::pixelsToEMU($pDrawing->getHeight())); + $objWriter->endElement(); - // xdr:pic - $objWriter->startElement('xdr:pic'); + // xdr:pic + $objWriter->startElement('xdr:pic'); - // xdr:nvPicPr - $objWriter->startElement('xdr:nvPicPr'); + // xdr:nvPicPr + $objWriter->startElement('xdr:nvPicPr'); - // xdr:cNvPr - $objWriter->startElement('xdr:cNvPr'); - $objWriter->writeAttribute('id', $pRelationId); - $objWriter->writeAttribute('name', $pDrawing->getName()); - $objWriter->writeAttribute('descr', $pDrawing->getDescription()); - $objWriter->endElement(); + // xdr:cNvPr + $objWriter->startElement('xdr:cNvPr'); + $objWriter->writeAttribute('id', $pRelationId); + $objWriter->writeAttribute('name', $pDrawing->getName()); + $objWriter->writeAttribute('descr', $pDrawing->getDescription()); + $objWriter->endElement(); - // xdr:cNvPicPr - $objWriter->startElement('xdr:cNvPicPr'); + // xdr:cNvPicPr + $objWriter->startElement('xdr:cNvPicPr'); - // a:picLocks - $objWriter->startElement('a:picLocks'); - $objWriter->writeAttribute('noChangeAspect', '1'); - $objWriter->endElement(); + // a:picLocks + $objWriter->startElement('a:picLocks'); + $objWriter->writeAttribute('noChangeAspect', '1'); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); - // xdr:blipFill - $objWriter->startElement('xdr:blipFill'); + // xdr:blipFill + $objWriter->startElement('xdr:blipFill'); - // a:blip - $objWriter->startElement('a:blip'); - $objWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'); - $objWriter->writeAttribute('r:embed', 'rId' . $pRelationId); - $objWriter->endElement(); + // a:blip + $objWriter->startElement('a:blip'); + $objWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'); + $objWriter->writeAttribute('r:embed', 'rId' . $pRelationId); + $objWriter->endElement(); - // a:stretch - $objWriter->startElement('a:stretch'); - $objWriter->writeElement('a:fillRect', null); - $objWriter->endElement(); + // a:stretch + $objWriter->startElement('a:stretch'); + $objWriter->writeElement('a:fillRect', null); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); - // xdr:spPr - $objWriter->startElement('xdr:spPr'); + // xdr:spPr + $objWriter->startElement('xdr:spPr'); - // a:xfrm - $objWriter->startElement('a:xfrm'); - $objWriter->writeAttribute('rot', PHPExcel_Shared_Drawing::degreesToAngle($pDrawing->getRotation())); - $objWriter->endElement(); + // a:xfrm + $objWriter->startElement('a:xfrm'); + $objWriter->writeAttribute('rot', PHPExcel_Shared_Drawing::degreesToAngle($pDrawing->getRotation())); + $objWriter->endElement(); - // a:prstGeom - $objWriter->startElement('a:prstGeom'); - $objWriter->writeAttribute('prst', 'rect'); + // a:prstGeom + $objWriter->startElement('a:prstGeom'); + $objWriter->writeAttribute('prst', 'rect'); - // a:avLst - $objWriter->writeElement('a:avLst', null); + // a:avLst + $objWriter->writeElement('a:avLst', null); - $objWriter->endElement(); + $objWriter->endElement(); // // a:solidFill // $objWriter->startElement('a:solidFill'); @@ -268,110 +267,110 @@ class PHPExcel_Writer_Excel2007_Drawing extends PHPExcel_Writer_Excel2007_Writer // $objWriter->endElement(); /* - // a:ln - $objWriter->startElement('a:ln'); - $objWriter->writeAttribute('w', '88900'); - $objWriter->writeAttribute('cap', 'sq'); + // a:ln + $objWriter->startElement('a:ln'); + $objWriter->writeAttribute('w', '88900'); + $objWriter->writeAttribute('cap', 'sq'); - // a:solidFill - $objWriter->startElement('a:solidFill'); + // a:solidFill + $objWriter->startElement('a:solidFill'); - // a:srgbClr - $objWriter->startElement('a:srgbClr'); - $objWriter->writeAttribute('val', 'FFFFFF'); - $objWriter->endElement(); - - $objWriter->endElement(); - - // a:miter - $objWriter->startElement('a:miter'); - $objWriter->writeAttribute('lim', '800000'); - $objWriter->endElement(); - - $objWriter->endElement(); -*/ - - if ($pDrawing->getShadow()->getVisible()) { - // a:effectLst - $objWriter->startElement('a:effectLst'); - - // a:outerShdw - $objWriter->startElement('a:outerShdw'); - $objWriter->writeAttribute('blurRad', PHPExcel_Shared_Drawing::pixelsToEMU($pDrawing->getShadow()->getBlurRadius())); - $objWriter->writeAttribute('dist', PHPExcel_Shared_Drawing::pixelsToEMU($pDrawing->getShadow()->getDistance())); - $objWriter->writeAttribute('dir', PHPExcel_Shared_Drawing::degreesToAngle($pDrawing->getShadow()->getDirection())); - $objWriter->writeAttribute('algn', $pDrawing->getShadow()->getAlignment()); - $objWriter->writeAttribute('rotWithShape', '0'); - - // a:srgbClr - $objWriter->startElement('a:srgbClr'); - $objWriter->writeAttribute('val', $pDrawing->getShadow()->getColor()->getRGB()); - - // a:alpha - $objWriter->startElement('a:alpha'); - $objWriter->writeAttribute('val', $pDrawing->getShadow()->getAlpha() * 1000); - $objWriter->endElement(); - - $objWriter->endElement(); - - $objWriter->endElement(); - - $objWriter->endElement(); - } -/* - - // a:scene3d - $objWriter->startElement('a:scene3d'); - - // a:camera - $objWriter->startElement('a:camera'); - $objWriter->writeAttribute('prst', 'orthographicFront'); - $objWriter->endElement(); - - // a:lightRig - $objWriter->startElement('a:lightRig'); - $objWriter->writeAttribute('rig', 'twoPt'); - $objWriter->writeAttribute('dir', 't'); - - // a:rot - $objWriter->startElement('a:rot'); - $objWriter->writeAttribute('lat', '0'); - $objWriter->writeAttribute('lon', '0'); - $objWriter->writeAttribute('rev', '0'); - $objWriter->endElement(); - - $objWriter->endElement(); - - $objWriter->endElement(); -*/ -/* - // a:sp3d - $objWriter->startElement('a:sp3d'); - - // a:bevelT - $objWriter->startElement('a:bevelT'); - $objWriter->writeAttribute('w', '25400'); - $objWriter->writeAttribute('h', '19050'); - $objWriter->endElement(); - - // a:contourClr - $objWriter->startElement('a:contourClr'); - - // a:srgbClr - $objWriter->startElement('a:srgbClr'); - $objWriter->writeAttribute('val', 'FFFFFF'); - $objWriter->endElement(); - - $objWriter->endElement(); - - $objWriter->endElement(); -*/ + // a:srgbClr + $objWriter->startElement('a:srgbClr'); + $objWriter->writeAttribute('val', 'FFFFFF'); $objWriter->endElement(); $objWriter->endElement(); - // xdr:clientData - $objWriter->writeElement('xdr:clientData', null); + // a:miter + $objWriter->startElement('a:miter'); + $objWriter->writeAttribute('lim', '800000'); + $objWriter->endElement(); + + $objWriter->endElement(); +*/ + + if ($pDrawing->getShadow()->getVisible()) { + // a:effectLst + $objWriter->startElement('a:effectLst'); + + // a:outerShdw + $objWriter->startElement('a:outerShdw'); + $objWriter->writeAttribute('blurRad', PHPExcel_Shared_Drawing::pixelsToEMU($pDrawing->getShadow()->getBlurRadius())); + $objWriter->writeAttribute('dist', PHPExcel_Shared_Drawing::pixelsToEMU($pDrawing->getShadow()->getDistance())); + $objWriter->writeAttribute('dir', PHPExcel_Shared_Drawing::degreesToAngle($pDrawing->getShadow()->getDirection())); + $objWriter->writeAttribute('algn', $pDrawing->getShadow()->getAlignment()); + $objWriter->writeAttribute('rotWithShape', '0'); + + // a:srgbClr + $objWriter->startElement('a:srgbClr'); + $objWriter->writeAttribute('val', $pDrawing->getShadow()->getColor()->getRGB()); + + // a:alpha + $objWriter->startElement('a:alpha'); + $objWriter->writeAttribute('val', $pDrawing->getShadow()->getAlpha() * 1000); + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + } +/* + + // a:scene3d + $objWriter->startElement('a:scene3d'); + + // a:camera + $objWriter->startElement('a:camera'); + $objWriter->writeAttribute('prst', 'orthographicFront'); + $objWriter->endElement(); + + // a:lightRig + $objWriter->startElement('a:lightRig'); + $objWriter->writeAttribute('rig', 'twoPt'); + $objWriter->writeAttribute('dir', 't'); + + // a:rot + $objWriter->startElement('a:rot'); + $objWriter->writeAttribute('lat', '0'); + $objWriter->writeAttribute('lon', '0'); + $objWriter->writeAttribute('rev', '0'); + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); +*/ +/* + // a:sp3d + $objWriter->startElement('a:sp3d'); + + // a:bevelT + $objWriter->startElement('a:bevelT'); + $objWriter->writeAttribute('w', '25400'); + $objWriter->writeAttribute('h', '19050'); + $objWriter->endElement(); + + // a:contourClr + $objWriter->startElement('a:contourClr'); + + // a:srgbClr + $objWriter->startElement('a:srgbClr'); + $objWriter->writeAttribute('val', 'FFFFFF'); + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); +*/ + $objWriter->endElement(); + + $objWriter->endElement(); + + // xdr:clientData + $objWriter->writeElement('xdr:clientData', null); $objWriter->endElement(); } else { @@ -399,8 +398,8 @@ class PHPExcel_Writer_Excel2007_Drawing extends PHPExcel_Writer_Excel2007_Writer // XML header $objWriter->startDocument('1.0', 'UTF-8', 'yes'); - // Header/footer images - $images = $pWorksheet->getHeaderFooter()->getImages(); + // Header/footer images + $images = $pWorksheet->getHeaderFooter()->getImages(); // xml $objWriter->startElement('xml'); @@ -408,117 +407,117 @@ class PHPExcel_Writer_Excel2007_Drawing extends PHPExcel_Writer_Excel2007_Writer $objWriter->writeAttribute('xmlns:o', 'urn:schemas-microsoft-com:office:office'); $objWriter->writeAttribute('xmlns:x', 'urn:schemas-microsoft-com:office:excel'); - // o:shapelayout - $objWriter->startElement('o:shapelayout'); - $objWriter->writeAttribute('v:ext', 'edit'); + // o:shapelayout + $objWriter->startElement('o:shapelayout'); + $objWriter->writeAttribute('v:ext', 'edit'); - // o:idmap - $objWriter->startElement('o:idmap'); - $objWriter->writeAttribute('v:ext', 'edit'); - $objWriter->writeAttribute('data', '1'); - $objWriter->endElement(); + // o:idmap + $objWriter->startElement('o:idmap'); + $objWriter->writeAttribute('v:ext', 'edit'); + $objWriter->writeAttribute('data', '1'); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); - // v:shapetype - $objWriter->startElement('v:shapetype'); - $objWriter->writeAttribute('id', '_x0000_t75'); - $objWriter->writeAttribute('coordsize', '21600,21600'); - $objWriter->writeAttribute('o:spt', '75'); - $objWriter->writeAttribute('o:preferrelative', 't'); - $objWriter->writeAttribute('path', 'm@4@5l@4@11@9@11@9@5xe'); - $objWriter->writeAttribute('filled', 'f'); - $objWriter->writeAttribute('stroked', 'f'); + // v:shapetype + $objWriter->startElement('v:shapetype'); + $objWriter->writeAttribute('id', '_x0000_t75'); + $objWriter->writeAttribute('coordsize', '21600,21600'); + $objWriter->writeAttribute('o:spt', '75'); + $objWriter->writeAttribute('o:preferrelative', 't'); + $objWriter->writeAttribute('path', 'm@4@5l@4@11@9@11@9@5xe'); + $objWriter->writeAttribute('filled', 'f'); + $objWriter->writeAttribute('stroked', 'f'); - // v:stroke - $objWriter->startElement('v:stroke'); - $objWriter->writeAttribute('joinstyle', 'miter'); - $objWriter->endElement(); + // v:stroke + $objWriter->startElement('v:stroke'); + $objWriter->writeAttribute('joinstyle', 'miter'); + $objWriter->endElement(); - // v:formulas - $objWriter->startElement('v:formulas'); + // v:formulas + $objWriter->startElement('v:formulas'); - // v:f - $objWriter->startElement('v:f'); - $objWriter->writeAttribute('eqn', 'if lineDrawn pixelLineWidth 0'); - $objWriter->endElement(); + // v:f + $objWriter->startElement('v:f'); + $objWriter->writeAttribute('eqn', 'if lineDrawn pixelLineWidth 0'); + $objWriter->endElement(); - // v:f - $objWriter->startElement('v:f'); - $objWriter->writeAttribute('eqn', 'sum @0 1 0'); - $objWriter->endElement(); + // v:f + $objWriter->startElement('v:f'); + $objWriter->writeAttribute('eqn', 'sum @0 1 0'); + $objWriter->endElement(); - // v:f - $objWriter->startElement('v:f'); - $objWriter->writeAttribute('eqn', 'sum 0 0 @1'); - $objWriter->endElement(); + // v:f + $objWriter->startElement('v:f'); + $objWriter->writeAttribute('eqn', 'sum 0 0 @1'); + $objWriter->endElement(); - // v:f - $objWriter->startElement('v:f'); - $objWriter->writeAttribute('eqn', 'prod @2 1 2'); - $objWriter->endElement(); + // v:f + $objWriter->startElement('v:f'); + $objWriter->writeAttribute('eqn', 'prod @2 1 2'); + $objWriter->endElement(); - // v:f - $objWriter->startElement('v:f'); - $objWriter->writeAttribute('eqn', 'prod @3 21600 pixelWidth'); - $objWriter->endElement(); + // v:f + $objWriter->startElement('v:f'); + $objWriter->writeAttribute('eqn', 'prod @3 21600 pixelWidth'); + $objWriter->endElement(); - // v:f - $objWriter->startElement('v:f'); - $objWriter->writeAttribute('eqn', 'prod @3 21600 pixelHeight'); - $objWriter->endElement(); + // v:f + $objWriter->startElement('v:f'); + $objWriter->writeAttribute('eqn', 'prod @3 21600 pixelHeight'); + $objWriter->endElement(); - // v:f - $objWriter->startElement('v:f'); - $objWriter->writeAttribute('eqn', 'sum @0 0 1'); - $objWriter->endElement(); + // v:f + $objWriter->startElement('v:f'); + $objWriter->writeAttribute('eqn', 'sum @0 0 1'); + $objWriter->endElement(); - // v:f - $objWriter->startElement('v:f'); - $objWriter->writeAttribute('eqn', 'prod @6 1 2'); - $objWriter->endElement(); + // v:f + $objWriter->startElement('v:f'); + $objWriter->writeAttribute('eqn', 'prod @6 1 2'); + $objWriter->endElement(); - // v:f - $objWriter->startElement('v:f'); - $objWriter->writeAttribute('eqn', 'prod @7 21600 pixelWidth'); - $objWriter->endElement(); + // v:f + $objWriter->startElement('v:f'); + $objWriter->writeAttribute('eqn', 'prod @7 21600 pixelWidth'); + $objWriter->endElement(); - // v:f - $objWriter->startElement('v:f'); - $objWriter->writeAttribute('eqn', 'sum @8 21600 0'); - $objWriter->endElement(); + // v:f + $objWriter->startElement('v:f'); + $objWriter->writeAttribute('eqn', 'sum @8 21600 0'); + $objWriter->endElement(); - // v:f - $objWriter->startElement('v:f'); - $objWriter->writeAttribute('eqn', 'prod @7 21600 pixelHeight'); - $objWriter->endElement(); + // v:f + $objWriter->startElement('v:f'); + $objWriter->writeAttribute('eqn', 'prod @7 21600 pixelHeight'); + $objWriter->endElement(); - // v:f - $objWriter->startElement('v:f'); - $objWriter->writeAttribute('eqn', 'sum @10 21600 0'); - $objWriter->endElement(); + // v:f + $objWriter->startElement('v:f'); + $objWriter->writeAttribute('eqn', 'sum @10 21600 0'); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); - // v:path - $objWriter->startElement('v:path'); - $objWriter->writeAttribute('o:extrusionok', 'f'); - $objWriter->writeAttribute('gradientshapeok', 't'); - $objWriter->writeAttribute('o:connecttype', 'rect'); - $objWriter->endElement(); + // v:path + $objWriter->startElement('v:path'); + $objWriter->writeAttribute('o:extrusionok', 'f'); + $objWriter->writeAttribute('gradientshapeok', 't'); + $objWriter->writeAttribute('o:connecttype', 'rect'); + $objWriter->endElement(); - // o:lock - $objWriter->startElement('o:lock'); - $objWriter->writeAttribute('v:ext', 'edit'); - $objWriter->writeAttribute('aspectratio', 't'); - $objWriter->endElement(); + // o:lock + $objWriter->startElement('o:lock'); + $objWriter->writeAttribute('v:ext', 'edit'); + $objWriter->writeAttribute('aspectratio', 't'); + $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); - // Loop through images - foreach ($images as $key => $value) { - $this->_writeVMLHeaderFooterImage($objWriter, $key, $value); - } + // Loop through images + foreach ($images as $key => $value) { + $this->_writeVMLHeaderFooterImage($objWriter, $key, $value); + } $objWriter->endElement(); @@ -548,22 +547,22 @@ class PHPExcel_Writer_Excel2007_Drawing extends PHPExcel_Writer_Excel2007_Writer // v:shape $objWriter->startElement('v:shape'); - $objWriter->writeAttribute('id', $pReference); - $objWriter->writeAttribute('o:spid', '_x0000_s' . $id); - $objWriter->writeAttribute('type', '#_x0000_t75'); - $objWriter->writeAttribute('style', "position:absolute;margin-left:{$marginLeft}px;margin-top:{$marginTop}px;width:{$width}px;height:{$height}px;z-index:1"); + $objWriter->writeAttribute('id', $pReference); + $objWriter->writeAttribute('o:spid', '_x0000_s' . $id); + $objWriter->writeAttribute('type', '#_x0000_t75'); + $objWriter->writeAttribute('style', "position:absolute;margin-left:{$marginLeft}px;margin-top:{$marginTop}px;width:{$width}px;height:{$height}px;z-index:1"); - // v:imagedata - $objWriter->startElement('v:imagedata'); - $objWriter->writeAttribute('o:relid', 'rId' . $pReference); - $objWriter->writeAttribute('o:title', $pImage->getName()); - $objWriter->endElement(); + // v:imagedata + $objWriter->startElement('v:imagedata'); + $objWriter->writeAttribute('o:relid', 'rId' . $pReference); + $objWriter->writeAttribute('o:title', $pImage->getName()); + $objWriter->endElement(); - // o:lock - $objWriter->startElement('o:lock'); - $objWriter->writeAttribute('v:ext', 'edit'); - $objWriter->writeAttribute('rotation', 't'); - $objWriter->endElement(); + // o:lock + $objWriter->startElement('o:lock'); + $objWriter->writeAttribute('v:ext', 'edit'); + $objWriter->writeAttribute('rotation', 't'); + $objWriter->endElement(); $objWriter->endElement(); } diff --git a/Classes/PHPExcel/Writer/Excel2007/StringTable.php b/Classes/PHPExcel/Writer/Excel2007/StringTable.php index f2e8a12e..4a28f13e 100644 --- a/Classes/PHPExcel/Writer/Excel2007/StringTable.php +++ b/Classes/PHPExcel/Writer/Excel2007/StringTable.php @@ -259,10 +259,10 @@ class PHPExcel_Writer_Excel2007_StringTable extends PHPExcel_Writer_Excel2007_Wr // Underline $underlineType = $element->getFont()->getUnderline(); switch ($underlineType) { - case 'single' : + case 'single': $underlineType = 'sng'; break; - case 'double' : + case 'double': $underlineType = 'dbl'; break; } @@ -304,7 +304,8 @@ class PHPExcel_Writer_Excel2007_StringTable extends PHPExcel_Writer_Excel2007_Wr * @param array $stringTable Stringtable * @return array */ - public function flipStringTable($stringTable = array()) { + public function flipStringTable($stringTable = array()) + { // Return value $returnValue = array(); diff --git a/Classes/PHPExcel/Writer/Excel2007/Worksheet.php b/Classes/PHPExcel/Writer/Excel2007/Worksheet.php index b1e7c1bd..176e44b1 100644 --- a/Classes/PHPExcel/Writer/Excel2007/Worksheet.php +++ b/Classes/PHPExcel/Writer/Excel2007/Worksheet.php @@ -210,102 +210,103 @@ class PHPExcel_Writer_Excel2007_Worksheet extends PHPExcel_Writer_Excel2007_Writ // sheetViews $objWriter->startElement('sheetViews'); - // Sheet selected? - $sheetSelected = false; - if ($this->getParentWriter()->getPHPExcel()->getIndex($pSheet) == $this->getParentWriter()->getPHPExcel()->getActiveSheetIndex()) { - $sheetSelected = true; + // Sheet selected? + $sheetSelected = false; + if ($this->getParentWriter()->getPHPExcel()->getIndex($pSheet) == $this->getParentWriter()->getPHPExcel()->getActiveSheetIndex()) { + $sheetSelected = true; + } + + // sheetView + $objWriter->startElement('sheetView'); + $objWriter->writeAttribute('tabSelected', $sheetSelected ? '1' : '0'); + $objWriter->writeAttribute('workbookViewId', '0'); + + // Zoom scales + if ($pSheet->getSheetView()->getZoomScale() != 100) { + $objWriter->writeAttribute('zoomScale', $pSheet->getSheetView()->getZoomScale()); + } + if ($pSheet->getSheetView()->getZoomScaleNormal() != 100) { + $objWriter->writeAttribute('zoomScaleNormal', $pSheet->getSheetView()->getZoomScaleNormal()); + } + + // View Layout Type + if ($pSheet->getSheetView()->getView() !== PHPExcel_Worksheet_SheetView::SHEETVIEW_NORMAL) { + $objWriter->writeAttribute('view', $pSheet->getSheetView()->getView()); + } + + // Gridlines + if ($pSheet->getShowGridlines()) { + $objWriter->writeAttribute('showGridLines', 'true'); + } else { + $objWriter->writeAttribute('showGridLines', 'false'); + } + + // Row and column headers + if ($pSheet->getShowRowColHeaders()) { + $objWriter->writeAttribute('showRowColHeaders', '1'); + } else { + $objWriter->writeAttribute('showRowColHeaders', '0'); + } + + // Right-to-left + if ($pSheet->getRightToLeft()) { + $objWriter->writeAttribute('rightToLeft', 'true'); + } + + $activeCell = $pSheet->getActiveCell(); + + // Pane + $pane = ''; + $topLeftCell = $pSheet->getFreezePane(); + if (($topLeftCell != '') && ($topLeftCell != 'A1')) { + $activeCell = $topLeftCell; + // Calculate freeze coordinates + $xSplit = $ySplit = 0; + + list($xSplit, $ySplit) = PHPExcel_Cell::coordinateFromString($topLeftCell); + $xSplit = PHPExcel_Cell::columnIndexFromString($xSplit); + + // pane + $pane = 'topRight'; + $objWriter->startElement('pane'); + if ($xSplit > 1) { + $objWriter->writeAttribute('xSplit', $xSplit - 1); } - - // sheetView - $objWriter->startElement('sheetView'); - $objWriter->writeAttribute('tabSelected', $sheetSelected ? '1' : '0'); - $objWriter->writeAttribute('workbookViewId', '0'); - - // Zoom scales - if ($pSheet->getSheetView()->getZoomScale() != 100) { - $objWriter->writeAttribute('zoomScale', $pSheet->getSheetView()->getZoomScale()); - } - if ($pSheet->getSheetView()->getZoomScaleNormal() != 100) { - $objWriter->writeAttribute('zoomScaleNormal', $pSheet->getSheetView()->getZoomScaleNormal()); - } - - // View Layout Type - if ($pSheet->getSheetView()->getView() !== PHPExcel_Worksheet_SheetView::SHEETVIEW_NORMAL) { - $objWriter->writeAttribute('view', $pSheet->getSheetView()->getView()); - } - - // Gridlines - if ($pSheet->getShowGridlines()) { - $objWriter->writeAttribute('showGridLines', 'true'); - } else { - $objWriter->writeAttribute('showGridLines', 'false'); - } - - // Row and column headers - if ($pSheet->getShowRowColHeaders()) { - $objWriter->writeAttribute('showRowColHeaders', '1'); - } else { - $objWriter->writeAttribute('showRowColHeaders', '0'); - } - - // Right-to-left - if ($pSheet->getRightToLeft()) { - $objWriter->writeAttribute('rightToLeft', 'true'); - } - - $activeCell = $pSheet->getActiveCell(); - - // Pane - $pane = ''; - $topLeftCell = $pSheet->getFreezePane(); - if (($topLeftCell != '') && ($topLeftCell != 'A1')) { - $activeCell = $topLeftCell; - // Calculate freeze coordinates - $xSplit = $ySplit = 0; - - list($xSplit, $ySplit) = PHPExcel_Cell::coordinateFromString($topLeftCell); - $xSplit = PHPExcel_Cell::columnIndexFromString($xSplit); - - // pane - $pane = 'topRight'; - $objWriter->startElement('pane'); - if ($xSplit > 1) - $objWriter->writeAttribute('xSplit', $xSplit - 1); - if ($ySplit > 1) { - $objWriter->writeAttribute('ySplit', $ySplit - 1); - $pane = ($xSplit > 1) ? 'bottomRight' : 'bottomLeft'; - } - $objWriter->writeAttribute('topLeftCell', $topLeftCell); - $objWriter->writeAttribute('activePane', $pane); - $objWriter->writeAttribute('state', 'frozen'); - $objWriter->endElement(); - - if (($xSplit > 1) && ($ySplit > 1)) { - // Write additional selections if more than two panes (ie both an X and a Y split) - $objWriter->startElement('selection'); - $objWriter->writeAttribute('pane', 'topRight'); - $objWriter->endElement(); - $objWriter->startElement('selection'); - $objWriter->writeAttribute('pane', 'bottomLeft'); - $objWriter->endElement(); - } - } - - // Selection -// if ($pane != '') { - // Only need to write selection element if we have a split pane - // We cheat a little by over-riding the active cell selection, setting it to the split cell - $objWriter->startElement('selection'); - if ($pane != '') { - $objWriter->writeAttribute('pane', $pane); - } - $objWriter->writeAttribute('activeCell', $activeCell); - $objWriter->writeAttribute('sqref', $activeCell); - $objWriter->endElement(); -// } - + if ($ySplit > 1) { + $objWriter->writeAttribute('ySplit', $ySplit - 1); + $pane = ($xSplit > 1) ? 'bottomRight' : 'bottomLeft'; + } + $objWriter->writeAttribute('topLeftCell', $topLeftCell); + $objWriter->writeAttribute('activePane', $pane); + $objWriter->writeAttribute('state', 'frozen'); $objWriter->endElement(); + if (($xSplit > 1) && ($ySplit > 1)) { + // Write additional selections if more than two panes (ie both an X and a Y split) + $objWriter->startElement('selection'); + $objWriter->writeAttribute('pane', 'topRight'); + $objWriter->endElement(); + $objWriter->startElement('selection'); + $objWriter->writeAttribute('pane', 'bottomLeft'); + $objWriter->endElement(); + } + } + + // Selection +// if ($pane != '') { + // Only need to write selection element if we have a split pane + // We cheat a little by over-riding the active cell selection, setting it to the split cell + $objWriter->startElement('selection'); + if ($pane != '') { + $objWriter->writeAttribute('pane', $pane); + } + $objWriter->writeAttribute('activeCell', $activeCell); + $objWriter->writeAttribute('sqref', $activeCell); + $objWriter->endElement(); +// } + + $objWriter->endElement(); + $objWriter->endElement(); } @@ -371,7 +372,7 @@ class PHPExcel_Writer_Excel2007_Worksheet extends PHPExcel_Writer_Excel2007_Writ private function _writeCols(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null) { // cols - if (count($pSheet->getColumnDimensions()) > 0) { + if (count($pSheet->getColumnDimensions()) > 0) { $objWriter->startElement('cols'); $pSheet->calculateColumnWidths(); @@ -485,50 +486,48 @@ class PHPExcel_Writer_Excel2007_Worksheet extends PHPExcel_Writer_Excel2007_Writ $objWriter->startElement('conditionalFormatting'); $objWriter->writeAttribute('sqref', $cellCoordinate); - // cfRule - $objWriter->startElement('cfRule'); - $objWriter->writeAttribute('type', $conditional->getConditionType()); - $objWriter->writeAttribute('dxfId', $this->getParentWriter()->getStylesConditionalHashTable()->getIndexForHashCode($conditional->getHashCode())); - $objWriter->writeAttribute('priority', $id++); + // cfRule + $objWriter->startElement('cfRule'); + $objWriter->writeAttribute('type', $conditional->getConditionType()); + $objWriter->writeAttribute('dxfId', $this->getParentWriter()->getStylesConditionalHashTable()->getIndexForHashCode($conditional->getHashCode())); + $objWriter->writeAttribute('priority', $id++); - if (($conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_CELLIS - || - $conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_CONTAINSTEXT) - && $conditional->getOperatorType() != PHPExcel_Style_Conditional::OPERATOR_NONE) { - $objWriter->writeAttribute('operator', $conditional->getOperatorType()); + if (($conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_CELLIS || $conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_CONTAINSTEXT) + && $conditional->getOperatorType() != PHPExcel_Style_Conditional::OPERATOR_NONE) { + $objWriter->writeAttribute('operator', $conditional->getOperatorType()); + } + + if ($conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_CONTAINSTEXT + && !is_null($conditional->getText())) { + $objWriter->writeAttribute('text', $conditional->getText()); + } + + if ($conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_CONTAINSTEXT + && $conditional->getOperatorType() == PHPExcel_Style_Conditional::OPERATOR_CONTAINSTEXT + && !is_null($conditional->getText())) { + $objWriter->writeElement('formula', 'NOT(ISERROR(SEARCH("' . $conditional->getText() . '",' . $cellCoordinate . ')))'); + } else if ($conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_CONTAINSTEXT + && $conditional->getOperatorType() == PHPExcel_Style_Conditional::OPERATOR_BEGINSWITH + && !is_null($conditional->getText())) { + $objWriter->writeElement('formula', 'LEFT(' . $cellCoordinate . ',' . strlen($conditional->getText()) . ')="' . $conditional->getText() . '"'); + } else if ($conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_CONTAINSTEXT + && $conditional->getOperatorType() == PHPExcel_Style_Conditional::OPERATOR_ENDSWITH + && !is_null($conditional->getText())) { + $objWriter->writeElement('formula', 'RIGHT(' . $cellCoordinate . ',' . strlen($conditional->getText()) . ')="' . $conditional->getText() . '"'); + } else if ($conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_CONTAINSTEXT + && $conditional->getOperatorType() == PHPExcel_Style_Conditional::OPERATOR_NOTCONTAINS + && !is_null($conditional->getText())) { + $objWriter->writeElement('formula', 'ISERROR(SEARCH("' . $conditional->getText() . '",' . $cellCoordinate . '))'); + } else if ($conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_CELLIS + || $conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_CONTAINSTEXT + || $conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_EXPRESSION) { + foreach ($conditional->getConditions() as $formula) { + // Formula + $objWriter->writeElement('formula', $formula); } + } - if ($conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_CONTAINSTEXT - && !is_null($conditional->getText())) { - $objWriter->writeAttribute('text', $conditional->getText()); - } - - if ($conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_CONTAINSTEXT - && $conditional->getOperatorType() == PHPExcel_Style_Conditional::OPERATOR_CONTAINSTEXT - && !is_null($conditional->getText())) { - $objWriter->writeElement('formula', 'NOT(ISERROR(SEARCH("' . $conditional->getText() . '",' . $cellCoordinate . ')))'); - } else if ($conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_CONTAINSTEXT - && $conditional->getOperatorType() == PHPExcel_Style_Conditional::OPERATOR_BEGINSWITH - && !is_null($conditional->getText())) { - $objWriter->writeElement('formula', 'LEFT(' . $cellCoordinate . ',' . strlen($conditional->getText()) . ')="' . $conditional->getText() . '"'); - } else if ($conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_CONTAINSTEXT - && $conditional->getOperatorType() == PHPExcel_Style_Conditional::OPERATOR_ENDSWITH - && !is_null($conditional->getText())) { - $objWriter->writeElement('formula', 'RIGHT(' . $cellCoordinate . ',' . strlen($conditional->getText()) . ')="' . $conditional->getText() . '"'); - } else if ($conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_CONTAINSTEXT - && $conditional->getOperatorType() == PHPExcel_Style_Conditional::OPERATOR_NOTCONTAINS - && !is_null($conditional->getText())) { - $objWriter->writeElement('formula', 'ISERROR(SEARCH("' . $conditional->getText() . '",' . $cellCoordinate . '))'); - } else if ($conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_CELLIS - || $conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_CONTAINSTEXT - || $conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_EXPRESSION) { - foreach ($conditional->getConditions() as $formula) { - // Formula - $objWriter->writeElement('formula', $formula); - } - } - - $objWriter->endElement(); + $objWriter->endElement(); $objWriter->endElement(); } @@ -656,17 +655,17 @@ class PHPExcel_Writer_Excel2007_Worksheet extends PHPExcel_Writer_Excel2007_Writ // protectedRanges $objWriter->startElement('protectedRanges'); - // Loop protectedRanges - foreach ($pSheet->getProtectedCells() as $protectedCell => $passwordHash) { - // protectedRange - $objWriter->startElement('protectedRange'); - $objWriter->writeAttribute('name', 'p' . md5($protectedCell)); - $objWriter->writeAttribute('sqref', $protectedCell); - if (!empty($passwordHash)) { - $objWriter->writeAttribute('password', $passwordHash); - } - $objWriter->endElement(); + // Loop protectedRanges + foreach ($pSheet->getProtectedCells() as $protectedCell => $passwordHash) { + // protectedRange + $objWriter->startElement('protectedRange'); + $objWriter->writeAttribute('name', 'p' . md5($protectedCell)); + $objWriter->writeAttribute('sqref', $protectedCell); + if (!empty($passwordHash)) { + $objWriter->writeAttribute('password', $passwordHash); } + $objWriter->endElement(); + } $objWriter->endElement(); } @@ -685,13 +684,13 @@ class PHPExcel_Writer_Excel2007_Worksheet extends PHPExcel_Writer_Excel2007_Writ // mergeCells $objWriter->startElement('mergeCells'); - // Loop mergeCells - foreach ($pSheet->getMergeCells() as $mergeCell) { - // mergeCell - $objWriter->startElement('mergeCell'); - $objWriter->writeAttribute('ref', $mergeCell); - $objWriter->endElement(); - } + // Loop mergeCells + foreach ($pSheet->getMergeCells() as $mergeCell) { + // mergeCell + $objWriter->startElement('mergeCell'); + $objWriter->writeAttribute('ref', $mergeCell); + $objWriter->endElement(); + } $objWriter->endElement(); } @@ -766,71 +765,70 @@ class PHPExcel_Writer_Excel2007_Worksheet extends PHPExcel_Writer_Excel2007_Writ } $range = implode(':', $range); - $objWriter->writeAttribute('ref', str_replace('$','', $range)); + $objWriter->writeAttribute('ref', str_replace('$', '', $range)); $columns = $pSheet->getAutoFilter()->getColumns(); if (count($columns > 0)) { foreach ($columns as $columnID => $column) { $rules = $column->getRules(); - if (count($rules > 0)) { + if (count($rules) > 0) { $objWriter->startElement('filterColumn'); - $objWriter->writeAttribute('colId', $pSheet->getAutoFilter()->getColumnOffset($columnID)); + $objWriter->writeAttribute('colId', $pSheet->getAutoFilter()->getColumnOffset($columnID)); - $objWriter->startElement($column->getFilterType()); - if ($column->getJoin() == PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_COLUMN_JOIN_AND) { - $objWriter->writeAttribute('and', 1); + $objWriter->startElement($column->getFilterType()); + if ($column->getJoin() == PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_COLUMN_JOIN_AND) { + $objWriter->writeAttribute('and', 1); + } + + foreach ($rules as $rule) { + if (($column->getFilterType() === PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_FILTER) && + ($rule->getOperator() === PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_EQUAL) && + ($rule->getValue() === '')) { + // Filter rule for Blanks + $objWriter->writeAttribute('blank', 1); + } elseif ($rule->getRuleType() === PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMICFILTER) { + // Dynamic Filter Rule + $objWriter->writeAttribute('type', $rule->getGrouping()); + $val = $column->getAttribute('val'); + if ($val !== null) { + $objWriter->writeAttribute('val', $val); } + $maxVal = $column->getAttribute('maxVal'); + if ($maxVal !== null) { + $objWriter->writeAttribute('maxVal', $maxVal); + } + } elseif ($rule->getRuleType() === PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_TOPTENFILTER) { + // Top 10 Filter Rule + $objWriter->writeAttribute('val', $rule->getValue()); + $objWriter->writeAttribute('percent', (($rule->getOperator() === PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT) ? '1' : '0')); + $objWriter->writeAttribute('top', (($rule->getGrouping() === PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP) ? '1': '0')); + } else { + // Filter, DateGroupItem or CustomFilter + $objWriter->startElement($rule->getRuleType()); - foreach ($rules as $rule) { - if (($column->getFilterType() === PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_FILTER) && - ($rule->getOperator() === PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_EQUAL) && - ($rule->getValue() === '')) { - // Filter rule for Blanks - $objWriter->writeAttribute('blank', 1); - } elseif ($rule->getRuleType() === PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMICFILTER) { - // Dynamic Filter Rule - $objWriter->writeAttribute('type', $rule->getGrouping()); - $val = $column->getAttribute('val'); - if ($val !== null) { - $objWriter->writeAttribute('val', $val); - } - $maxVal = $column->getAttribute('maxVal'); - if ($maxVal !== null) { - $objWriter->writeAttribute('maxVal', $maxVal); - } - } elseif ($rule->getRuleType() === PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_TOPTENFILTER) { - // Top 10 Filter Rule - $objWriter->writeAttribute('val', $rule->getValue()); - $objWriter->writeAttribute('percent', (($rule->getOperator() === PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT) ? '1' : '0')); - $objWriter->writeAttribute('top', (($rule->getGrouping() === PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP) ? '1': '0')); - } else { - // Filter, DateGroupItem or CustomFilter - $objWriter->startElement($rule->getRuleType()); - - if ($rule->getOperator() !== PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_EQUAL) { - $objWriter->writeAttribute('operator', $rule->getOperator()); - } - if ($rule->getRuleType() === PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP) { - // Date Group filters - foreach ($rule->getValue() as $key => $value) { - if ($value > '') $objWriter->writeAttribute($key, $value); - } - $objWriter->writeAttribute('dateTimeGrouping', $rule->getGrouping()); - } else { - $objWriter->writeAttribute('val', $rule->getValue()); - } - - $objWriter->endElement(); + if ($rule->getOperator() !== PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_EQUAL) { + $objWriter->writeAttribute('operator', $rule->getOperator()); + } + if ($rule->getRuleType() === PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP) { + // Date Group filters + foreach ($rule->getValue() as $key => $value) { + if ($value > '') $objWriter->writeAttribute($key, $value); } + $objWriter->writeAttribute('dateTimeGrouping', $rule->getGrouping()); + } else { + $objWriter->writeAttribute('val', $rule->getValue()); } - $objWriter->endElement(); + $objWriter->endElement(); + } + } + + $objWriter->endElement(); $objWriter->endElement(); } } } - $objWriter->endElement(); } } @@ -921,14 +919,14 @@ class PHPExcel_Writer_Excel2007_Worksheet extends PHPExcel_Writer_Excel2007_Writ $objWriter->writeAttribute('count', count($aRowBreaks)); $objWriter->writeAttribute('manualBreakCount', count($aRowBreaks)); - foreach ($aRowBreaks as $cell) { - $coords = PHPExcel_Cell::coordinateFromString($cell); + foreach ($aRowBreaks as $cell) { + $coords = PHPExcel_Cell::coordinateFromString($cell); - $objWriter->startElement('brk'); - $objWriter->writeAttribute('id', $coords[1]); - $objWriter->writeAttribute('man', '1'); - $objWriter->endElement(); - } + $objWriter->startElement('brk'); + $objWriter->writeAttribute('id', $coords[1]); + $objWriter->writeAttribute('man', '1'); + $objWriter->endElement(); + } $objWriter->endElement(); } @@ -939,14 +937,14 @@ class PHPExcel_Writer_Excel2007_Worksheet extends PHPExcel_Writer_Excel2007_Writ $objWriter->writeAttribute('count', count($aColumnBreaks)); $objWriter->writeAttribute('manualBreakCount', count($aColumnBreaks)); - foreach ($aColumnBreaks as $cell) { - $coords = PHPExcel_Cell::coordinateFromString($cell); + foreach ($aColumnBreaks as $cell) { + $coords = PHPExcel_Cell::coordinateFromString($cell); - $objWriter->startElement('brk'); - $objWriter->writeAttribute('id', PHPExcel_Cell::columnIndexFromString($coords[0]) - 1); - $objWriter->writeAttribute('man', '1'); - $objWriter->endElement(); - } + $objWriter->startElement('brk'); + $objWriter->writeAttribute('id', PHPExcel_Cell::columnIndexFromString($coords[0]) - 1); + $objWriter->writeAttribute('man', '1'); + $objWriter->endElement(); + } $objWriter->endElement(); } diff --git a/Classes/PHPExcel/Writer/Excel5/Parser.php b/Classes/PHPExcel/Writer/Excel5/Parser.php index 56449fcf..05ea60ef 100644 --- a/Classes/PHPExcel/Writer/Excel5/Parser.php +++ b/Classes/PHPExcel/Writer/Excel5/Parser.php @@ -1135,8 +1135,7 @@ class PHPExcel_Writer_Excel5_Parser } elseif (preg_match("/^" . self::REGEX_SHEET_TITLE_UNQUOTED . "(\:" . self::REGEX_SHEET_TITLE_UNQUOTED . ")?\!\\$?[A-Ia-i]?[A-Za-z]\\$?[0-9]+$/u", $token) and !preg_match("/[0-9]/", $this->_lookahead) and ($this->_lookahead != ':') and ($this->_lookahead != '.')) { // If it's an external reference (Sheet1!A1 or Sheet1:Sheet2!A1 or Sheet1!$A$1 or Sheet1:Sheet2!$A$1) return $token; - } - elseif (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . "(\:" . self::REGEX_SHEET_TITLE_QUOTED . ")?'\!\\$?[A-Ia-i]?[A-Za-z]\\$?[0-9]+$/u", $token) and !preg_match("/[0-9]/", $this->_lookahead) and ($this->_lookahead != ':') and ($this->_lookahead != '.')) { + } elseif (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . "(\:" . self::REGEX_SHEET_TITLE_QUOTED . ")?'\!\\$?[A-Ia-i]?[A-Za-z]\\$?[0-9]+$/u", $token) and !preg_match("/[0-9]/", $this->_lookahead) and ($this->_lookahead != ':') and ($this->_lookahead != '.')) { // If it's an external reference ('Sheet1'!A1 or 'Sheet1:Sheet2'!A1 or 'Sheet1'!$A$1 or 'Sheet1:Sheet2'!$A$1) return $token; } elseif (preg_match('/^(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+:(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+$/', $token) && !preg_match("/[0-9]/", $this->_lookahead)) { @@ -1253,7 +1252,7 @@ class PHPExcel_Writer_Excel5_Parser $this->_advance(); return $result; // If it's an error code - } elseif (preg_match("/^#[A-Z0\/]{3,5}[!?]{1}$/", $this->_current_token) or $this->_current_token == '#N/A'){ + } elseif (preg_match("/^#[A-Z0\/]{3,5}[!?]{1}$/", $this->_current_token) or $this->_current_token == '#N/A') { $result = $this->_createTree($this->_current_token, 'ptgErr', ''); $this->_advance(); return $result; @@ -1361,45 +1360,39 @@ class PHPExcel_Writer_Excel5_Parser $result = $this->_createTree($this->_current_token, '', ''); $this->_advance(); return $result; - } - // If it's an external reference (Sheet1!A1 or Sheet1:Sheet2!A1 or Sheet1!$A$1 or Sheet1:Sheet2!$A$1) - elseif (preg_match("/^" . self::REGEX_SHEET_TITLE_UNQUOTED . "(\:" . self::REGEX_SHEET_TITLE_UNQUOTED . ")?\!\\$?[A-Ia-i]?[A-Za-z]\\$?[0-9]+$/u", $this->_current_token)) { + } elseif (preg_match("/^" . self::REGEX_SHEET_TITLE_UNQUOTED . "(\:" . self::REGEX_SHEET_TITLE_UNQUOTED . ")?\!\\$?[A-Ia-i]?[A-Za-z]\\$?[0-9]+$/u", $this->_current_token)) { + // If it's an external reference (Sheet1!A1 or Sheet1:Sheet2!A1 or Sheet1!$A$1 or Sheet1:Sheet2!$A$1) $result = $this->_createTree($this->_current_token, '', ''); $this->_advance(); return $result; - } - // If it's an external reference ('Sheet1'!A1 or 'Sheet1:Sheet2'!A1 or 'Sheet1'!$A$1 or 'Sheet1:Sheet2'!$A$1) - elseif (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . "(\:" . self::REGEX_SHEET_TITLE_QUOTED . ")?'\!\\$?[A-Ia-i]?[A-Za-z]\\$?[0-9]+$/u", $this->_current_token)) { + } elseif (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . "(\:" . self::REGEX_SHEET_TITLE_QUOTED . ")?'\!\\$?[A-Ia-i]?[A-Za-z]\\$?[0-9]+$/u", $this->_current_token)) { + // If it's an external reference ('Sheet1'!A1 or 'Sheet1:Sheet2'!A1 or 'Sheet1'!$A$1 or 'Sheet1:Sheet2'!$A$1) $result = $this->_createTree($this->_current_token, '', ''); $this->_advance(); return $result; - } - // if it's a range A1:B2 or $A$1:$B$2 - elseif (preg_match('/^(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+:(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+$/', $this->_current_token) or + } elseif (preg_match('/^(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+:(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+$/', $this->_current_token) or preg_match('/^(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+\.\.(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+$/', $this->_current_token)) { + // if it's a range A1:B2 or $A$1:$B$2 // must be an error? $result = $this->_createTree($this->_current_token, '', ''); $this->_advance(); return $result; - } - // If it's an external range (Sheet1!A1:B2 or Sheet1:Sheet2!A1:B2 or Sheet1!$A$1:$B$2 or Sheet1:Sheet2!$A$1:$B$2) - elseif (preg_match("/^" . self::REGEX_SHEET_TITLE_UNQUOTED . "(\:" . self::REGEX_SHEET_TITLE_UNQUOTED . ")?\!\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+:\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+$/u", $this->_current_token)) { + } elseif (preg_match("/^" . self::REGEX_SHEET_TITLE_UNQUOTED . "(\:" . self::REGEX_SHEET_TITLE_UNQUOTED . ")?\!\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+:\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+$/u", $this->_current_token)) { + // If it's an external range (Sheet1!A1:B2 or Sheet1:Sheet2!A1:B2 or Sheet1!$A$1:$B$2 or Sheet1:Sheet2!$A$1:$B$2) // must be an error? //$result = $this->_current_token; $result = $this->_createTree($this->_current_token, '', ''); $this->_advance(); return $result; - } - // If it's an external range ('Sheet1'!A1:B2 or 'Sheet1'!A1:B2 or 'Sheet1'!$A$1:$B$2 or 'Sheet1'!$A$1:$B$2) - elseif (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . "(\:" . self::REGEX_SHEET_TITLE_QUOTED . ")?'\!\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+:\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+$/u", $this->_current_token)) { + } elseif (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . "(\:" . self::REGEX_SHEET_TITLE_QUOTED . ")?'\!\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+:\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+$/u", $this->_current_token)) { + // If it's an external range ('Sheet1'!A1:B2 or 'Sheet1'!A1:B2 or 'Sheet1'!$A$1:$B$2 or 'Sheet1'!$A$1:$B$2) // must be an error? //$result = $this->_current_token; $result = $this->_createTree($this->_current_token, '', ''); $this->_advance(); return $result; - } - // If it's a number or a percent - elseif (is_numeric($this->_current_token)) { + } elseif (is_numeric($this->_current_token)) { + // If it's a number or a percent if ($this->_lookahead == '%') { $result = $this->_createTree('ptgPercent', $this->_current_token, ''); $this->_advance(); // Skip the percentage operator once we've pre-built that tree @@ -1408,15 +1401,12 @@ class PHPExcel_Writer_Excel5_Parser } $this->_advance(); return $result; - } - // if it's a function call - elseif (preg_match("/^[A-Z0-9\xc0-\xdc\.]+$/i", $this->_current_token)) { + } elseif (preg_match("/^[A-Z0-9\xc0-\xdc\.]+$/i", $this->_current_token)) { + // if it's a function call $result = $this->_func(); return $result; } - throw new PHPExcel_Writer_Exception("Syntax error: ".$this->_current_token. - ", lookahead: ".$this->_lookahead. - ", current char: ".$this->_current_char); + throw new PHPExcel_Writer_Exception("Syntax error: ".$this->_current_token.", lookahead: ".$this->_lookahead.", current char: ".$this->_current_char); } /** From 5508013569b122c71dce94bf2cab7add370bbd46 Mon Sep 17 00:00:00 2001 From: Progi1984 Date: Fri, 15 May 2015 13:17:40 +0200 Subject: [PATCH 3/5] PSR-2 : Fixes --- Classes/PHPExcel/Worksheet/PageSetup.php | 149 ++++++------- Classes/PHPExcel/Worksheet/Protection.php | 110 +++++---- Classes/PHPExcel/Writer/Abstract.php | 20 +- Classes/PHPExcel/Writer/Excel2007.php | 4 +- Classes/PHPExcel/Writer/Excel2007/Chart.php | 49 ++-- .../PHPExcel/Writer/Excel2007/Comments.php | 112 +++++----- .../Writer/Excel2007/ContentTypes.php | 209 +++++++++--------- .../PHPExcel/Writer/Excel2007/Worksheet.php | 28 +-- 8 files changed, 371 insertions(+), 310 deletions(-) diff --git a/Classes/PHPExcel/Worksheet/PageSetup.php b/Classes/PHPExcel/Worksheet/PageSetup.php index 6a98d47b..e5fe06ac 100644 --- a/Classes/PHPExcel/Worksheet/PageSetup.php +++ b/Classes/PHPExcel/Worksheet/PageSetup.php @@ -107,81 +107,81 @@ class PHPExcel_Worksheet_PageSetup { /* Paper size */ - const PAPERSIZE_LETTER = 1; + const PAPERSIZE_LETTER = 1; const PAPERSIZE_LETTER_SMALL = 2; - const PAPERSIZE_TABLOID = 3; - const PAPERSIZE_LEDGER = 4; - const PAPERSIZE_LEGAL = 5; - const PAPERSIZE_STATEMENT = 6; - const PAPERSIZE_EXECUTIVE = 7; - const PAPERSIZE_A3 = 8; - const PAPERSIZE_A4 = 9; + const PAPERSIZE_TABLOID = 3; + const PAPERSIZE_LEDGER = 4; + const PAPERSIZE_LEGAL = 5; + const PAPERSIZE_STATEMENT = 6; + const PAPERSIZE_EXECUTIVE = 7; + const PAPERSIZE_A3 = 8; + const PAPERSIZE_A4 = 9; const PAPERSIZE_A4_SMALL = 10; - const PAPERSIZE_A5 = 11; - const PAPERSIZE_B4 = 12; - const PAPERSIZE_B5 = 13; - const PAPERSIZE_FOLIO = 14; - const PAPERSIZE_QUARTO = 15; - const PAPERSIZE_STANDARD_1 = 16; - const PAPERSIZE_STANDARD_2 = 17; + const PAPERSIZE_A5 = 11; + const PAPERSIZE_B4 = 12; + const PAPERSIZE_B5 = 13; + const PAPERSIZE_FOLIO = 14; + const PAPERSIZE_QUARTO = 15; + const PAPERSIZE_STANDARD_1 = 16; + const PAPERSIZE_STANDARD_2 = 17; const PAPERSIZE_NOTE = 18; const PAPERSIZE_NO9_ENVELOPE = 19; - const PAPERSIZE_NO10_ENVELOPE = 20; - const PAPERSIZE_NO11_ENVELOPE = 21; - const PAPERSIZE_NO12_ENVELOPE = 22; - const PAPERSIZE_NO14_ENVELOPE = 23; - const PAPERSIZE_C = 24; - const PAPERSIZE_D = 25; - const PAPERSIZE_E = 26; - const PAPERSIZE_DL_ENVELOPE = 27; - const PAPERSIZE_C5_ENVELOPE = 28; - const PAPERSIZE_C3_ENVELOPE = 29; - const PAPERSIZE_C4_ENVELOPE = 30; - const PAPERSIZE_C6_ENVELOPE = 31; + const PAPERSIZE_NO10_ENVELOPE = 20; + const PAPERSIZE_NO11_ENVELOPE = 21; + const PAPERSIZE_NO12_ENVELOPE = 22; + const PAPERSIZE_NO14_ENVELOPE = 23; + const PAPERSIZE_C = 24; + const PAPERSIZE_D = 25; + const PAPERSIZE_E = 26; + const PAPERSIZE_DL_ENVELOPE = 27; + const PAPERSIZE_C5_ENVELOPE = 28; + const PAPERSIZE_C3_ENVELOPE = 29; + const PAPERSIZE_C4_ENVELOPE = 30; + const PAPERSIZE_C6_ENVELOPE = 31; const PAPERSIZE_C65_ENVELOPE = 32; - const PAPERSIZE_B4_ENVELOPE = 33; - const PAPERSIZE_B5_ENVELOPE = 34; - const PAPERSIZE_B6_ENVELOPE = 35; - const PAPERSIZE_ITALY_ENVELOPE = 36; + const PAPERSIZE_B4_ENVELOPE = 33; + const PAPERSIZE_B5_ENVELOPE = 34; + const PAPERSIZE_B6_ENVELOPE = 35; + const PAPERSIZE_ITALY_ENVELOPE = 36; const PAPERSIZE_MONARCH_ENVELOPE = 37; - const PAPERSIZE_6_3_4_ENVELOPE = 38; - const PAPERSIZE_US_STANDARD_FANFOLD = 39; - const PAPERSIZE_GERMAN_STANDARD_FANFOLD = 40; + const PAPERSIZE_6_3_4_ENVELOPE = 38; + const PAPERSIZE_US_STANDARD_FANFOLD = 39; + const PAPERSIZE_GERMAN_STANDARD_FANFOLD = 40; const PAPERSIZE_GERMAN_LEGAL_FANFOLD = 41; - const PAPERSIZE_ISO_B4 = 42; + const PAPERSIZE_ISO_B4 = 42; const PAPERSIZE_JAPANESE_DOUBLE_POSTCARD = 43; const PAPERSIZE_STANDARD_PAPER_1 = 44; const PAPERSIZE_STANDARD_PAPER_2 = 45; const PAPERSIZE_STANDARD_PAPER_3 = 46; - const PAPERSIZE_INVITE_ENVELOPE = 47; - const PAPERSIZE_LETTER_EXTRA_PAPER = 48; - const PAPERSIZE_LEGAL_EXTRA_PAPER = 49; - const PAPERSIZE_TABLOID_EXTRA_PAPER = 50; - const PAPERSIZE_A4_EXTRA_PAPER = 51; - const PAPERSIZE_LETTER_TRANSVERSE_PAPER = 52; - const PAPERSIZE_A4_TRANSVERSE_PAPER = 53; - const PAPERSIZE_LETTER_EXTRA_TRANSVERSE_PAPER = 54; - const PAPERSIZE_SUPERA_SUPERA_A4_PAPER = 55; - const PAPERSIZE_SUPERB_SUPERB_A3_PAPER = 56; - const PAPERSIZE_LETTER_PLUS_PAPER = 57; - const PAPERSIZE_A4_PLUS_PAPER = 58; - const PAPERSIZE_A5_TRANSVERSE_PAPER = 59; - const PAPERSIZE_JIS_B5_TRANSVERSE_PAPER = 60; - const PAPERSIZE_A3_EXTRA_PAPER = 61; - const PAPERSIZE_A5_EXTRA_PAPER = 62; - const PAPERSIZE_ISO_B5_EXTRA_PAPER = 63; + const PAPERSIZE_INVITE_ENVELOPE = 47; + const PAPERSIZE_LETTER_EXTRA_PAPER = 48; + const PAPERSIZE_LEGAL_EXTRA_PAPER = 49; + const PAPERSIZE_TABLOID_EXTRA_PAPER = 50; + const PAPERSIZE_A4_EXTRA_PAPER = 51; + const PAPERSIZE_LETTER_TRANSVERSE_PAPER = 52; + const PAPERSIZE_A4_TRANSVERSE_PAPER = 53; + const PAPERSIZE_LETTER_EXTRA_TRANSVERSE_PAPER = 54; + const PAPERSIZE_SUPERA_SUPERA_A4_PAPER = 55; + const PAPERSIZE_SUPERB_SUPERB_A3_PAPER = 56; + const PAPERSIZE_LETTER_PLUS_PAPER = 57; + const PAPERSIZE_A4_PLUS_PAPER = 58; + const PAPERSIZE_A5_TRANSVERSE_PAPER = 59; + const PAPERSIZE_JIS_B5_TRANSVERSE_PAPER = 60; + const PAPERSIZE_A3_EXTRA_PAPER = 61; + const PAPERSIZE_A5_EXTRA_PAPER = 62; + const PAPERSIZE_ISO_B5_EXTRA_PAPER = 63; const PAPERSIZE_A2_PAPER = 64; - const PAPERSIZE_A3_TRANSVERSE_PAPER = 65; - const PAPERSIZE_A3_EXTRA_TRANSVERSE_PAPER = 66; + const PAPERSIZE_A3_TRANSVERSE_PAPER = 65; + const PAPERSIZE_A3_EXTRA_TRANSVERSE_PAPER = 66; /* Page orientation */ - const ORIENTATION_DEFAULT = 'default'; - const ORIENTATION_LANDSCAPE = 'landscape'; - const ORIENTATION_PORTRAIT = 'portrait'; + const ORIENTATION_DEFAULT = 'default'; + const ORIENTATION_LANDSCAPE = 'landscape'; + const ORIENTATION_PORTRAIT = 'portrait'; /* Print Range Set Method */ - const SETPRINTRANGE_OVERWRITE = 'O'; - const SETPRINTRANGE_INSERT = 'I'; + const SETPRINTRANGE_OVERWRITE = 'O'; + const SETPRINTRANGE_INSERT = 'I'; /** @@ -189,14 +189,14 @@ class PHPExcel_Worksheet_PageSetup * * @var int */ - private $_paperSize = PHPExcel_Worksheet_PageSetup::PAPERSIZE_LETTER; + private $_paperSize = PHPExcel_Worksheet_PageSetup::PAPERSIZE_LETTER; /** * Orientation * * @var string */ - private $_orientation = PHPExcel_Worksheet_PageSetup::ORIENTATION_DEFAULT; + private $_orientation = PHPExcel_Worksheet_PageSetup::ORIENTATION_DEFAULT; /** * Scale (Print Scale) @@ -206,7 +206,7 @@ class PHPExcel_Worksheet_PageSetup * * @var int? */ - private $_scale = 100; + private $_scale = 100; /** * Fit To Page @@ -214,7 +214,7 @@ class PHPExcel_Worksheet_PageSetup * * @var boolean */ - private $_fitToPage = FALSE; + private $_fitToPage = false; /** * Fit To Height @@ -251,28 +251,28 @@ class PHPExcel_Worksheet_PageSetup * * @var boolean */ - private $_horizontalCentered = FALSE; + private $_horizontalCentered = false; /** * Center page vertically * * @var boolean */ - private $_verticalCentered = FALSE; + private $_verticalCentered = false; /** * Print area * * @var string */ - private $_printArea = NULL; + private $_printArea = null; /** * First page number * * @var int */ - private $_firstPageNumber = NULL; + private $_firstPageNumber = null; /** * Create a new PHPExcel_Worksheet_PageSetup @@ -286,7 +286,8 @@ class PHPExcel_Worksheet_PageSetup * * @return int */ - public function getPaperSize() { + public function getPaperSize() + { return $this->_paperSize; } @@ -370,7 +371,7 @@ class PHPExcel_Worksheet_PageSetup * @param boolean $pValue * @return PHPExcel_Worksheet_PageSetup */ - public function setFitToPage($pValue = TRUE) { + public function setFitToPage($pValue = true) { $this->_fitToPage = $pValue; return $this; } @@ -391,10 +392,10 @@ class PHPExcel_Worksheet_PageSetup * @param boolean $pUpdate Update fitToPage so it applies rather than scaling * @return PHPExcel_Worksheet_PageSetup */ - public function setFitToHeight($pValue = 1, $pUpdate = TRUE) { + public function setFitToHeight($pValue = 1, $pUpdate = true) { $this->_fitToHeight = $pValue; if ($pUpdate) { - $this->_fitToPage = TRUE; + $this->_fitToPage = true; } return $this; } @@ -415,10 +416,10 @@ class PHPExcel_Worksheet_PageSetup * @param boolean $pUpdate Update fitToPage so it applies rather than scaling * @return PHPExcel_Worksheet_PageSetup */ - public function setFitToWidth($pValue = 1, $pUpdate = TRUE) { + public function setFitToWidth($pValue = 1, $pUpdate = true) { $this->_fitToWidth = $pValue; if ($pUpdate) { - $this->_fitToPage = TRUE; + $this->_fitToPage = true; } return $this; } @@ -610,7 +611,7 @@ class PHPExcel_Worksheet_PageSetup */ public function clearPrintArea($index = 0) { if ($index == 0) { - $this->_printArea = NULL; + $this->_printArea = null; } else { $printAreas = explode(',', $this->_printArea); if (isset($printAreas[$index-1])) { diff --git a/Classes/PHPExcel/Worksheet/Protection.php b/Classes/PHPExcel/Worksheet/Protection.php index af341988..d6ab223a 100644 --- a/Classes/PHPExcel/Worksheet/Protection.php +++ b/Classes/PHPExcel/Worksheet/Protection.php @@ -166,8 +166,9 @@ class PHPExcel_Worksheet_Protection * * @return boolean */ - function isProtectionEnabled() { - return $this->_sheet || + function isProtectionEnabled() + { + return $this->_sheet || $this->_objects || $this->_scenarios || $this->_formatCells || @@ -190,7 +191,8 @@ class PHPExcel_Worksheet_Protection * * @return boolean */ - function getSheet() { + function getSheet() + { return $this->_sheet; } @@ -200,7 +202,8 @@ class PHPExcel_Worksheet_Protection * @param boolean $pValue * @return PHPExcel_Worksheet_Protection */ - function setSheet($pValue = false) { + function setSheet($pValue = false) + { $this->_sheet = $pValue; return $this; } @@ -210,7 +213,8 @@ class PHPExcel_Worksheet_Protection * * @return boolean */ - function getObjects() { + function getObjects() + { return $this->_objects; } @@ -220,7 +224,8 @@ class PHPExcel_Worksheet_Protection * @param boolean $pValue * @return PHPExcel_Worksheet_Protection */ - function setObjects($pValue = false) { + function setObjects($pValue = false) + { $this->_objects = $pValue; return $this; } @@ -230,7 +235,8 @@ class PHPExcel_Worksheet_Protection * * @return boolean */ - function getScenarios() { + function getScenarios() + { return $this->_scenarios; } @@ -240,7 +246,8 @@ class PHPExcel_Worksheet_Protection * @param boolean $pValue * @return PHPExcel_Worksheet_Protection */ - function setScenarios($pValue = false) { + function setScenarios($pValue = false) + { $this->_scenarios = $pValue; return $this; } @@ -250,7 +257,8 @@ class PHPExcel_Worksheet_Protection * * @return boolean */ - function getFormatCells() { + function getFormatCells() + { return $this->_formatCells; } @@ -260,7 +268,8 @@ class PHPExcel_Worksheet_Protection * @param boolean $pValue * @return PHPExcel_Worksheet_Protection */ - function setFormatCells($pValue = false) { + function setFormatCells($pValue = false) + { $this->_formatCells = $pValue; return $this; } @@ -270,7 +279,8 @@ class PHPExcel_Worksheet_Protection * * @return boolean */ - function getFormatColumns() { + function getFormatColumns() + { return $this->_formatColumns; } @@ -280,7 +290,8 @@ class PHPExcel_Worksheet_Protection * @param boolean $pValue * @return PHPExcel_Worksheet_Protection */ - function setFormatColumns($pValue = false) { + function setFormatColumns($pValue = false) + { $this->_formatColumns = $pValue; return $this; } @@ -290,7 +301,8 @@ class PHPExcel_Worksheet_Protection * * @return boolean */ - function getFormatRows() { + function getFormatRows() + { return $this->_formatRows; } @@ -300,7 +312,8 @@ class PHPExcel_Worksheet_Protection * @param boolean $pValue * @return PHPExcel_Worksheet_Protection */ - function setFormatRows($pValue = false) { + function setFormatRows($pValue = false) + { $this->_formatRows = $pValue; return $this; } @@ -310,7 +323,8 @@ class PHPExcel_Worksheet_Protection * * @return boolean */ - function getInsertColumns() { + function getInsertColumns() + { return $this->_insertColumns; } @@ -320,7 +334,8 @@ class PHPExcel_Worksheet_Protection * @param boolean $pValue * @return PHPExcel_Worksheet_Protection */ - function setInsertColumns($pValue = false) { + function setInsertColumns($pValue = false) + { $this->_insertColumns = $pValue; return $this; } @@ -330,7 +345,8 @@ class PHPExcel_Worksheet_Protection * * @return boolean */ - function getInsertRows() { + function getInsertRows() + { return $this->_insertRows; } @@ -340,7 +356,8 @@ class PHPExcel_Worksheet_Protection * @param boolean $pValue * @return PHPExcel_Worksheet_Protection */ - function setInsertRows($pValue = false) { + function setInsertRows($pValue = false) + { $this->_insertRows = $pValue; return $this; } @@ -350,7 +367,8 @@ class PHPExcel_Worksheet_Protection * * @return boolean */ - function getInsertHyperlinks() { + function getInsertHyperlinks() + { return $this->_insertHyperlinks; } @@ -360,7 +378,8 @@ class PHPExcel_Worksheet_Protection * @param boolean $pValue * @return PHPExcel_Worksheet_Protection */ - function setInsertHyperlinks($pValue = false) { + function setInsertHyperlinks($pValue = false) + { $this->_insertHyperlinks = $pValue; return $this; } @@ -370,7 +389,8 @@ class PHPExcel_Worksheet_Protection * * @return boolean */ - function getDeleteColumns() { + function getDeleteColumns() + { return $this->_deleteColumns; } @@ -380,7 +400,8 @@ class PHPExcel_Worksheet_Protection * @param boolean $pValue * @return PHPExcel_Worksheet_Protection */ - function setDeleteColumns($pValue = false) { + function setDeleteColumns($pValue = false) + { $this->_deleteColumns = $pValue; return $this; } @@ -390,7 +411,8 @@ class PHPExcel_Worksheet_Protection * * @return boolean */ - function getDeleteRows() { + function getDeleteRows() + { return $this->_deleteRows; } @@ -400,7 +422,8 @@ class PHPExcel_Worksheet_Protection * @param boolean $pValue * @return PHPExcel_Worksheet_Protection */ - function setDeleteRows($pValue = false) { + function setDeleteRows($pValue = false) + { $this->_deleteRows = $pValue; return $this; } @@ -410,7 +433,8 @@ class PHPExcel_Worksheet_Protection * * @return boolean */ - function getSelectLockedCells() { + function getSelectLockedCells() + { return $this->_selectLockedCells; } @@ -420,7 +444,8 @@ class PHPExcel_Worksheet_Protection * @param boolean $pValue * @return PHPExcel_Worksheet_Protection */ - function setSelectLockedCells($pValue = false) { + function setSelectLockedCells($pValue = false) + { $this->_selectLockedCells = $pValue; return $this; } @@ -430,7 +455,8 @@ class PHPExcel_Worksheet_Protection * * @return boolean */ - function getSort() { + function getSort() + { return $this->_sort; } @@ -440,7 +466,8 @@ class PHPExcel_Worksheet_Protection * @param boolean $pValue * @return PHPExcel_Worksheet_Protection */ - function setSort($pValue = false) { + function setSort($pValue = false) + { $this->_sort = $pValue; return $this; } @@ -450,7 +477,8 @@ class PHPExcel_Worksheet_Protection * * @return boolean */ - function getAutoFilter() { + function getAutoFilter() + { return $this->_autoFilter; } @@ -460,7 +488,8 @@ class PHPExcel_Worksheet_Protection * @param boolean $pValue * @return PHPExcel_Worksheet_Protection */ - function setAutoFilter($pValue = false) { + function setAutoFilter($pValue = false) + { $this->_autoFilter = $pValue; return $this; } @@ -470,7 +499,8 @@ class PHPExcel_Worksheet_Protection * * @return boolean */ - function getPivotTables() { + function getPivotTables() + { return $this->_pivotTables; } @@ -480,7 +510,8 @@ class PHPExcel_Worksheet_Protection * @param boolean $pValue * @return PHPExcel_Worksheet_Protection */ - function setPivotTables($pValue = false) { + function setPivotTables($pValue = false) + { $this->_pivotTables = $pValue; return $this; } @@ -490,7 +521,8 @@ class PHPExcel_Worksheet_Protection * * @return boolean */ - function getSelectUnlockedCells() { + function getSelectUnlockedCells() + { return $this->_selectUnlockedCells; } @@ -500,7 +532,8 @@ class PHPExcel_Worksheet_Protection * @param boolean $pValue * @return PHPExcel_Worksheet_Protection */ - function setSelectUnlockedCells($pValue = false) { + function setSelectUnlockedCells($pValue = false) + { $this->_selectUnlockedCells = $pValue; return $this; } @@ -510,7 +543,8 @@ class PHPExcel_Worksheet_Protection * * @return string */ - function getPassword() { + function getPassword() + { return $this->_password; } @@ -521,7 +555,8 @@ class PHPExcel_Worksheet_Protection * @param boolean $pAlreadyHashed If the password has already been hashed, set this to true * @return PHPExcel_Worksheet_Protection */ - function setPassword($pValue = '', $pAlreadyHashed = false) { + function setPassword($pValue = '', $pAlreadyHashed = false) + { if (!$pAlreadyHashed) { $pValue = PHPExcel_Shared_PasswordHasher::hashPassword($pValue); } @@ -532,7 +567,8 @@ class PHPExcel_Worksheet_Protection /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ - public function __clone() { + public function __clone() + { $vars = get_object_vars($this); foreach ($vars as $key => $value) { if (is_object($value)) { diff --git a/Classes/PHPExcel/Writer/Abstract.php b/Classes/PHPExcel/Writer/Abstract.php index 911dc5dd..a0f14100 100644 --- a/Classes/PHPExcel/Writer/Abstract.php +++ b/Classes/PHPExcel/Writer/Abstract.php @@ -65,7 +65,8 @@ abstract class PHPExcel_Writer_Abstract implements PHPExcel_Writer_IWriter * * @return boolean */ - public function getIncludeCharts() { + public function getIncludeCharts() + { return $this->_includeCharts; } @@ -93,7 +94,8 @@ abstract class PHPExcel_Writer_Abstract implements PHPExcel_Writer_IWriter * * @return boolean */ - public function getPreCalculateFormulas() { + public function getPreCalculateFormulas() + { return $this->_preCalculateFormulas; } @@ -105,7 +107,8 @@ abstract class PHPExcel_Writer_Abstract implements PHPExcel_Writer_IWriter * @param boolean $pValue Pre-Calculate Formulas? * @return PHPExcel_Writer_IWriter */ - public function setPreCalculateFormulas($pValue = TRUE) { + public function setPreCalculateFormulas($pValue = true) + { $this->_preCalculateFormulas = (boolean) $pValue; return $this; } @@ -115,7 +118,8 @@ abstract class PHPExcel_Writer_Abstract implements PHPExcel_Writer_IWriter * * @return boolean */ - public function getUseDiskCaching() { + public function getUseDiskCaching() + { return $this->_useDiskCaching; } @@ -127,10 +131,11 @@ abstract class PHPExcel_Writer_Abstract implements PHPExcel_Writer_IWriter * @throws PHPExcel_Writer_Exception when directory does not exist * @return PHPExcel_Writer_Excel2007 */ - public function setUseDiskCaching($pValue = FALSE, $pDirectory = NULL) { + public function setUseDiskCaching($pValue = false, $pDirectory = null) + { $this->_useDiskCaching = $pValue; - if ($pDirectory !== NULL) { + if ($pDirectory !== null) { if (is_dir($pDirectory)) { $this->_diskCachingDirectory = $pDirectory; } else { @@ -145,7 +150,8 @@ abstract class PHPExcel_Writer_Abstract implements PHPExcel_Writer_IWriter * * @return string */ - public function getDiskCachingDirectory() { + public function getDiskCachingDirectory() + { return $this->_diskCachingDirectory; } } diff --git a/Classes/PHPExcel/Writer/Excel2007.php b/Classes/PHPExcel/Writer/Excel2007.php index 756bf4dc..e7f26ff5 100644 --- a/Classes/PHPExcel/Writer/Excel2007.php +++ b/Classes/PHPExcel/Writer/Excel2007.php @@ -257,7 +257,7 @@ class PHPExcel_Writer_Excel2007 extends PHPExcel_Writer_Abstract implements PHPE if ($this->_spreadSheet->hasRibbonBinObjects()) { $tmpRootPath=dirname($tmpRibbonTarget).'/'; $ribbonBinObjects=$this->_spreadSheet->getRibbonBinObjects('data');//the files to write - foreach ($ribbonBinObjects as $aPath=>$aContent) { + foreach ($ribbonBinObjects as $aPath => $aContent) { $objZip->addFromString($tmpRootPath.$aPath, $aContent); } //the rels for files @@ -494,7 +494,7 @@ class PHPExcel_Writer_Excel2007 extends PHPExcel_Writer_Abstract implements PHPE * * @return PHPExcel_HashTable */ - public function getNumFmtHashTable() + public function getNumFmtHashTable() { return $this->_numFmtHashTable; } diff --git a/Classes/PHPExcel/Writer/Excel2007/Chart.php b/Classes/PHPExcel/Writer/Excel2007/Chart.php index 93cff286..6aefa80a 100644 --- a/Classes/PHPExcel/Writer/Excel2007/Chart.php +++ b/Classes/PHPExcel/Writer/Excel2007/Chart.php @@ -32,7 +32,8 @@ * @package PHPExcel_Writer_Excel2007 * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) */ -class PHPExcel_Writer_Excel2007_Chart extends PHPExcel_Writer_Excel2007_WriterPart { +class PHPExcel_Writer_Excel2007_Chart extends PHPExcel_Writer_Excel2007_WriterPart +{ /** * Write charts to XML format * @@ -41,7 +42,8 @@ class PHPExcel_Writer_Excel2007_Chart extends PHPExcel_Writer_Excel2007_WriterPa * @return string XML Output * @throws PHPExcel_Writer_Exception */ - public function writeChart(PHPExcel_Chart $pChart = null) { + public function writeChart(PHPExcel_Chart $pChart = null) + { // Create XML writer $objWriter = null; if ($this->getParentWriter()->getUseDiskCaching()) { @@ -115,7 +117,8 @@ class PHPExcel_Writer_Excel2007_Chart extends PHPExcel_Writer_Excel2007_WriterPa * * @throws PHPExcel_Writer_Exception */ - private function _writeTitle(PHPExcel_Chart_Title $title = null, $objWriter) { + private function _writeTitle(PHPExcel_Chart_Title $title = null, $objWriter) + { if (is_null($title)) { return; } @@ -159,7 +162,8 @@ class PHPExcel_Writer_Excel2007_Chart extends PHPExcel_Writer_Excel2007_WriterPa * * @throws PHPExcel_Writer_Exception */ - private function _writeLegend(PHPExcel_Chart_Legend $legend = null, $objWriter) { + private function _writeLegend(PHPExcel_Chart_Legend $legend = null, $objWriter) + { if (is_null($legend)) { return; } @@ -210,10 +214,10 @@ class PHPExcel_Writer_Excel2007_Chart extends PHPExcel_Writer_Excel2007_WriterPa * @param PHPExcel_Chart_Axis $xAxis * @param PHPExcel_Chart_Axis $yAxis * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer - * + * * @throws PHPExcel_Writer_Exception */ - private function _writePlotArea(PHPExcel_Chart_PlotArea $plotArea, PHPExcel_Chart_Title $xAxisLabel = null, PHPExcel_Chart_Title $yAxisLabel = null, $objWriter, PHPExcel_Worksheet $pSheet, PHPExcel_Chart_Axis $xAxis, PHPExcel_Chart_Axis $yAxis, PHPExcel_Chart_GridLines $majorGridlines, PHPExcel_Chart_GridLines $minorGridlines ) + private function _writePlotArea(PHPExcel_Chart_PlotArea $plotArea, PHPExcel_Chart_Title $xAxisLabel = null, PHPExcel_Chart_Title $yAxisLabel = null, $objWriter, PHPExcel_Worksheet $pSheet, PHPExcel_Chart_Axis $xAxis, PHPExcel_Chart_Axis $yAxis, PHPExcel_Chart_GridLines $majorGridlines, PHPExcel_Chart_GridLines $minorGridlines) { if (is_null($plotArea)) { return; @@ -349,7 +353,8 @@ class PHPExcel_Writer_Excel2007_Chart extends PHPExcel_Writer_Excel2007_WriterPa * * @throws PHPExcel_Writer_Exception */ - private function _writeDataLbls($objWriter, $chartLayout) { + private function _writeDataLbls($objWriter, $chartLayout) + { $objWriter->startElement('c:dLbls'); $objWriter->startElement('c:showLegendKey'); @@ -403,7 +408,8 @@ class PHPExcel_Writer_Excel2007_Chart extends PHPExcel_Writer_Excel2007_WriterPa * * @throws PHPExcel_Writer_Exception */ - private function _writeCatAx($objWriter, PHPExcel_Chart_PlotArea $plotArea, $xAxisLabel, $groupType, $id1, $id2, $isMultiLevelSeries, $xAxis, $yAxis) { + private function _writeCatAx($objWriter, PHPExcel_Chart_PlotArea $plotArea, $xAxisLabel, $groupType, $id1, $id2, $isMultiLevelSeries, $xAxis, $yAxis) + { $objWriter->startElement('c:catAx'); if ($id1 > 0) { @@ -524,7 +530,8 @@ class PHPExcel_Writer_Excel2007_Chart extends PHPExcel_Writer_Excel2007_WriterPa * * @throws PHPExcel_Writer_Exception */ - private function _writeValAx($objWriter, PHPExcel_Chart_PlotArea $plotArea, $yAxisLabel, $groupType, $id1, $id2, $isMultiLevelSeries, $xAxis, $yAxis, $majorGridlines, $minorGridlines) { + private function _writeValAx($objWriter, PHPExcel_Chart_PlotArea $plotArea, $yAxisLabel, $groupType, $id1, $id2, $isMultiLevelSeries, $xAxis, $yAxis, $majorGridlines, $minorGridlines) + { $objWriter->startElement('c:valAx'); if ($id2 > 0) { @@ -1004,7 +1011,8 @@ class PHPExcel_Writer_Excel2007_Chart extends PHPExcel_Writer_Excel2007_WriterPa * @return string|array * @throws PHPExcel_Writer_Exception */ - private static function _getChartType($plotArea) { + private static function _getChartType($plotArea) + { $groupCount = $plotArea->getPlotGroupCount(); if ($groupCount == 1) { @@ -1036,7 +1044,8 @@ class PHPExcel_Writer_Excel2007_Chart extends PHPExcel_Writer_Excel2007_WriterPa * * @throws PHPExcel_Writer_Exception */ - private function _writePlotGroup($plotGroup, $groupType, $objWriter, &$catIsMultiLevelSeries, &$valIsMultiLevelSeries, &$plotGroupingType, PHPExcel_Worksheet $pSheet ) { + private function _writePlotGroup($plotGroup, $groupType, $objWriter, &$catIsMultiLevelSeries, &$valIsMultiLevelSeries, &$plotGroupingType, PHPExcel_Worksheet $pSheet) + { if (is_null($plotGroup)) { return; } @@ -1209,7 +1218,8 @@ class PHPExcel_Writer_Excel2007_Chart extends PHPExcel_Writer_Excel2007_WriterPa * * @throws PHPExcel_Writer_Exception */ - private function _writePlotSeriesLabel($plotSeriesLabel, $objWriter) { + private function _writePlotSeriesLabel($plotSeriesLabel, $objWriter) + { if (is_null($plotSeriesLabel)) { return; } @@ -1246,7 +1256,8 @@ class PHPExcel_Writer_Excel2007_Chart extends PHPExcel_Writer_Excel2007_WriterPa * * @throws PHPExcel_Writer_Exception */ - private function _writePlotSeriesValues($plotSeriesValues, $objWriter, $groupType, $dataType = 'str', PHPExcel_Worksheet $pSheet) { + private function _writePlotSeriesValues($plotSeriesValues, $objWriter, $groupType, $dataType = 'str', PHPExcel_Worksheet $pSheet) + { if (is_null($plotSeriesValues)) { return; } @@ -1337,7 +1348,8 @@ class PHPExcel_Writer_Excel2007_Chart extends PHPExcel_Writer_Excel2007_WriterPa * * @throws PHPExcel_Writer_Exception */ - private function _writeBubbles($plotSeriesValues, $objWriter, PHPExcel_Worksheet $pSheet) { + private function _writeBubbles($plotSeriesValues, $objWriter, PHPExcel_Worksheet $pSheet) + { if (is_null($plotSeriesValues)) { return; } @@ -1383,7 +1395,8 @@ class PHPExcel_Writer_Excel2007_Chart extends PHPExcel_Writer_Excel2007_WriterPa * * @throws PHPExcel_Writer_Exception */ - private function _writeLayout(PHPExcel_Chart_Layout $layout = null, $objWriter) { + private function _writeLayout(PHPExcel_Chart_Layout $layout = null, $objWriter) + { $objWriter->startElement('c:layout'); if (!is_null($layout)) { @@ -1451,7 +1464,8 @@ class PHPExcel_Writer_Excel2007_Chart extends PHPExcel_Writer_Excel2007_WriterPa * * @throws PHPExcel_Writer_Exception */ - private function _writeAlternateContent($objWriter) { + private function _writeAlternateContent($objWriter) + { $objWriter->startElement('mc:AlternateContent'); $objWriter->writeAttribute('xmlns:mc', 'http://schemas.openxmlformats.org/markup-compatibility/2006'); @@ -1480,7 +1494,8 @@ class PHPExcel_Writer_Excel2007_Chart extends PHPExcel_Writer_Excel2007_WriterPa * * @throws PHPExcel_Writer_Exception */ - private function _writePrintSettings($objWriter) { + private function _writePrintSettings($objWriter) + { $objWriter->startElement('c:printSettings'); $objWriter->startElement('c:headerFooter'); diff --git a/Classes/PHPExcel/Writer/Excel2007/Comments.php b/Classes/PHPExcel/Writer/Excel2007/Comments.php index 61ba4ad0..95336e86 100644 --- a/Classes/PHPExcel/Writer/Excel2007/Comments.php +++ b/Classes/PHPExcel/Writer/Excel2007/Comments.php @@ -71,19 +71,19 @@ class PHPExcel_Writer_Excel2007_Comments extends PHPExcel_Writer_Excel2007_Write $objWriter->startElement('comments'); $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main'); - // Loop through authors - $objWriter->startElement('authors'); - foreach ($authors as $author => $index) { - $objWriter->writeElement('author', $author); - } - $objWriter->endElement(); + // Loop through authors + $objWriter->startElement('authors'); + foreach ($authors as $author => $index) { + $objWriter->writeElement('author', $author); + } + $objWriter->endElement(); - // Loop through comments - $objWriter->startElement('commentList'); - foreach ($comments as $key => $value) { - $this->_writeComment($objWriter, $key, $value, $authors); - } - $objWriter->endElement(); + // Loop through comments + $objWriter->startElement('commentList'); + foreach ($comments as $key => $value) { + $this->_writeComment($objWriter, $key, $value, $authors); + } + $objWriter->endElement(); $objWriter->endElement(); @@ -104,13 +104,13 @@ class PHPExcel_Writer_Excel2007_Comments extends PHPExcel_Writer_Excel2007_Write { // comment $objWriter->startElement('comment'); - $objWriter->writeAttribute('ref', $pCellReference); - $objWriter->writeAttribute('authorId', $pAuthors[$pComment->getAuthor()]); + $objWriter->writeAttribute('ref', $pCellReference); + $objWriter->writeAttribute('authorId', $pAuthors[$pComment->getAuthor()]); - // text - $objWriter->startElement('text'); - $this->getParentWriter()->getWriterPart('stringtable')->writeRichText($objWriter, $pComment->getText()); - $objWriter->endElement(); + // text + $objWriter->startElement('text'); + $this->getParentWriter()->getWriterPart('stringtable')->writeRichText($objWriter, $pComment->getText()); + $objWriter->endElement(); $objWriter->endElement(); } @@ -144,42 +144,42 @@ class PHPExcel_Writer_Excel2007_Comments extends PHPExcel_Writer_Excel2007_Write $objWriter->writeAttribute('xmlns:o', 'urn:schemas-microsoft-com:office:office'); $objWriter->writeAttribute('xmlns:x', 'urn:schemas-microsoft-com:office:excel'); - // o:shapelayout - $objWriter->startElement('o:shapelayout'); - $objWriter->writeAttribute('v:ext', 'edit'); - - // o:idmap - $objWriter->startElement('o:idmap'); - $objWriter->writeAttribute('v:ext', 'edit'); - $objWriter->writeAttribute('data', '1'); - $objWriter->endElement(); + // o:shapelayout + $objWriter->startElement('o:shapelayout'); + $objWriter->writeAttribute('v:ext', 'edit'); + // o:idmap + $objWriter->startElement('o:idmap'); + $objWriter->writeAttribute('v:ext', 'edit'); + $objWriter->writeAttribute('data', '1'); $objWriter->endElement(); - // v:shapetype - $objWriter->startElement('v:shapetype'); - $objWriter->writeAttribute('id', '_x0000_t202'); - $objWriter->writeAttribute('coordsize', '21600,21600'); - $objWriter->writeAttribute('o:spt', '202'); - $objWriter->writeAttribute('path', 'm,l,21600r21600,l21600,xe'); + $objWriter->endElement(); - // v:stroke - $objWriter->startElement('v:stroke'); - $objWriter->writeAttribute('joinstyle', 'miter'); - $objWriter->endElement(); - - // v:path - $objWriter->startElement('v:path'); - $objWriter->writeAttribute('gradientshapeok', 't'); - $objWriter->writeAttribute('o:connecttype', 'rect'); - $objWriter->endElement(); + // v:shapetype + $objWriter->startElement('v:shapetype'); + $objWriter->writeAttribute('id', '_x0000_t202'); + $objWriter->writeAttribute('coordsize', '21600,21600'); + $objWriter->writeAttribute('o:spt', '202'); + $objWriter->writeAttribute('path', 'm,l,21600r21600,l21600,xe'); + // v:stroke + $objWriter->startElement('v:stroke'); + $objWriter->writeAttribute('joinstyle', 'miter'); $objWriter->endElement(); - // Loop through comments - foreach ($comments as $key => $value) { - $this->_writeVMLComment($objWriter, $key, $value); - } + // v:path + $objWriter->startElement('v:path'); + $objWriter->writeAttribute('gradientshapeok', 't'); + $objWriter->writeAttribute('o:connecttype', 'rect'); + $objWriter->endElement(); + + $objWriter->endElement(); + + // Loop through comments + foreach ($comments as $key => $value) { + $this->_writeVMLComment($objWriter, $key, $value); + } $objWriter->endElement(); @@ -205,22 +205,22 @@ class PHPExcel_Writer_Excel2007_Comments extends PHPExcel_Writer_Excel2007_Write // v:shape $objWriter->startElement('v:shape'); - $objWriter->writeAttribute('id', '_x0000_s' . $id); - $objWriter->writeAttribute('type', '#_x0000_t202'); - $objWriter->writeAttribute('style', 'position:absolute;margin-left:' . $pComment->getMarginLeft() . ';margin-top:' . $pComment->getMarginTop() . ';width:' . $pComment->getWidth() . ';height:' . $pComment->getHeight() . ';z-index:1;visibility:' . ($pComment->getVisible() ? 'visible' : 'hidden')); - $objWriter->writeAttribute('fillcolor', '#' . $pComment->getFillColor()->getRGB()); - $objWriter->writeAttribute('o:insetmode', 'auto'); + $objWriter->writeAttribute('id', '_x0000_s' . $id); + $objWriter->writeAttribute('type', '#_x0000_t202'); + $objWriter->writeAttribute('style', 'position:absolute;margin-left:' . $pComment->getMarginLeft() . ';margin-top:' . $pComment->getMarginTop() . ';width:' . $pComment->getWidth() . ';height:' . $pComment->getHeight() . ';z-index:1;visibility:' . ($pComment->getVisible() ? 'visible' : 'hidden')); + $objWriter->writeAttribute('fillcolor', '#' . $pComment->getFillColor()->getRGB()); + $objWriter->writeAttribute('o:insetmode', 'auto'); // v:fill $objWriter->startElement('v:fill'); - $objWriter->writeAttribute('color2', '#' . $pComment->getFillColor()->getRGB()); + $objWriter->writeAttribute('color2', '#' . $pComment->getFillColor()->getRGB()); $objWriter->endElement(); // v:shadow $objWriter->startElement('v:shadow'); - $objWriter->writeAttribute('on', 't'); - $objWriter->writeAttribute('color', 'black'); - $objWriter->writeAttribute('obscured', 't'); + $objWriter->writeAttribute('on', 't'); + $objWriter->writeAttribute('color', 'black'); + $objWriter->writeAttribute('obscured', 't'); $objWriter->endElement(); // v:path diff --git a/Classes/PHPExcel/Writer/Excel2007/ContentTypes.php b/Classes/PHPExcel/Writer/Excel2007/ContentTypes.php index 2ecf9320..ef572133 100644 --- a/Classes/PHPExcel/Writer/Excel2007/ContentTypes.php +++ b/Classes/PHPExcel/Writer/Excel2007/ContentTypes.php @@ -60,125 +60,126 @@ class PHPExcel_Writer_Excel2007_ContentTypes extends PHPExcel_Writer_Excel2007_W $objWriter->startElement('Types'); $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/content-types'); - // Theme - $this->_writeOverrideContentType($objWriter, '/xl/theme/theme1.xml', 'application/vnd.openxmlformats-officedocument.theme+xml'); + // Theme + $this->_writeOverrideContentType($objWriter, '/xl/theme/theme1.xml', 'application/vnd.openxmlformats-officedocument.theme+xml'); - // Styles - $this->_writeOverrideContentType($objWriter, '/xl/styles.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml'); + // Styles + $this->_writeOverrideContentType($objWriter, '/xl/styles.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml'); - // Rels - $this->_writeDefaultContentType($objWriter, 'rels', 'application/vnd.openxmlformats-package.relationships+xml'); + // Rels + $this->_writeDefaultContentType($objWriter, 'rels', 'application/vnd.openxmlformats-package.relationships+xml'); - // XML - $this->_writeDefaultContentType($objWriter, 'xml', 'application/xml'); + // XML + $this->_writeDefaultContentType($objWriter, 'xml', 'application/xml'); - // VML - $this->_writeDefaultContentType($objWriter, 'vml', 'application/vnd.openxmlformats-officedocument.vmlDrawing'); + // VML + $this->_writeDefaultContentType($objWriter, 'vml', 'application/vnd.openxmlformats-officedocument.vmlDrawing'); - // Workbook - if ($pPHPExcel->hasMacros()) { //Macros in workbook ? - // Yes : not standard content but "macroEnabled" - $this->_writeOverrideContentType($objWriter, '/xl/workbook.xml', 'application/vnd.ms-excel.sheet.macroEnabled.main+xml'); - //... and define a new type for the VBA project - $this->_writeDefaultContentType($objWriter, 'bin', 'application/vnd.ms-office.vbaProject'); - if ($pPHPExcel->hasMacrosCertificate()) {// signed macros ? - // Yes : add needed information - $this->_writeOverrideContentType($objWriter, '/xl/vbaProjectSignature.bin', 'application/vnd.ms-office.vbaProjectSignature'); + // Workbook + if ($pPHPExcel->hasMacros()) { //Macros in workbook ? + // Yes : not standard content but "macroEnabled" + $this->_writeOverrideContentType($objWriter, '/xl/workbook.xml', 'application/vnd.ms-excel.sheet.macroEnabled.main+xml'); + //... and define a new type for the VBA project + $this->_writeDefaultContentType($objWriter, 'bin', 'application/vnd.ms-office.vbaProject'); + if ($pPHPExcel->hasMacrosCertificate()) {// signed macros ? + // Yes : add needed information + $this->_writeOverrideContentType($objWriter, '/xl/vbaProjectSignature.bin', 'application/vnd.ms-office.vbaProjectSignature'); + } + } else {// no macros in workbook, so standard type + $this->_writeOverrideContentType($objWriter, '/xl/workbook.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml'); + } + + // DocProps + $this->_writeOverrideContentType($objWriter, '/docProps/app.xml', 'application/vnd.openxmlformats-officedocument.extended-properties+xml'); + + $this->_writeOverrideContentType($objWriter, '/docProps/core.xml', 'application/vnd.openxmlformats-package.core-properties+xml'); + + $customPropertyList = $pPHPExcel->getProperties()->getCustomProperties(); + if (!empty($customPropertyList)) { + $this->_writeOverrideContentType($objWriter, '/docProps/custom.xml', 'application/vnd.openxmlformats-officedocument.custom-properties+xml'); + } + + // Worksheets + $sheetCount = $pPHPExcel->getSheetCount(); + for ($i = 0; $i < $sheetCount; ++$i) { + $this->_writeOverrideContentType($objWriter, '/xl/worksheets/sheet' . ($i + 1) . '.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml'); + } + + // Shared strings + $this->_writeOverrideContentType($objWriter, '/xl/sharedStrings.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml'); + + // Add worksheet relationship content types + $chart = 1; + for ($i = 0; $i < $sheetCount; ++$i) { + $drawings = $pPHPExcel->getSheet($i)->getDrawingCollection(); + $drawingCount = count($drawings); + $chartCount = ($includeCharts) ? $pPHPExcel->getSheet($i)->getChartCount() : 0; + + // We need a drawing relationship for the worksheet if we have either drawings or charts + if (($drawingCount > 0) || ($chartCount > 0)) { + $this->_writeOverrideContentType($objWriter, '/xl/drawings/drawing' . ($i + 1) . '.xml', 'application/vnd.openxmlformats-officedocument.drawing+xml'); + } + + // If we have charts, then we need a chart relationship for every individual chart + if ($chartCount > 0) { + for ($c = 0; $c < $chartCount; ++$c) { + $this->_writeOverrideContentType($objWriter, '/xl/charts/chart' . $chart++ . '.xml', 'application/vnd.openxmlformats-officedocument.drawingml.chart+xml'); } - } else {// no macros in workbook, so standard type - $this->_writeOverrideContentType($objWriter, '/xl/workbook.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml'); + } + } + + // Comments + for ($i = 0; $i < $sheetCount; ++$i) { + if (count($pPHPExcel->getSheet($i)->getComments()) > 0) { + $this->_writeOverrideContentType($objWriter, '/xl/comments' . ($i + 1) . '.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml'); + } + } + + // Add media content-types + $aMediaContentTypes = array(); + $mediaCount = $this->getParentWriter()->getDrawingHashTable()->count(); + for ($i = 0; $i < $mediaCount; ++$i) { + $extension = ''; + $mimeType = ''; + + if ($this->getParentWriter()->getDrawingHashTable()->getByIndex($i) instanceof PHPExcel_Worksheet_Drawing) { + $extension = strtolower($this->getParentWriter()->getDrawingHashTable()->getByIndex($i)->getExtension()); + $mimeType = $this->_getImageMimeType( $this->getParentWriter()->getDrawingHashTable()->getByIndex($i)->getPath()); + } else if ($this->getParentWriter()->getDrawingHashTable()->getByIndex($i) instanceof PHPExcel_Worksheet_MemoryDrawing) { + $extension = strtolower($this->getParentWriter()->getDrawingHashTable()->getByIndex($i)->getMimeType()); + $extension = explode('/', $extension); + $extension = $extension[1]; + + $mimeType = $this->getParentWriter()->getDrawingHashTable()->getByIndex($i)->getMimeType(); } - // DocProps - $this->_writeOverrideContentType($objWriter, '/docProps/app.xml', 'application/vnd.openxmlformats-officedocument.extended-properties+xml'); + if (!isset( $aMediaContentTypes[$extension])) { + $aMediaContentTypes[$extension] = $mimeType; - $this->_writeOverrideContentType($objWriter, '/docProps/core.xml', 'application/vnd.openxmlformats-package.core-properties+xml'); - - $customPropertyList = $pPHPExcel->getProperties()->getCustomProperties(); - if (!empty($customPropertyList)) { - $this->_writeOverrideContentType($objWriter, '/docProps/custom.xml', 'application/vnd.openxmlformats-officedocument.custom-properties+xml'); + $this->_writeDefaultContentType($objWriter, $extension, $mimeType); } - - // Worksheets - $sheetCount = $pPHPExcel->getSheetCount(); - for ($i = 0; $i < $sheetCount; ++$i) { - $this->_writeOverrideContentType($objWriter, '/xl/worksheets/sheet' . ($i + 1) . '.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml'); + } + if ($pPHPExcel->hasRibbonBinObjects()) { + // Some additional objects in the ribbon ? + // we need to write "Extension" but not already write for media content + $tabRibbonTypes=array_diff($pPHPExcel->getRibbonBinObjects('types'), array_keys($aMediaContentTypes)); + foreach ($tabRibbonTypes as $aRibbonType) { + $mimeType='image/.'.$aRibbonType;//we wrote $mimeType like customUI Editor + $this->_writeDefaultContentType($objWriter, $aRibbonType, $mimeType); } + } + $sheetCount = $pPHPExcel->getSheetCount(); + for ($i = 0; $i < $sheetCount; ++$i) { + if (count($pPHPExcel->getSheet()->getHeaderFooter()->getImages()) > 0) { + foreach ($pPHPExcel->getSheet()->getHeaderFooter()->getImages() as $image) { + if (!isset( $aMediaContentTypes[strtolower($image->getExtension())])) { + $aMediaContentTypes[strtolower($image->getExtension())] = $this->_getImageMimeType($image->getPath()); - // Shared strings - $this->_writeOverrideContentType($objWriter, '/xl/sharedStrings.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml'); - - // Add worksheet relationship content types - $chart = 1; - for ($i = 0; $i < $sheetCount; ++$i) { - $drawings = $pPHPExcel->getSheet($i)->getDrawingCollection(); - $drawingCount = count($drawings); - $chartCount = ($includeCharts) ? $pPHPExcel->getSheet($i)->getChartCount() : 0; - - // We need a drawing relationship for the worksheet if we have either drawings or charts - if (($drawingCount > 0) || ($chartCount > 0)) { - $this->_writeOverrideContentType($objWriter, '/xl/drawings/drawing' . ($i + 1) . '.xml', 'application/vnd.openxmlformats-officedocument.drawing+xml'); - } - - // If we have charts, then we need a chart relationship for every individual chart - if ($chartCount > 0) { - for ($c = 0; $c < $chartCount; ++$c) { - $this->_writeOverrideContentType($objWriter, '/xl/charts/chart' . $chart++ . '.xml', 'application/vnd.openxmlformats-officedocument.drawingml.chart+xml'); - } - } - } - - // Comments - for ($i = 0; $i < $sheetCount; ++$i) { - if (count($pPHPExcel->getSheet($i)->getComments()) > 0) { - $this->_writeOverrideContentType($objWriter, '/xl/comments' . ($i + 1) . '.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml'); - } - } - - // Add media content-types - $aMediaContentTypes = array(); - $mediaCount = $this->getParentWriter()->getDrawingHashTable()->count(); - for ($i = 0; $i < $mediaCount; ++$i) { - $extension = ''; - $mimeType = ''; - - if ($this->getParentWriter()->getDrawingHashTable()->getByIndex($i) instanceof PHPExcel_Worksheet_Drawing) { - $extension = strtolower($this->getParentWriter()->getDrawingHashTable()->getByIndex($i)->getExtension()); - $mimeType = $this->_getImageMimeType( $this->getParentWriter()->getDrawingHashTable()->getByIndex($i)->getPath() ); - } else if ($this->getParentWriter()->getDrawingHashTable()->getByIndex($i) instanceof PHPExcel_Worksheet_MemoryDrawing) { - $extension = strtolower($this->getParentWriter()->getDrawingHashTable()->getByIndex($i)->getMimeType()); - $extension = explode('/', $extension); - $extension = $extension[1]; - - $mimeType = $this->getParentWriter()->getDrawingHashTable()->getByIndex($i)->getMimeType(); - } - - if (!isset( $aMediaContentTypes[$extension]) ) { - $aMediaContentTypes[$extension] = $mimeType; - - $this->_writeDefaultContentType($objWriter, $extension, $mimeType); - } - } - if ($pPHPExcel->hasRibbonBinObjects()) {//Some additional objects in the ribbon ? - //we need to write "Extension" but not already write for media content - $tabRibbonTypes=array_diff($pPHPExcel->getRibbonBinObjects('types'), array_keys($aMediaContentTypes)); - foreach ($tabRibbonTypes as $aRibbonType) { - $mimeType='image/.'.$aRibbonType;//we wrote $mimeType like customUI Editor - $this->_writeDefaultContentType($objWriter, $aRibbonType, $mimeType); - } - } - $sheetCount = $pPHPExcel->getSheetCount(); - for ($i = 0; $i < $sheetCount; ++$i) { - if (count($pPHPExcel->getSheet()->getHeaderFooter()->getImages()) > 0) { - foreach ($pPHPExcel->getSheet()->getHeaderFooter()->getImages() as $image) { - if (!isset( $aMediaContentTypes[strtolower($image->getExtension())])) { - $aMediaContentTypes[strtolower($image->getExtension())] = $this->_getImageMimeType($image->getPath()); - - $this->_writeDefaultContentType($objWriter, strtolower($image->getExtension()), $aMediaContentTypes[strtolower($image->getExtension())]); - } + $this->_writeDefaultContentType($objWriter, strtolower($image->getExtension()), $aMediaContentTypes[strtolower($image->getExtension())]); } } } + } $objWriter->endElement(); diff --git a/Classes/PHPExcel/Writer/Excel2007/Worksheet.php b/Classes/PHPExcel/Writer/Excel2007/Worksheet.php index 176e44b1..cb153f8a 100644 --- a/Classes/PHPExcel/Writer/Excel2007/Worksheet.php +++ b/Classes/PHPExcel/Writer/Excel2007/Worksheet.php @@ -231,7 +231,7 @@ class PHPExcel_Writer_Excel2007_Worksheet extends PHPExcel_Writer_Excel2007_Writ // View Layout Type if ($pSheet->getSheetView()->getView() !== PHPExcel_Worksheet_SheetView::SHEETVIEW_NORMAL) { - $objWriter->writeAttribute('view', $pSheet->getSheetView()->getView()); + $objWriter->writeAttribute('view', $pSheet->getSheetView()->getView()); } // Gridlines @@ -294,15 +294,15 @@ class PHPExcel_Writer_Excel2007_Worksheet extends PHPExcel_Writer_Excel2007_Writ // Selection // if ($pane != '') { - // Only need to write selection element if we have a split pane - // We cheat a little by over-riding the active cell selection, setting it to the split cell - $objWriter->startElement('selection'); - if ($pane != '') { - $objWriter->writeAttribute('pane', $pane); - } - $objWriter->writeAttribute('activeCell', $activeCell); - $objWriter->writeAttribute('sqref', $activeCell); - $objWriter->endElement(); + // Only need to write selection element if we have a split pane + // We cheat a little by over-riding the active cell selection, setting it to the split cell + $objWriter->startElement('selection'); + if ($pane != '') { + $objWriter->writeAttribute('pane', $pane); + } + $objWriter->writeAttribute('activeCell', $activeCell); + $objWriter->writeAttribute('sqref', $activeCell); + $objWriter->endElement(); // } $objWriter->endElement(); @@ -760,7 +760,7 @@ class PHPExcel_Writer_Excel2007_Worksheet extends PHPExcel_Writer_Excel2007_Writ $range = PHPExcel_Cell::splitRange($autoFilterRange); $range = $range[0]; // Strip any worksheet ref - if (strpos($range[0],'!') !== false) { + if (strpos($range[0], '!') !== false) { list($ws, $range[0]) = explode('!', $range[0]); } $range = implode(':', $range); @@ -785,7 +785,7 @@ class PHPExcel_Writer_Excel2007_Worksheet extends PHPExcel_Writer_Excel2007_Writ ($rule->getOperator() === PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_EQUAL) && ($rule->getValue() === '')) { // Filter rule for Blanks - $objWriter->writeAttribute('blank', 1); + $objWriter->writeAttribute('blank', 1); } elseif ($rule->getRuleType() === PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMICFILTER) { // Dynamic Filter Rule $objWriter->writeAttribute('type', $rule->getGrouping()); @@ -812,7 +812,9 @@ class PHPExcel_Writer_Excel2007_Worksheet extends PHPExcel_Writer_Excel2007_Writ if ($rule->getRuleType() === PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP) { // Date Group filters foreach ($rule->getValue() as $key => $value) { - if ($value > '') $objWriter->writeAttribute($key, $value); + if ($value > '') { + $objWriter->writeAttribute($key, $value); + } } $objWriter->writeAttribute('dateTimeGrouping', $rule->getGrouping()); } else { From 121eccd4c8a5b8f43dfc62a2ad7d4200eec0a445 Mon Sep 17 00:00:00 2001 From: Progi1984 Date: Fri, 15 May 2015 13:36:15 +0200 Subject: [PATCH 4/5] PSR-2 : Fixes --- Classes/PHPExcel/Worksheet/AutoFilter.php | 194 ++++++++---------- .../PHPExcel/Worksheet/AutoFilter/Column.php | 4 +- .../Worksheet/AutoFilter/Column/Rule.php | 2 +- .../PHPExcel/Worksheet/ColumnDimension.php | 1 - Classes/PHPExcel/Worksheet/Drawing.php | 23 ++- Classes/PHPExcel/Worksheet/Drawing/Shadow.php | 64 +++--- Classes/PHPExcel/Worksheet/HeaderFooter.php | 99 ++++++--- Classes/PHPExcel/Worksheet/MemoryDrawing.php | 3 +- Classes/PHPExcel/Worksheet/PageSetup.php | 101 +++++---- Classes/PHPExcel/Writer/Excel2007/Chart.php | 2 +- .../Writer/Excel2007/ContentTypes.php | 2 +- 11 files changed, 283 insertions(+), 212 deletions(-) diff --git a/Classes/PHPExcel/Worksheet/AutoFilter.php b/Classes/PHPExcel/Worksheet/AutoFilter.php index 325c906d..36407e6e 100644 --- a/Classes/PHPExcel/Worksheet/AutoFilter.php +++ b/Classes/PHPExcel/Worksheet/AutoFilter.php @@ -40,7 +40,7 @@ class PHPExcel_Worksheet_AutoFilter * * @var PHPExcel_Worksheet */ - private $_workSheet = NULL; + private $_workSheet = null; /** @@ -65,7 +65,7 @@ class PHPExcel_Worksheet_AutoFilter * @param string $pRange Cell range (i.e. A1:E10) * @param PHPExcel_Worksheet $pSheet */ - public function __construct($pRange = '', PHPExcel_Worksheet $pSheet = NULL) + public function __construct($pRange = '', PHPExcel_Worksheet $pSheet = null) { $this->_range = $pRange; $this->_workSheet = $pSheet; @@ -76,7 +76,8 @@ class PHPExcel_Worksheet_AutoFilter * * @return PHPExcel_Worksheet */ - public function getParent() { + public function getParent() + { return $this->_workSheet; } @@ -86,7 +87,8 @@ class PHPExcel_Worksheet_AutoFilter * @param PHPExcel_Worksheet $pSheet * @return PHPExcel_Worksheet_AutoFilter */ - public function setParent(PHPExcel_Worksheet $pSheet = NULL) { + public function setParent(PHPExcel_Worksheet $pSheet = null) + { $this->_workSheet = $pSheet; return $this; @@ -97,7 +99,8 @@ class PHPExcel_Worksheet_AutoFilter * * @return string */ - public function getRange() { + public function getRange() + { return $this->_range; } @@ -108,14 +111,15 @@ class PHPExcel_Worksheet_AutoFilter * @throws PHPExcel_Exception * @return PHPExcel_Worksheet_AutoFilter */ - public function setRange($pRange = '') { + public function setRange($pRange = '') + { // Uppercase coordinate $cellAddress = explode('!',strtoupper($pRange)); if (count($cellAddress) > 1) { list($worksheet, $pRange) = $cellAddress; } - if (strpos($pRange,':') !== FALSE) { + if (strpos($pRange, ':') !== false) { $this->_range = $pRange; } elseif (empty($pRange)) { $this->_range = ''; @@ -146,7 +150,8 @@ class PHPExcel_Worksheet_AutoFilter * @throws PHPExcel_Exception * @return array of PHPExcel_Worksheet_AutoFilter_Column */ - public function getColumns() { + public function getColumns() + { return $this->_columns; } @@ -157,7 +162,8 @@ class PHPExcel_Worksheet_AutoFilter * @throws PHPExcel_Exception * @return integer The column offset within the autofilter range */ - public function testColumnInRange($column) { + public function testColumnInRange($column) + { if (empty($this->_range)) { throw new PHPExcel_Exception("No autofilter range is defined."); } @@ -178,7 +184,8 @@ class PHPExcel_Worksheet_AutoFilter * @throws PHPExcel_Exception * @return integer The offset of the specified column within the autofilter range */ - public function getColumnOffset($pColumn) { + public function getColumnOffset($pColumn) + { return $this->testColumnInRange($pColumn); } @@ -189,7 +196,8 @@ class PHPExcel_Worksheet_AutoFilter * @throws PHPExcel_Exception * @return PHPExcel_Worksheet_AutoFilter_Column */ - public function getColumn($pColumn) { + public function getColumn($pColumn) + { $this->testColumnInRange($pColumn); if (!isset($this->_columns[$pColumn])) { @@ -206,7 +214,8 @@ class PHPExcel_Worksheet_AutoFilter * @throws PHPExcel_Exception * @return PHPExcel_Worksheet_AutoFilter_Column */ - public function getColumnByOffset($pColumnOffset = 0) { + public function getColumnByOffset($pColumnOffset = 0) + { list($rangeStart, $rangeEnd) = PHPExcel_Cell::rangeBoundaries($this->_range); $pColumn = PHPExcel_Cell::stringFromColumnIndex($rangeStart[0] + $pColumnOffset - 1); @@ -250,7 +259,8 @@ class PHPExcel_Worksheet_AutoFilter * @throws PHPExcel_Exception * @return PHPExcel_Worksheet_AutoFilter */ - public function clearColumn($pColumn) { + public function clearColumn($pColumn) + { $this->testColumnInRange($pColumn); if (isset($this->_columns[$pColumn])) { @@ -271,11 +281,12 @@ class PHPExcel_Worksheet_AutoFilter * @param string $toColumn Column name (e.g. B) * @return PHPExcel_Worksheet_AutoFilter */ - public function shiftColumn($fromColumn=NULL, $toColumn=NULL) { + public function shiftColumn($fromColumn = null, $toColumn = null) + { $fromColumn = strtoupper($fromColumn); $toColumn = strtoupper($toColumn); - if (($fromColumn !== NULL) && (isset($this->_columns[$fromColumn])) && ($toColumn !== NULL)) { + if (($fromColumn !== null) && (isset($this->_columns[$fromColumn])) && ($toColumn !== null)) { $this->_columns[$fromColumn]->setParent(); $this->_columns[$fromColumn]->setColumnIndex($toColumn); $this->_columns[$toColumn] = $this->_columns[$fromColumn]; @@ -300,7 +311,7 @@ class PHPExcel_Worksheet_AutoFilter { $dataSetValues = $dataSet['filterValues']; $blanks = $dataSet['blanks']; - if (($cellValue == '') || ($cellValue === NULL)) { + if (($cellValue == '') || ($cellValue === null)) { return $blanks; } return in_array($cellValue, $dataSetValues); @@ -317,7 +328,7 @@ class PHPExcel_Worksheet_AutoFilter { $dateSet = $dataSet['filterValues']; $blanks = $dataSet['blanks']; - if (($cellValue == '') || ($cellValue === NULL)) { + if (($cellValue == '') || ($cellValue === null)) { return $blanks; } @@ -338,12 +349,12 @@ class PHPExcel_Worksheet_AutoFilter } foreach ($dateSet as $dateValue) { // Use of substr to extract value at the appropriate group level - if (substr($dtVal,0,strlen($dateValue)) == $dateValue) - return TRUE; + if (substr($dtVal,0,strlen($dateValue)) == $dateValue) { + return true; + } } } - - return FALSE; + return false; } /** @@ -357,12 +368,12 @@ class PHPExcel_Worksheet_AutoFilter { $dataSet = $ruleSet['filterRules']; $join = $ruleSet['join']; - $customRuleForBlanks = isset($ruleSet['customRuleForBlanks']) ? $ruleSet['customRuleForBlanks'] : FALSE; + $customRuleForBlanks = isset($ruleSet['customRuleForBlanks']) ? $ruleSet['customRuleForBlanks'] : false; if (!$customRuleForBlanks) { // Blank cells are always ignored, so return a FALSE - if (($cellValue == '') || ($cellValue === NULL)) { - return FALSE; + if (($cellValue == '') || ($cellValue === null)) { + return false; } } $returnVal = ($join == PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_COLUMN_JOIN_AND); @@ -392,13 +403,13 @@ class PHPExcel_Worksheet_AutoFilter } elseif ($rule['value'] == '') { switch ($rule['operator']) { case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_EQUAL : - $retVal = (($cellValue == '') || ($cellValue === NULL)); + $retVal = (($cellValue == '') || ($cellValue === null)); break; case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_NOTEQUAL : - $retVal = (($cellValue != '') && ($cellValue !== NULL)); + $retVal = (($cellValue != '') && ($cellValue !== null)); break; default : - $retVal = TRUE; + $retVal = true; break; } } else { @@ -411,8 +422,9 @@ class PHPExcel_Worksheet_AutoFilter $returnVal = $returnVal || $retVal; // Break as soon as we have a TRUE match for OR joins, // to avoid unnecessary additional code execution - if ($returnVal) + if ($returnVal) { return $returnVal; + } break; case PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_COLUMN_JOIN_AND : $returnVal = $returnVal && $retVal; @@ -433,18 +445,18 @@ class PHPExcel_Worksheet_AutoFilter private static function _filterTestInPeriodDateSet($cellValue, $monthSet) { // Blank cells are always ignored, so return a FALSE - if (($cellValue == '') || ($cellValue === NULL)) { - return FALSE; + if (($cellValue == '') || ($cellValue === null)) { + return false; } if (is_numeric($cellValue)) { $dateValue = date('m',PHPExcel_Shared_Date::ExcelToPHP($cellValue)); if (in_array($dateValue, $monthSet)) { - return TRUE; + return true; } } - return FALSE; + return false; } /** @@ -467,7 +479,7 @@ class PHPExcel_Worksheet_AutoFilter { $rDateType = PHPExcel_Calculation_Functions::getReturnDateType(); PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC); - $val = $maxVal = NULL; + $val = $maxVal = null; $ruleValues = array(); $baseDate = PHPExcel_Calculation_DateTime::DATENOW(); @@ -480,22 +492,22 @@ class PHPExcel_Worksheet_AutoFilter $baseDate = strtotime('-7 days', $baseDate); break; case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTMONTH : - $baseDate = strtotime('-1 month',gmmktime(0,0,0,1,date('m', $baseDate),date('Y', $baseDate))); + $baseDate = strtotime('-1 month',gmmktime(0, 0, 0, 1, date('m', $baseDate), date('Y', $baseDate))); break; case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTMONTH : - $baseDate = strtotime('+1 month',gmmktime(0,0,0,1,date('m', $baseDate),date('Y', $baseDate))); + $baseDate = strtotime('+1 month',gmmktime(0, 0, 0, 1, date('m', $baseDate), date('Y', $baseDate))); break; case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTQUARTER : - $baseDate = strtotime('-3 month',gmmktime(0,0,0,1,date('m', $baseDate),date('Y', $baseDate))); + $baseDate = strtotime('-3 month',gmmktime(0, 0, 0, 1, date('m', $baseDate), date('Y', $baseDate))); break; case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTQUARTER : - $baseDate = strtotime('+3 month',gmmktime(0,0,0,1,date('m', $baseDate),date('Y', $baseDate))); + $baseDate = strtotime('+3 month',gmmktime(0, 0, 0, 1, date('m', $baseDate), date('Y', $baseDate))); break; case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTYEAR : - $baseDate = strtotime('-1 year',gmmktime(0,0,0,1,date('m', $baseDate),date('Y', $baseDate))); + $baseDate = strtotime('-1 year',gmmktime(0, 0, 0, 1, date('m', $baseDate), date('Y', $baseDate))); break; case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTYEAR : - $baseDate = strtotime('+1 year',gmmktime(0,0,0,1,date('m', $baseDate),date('Y', $baseDate))); + $baseDate = strtotime('+1 year',gmmktime(0, 0, 0, 1, date('m', $baseDate), date('Y', $baseDate))); break; } @@ -508,30 +520,30 @@ class PHPExcel_Worksheet_AutoFilter break; case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_YEARTODATE : $maxVal = (int) PHPExcel_Shared_Date::PHPtoExcel(strtotime('+1 day', $baseDate)); - $val = (int) PHPExcel_Shared_Date::PHPToExcel(gmmktime(0,0,0,1,1,date('Y', $baseDate))); + $val = (int) PHPExcel_Shared_Date::PHPToExcel(gmmktime(0, 0, 0, 1, 1, date('Y', $baseDate))); break; case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISYEAR : case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTYEAR : case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTYEAR : - $maxVal = (int) PHPExcel_Shared_Date::PHPToExcel(gmmktime(0,0,0,31,12,date('Y', $baseDate))); + $maxVal = (int) PHPExcel_Shared_Date::PHPToExcel(gmmktime(0, 0, 0, 31, 12, date('Y', $baseDate))); ++$maxVal; - $val = (int) PHPExcel_Shared_Date::PHPToExcel(gmmktime(0,0,0,1,1,date('Y', $baseDate))); + $val = (int) PHPExcel_Shared_Date::PHPToExcel(gmmktime(0, 0, 0, 1, 1, date('Y', $baseDate))); break; case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISQUARTER : case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTQUARTER : case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTQUARTER : $thisMonth = date('m', $baseDate); $thisQuarter = floor(--$thisMonth / 3); - $maxVal = (int) PHPExcel_Shared_Date::PHPtoExcel(gmmktime(0,0,0,date('t', $baseDate),(1+$thisQuarter)*3,date('Y', $baseDate))); + $maxVal = (int) PHPExcel_Shared_Date::PHPtoExcel(gmmktime(0, 0, 0, date('t', $baseDate), (1+$thisQuarter)*3, date('Y', $baseDate))); ++$maxVal; - $val = (int) PHPExcel_Shared_Date::PHPToExcel(gmmktime(0,0,0,1,1+$thisQuarter*3,date('Y', $baseDate))); + $val = (int) PHPExcel_Shared_Date::PHPToExcel(gmmktime(0, 0, 0, 1, 1+$thisQuarter*3, date('Y', $baseDate))); break; case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISMONTH : case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTMONTH : case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTMONTH : - $maxVal = (int) PHPExcel_Shared_Date::PHPtoExcel(gmmktime(0,0,0,date('t', $baseDate),date('m', $baseDate),date('Y', $baseDate))); + $maxVal = (int) PHPExcel_Shared_Date::PHPtoExcel(gmmktime(0, 0, 0, date('t', $baseDate), date('m', $baseDate), date('Y', $baseDate))); ++$maxVal; - $val = (int) PHPExcel_Shared_Date::PHPToExcel(gmmktime(0,0,0,1,date('m', $baseDate),date('Y', $baseDate))); + $val = (int) PHPExcel_Shared_Date::PHPToExcel(gmmktime(0, 0, 0, 1, date('m', $baseDate), date('Y', $baseDate))); break; case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISWEEK : case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTWEEK : @@ -555,33 +567,20 @@ class PHPExcel_Worksheet_AutoFilter } // Set the filter column rule attributes ready for writing - $filterColumn->setAttributes(array( 'val' => $val, - 'maxVal' => $maxVal - ) - ); + $filterColumn->setAttributes(array('val' => $val, 'maxVal' => $maxVal)); // Set the rules for identifying rows for hide/show - $ruleValues[] = array( 'operator' => PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL, - 'value' => $val - ); - $ruleValues[] = array( 'operator' => PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_LESSTHAN, - 'value' => $maxVal - ); + $ruleValues[] = array('operator' => PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL, 'value' => $val); + $ruleValues[] = array('operator' => PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_LESSTHAN, 'value' => $maxVal); PHPExcel_Calculation_Functions::setReturnDateType($rDateType); - return array( - 'method' => '_filterTestInCustomDataSet', - 'arguments' => array( 'filterRules' => $ruleValues, - 'join' => PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_COLUMN_JOIN_AND - ) - ); + return array('method' => '_filterTestInCustomDataSet', 'arguments' => array('filterRules' => $ruleValues, 'join' => PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_COLUMN_JOIN_AND)); } - private function _calculateTopTenValue($columnID, $startRow, $endRow, $ruleType, $ruleValue) { + private function _calculateTopTenValue($columnID, $startRow, $endRow, $ruleType, $ruleValue) + { $range = $columnID.$startRow.':'.$columnID.$endRow; - $dataValues = PHPExcel_Calculation_Functions::flattenArray( - $this->_workSheet->rangeToArray($range,NULL,TRUE,FALSE) - ); + $dataValues = PHPExcel_Calculation_Functions::flattenArray($this->_workSheet->rangeToArray($range, null, true, false)); $dataValues = array_filter($dataValues); if ($ruleType == PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP) { @@ -605,7 +604,7 @@ class PHPExcel_Worksheet_AutoFilter // The heading row should always be visible // echo 'AutoFilter Heading Row ', $rangeStart[1],' is always SHOWN',PHP_EOL; - $this->_workSheet->getRowDimension($rangeStart[1])->setVisible(TRUE); + $this->_workSheet->getRowDimension($rangeStart[1])->setVisible(true); $columnFilterTests = array(); foreach ($this->_columns as $columnID => $filterColumn) { @@ -619,17 +618,15 @@ class PHPExcel_Worksheet_AutoFilter $ruleValues[] = $rule->getValue(); } // Test if we want to include blanks in our filter criteria - $blanks = FALSE; + $blanks = false; $ruleDataSet = array_filter($ruleValues); if (count($ruleValues) != count($ruleDataSet)) - $blanks = TRUE; + $blanks = true; if ($ruleType == PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_FILTER) { // Filter on absolute values $columnFilterTests[$columnID] = array( 'method' => '_filterTestInSimpleDataSet', - 'arguments' => array( 'filterValues' => $ruleDataSet, - 'blanks' => $blanks - ) + 'arguments' => array('filterValues' => $ruleDataSet, 'blanks' => $blanks) ); } else { // Filter on date group values @@ -669,14 +666,12 @@ class PHPExcel_Worksheet_AutoFilter $arguments['dateTime'] = array_filter($arguments['dateTime']); $columnFilterTests[$columnID] = array( 'method' => '_filterTestInDateGroupSet', - 'arguments' => array( 'filterValues' => $arguments, - 'blanks' => $blanks - ) + 'arguments' => array('filterValues' => $arguments, 'blanks' => $blanks) ); } break; case PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_CUSTOMFILTER : - $customRuleForBlanks = FALSE; + $customRuleForBlanks = false; $ruleValues = array(); // Build a list of the filter value selections foreach ($rules as $rule) { @@ -687,21 +682,16 @@ class PHPExcel_Worksheet_AutoFilter $ruleValue = preg_quote($ruleValue); $ruleValue = str_replace(self::$_fromReplace,self::$_toReplace, $ruleValue); if (trim($ruleValue) == '') { - $customRuleForBlanks = TRUE; + $customRuleForBlanks = true; $ruleValue = trim($ruleValue); } } - $ruleValues[] = array( 'operator' => $rule->getOperator(), - 'value' => $ruleValue - ); + $ruleValues[] = array('operator' => $rule->getOperator(), 'value' => $ruleValue); } $join = $filterColumn->getJoin(); $columnFilterTests[$columnID] = array( 'method' => '_filterTestInCustomDataSet', - 'arguments' => array( 'filterRules' => $ruleValues, - 'join' => $join, - 'customRuleForBlanks' => $customRuleForBlanks - ) + 'arguments' => array('filterRules' => $ruleValues, 'join' => $join, 'customRuleForBlanks' => $customRuleForBlanks) ); break; case PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_DYNAMICFILTER : @@ -714,19 +704,17 @@ class PHPExcel_Worksheet_AutoFilter // Number (Average) based // Calculate the average $averageFormula = '=AVERAGE('.$columnID.($rangeStart[1]+1).':'.$columnID.$rangeEnd[1].')'; - $average = PHPExcel_Calculation::getInstance()->calculateFormula($averageFormula,NULL, $this->_workSheet->getCell('A1')); + $average = PHPExcel_Calculation::getInstance()->calculateFormula($averageFormula,null, $this->_workSheet->getCell('A1')); // Set above/below rule based on greaterThan or LessTan $operator = ($dynamicRuleType === PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_ABOVEAVERAGE) ? PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_GREATERTHAN : PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_LESSTHAN; - $ruleValues[] = array( 'operator' => $operator, + $ruleValues[] = array('operator' => $operator, 'value' => $average ); $columnFilterTests[$columnID] = array( 'method' => '_filterTestInCustomDataSet', - 'arguments' => array( 'filterRules' => $ruleValues, - 'join' => PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_COLUMN_JOIN_OR - ) + 'arguments' => array('filterRules' => $ruleValues, 'join' => PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_COLUMN_JOIN_OR) ); } else { // Date based @@ -774,18 +762,12 @@ class PHPExcel_Worksheet_AutoFilter $operator = ($toptenRuleType == PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP) ? PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL : PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_LESSTHANOREQUAL; - $ruleValues[] = array( 'operator' => $operator, - 'value' => $maxVal - ); + $ruleValues[] = array('operator' => $operator, 'value' => $maxVal); $columnFilterTests[$columnID] = array( 'method' => '_filterTestInCustomDataSet', - 'arguments' => array( 'filterRules' => $ruleValues, - 'join' => PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_COLUMN_JOIN_OR - ) - ); - $filterColumn->setAttributes( - array('maxVal' => $maxVal) + 'arguments' => array('filterRules' => $ruleValues, 'join' => PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_COLUMN_JOIN_OR) ); + $filterColumn->setAttributes(array('maxVal' => $maxVal)); break; } } @@ -796,7 +778,7 @@ class PHPExcel_Worksheet_AutoFilter // Execute the column tests for each row in the autoFilter range to determine show/hide, for ($row = $rangeStart[1]+1; $row <= $rangeEnd[1]; ++$row) { // echo 'Testing Row = ', $row,PHP_EOL; - $result = TRUE; + $result = true; foreach ($columnFilterTests as $columnID => $columnFilterTest) { // echo 'Testing cell ', $columnID.$row,PHP_EOL; $cellValue = $this->_workSheet->getCell($columnID.$row)->getCalculatedValue(); @@ -805,15 +787,13 @@ class PHPExcel_Worksheet_AutoFilter $result = $result && call_user_func_array( array('PHPExcel_Worksheet_AutoFilter', $columnFilterTest['method']), - array( - $cellValue, - $columnFilterTest['arguments'] - ) + array($cellValue, $columnFilterTest['arguments']) ); // echo (($result) ? 'VALID' : 'INVALID'),PHP_EOL; // If filter test has resulted in FALSE, exit the loop straightaway rather than running any more tests - if (!$result) + if (!$result) { break; + } } // Set show/hide for the row based on the result of the autoFilter result // echo (($result) ? 'SHOW' : 'HIDE'),PHP_EOL; @@ -827,13 +807,14 @@ class PHPExcel_Worksheet_AutoFilter /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ - public function __clone() { + public function __clone() + { $vars = get_object_vars($this); foreach ($vars as $key => $value) { if (is_object($value)) { if ($key == '_workSheet') { // Detach from worksheet - $this->{$key} = NULL; + $this->{$key} = null; } else { $this->{$key} = clone $value; } @@ -858,5 +839,4 @@ class PHPExcel_Worksheet_AutoFilter public function __toString() { return (string) $this->_range; } - } diff --git a/Classes/PHPExcel/Worksheet/AutoFilter/Column.php b/Classes/PHPExcel/Worksheet/AutoFilter/Column.php index 9f705cab..e30cb3cd 100644 --- a/Classes/PHPExcel/Worksheet/AutoFilter/Column.php +++ b/Classes/PHPExcel/Worksheet/AutoFilter/Column.php @@ -220,7 +220,8 @@ class PHPExcel_Worksheet_AutoFilter_Column * * @return string */ - public function getJoin() { + public function getJoin() + { return $this->_join; } @@ -409,5 +410,4 @@ class PHPExcel_Worksheet_AutoFilter_Column } } } - } diff --git a/Classes/PHPExcel/Worksheet/AutoFilter/Column/Rule.php b/Classes/PHPExcel/Worksheet/AutoFilter/Column/Rule.php index e31c9cfc..2250bcde 100644 --- a/Classes/PHPExcel/Worksheet/AutoFilter/Column/Rule.php +++ b/Classes/PHPExcel/Worksheet/AutoFilter/Column/Rule.php @@ -333,7 +333,7 @@ class PHPExcel_Worksheet_AutoFilter_Column_Rule unset($pValue[$key]); } else { // Work out what the dateTime grouping will be - $grouping = max($grouping, array_search($key,self::$_dateTimeGroups)); + $grouping = max($grouping, array_search($key, self::$_dateTimeGroups)); } } if (count($pValue) == 0) { diff --git a/Classes/PHPExcel/Worksheet/ColumnDimension.php b/Classes/PHPExcel/Worksheet/ColumnDimension.php index 05be76fa..fe007c81 100644 --- a/Classes/PHPExcel/Worksheet/ColumnDimension.php +++ b/Classes/PHPExcel/Worksheet/ColumnDimension.php @@ -267,5 +267,4 @@ class PHPExcel_Worksheet_ColumnDimension } } } - } diff --git a/Classes/PHPExcel/Worksheet/Drawing.php b/Classes/PHPExcel/Worksheet/Drawing.php index 7f9dfd55..983bda48 100644 --- a/Classes/PHPExcel/Worksheet/Drawing.php +++ b/Classes/PHPExcel/Worksheet/Drawing.php @@ -59,7 +59,8 @@ class PHPExcel_Worksheet_Drawing extends PHPExcel_Worksheet_BaseDrawing implemen * * @return string */ - public function getFilename() { + public function getFilename() + { return basename($this->_path); } @@ -68,7 +69,8 @@ class PHPExcel_Worksheet_Drawing extends PHPExcel_Worksheet_BaseDrawing implemen * * @return string */ - public function getIndexedFilename() { + public function getIndexedFilename() + { $fileName = $this->getFilename(); $fileName = str_replace(' ', '_', $fileName); return str_replace('.' . $this->getExtension(), '', $fileName) . $this->getImageIndex() . '.' . $this->getExtension(); @@ -79,7 +81,8 @@ class PHPExcel_Worksheet_Drawing extends PHPExcel_Worksheet_BaseDrawing implemen * * @return string */ - public function getExtension() { + public function getExtension() + { $exploded = explode(".", basename($this->_path)); return $exploded[count($exploded) - 1]; } @@ -89,7 +92,8 @@ class PHPExcel_Worksheet_Drawing extends PHPExcel_Worksheet_BaseDrawing implemen * * @return string */ - public function getPath() { + public function getPath() + { return $this->_path; } @@ -101,7 +105,8 @@ class PHPExcel_Worksheet_Drawing extends PHPExcel_Worksheet_BaseDrawing implemen * @throws PHPExcel_Exception * @return PHPExcel_Worksheet_Drawing */ - public function setPath($pValue = '', $pVerifyFile = true) { + public function setPath($pValue = '', $pVerifyFile = true) + { if ($pVerifyFile) { if (file_exists($pValue)) { $this->_path = $pValue; @@ -124,9 +129,10 @@ class PHPExcel_Worksheet_Drawing extends PHPExcel_Worksheet_BaseDrawing implemen * * @return string Hash code */ - public function getHashCode() { + public function getHashCode() + { return md5( - $this->_path + $this->_path . parent::getHashCode() . __CLASS__ ); @@ -135,7 +141,8 @@ class PHPExcel_Worksheet_Drawing extends PHPExcel_Worksheet_BaseDrawing implemen /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ - public function __clone() { + public function __clone() + { $vars = get_object_vars($this); foreach ($vars as $key => $value) { if (is_object($value)) { diff --git a/Classes/PHPExcel/Worksheet/Drawing/Shadow.php b/Classes/PHPExcel/Worksheet/Drawing/Shadow.php index 8776745f..9806bb90 100644 --- a/Classes/PHPExcel/Worksheet/Drawing/Shadow.php +++ b/Classes/PHPExcel/Worksheet/Drawing/Shadow.php @@ -104,13 +104,13 @@ class PHPExcel_Worksheet_Drawing_Shadow implements PHPExcel_IComparable public function __construct() { // Initialise values - $this->_visible = false; - $this->_blurRadius = 6; - $this->_distance = 2; - $this->_direction = 0; - $this->_alignment = PHPExcel_Worksheet_Drawing_Shadow::SHADOW_BOTTOM_RIGHT; - $this->_color = new PHPExcel_Style_Color(PHPExcel_Style_Color::COLOR_BLACK); - $this->_alpha = 50; + $this->_visible = false; + $this->_blurRadius = 6; + $this->_distance = 2; + $this->_direction = 0; + $this->_alignment = PHPExcel_Worksheet_Drawing_Shadow::SHADOW_BOTTOM_RIGHT; + $this->_color = new PHPExcel_Style_Color(PHPExcel_Style_Color::COLOR_BLACK); + $this->_alpha = 50; } /** @@ -118,7 +118,8 @@ class PHPExcel_Worksheet_Drawing_Shadow implements PHPExcel_IComparable * * @return boolean */ - public function getVisible() { + public function getVisible() + { return $this->_visible; } @@ -128,7 +129,8 @@ class PHPExcel_Worksheet_Drawing_Shadow implements PHPExcel_IComparable * @param boolean $pValue * @return PHPExcel_Worksheet_Drawing_Shadow */ - public function setVisible($pValue = false) { + public function setVisible($pValue = false) + { $this->_visible = $pValue; return $this; } @@ -138,7 +140,8 @@ class PHPExcel_Worksheet_Drawing_Shadow implements PHPExcel_IComparable * * @return int */ - public function getBlurRadius() { + public function getBlurRadius() + { return $this->_blurRadius; } @@ -148,7 +151,8 @@ class PHPExcel_Worksheet_Drawing_Shadow implements PHPExcel_IComparable * @param int $pValue * @return PHPExcel_Worksheet_Drawing_Shadow */ - public function setBlurRadius($pValue = 6) { + public function setBlurRadius($pValue = 6) + { $this->_blurRadius = $pValue; return $this; } @@ -158,7 +162,8 @@ class PHPExcel_Worksheet_Drawing_Shadow implements PHPExcel_IComparable * * @return int */ - public function getDistance() { + public function getDistance() + { return $this->_distance; } @@ -168,7 +173,8 @@ class PHPExcel_Worksheet_Drawing_Shadow implements PHPExcel_IComparable * @param int $pValue * @return PHPExcel_Worksheet_Drawing_Shadow */ - public function setDistance($pValue = 2) { + public function setDistance($pValue = 2) + { $this->_distance = $pValue; return $this; } @@ -178,7 +184,8 @@ class PHPExcel_Worksheet_Drawing_Shadow implements PHPExcel_IComparable * * @return int */ - public function getDirection() { + public function getDirection() + { return $this->_direction; } @@ -188,7 +195,8 @@ class PHPExcel_Worksheet_Drawing_Shadow implements PHPExcel_IComparable * @param int $pValue * @return PHPExcel_Worksheet_Drawing_Shadow */ - public function setDirection($pValue = 0) { + public function setDirection($pValue = 0) + { $this->_direction = $pValue; return $this; } @@ -198,7 +206,8 @@ class PHPExcel_Worksheet_Drawing_Shadow implements PHPExcel_IComparable * * @return int */ - public function getAlignment() { + public function getAlignment() + { return $this->_alignment; } @@ -208,7 +217,8 @@ class PHPExcel_Worksheet_Drawing_Shadow implements PHPExcel_IComparable * @param int $pValue * @return PHPExcel_Worksheet_Drawing_Shadow */ - public function setAlignment($pValue = 0) { + public function setAlignment($pValue = 0) + { $this->_alignment = $pValue; return $this; } @@ -218,7 +228,8 @@ class PHPExcel_Worksheet_Drawing_Shadow implements PHPExcel_IComparable * * @return PHPExcel_Style_Color */ - public function getColor() { + public function getColor() + { return $this->_color; } @@ -229,7 +240,8 @@ class PHPExcel_Worksheet_Drawing_Shadow implements PHPExcel_IComparable * @throws PHPExcel_Exception * @return PHPExcel_Worksheet_Drawing_Shadow */ - public function setColor(PHPExcel_Style_Color $pValue = null) { + public function setColor(PHPExcel_Style_Color $pValue = null) + { $this->_color = $pValue; return $this; } @@ -239,7 +251,8 @@ class PHPExcel_Worksheet_Drawing_Shadow implements PHPExcel_IComparable * * @return int */ - public function getAlpha() { + public function getAlpha() + { return $this->_alpha; } @@ -249,7 +262,8 @@ class PHPExcel_Worksheet_Drawing_Shadow implements PHPExcel_IComparable * @param int $pValue * @return PHPExcel_Worksheet_Drawing_Shadow */ - public function setAlpha($pValue = 0) { + public function setAlpha($pValue = 0) + { $this->_alpha = $pValue; return $this; } @@ -259,9 +273,10 @@ class PHPExcel_Worksheet_Drawing_Shadow implements PHPExcel_IComparable * * @return string Hash code */ - public function getHashCode() { + public function getHashCode() + { return md5( - ($this->_visible ? 't' : 'f') + ($this->_visible ? 't' : 'f') . $this->_blurRadius . $this->_distance . $this->_direction @@ -275,7 +290,8 @@ class PHPExcel_Worksheet_Drawing_Shadow implements PHPExcel_IComparable /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ - public function __clone() { + public function __clone() + { $vars = get_object_vars($this); foreach ($vars as $key => $value) { if (is_object($value)) { diff --git a/Classes/PHPExcel/Worksheet/HeaderFooter.php b/Classes/PHPExcel/Worksheet/HeaderFooter.php index 3d2271ab..f4ba2a42 100644 --- a/Classes/PHPExcel/Worksheet/HeaderFooter.php +++ b/Classes/PHPExcel/Worksheet/HeaderFooter.php @@ -192,7 +192,8 @@ class PHPExcel_Worksheet_HeaderFooter * * @return string */ - public function getOddHeader() { + public function getOddHeader() + { return $this->_oddHeader; } @@ -202,7 +203,8 @@ class PHPExcel_Worksheet_HeaderFooter * @param string $pValue * @return PHPExcel_Worksheet_HeaderFooter */ - public function setOddHeader($pValue) { + public function setOddHeader($pValue) + { $this->_oddHeader = $pValue; return $this; } @@ -212,7 +214,8 @@ class PHPExcel_Worksheet_HeaderFooter * * @return string */ - public function getOddFooter() { + public function getOddFooter() + { return $this->_oddFooter; } @@ -222,7 +225,8 @@ class PHPExcel_Worksheet_HeaderFooter * @param string $pValue * @return PHPExcel_Worksheet_HeaderFooter */ - public function setOddFooter($pValue) { + public function setOddFooter($pValue) + { $this->_oddFooter = $pValue; return $this; } @@ -232,7 +236,8 @@ class PHPExcel_Worksheet_HeaderFooter * * @return string */ - public function getEvenHeader() { + public function getEvenHeader() + return $this->_evenHeader; } @@ -242,7 +247,8 @@ class PHPExcel_Worksheet_HeaderFooter * @param string $pValue * @return PHPExcel_Worksheet_HeaderFooter */ - public function setEvenHeader($pValue) { + public function setEvenHeader($pValue) + { $this->_evenHeader = $pValue; return $this; } @@ -252,7 +258,8 @@ class PHPExcel_Worksheet_HeaderFooter * * @return string */ - public function getEvenFooter() { + public function getEvenFooter() + { return $this->_evenFooter; } @@ -262,7 +269,8 @@ class PHPExcel_Worksheet_HeaderFooter * @param string $pValue * @return PHPExcel_Worksheet_HeaderFooter */ - public function setEvenFooter($pValue) { + public function setEvenFooter($pValue) + { $this->_evenFooter = $pValue; return $this; } @@ -272,7 +280,8 @@ class PHPExcel_Worksheet_HeaderFooter * * @return string */ - public function getFirstHeader() { + public function getFirstHeader() + { return $this->_firstHeader; } @@ -282,7 +291,8 @@ class PHPExcel_Worksheet_HeaderFooter * @param string $pValue * @return PHPExcel_Worksheet_HeaderFooter */ - public function setFirstHeader($pValue) { + public function setFirstHeader($pValue) + { $this->_firstHeader = $pValue; return $this; } @@ -292,7 +302,8 @@ class PHPExcel_Worksheet_HeaderFooter * * @return string */ - public function getFirstFooter() { + public function getFirstFooter() + { return $this->_firstFooter; } @@ -302,7 +313,8 @@ class PHPExcel_Worksheet_HeaderFooter * @param string $pValue * @return PHPExcel_Worksheet_HeaderFooter */ - public function setFirstFooter($pValue) { + public function setFirstFooter($pValue) + { $this->_firstFooter = $pValue; return $this; } @@ -312,7 +324,8 @@ class PHPExcel_Worksheet_HeaderFooter * * @return boolean */ - public function getDifferentOddEven() { + public function getDifferentOddEven() + { return $this->_differentOddEven; } @@ -322,7 +335,8 @@ class PHPExcel_Worksheet_HeaderFooter * @param boolean $pValue * @return PHPExcel_Worksheet_HeaderFooter */ - public function setDifferentOddEven($pValue = false) { + public function setDifferentOddEven($pValue = false) + { $this->_differentOddEven = $pValue; return $this; } @@ -332,7 +346,8 @@ class PHPExcel_Worksheet_HeaderFooter * * @return boolean */ - public function getDifferentFirst() { + public function getDifferentFirst() + { return $this->_differentFirst; } @@ -342,7 +357,8 @@ class PHPExcel_Worksheet_HeaderFooter * @param boolean $pValue * @return PHPExcel_Worksheet_HeaderFooter */ - public function setDifferentFirst($pValue = false) { + public function setDifferentFirst($pValue = false) + { $this->_differentFirst = $pValue; return $this; } @@ -352,7 +368,8 @@ class PHPExcel_Worksheet_HeaderFooter * * @return boolean */ - public function getScaleWithDocument() { + public function getScaleWithDocument() + { return $this->_scaleWithDocument; } @@ -362,7 +379,8 @@ class PHPExcel_Worksheet_HeaderFooter * @param boolean $pValue * @return PHPExcel_Worksheet_HeaderFooter */ - public function setScaleWithDocument($pValue = true) { + public function setScaleWithDocument($pValue = true) + { $this->_scaleWithDocument = $pValue; return $this; } @@ -372,7 +390,8 @@ class PHPExcel_Worksheet_HeaderFooter * * @return boolean */ - public function getAlignWithMargins() { + public function getAlignWithMargins() + { return $this->_alignWithMargins; } @@ -382,7 +401,8 @@ class PHPExcel_Worksheet_HeaderFooter * @param boolean $pValue * @return PHPExcel_Worksheet_HeaderFooter */ - public function setAlignWithMargins($pValue = true) { + public function setAlignWithMargins($pValue = true) + { $this->_alignWithMargins = $pValue; return $this; } @@ -395,7 +415,8 @@ class PHPExcel_Worksheet_HeaderFooter * @throws PHPExcel_Exception * @return PHPExcel_Worksheet_HeaderFooter */ - public function addImage(PHPExcel_Worksheet_HeaderFooterDrawing $image = null, $location = self::IMAGE_HEADER_LEFT) { + public function addImage(PHPExcel_Worksheet_HeaderFooterDrawing $image = null, $location = self::IMAGE_HEADER_LEFT) + { $this->_headerFooterImages[$location] = $image; return $this; } @@ -407,7 +428,8 @@ class PHPExcel_Worksheet_HeaderFooter * @throws PHPExcel_Exception * @return PHPExcel_Worksheet_HeaderFooter */ - public function removeImage($location = self::IMAGE_HEADER_LEFT) { + public function removeImage($location = self::IMAGE_HEADER_LEFT) + { if (isset($this->_headerFooterImages[$location])) { unset($this->_headerFooterImages[$location]); } @@ -421,7 +443,8 @@ class PHPExcel_Worksheet_HeaderFooter * @throws PHPExcel_Exception * @return PHPExcel_Worksheet_HeaderFooter */ - public function setImages($images) { + public function setImages($images) + { if (!is_array($images)) { throw new PHPExcel_Exception('Invalid parameter!'); } @@ -435,15 +458,28 @@ class PHPExcel_Worksheet_HeaderFooter * * @return PHPExcel_Worksheet_HeaderFooterDrawing[] */ - public function getImages() { + public function getImages() + { // Sort array $images = array(); - if (isset($this->_headerFooterImages[self::IMAGE_HEADER_LEFT])) $images[self::IMAGE_HEADER_LEFT] = $this->_headerFooterImages[self::IMAGE_HEADER_LEFT]; - if (isset($this->_headerFooterImages[self::IMAGE_HEADER_CENTER])) $images[self::IMAGE_HEADER_CENTER] = $this->_headerFooterImages[self::IMAGE_HEADER_CENTER]; - if (isset($this->_headerFooterImages[self::IMAGE_HEADER_RIGHT])) $images[self::IMAGE_HEADER_RIGHT] = $this->_headerFooterImages[self::IMAGE_HEADER_RIGHT]; - if (isset($this->_headerFooterImages[self::IMAGE_FOOTER_LEFT])) $images[self::IMAGE_FOOTER_LEFT] = $this->_headerFooterImages[self::IMAGE_FOOTER_LEFT]; - if (isset($this->_headerFooterImages[self::IMAGE_FOOTER_CENTER])) $images[self::IMAGE_FOOTER_CENTER] = $this->_headerFooterImages[self::IMAGE_FOOTER_CENTER]; - if (isset($this->_headerFooterImages[self::IMAGE_FOOTER_RIGHT])) $images[self::IMAGE_FOOTER_RIGHT] = $this->_headerFooterImages[self::IMAGE_FOOTER_RIGHT]; + if (isset($this->_headerFooterImages[self::IMAGE_HEADER_LEFT])) { + $images[self::IMAGE_HEADER_LEFT] = $this->_headerFooterImages[self::IMAGE_HEADER_LEFT]; + } + if (isset($this->_headerFooterImages[self::IMAGE_HEADER_CENTER])) { + $images[self::IMAGE_HEADER_CENTER] = $this->_headerFooterImages[self::IMAGE_HEADER_CENTER]; + } + if (isset($this->_headerFooterImages[self::IMAGE_HEADER_RIGHT])) { + $images[self::IMAGE_HEADER_RIGHT] = $this->_headerFooterImages[self::IMAGE_HEADER_RIGHT]; + } + if (isset($this->_headerFooterImages[self::IMAGE_FOOTER_LEFT])) { + $images[self::IMAGE_FOOTER_LEFT] = $this->_headerFooterImages[self::IMAGE_FOOTER_LEFT]; + } + if (isset($this->_headerFooterImages[self::IMAGE_FOOTER_CENTER])) { + $images[self::IMAGE_FOOTER_CENTER] = $this->_headerFooterImages[self::IMAGE_FOOTER_CENTER]; + } + if (isset($this->_headerFooterImages[self::IMAGE_FOOTER_RIGHT])) { + $images[self::IMAGE_FOOTER_RIGHT] = $this->_headerFooterImages[self::IMAGE_FOOTER_RIGHT]; + } $this->_headerFooterImages = $images; return $this->_headerFooterImages; @@ -452,7 +488,8 @@ class PHPExcel_Worksheet_HeaderFooter /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ - public function __clone() { + public function __clone() + { $vars = get_object_vars($this); foreach ($vars as $key => $value) { if (is_object($value)) { diff --git a/Classes/PHPExcel/Worksheet/MemoryDrawing.php b/Classes/PHPExcel/Worksheet/MemoryDrawing.php index 1f19b4d0..04f8d110 100644 --- a/Classes/PHPExcel/Worksheet/MemoryDrawing.php +++ b/Classes/PHPExcel/Worksheet/MemoryDrawing.php @@ -195,7 +195,8 @@ class PHPExcel_Worksheet_MemoryDrawing extends PHPExcel_Worksheet_BaseDrawing im /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ - public function __clone() { + public function __clone() + { $vars = get_object_vars($this); foreach ($vars as $key => $value) { if (is_object($value)) { diff --git a/Classes/PHPExcel/Worksheet/PageSetup.php b/Classes/PHPExcel/Worksheet/PageSetup.php index e5fe06ac..71649fce 100644 --- a/Classes/PHPExcel/Worksheet/PageSetup.php +++ b/Classes/PHPExcel/Worksheet/PageSetup.php @@ -297,7 +297,8 @@ class PHPExcel_Worksheet_PageSetup * @param int $pValue * @return PHPExcel_Worksheet_PageSetup */ - public function setPaperSize($pValue = PHPExcel_Worksheet_PageSetup::PAPERSIZE_LETTER) { + public function setPaperSize($pValue = PHPExcel_Worksheet_PageSetup::PAPERSIZE_LETTER) + { $this->_paperSize = $pValue; return $this; } @@ -307,7 +308,8 @@ class PHPExcel_Worksheet_PageSetup * * @return string */ - public function getOrientation() { + public function getOrientation() + { return $this->_orientation; } @@ -317,7 +319,8 @@ class PHPExcel_Worksheet_PageSetup * @param string $pValue * @return PHPExcel_Worksheet_PageSetup */ - public function setOrientation($pValue = PHPExcel_Worksheet_PageSetup::ORIENTATION_DEFAULT) { + public function setOrientation($pValue = PHPExcel_Worksheet_PageSetup::ORIENTATION_DEFAULT) + { $this->_orientation = $pValue; return $this; } @@ -327,7 +330,8 @@ class PHPExcel_Worksheet_PageSetup * * @return int? */ - public function getScale() { + public function getScale() + { return $this->_scale; } @@ -342,7 +346,8 @@ class PHPExcel_Worksheet_PageSetup * @return PHPExcel_Worksheet_PageSetup * @throws PHPExcel_Exception */ - public function setScale($pValue = 100, $pUpdate = true) { + public function setScale($pValue = 100, $pUpdate = true) + { // Microsoft Office Excel 2007 only allows setting a scale between 10 and 400 via the user interface, // but it is apparently still able to handle any scale >= 0, where 0 results in 100 if (($pValue >= 0) || is_null($pValue)) { @@ -371,7 +376,8 @@ class PHPExcel_Worksheet_PageSetup * @param boolean $pValue * @return PHPExcel_Worksheet_PageSetup */ - public function setFitToPage($pValue = true) { + public function setFitToPage($pValue = true) + { $this->_fitToPage = $pValue; return $this; } @@ -381,7 +387,8 @@ class PHPExcel_Worksheet_PageSetup * * @return int? */ - public function getFitToHeight() { + public function getFitToHeight() + { return $this->_fitToHeight; } @@ -392,7 +399,8 @@ class PHPExcel_Worksheet_PageSetup * @param boolean $pUpdate Update fitToPage so it applies rather than scaling * @return PHPExcel_Worksheet_PageSetup */ - public function setFitToHeight($pValue = 1, $pUpdate = true) { + public function setFitToHeight($pValue = 1, $pUpdate = true) + { $this->_fitToHeight = $pValue; if ($pUpdate) { $this->_fitToPage = true; @@ -405,7 +413,8 @@ class PHPExcel_Worksheet_PageSetup * * @return int? */ - public function getFitToWidth() { + public function getFitToWidth() + { return $this->_fitToWidth; } @@ -416,7 +425,8 @@ class PHPExcel_Worksheet_PageSetup * @param boolean $pUpdate Update fitToPage so it applies rather than scaling * @return PHPExcel_Worksheet_PageSetup */ - public function setFitToWidth($pValue = 1, $pUpdate = true) { + public function setFitToWidth($pValue = 1, $pUpdate = true) + { $this->_fitToWidth = $pValue; if ($pUpdate) { $this->_fitToPage = true; @@ -429,7 +439,8 @@ class PHPExcel_Worksheet_PageSetup * * @return boolean */ - public function isColumnsToRepeatAtLeftSet() { + public function isColumnsToRepeatAtLeftSet() + { if (is_array($this->_columnsToRepeatAtLeft)) { if ($this->_columnsToRepeatAtLeft[0] != '' && $this->_columnsToRepeatAtLeft[1] != '') { return true; @@ -444,7 +455,8 @@ class PHPExcel_Worksheet_PageSetup * * @return array Containing start column and end column, empty array if option unset */ - public function getColumnsToRepeatAtLeft() { + public function getColumnsToRepeatAtLeft() + { return $this->_columnsToRepeatAtLeft; } @@ -454,7 +466,8 @@ class PHPExcel_Worksheet_PageSetup * @param array $pValue Containing start column and end column, empty array if option unset * @return PHPExcel_Worksheet_PageSetup */ - public function setColumnsToRepeatAtLeft($pValue = null) { + public function setColumnsToRepeatAtLeft($pValue = null) + { if (is_array($pValue)) { $this->_columnsToRepeatAtLeft = $pValue; } @@ -468,7 +481,8 @@ class PHPExcel_Worksheet_PageSetup * @param string $pEnd * @return PHPExcel_Worksheet_PageSetup */ - public function setColumnsToRepeatAtLeftByStartAndEnd($pStart = 'A', $pEnd = 'A') { + public function setColumnsToRepeatAtLeftByStartAndEnd($pStart = 'A', $pEnd = 'A') + { $this->_columnsToRepeatAtLeft = array($pStart, $pEnd); return $this; } @@ -478,7 +492,8 @@ class PHPExcel_Worksheet_PageSetup * * @return boolean */ - public function isRowsToRepeatAtTopSet() { + public function isRowsToRepeatAtTopSet() + { if (is_array($this->_rowsToRepeatAtTop)) { if ($this->_rowsToRepeatAtTop[0] != 0 && $this->_rowsToRepeatAtTop[1] != 0) { return true; @@ -493,7 +508,8 @@ class PHPExcel_Worksheet_PageSetup * * @return array Containing start column and end column, empty array if option unset */ - public function getRowsToRepeatAtTop() { + public function getRowsToRepeatAtTop() + { return $this->_rowsToRepeatAtTop; } @@ -503,7 +519,8 @@ class PHPExcel_Worksheet_PageSetup * @param array $pValue Containing start column and end column, empty array if option unset * @return PHPExcel_Worksheet_PageSetup */ - public function setRowsToRepeatAtTop($pValue = null) { + public function setRowsToRepeatAtTop($pValue = null) + { if (is_array($pValue)) { $this->_rowsToRepeatAtTop = $pValue; } @@ -517,7 +534,8 @@ class PHPExcel_Worksheet_PageSetup * @param int $pEnd * @return PHPExcel_Worksheet_PageSetup */ - public function setRowsToRepeatAtTopByStartAndEnd($pStart = 1, $pEnd = 1) { + public function setRowsToRepeatAtTopByStartAndEnd($pStart = 1, $pEnd = 1) + { $this->_rowsToRepeatAtTop = array($pStart, $pEnd); return $this; } @@ -527,7 +545,8 @@ class PHPExcel_Worksheet_PageSetup * * @return bool */ - public function getHorizontalCentered() { + public function getHorizontalCentered() + { return $this->_horizontalCentered; } @@ -537,7 +556,8 @@ class PHPExcel_Worksheet_PageSetup * @param bool $value * @return PHPExcel_Worksheet_PageSetup */ - public function setHorizontalCentered($value = false) { + public function setHorizontalCentered($value = false) + { $this->_horizontalCentered = $value; return $this; } @@ -547,7 +567,8 @@ class PHPExcel_Worksheet_PageSetup * * @return bool */ - public function getVerticalCentered() { + public function getVerticalCentered() + { return $this->_verticalCentered; } @@ -557,7 +578,8 @@ class PHPExcel_Worksheet_PageSetup * @param bool $value * @return PHPExcel_Worksheet_PageSetup */ - public function setVerticalCentered($value = false) { + public function setVerticalCentered($value = false) + { $this->_verticalCentered = $value; return $this; } @@ -572,7 +594,8 @@ class PHPExcel_Worksheet_PageSetup * @throws PHPExcel_Exception * @return string */ - public function getPrintArea($index = 0) { + public function getPrintArea($index = 0) + { if ($index == 0) { return $this->_printArea; } @@ -592,7 +615,8 @@ class PHPExcel_Worksheet_PageSetup * Print areas are numbered from 1 * @return boolean */ - public function isPrintAreaSet($index = 0) { + public function isPrintAreaSet($index = 0) + { if ($index == 0) { return !is_null($this->_printArea); } @@ -609,7 +633,8 @@ class PHPExcel_Worksheet_PageSetup * Print areas are numbered from 1 * @return PHPExcel_Worksheet_PageSetup */ - public function clearPrintArea($index = 0) { + public function clearPrintArea($index = 0) + { if ($index == 0) { $this->_printArea = null; } else { @@ -643,12 +668,13 @@ class PHPExcel_Worksheet_PageSetup * @return PHPExcel_Worksheet_PageSetup * @throws PHPExcel_Exception */ - public function setPrintArea($value, $index = 0, $method = self::SETPRINTRANGE_OVERWRITE) { - if (strpos($value,'!') !== false) { + public function setPrintArea($value, $index = 0, $method = self::SETPRINTRANGE_OVERWRITE) + { + if (strpos($value, '!') !== false) { throw new PHPExcel_Exception('Cell coordinate must not specify a worksheet.'); - } elseif (strpos($value,':') === false) { + } elseif (strpos($value, ':') === false) { throw new PHPExcel_Exception('Cell coordinate must be a range of cells.'); - } elseif (strpos($value,'$') !== false) { + } elseif (strpos($value, '$') !== false) { throw new PHPExcel_Exception('Cell coordinate must not be absolute.'); } $value = strtoupper($value); @@ -678,7 +704,7 @@ class PHPExcel_Worksheet_PageSetup if ($index > count($printAreas)) { throw new PHPExcel_Exception('Invalid index for setting print range.'); } - $printAreas = array_merge(array_slice($printAreas,0, $index),array($value),array_slice($printAreas, $index)); + $printAreas = array_merge(array_slice($printAreas, 0, $index), array($value), array_slice($printAreas, $index)); $this->_printArea = implode(',', $printAreas); } } else { @@ -701,7 +727,8 @@ class PHPExcel_Worksheet_PageSetup * @return PHPExcel_Worksheet_PageSetup * @throws PHPExcel_Exception */ - public function addPrintArea($value, $index = -1) { + public function addPrintArea($value, $index = -1) + { return $this->setPrintArea($value, $index, self::SETPRINTRANGE_INSERT); } @@ -759,7 +786,8 @@ class PHPExcel_Worksheet_PageSetup * * @return int */ - public function getFirstPageNumber() { + public function getFirstPageNumber() + { return $this->_firstPageNumber; } @@ -769,7 +797,8 @@ class PHPExcel_Worksheet_PageSetup * @param int $value * @return PHPExcel_Worksheet_HeaderFooter */ - public function setFirstPageNumber($value = null) { + public function setFirstPageNumber($value = null) + { $this->_firstPageNumber = $value; return $this; } @@ -779,14 +808,16 @@ class PHPExcel_Worksheet_PageSetup * * @return PHPExcel_Worksheet_HeaderFooter */ - public function resetFirstPageNumber() { + public function resetFirstPageNumber() + { return $this->setFirstPageNumber(null); } /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ - public function __clone() { + public function __clone() + { $vars = get_object_vars($this); foreach ($vars as $key => $value) { if (is_object($value)) { diff --git a/Classes/PHPExcel/Writer/Excel2007/Chart.php b/Classes/PHPExcel/Writer/Excel2007/Chart.php index 6aefa80a..8afa52f2 100644 --- a/Classes/PHPExcel/Writer/Excel2007/Chart.php +++ b/Classes/PHPExcel/Writer/Excel2007/Chart.php @@ -405,7 +405,7 @@ class PHPExcel_Writer_Excel2007_Chart extends PHPExcel_Writer_Excel2007_WriterPa * @param string $id1 * @param string $id2 * @param boolean $isMultiLevelSeries - * + * * @throws PHPExcel_Writer_Exception */ private function _writeCatAx($objWriter, PHPExcel_Chart_PlotArea $plotArea, $xAxisLabel, $groupType, $id1, $id2, $isMultiLevelSeries, $xAxis, $yAxis) diff --git a/Classes/PHPExcel/Writer/Excel2007/ContentTypes.php b/Classes/PHPExcel/Writer/Excel2007/ContentTypes.php index ef572133..4f0b1eba 100644 --- a/Classes/PHPExcel/Writer/Excel2007/ContentTypes.php +++ b/Classes/PHPExcel/Writer/Excel2007/ContentTypes.php @@ -144,7 +144,7 @@ class PHPExcel_Writer_Excel2007_ContentTypes extends PHPExcel_Writer_Excel2007_W if ($this->getParentWriter()->getDrawingHashTable()->getByIndex($i) instanceof PHPExcel_Worksheet_Drawing) { $extension = strtolower($this->getParentWriter()->getDrawingHashTable()->getByIndex($i)->getExtension()); - $mimeType = $this->_getImageMimeType( $this->getParentWriter()->getDrawingHashTable()->getByIndex($i)->getPath()); + $mimeType = $this->_getImageMimeType($this->getParentWriter()->getDrawingHashTable()->getByIndex($i)->getPath()); } else if ($this->getParentWriter()->getDrawingHashTable()->getByIndex($i) instanceof PHPExcel_Worksheet_MemoryDrawing) { $extension = strtolower($this->getParentWriter()->getDrawingHashTable()->getByIndex($i)->getMimeType()); $extension = explode('/', $extension); From 4c8dd00dffd2f6e55ab9bff54219158844902874 Mon Sep 17 00:00:00 2001 From: MarkBaker Date: Fri, 15 May 2015 23:41:50 +0100 Subject: [PATCH 5/5] More psr-2 goodness --- Classes/PHPExcel/Calculation.php | 322 +- Classes/PHPExcel/Calculation/Token/Stack.php | 2 +- Classes/PHPExcel/Cell.php | 118 +- Classes/PHPExcel/Chart/Renderer/jpgraph.php | 1720 +-- Classes/PHPExcel/Shared/PCLZip/pclzip.lib.php | 10838 ++++++++-------- Classes/PHPExcel/Worksheet/HeaderFooter.php | 4 +- 6 files changed, 6595 insertions(+), 6409 deletions(-) diff --git a/Classes/PHPExcel/Calculation.php b/Classes/PHPExcel/Calculation.php index 63a2ace4..6a21bcac 100644 --- a/Classes/PHPExcel/Calculation.php +++ b/Classes/PHPExcel/Calculation.php @@ -83,7 +83,7 @@ class PHPExcel_Calculation * @access private * @var PHPExcel_Calculation */ - private static $_instance; + private static $instance; /** @@ -92,7 +92,7 @@ class PHPExcel_Calculation * @access private * @var PHPExcel */ - private $_workbook; + private $workbook; /** * List of instances of the calculation engine that we've instantiated for individual workbooks @@ -100,7 +100,7 @@ class PHPExcel_Calculation * @access private * @var PHPExcel_Calculation[] */ - private static $_workbookSets; + private static $workbookSets; /** * Calculation cache @@ -108,7 +108,7 @@ class PHPExcel_Calculation * @access private * @var array */ - private $_calculationCache = array (); + private $calculationCache = array (); /** @@ -117,7 +117,7 @@ class PHPExcel_Calculation * @access private * @var boolean */ - private $_calculationCacheEnabled = true; + private $calculationCacheEnabled = true; /** @@ -127,7 +127,7 @@ class PHPExcel_Calculation * @access private * @var array */ - private static $_operators = array( + private static $operators = array( '+' => true, '-' => true, '*' => true, '/' => true, '^' => true, '&' => true, '%' => false, '~' => false, '>' => true, '<' => true, '=' => true, '>=' => true, @@ -140,7 +140,7 @@ class PHPExcel_Calculation * @access private * @var array */ - private static $_binaryOperators = array( + private static $binaryOperators = array( '+' => true, '-' => true, '*' => true, '/' => true, '^' => true, '&' => true, '>' => true, '<' => true, '=' => true, '>=' => true, '<=' => true, '<>' => true, @@ -183,9 +183,9 @@ class PHPExcel_Calculation * @var array of string * */ - private $_cyclicReferenceStack; + private $cyclicReferenceStack; - private $_cellStack = array(); + private $cellStack = array(); /** * Current iteration counter for cyclic formulae @@ -195,9 +195,9 @@ class PHPExcel_Calculation * @var integer * */ - private $_cyclicFormulaCount = 1; + private $cyclicFormulaCounter = 1; - private $_cyclicFormulaCell = ''; + private $cyclicFormulaCell = ''; /** * Number of iterations for cyclic formulae @@ -213,7 +213,7 @@ class PHPExcel_Calculation * @var integer * */ - private $_savedPrecision = 14; + private $savedPrecision = 14; /** @@ -222,7 +222,7 @@ class PHPExcel_Calculation * @var string * */ - private static $_localeLanguage = 'en_us'; // US English (default locale) + private static $localeLanguage = 'en_us'; // US English (default locale) /** * List of available locale settings @@ -231,7 +231,7 @@ class PHPExcel_Calculation * @var string[] * */ - private static $_validLocaleLanguages = array( + private static $validLocaleLanguages = array( 'en' // English (default language) ); @@ -241,8 +241,8 @@ class PHPExcel_Calculation * @var string * */ - private static $_localeArgumentSeparator = ','; - private static $_localeFunctions = array(); + private static $localeArgumentSeparator = ','; + private static $localeFunctions = array(); /** * Locale-specific translations for Excel constants (True, False and Null) @@ -250,10 +250,10 @@ class PHPExcel_Calculation * @var string[] * */ - public static $_localeBoolean = array( - 'TRUE' => 'TRUE', - 'FALSE' => 'FALSE', - 'NULL' => 'NULL' + public static $localeBoolean = array( + 'TRUE' => 'TRUE', + 'FALSE' => 'FALSE', + 'NULL' => 'NULL' ); /** @@ -263,14 +263,14 @@ class PHPExcel_Calculation * @var string[] * */ - private static $_ExcelConstants = array( - 'TRUE' => true, - 'FALSE' => false, - 'NULL' => null + private static $excelConstants = array( + 'TRUE' => true, + 'FALSE' => false, + 'NULL' => null ); // PHPExcel functions - private static $_PHPExcelFunctions = array( // PHPExcel functions + private static $PHPExcelFunctions = array( // PHPExcel functions 'ABS' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, 'functionCall' => 'abs', 'argumentCount' => '1' @@ -1705,7 +1705,7 @@ class PHPExcel_Calculation // Internal functions used for special control purposes - private static $_controlFunctions = array( + private static $controlFunctions = array( 'MKMATRIX' => array( 'argumentCount' => '*', 'functionCall' => 'self::_mkMatrix' @@ -1716,26 +1716,26 @@ class PHPExcel_Calculation private function __construct(PHPExcel $workbook = null) { $setPrecision = (PHP_INT_SIZE == 4) ? 14 : 16; - $this->_savedPrecision = ini_get('precision'); - if ($this->_savedPrecision < $setPrecision) { + $this->savedPrecision = ini_get('precision'); + if ($this->savedPrecision < $setPrecision) { ini_set('precision', $setPrecision); } $this->delta = 1 * pow(10, -$setPrecision); if ($workbook !== null) { - self::$_workbookSets[$workbook->getID()] = $this; + self::$workbookSets[$workbook->getID()] = $this; } - $this->_workbook = $workbook; - $this->_cyclicReferenceStack = new PHPExcel_CalcEngine_CyclicReferenceStack(); - $this->_debugLog = new PHPExcel_CalcEngine_Logger($this->_cyclicReferenceStack); + $this->workbook = $workbook; + $this->cyclicReferenceStack = new PHPExcel_CalcEngine_CyclicReferenceStack(); + $this->_debugLog = new PHPExcel_CalcEngine_Logger($this->cyclicReferenceStack); } public function __destruct() { - if ($this->_savedPrecision != ini_get('precision')) { - ini_set('precision', $this->_savedPrecision); + if ($this->savedPrecision != ini_get('precision')) { + ini_set('precision', $this->savedPrecision); } } @@ -1745,7 +1745,7 @@ class PHPExcel_Calculation foreach (glob($localeFileDirectory.'/*', GLOB_ONLYDIR) as $filename) { $filename = substr($filename, strlen($localeFileDirectory)+1); if ($filename != 'en') { - self::$_validLocaleLanguages[] = $filename; + self::$validLocaleLanguages[] = $filename; } } } @@ -1761,17 +1761,17 @@ class PHPExcel_Calculation public static function getInstance(PHPExcel $workbook = null) { if ($workbook !== null) { - if (isset(self::$_workbookSets[$workbook->getID()])) { - return self::$_workbookSets[$workbook->getID()]; + if (isset(self::$workbookSets[$workbook->getID()])) { + return self::$workbookSets[$workbook->getID()]; } return new PHPExcel_Calculation($workbook); } - if (!isset(self::$_instance) || (self::$_instance === null)) { - self::$_instance = new PHPExcel_Calculation(); + if (!isset(self::$instance) || (self::$instance === null)) { + self::$instance = new PHPExcel_Calculation(); } - return self::$_instance; + return self::$instance; } /** @@ -1783,8 +1783,8 @@ class PHPExcel_Calculation public static function unsetInstance(PHPExcel $workbook = null) { if ($workbook !== null) { - if (isset(self::$_workbookSets[$workbook->getID()])) { - unset(self::$_workbookSets[$workbook->getID()]); + if (isset(self::$workbookSets[$workbook->getID()])) { + unset(self::$workbookSets[$workbook->getID()]); } } } @@ -1833,7 +1833,7 @@ class PHPExcel_Calculation */ public static function getTRUE() { - return self::$_localeBoolean['TRUE']; + return self::$localeBoolean['TRUE']; } /** @@ -1844,7 +1844,7 @@ class PHPExcel_Calculation */ public static function getFALSE() { - return self::$_localeBoolean['FALSE']; + return self::$localeBoolean['FALSE']; } /** @@ -1886,7 +1886,7 @@ class PHPExcel_Calculation */ public function getCalculationCacheEnabled() { - return $this->_calculationCacheEnabled; + return $this->calculationCacheEnabled; } /** @@ -1897,7 +1897,7 @@ class PHPExcel_Calculation */ public function setCalculationCacheEnabled($pValue = true) { - $this->_calculationCacheEnabled = $pValue; + $this->calculationCacheEnabled = $pValue; $this->clearCalculationCache(); } @@ -1925,7 +1925,7 @@ class PHPExcel_Calculation */ public function clearCalculationCache() { - $this->_calculationCache = array(); + $this->calculationCache = array(); } /** @@ -1935,8 +1935,8 @@ class PHPExcel_Calculation */ public function clearCalculationCacheForWorksheet($worksheetName) { - if (isset($this->_calculationCache[$worksheetName])) { - unset($this->_calculationCache[$worksheetName]); + if (isset($this->calculationCache[$worksheetName])) { + unset($this->calculationCache[$worksheetName]); } } @@ -1948,9 +1948,9 @@ class PHPExcel_Calculation */ public function renameCalculationCacheForWorksheet($fromWorksheetName, $toWorksheetName) { - if (isset($this->_calculationCache[$fromWorksheetName])) { - $this->_calculationCache[$toWorksheetName] = &$this->_calculationCache[$fromWorksheetName]; - unset($this->_calculationCache[$fromWorksheetName]); + if (isset($this->calculationCache[$fromWorksheetName])) { + $this->calculationCache[$toWorksheetName] = &$this->calculationCache[$fromWorksheetName]; + unset($this->calculationCache[$fromWorksheetName]); } } @@ -1962,7 +1962,7 @@ class PHPExcel_Calculation */ public function getLocale() { - return self::$_localeLanguage; + return self::$localeLanguage; } @@ -1980,15 +1980,15 @@ class PHPExcel_Calculation list($language) = explode('_', $locale); } - if (count(self::$_validLocaleLanguages) == 1) { + if (count(self::$validLocaleLanguages) == 1) { self::_loadLocales(); } // Test whether we have any language data for this language (any locale) - if (in_array($language, self::$_validLocaleLanguages)) { + if (in_array($language, self::$validLocaleLanguages)) { // initialise language/locale settings - self::$_localeFunctions = array(); - self::$_localeArgumentSeparator = ','; - self::$_localeBoolean = array('TRUE' => 'TRUE', 'FALSE' => 'FALSE', 'NULL' => 'NULL'); + self::$localeFunctions = array(); + self::$localeArgumentSeparator = ','; + self::$localeBoolean = array('TRUE' => 'TRUE', 'FALSE' => 'FALSE', 'NULL' => 'NULL'); // Default is English, if user isn't requesting english, then read the necessary data from the locale files if ($locale != 'en_us') { // Search for a file with a list of function names for locale @@ -2008,17 +2008,17 @@ class PHPExcel_Calculation list($fName, $lfName) = explode('=', $localeFunction); $fName = trim($fName); $lfName = trim($lfName); - if ((isset(self::$_PHPExcelFunctions[$fName])) && ($lfName != '') && ($fName != $lfName)) { - self::$_localeFunctions[$fName] = $lfName; + if ((isset(self::$PHPExcelFunctions[$fName])) && ($lfName != '') && ($fName != $lfName)) { + self::$localeFunctions[$fName] = $lfName; } } } // Default the TRUE and FALSE constants to the locale names of the TRUE() and FALSE() functions - if (isset(self::$_localeFunctions['TRUE'])) { - self::$_localeBoolean['TRUE'] = self::$_localeFunctions['TRUE']; + if (isset(self::$localeFunctions['TRUE'])) { + self::$localeBoolean['TRUE'] = self::$localeFunctions['TRUE']; } - if (isset(self::$_localeFunctions['FALSE'])) { - self::$_localeBoolean['FALSE'] = self::$_localeFunctions['FALSE']; + if (isset(self::$localeFunctions['FALSE'])) { + self::$localeBoolean['FALSE'] = self::$localeFunctions['FALSE']; } $configFile = PHPEXCEL_ROOT . 'PHPExcel'.DIRECTORY_SEPARATOR.'locale'.DIRECTORY_SEPARATOR.str_replace('_', DIRECTORY_SEPARATOR, $locale).DIRECTORY_SEPARATOR.'config'; @@ -2034,7 +2034,7 @@ class PHPExcel_Calculation $settingName = strtoupper(trim($settingName)); switch ($settingName) { case 'ARGUMENTSEPARATOR': - self::$_localeArgumentSeparator = trim($settingValue); + self::$localeArgumentSeparator = trim($settingValue); break; } } @@ -2044,7 +2044,7 @@ class PHPExcel_Calculation self::$functionReplaceFromExcel = self::$functionReplaceToExcel = self::$functionReplaceFromLocale = self::$functionReplaceToLocale = null; - self::$_localeLanguage = $locale; + self::$localeLanguage = $locale; return true; } return false; @@ -2076,7 +2076,7 @@ class PHPExcel_Calculation private static function _translateFormula($from, $to, $formula, $fromSeparator, $toSeparator) { // Convert any Excel function names to the required language - if (self::$_localeLanguage !== 'en_us') { + if (self::$localeLanguage !== 'en_us') { $inBraces = false; // If there is the possibility of braces within a quoted string, then we don't treat those as matrix indicators if (strpos($formula, '"') !== false) { @@ -2111,10 +2111,10 @@ class PHPExcel_Calculation { if (self::$functionReplaceFromExcel === null) { self::$functionReplaceFromExcel = array(); - foreach (array_keys(self::$_localeFunctions) as $excelFunctionName) { + foreach (array_keys(self::$localeFunctions) as $excelFunctionName) { self::$functionReplaceFromExcel[] = '/(@?[^\w\.])'.preg_quote($excelFunctionName).'([\s]*\()/Ui'; } - foreach (array_keys(self::$_localeBoolean) as $excelBoolean) { + foreach (array_keys(self::$localeBoolean) as $excelBoolean) { self::$functionReplaceFromExcel[] = '/(@?[^\w\.])'.preg_quote($excelBoolean).'([^\w\.])/Ui'; } @@ -2122,15 +2122,15 @@ class PHPExcel_Calculation if (self::$functionReplaceToLocale === null) { self::$functionReplaceToLocale = array(); - foreach (array_values(self::$_localeFunctions) as $localeFunctionName) { + foreach (array_values(self::$localeFunctions) as $localeFunctionName) { self::$functionReplaceToLocale[] = '$1'.trim($localeFunctionName).'$2'; } - foreach (array_values(self::$_localeBoolean) as $localeBoolean) { + foreach (array_values(self::$localeBoolean) as $localeBoolean) { self::$functionReplaceToLocale[] = '$1'.trim($localeBoolean).'$2'; } } - return self::_translateFormula(self::$functionReplaceFromExcel, self::$functionReplaceToLocale, $formula, ',', self::$_localeArgumentSeparator); + return self::_translateFormula(self::$functionReplaceFromExcel, self::$functionReplaceToLocale, $formula, ',', self::$localeArgumentSeparator); } @@ -2141,35 +2141,35 @@ class PHPExcel_Calculation { if (self::$functionReplaceFromLocale === null) { self::$functionReplaceFromLocale = array(); - foreach (array_values(self::$_localeFunctions) as $localeFunctionName) { + foreach (array_values(self::$localeFunctions) as $localeFunctionName) { self::$functionReplaceFromLocale[] = '/(@?[^\w\.])'.preg_quote($localeFunctionName).'([\s]*\()/Ui'; } - foreach (array_values(self::$_localeBoolean) as $excelBoolean) { + foreach (array_values(self::$localeBoolean) as $excelBoolean) { self::$functionReplaceFromLocale[] = '/(@?[^\w\.])'.preg_quote($excelBoolean).'([^\w\.])/Ui'; } } if (self::$functionReplaceToExcel === null) { self::$functionReplaceToExcel = array(); - foreach (array_keys(self::$_localeFunctions) as $excelFunctionName) { + foreach (array_keys(self::$localeFunctions) as $excelFunctionName) { self::$functionReplaceToExcel[] = '$1'.trim($excelFunctionName).'$2'; } - foreach (array_keys(self::$_localeBoolean) as $excelBoolean) { + foreach (array_keys(self::$localeBoolean) as $excelBoolean) { self::$functionReplaceToExcel[] = '$1'.trim($excelBoolean).'$2'; } } - return self::_translateFormula(self::$functionReplaceFromLocale, self::$functionReplaceToExcel, $formula, self::$_localeArgumentSeparator, ','); + return self::_translateFormula(self::$functionReplaceFromLocale, self::$functionReplaceToExcel, $formula, self::$localeArgumentSeparator, ','); } - public static function _localeFunc($function) + public static function localeFunc($function) { - if (self::$_localeLanguage !== 'en_us') { + if (self::$localeLanguage !== 'en_us') { $functionName = trim($function, '('); - if (isset(self::$_localeFunctions[$functionName])) { + if (isset(self::$localeFunctions[$functionName])) { $brace = ($functionName != $function); - $function = self::$_localeFunctions[$functionName]; + $function = self::$localeFunctions[$functionName]; if ($brace) { $function .= '('; } @@ -2267,24 +2267,24 @@ class PHPExcel_Calculation // Initialise the logging settings if requested $this->formulaError = null; $this->_debugLog->clearLog(); - $this->_cyclicReferenceStack->clear(); - $this->_cyclicFormulaCount = 1; + $this->cyclicReferenceStack->clear(); + $this->cyclicFormulaCounter = 1; self::$returnArrayAsType = self::RETURN_ARRAY_AS_ARRAY; } // Execute the calculation for the cell formula - $this->_cellStack[] = array( + $this->cellStack[] = array( 'sheet' => $pCell->getWorksheet()->getTitle(), 'cell' => $pCell->getCoordinate(), ); try { $result = self::_unwrapResult($this->_calculateFormulaValue($pCell->getValue(), $pCell->getCoordinate(), $pCell)); - $cellAddress = array_pop($this->_cellStack); - $this->_workbook->getSheetByName($cellAddress['sheet'])->getCell($cellAddress['cell']); + $cellAddress = array_pop($this->cellStack); + $this->workbook->getSheetByName($cellAddress['sheet'])->getCell($cellAddress['cell']); } catch (PHPExcel_Exception $e) { - $cellAddress = array_pop($this->_cellStack); - $this->_workbook->getSheetByName($cellAddress['sheet'])->getCell($cellAddress['cell']); + $cellAddress = array_pop($this->cellStack); + $this->workbook->getSheetByName($cellAddress['sheet'])->getCell($cellAddress['cell']); throw new PHPExcel_Calculation_Exception($e->getMessage()); } @@ -2363,12 +2363,12 @@ class PHPExcel_Calculation // Initialise the logging settings $this->formulaError = null; $this->_debugLog->clearLog(); - $this->_cyclicReferenceStack->clear(); + $this->cyclicReferenceStack->clear(); // Disable calculation cacheing because it only applies to cell calculations, not straight formulae // But don't actually flush any cache $resetCache = $this->getCalculationCacheEnabled(); - $this->_calculationCacheEnabled = false; + $this->calculationCacheEnabled = false; // Execute the calculation try { $result = self::_unwrapResult($this->_calculateFormulaValue($formula, $cellID, $pCell)); @@ -2377,7 +2377,7 @@ class PHPExcel_Calculation } // Reset calculation cacheing to its previous state - $this->_calculationCacheEnabled = $resetCache; + $this->calculationCacheEnabled = $resetCache; return $result; } @@ -2388,10 +2388,10 @@ class PHPExcel_Calculation // Is calculation cacheing enabled? // Is the value present in calculation cache? $this->_debugLog->writeDebugLog('Testing cache value for cell ', $cellReference); - if (($this->_calculationCacheEnabled) && (isset($this->_calculationCache[$cellReference]))) { + if (($this->calculationCacheEnabled) && (isset($this->calculationCache[$cellReference]))) { $this->_debugLog->writeDebugLog('Retrieving value for cell ', $cellReference, ' from cache'); // Return the cached result - $cellValue = $this->_calculationCache[$cellReference]; + $cellValue = $this->calculationCache[$cellReference]; return true; } return false; @@ -2399,8 +2399,8 @@ class PHPExcel_Calculation public function saveValueToCache($cellReference, $cellValue) { - if ($this->_calculationCacheEnabled) { - $this->_calculationCache[$cellReference] = $cellValue; + if ($this->calculationCacheEnabled) { + $this->calculationCache[$cellReference] = $cellValue; } } @@ -2436,28 +2436,28 @@ class PHPExcel_Calculation return $cellValue; } - if (($wsTitle{0} !== "\x00") && ($this->_cyclicReferenceStack->onStack($wsCellReference))) { + if (($wsTitle{0} !== "\x00") && ($this->cyclicReferenceStack->onStack($wsCellReference))) { if ($this->cyclicFormulaCount <= 0) { - $this->_cyclicFormulaCell = ''; + $this->cyclicFormulaCell = ''; return $this->_raiseFormulaError('Cyclic Reference in Formula'); - } elseif ($this->_cyclicFormulaCell === $wsCellReference) { - ++$this->_cyclicFormulaCount; - if ($this->_cyclicFormulaCount >= $this->cyclicFormulaCount) { - $this->_cyclicFormulaCell = ''; + } elseif ($this->cyclicFormulaCell === $wsCellReference) { + ++$this->cyclicFormulaCounter; + if ($this->cyclicFormulaCounter >= $this->cyclicFormulaCount) { + $this->cyclicFormulaCell = ''; return $cellValue; } - } elseif ($this->_cyclicFormulaCell == '') { - if ($this->_cyclicFormulaCount >= $this->cyclicFormulaCount) { + } elseif ($this->cyclicFormulaCell == '') { + if ($this->cyclicFormulaCounter >= $this->cyclicFormulaCount) { return $cellValue; } - $this->_cyclicFormulaCell = $wsCellReference; + $this->cyclicFormulaCell = $wsCellReference; } } // Parse the formula onto the token stack and calculate the value - $this->_cyclicReferenceStack->push($wsCellReference); + $this->cyclicReferenceStack->push($wsCellReference); $cellValue = $this->_processTokenStack($this->_parseFormula($formula, $pCell), $cellID, $pCell); - $this->_cyclicReferenceStack->pop(); + $this->cyclicReferenceStack->pop(); // Save to calculation cache if ($cellID !== null) { @@ -2656,7 +2656,7 @@ class PHPExcel_Calculation } elseif (is_string($value) && (trim($value, '"') == $value)) { return '"'.$value.'"'; } elseif (is_bool($value)) { - return ($value) ? self::$_localeBoolean['TRUE'] : self::$_localeBoolean['FALSE']; + return ($value) ? self::$localeBoolean['TRUE'] : self::$localeBoolean['FALSE']; } } return PHPExcel_Calculation_Functions::flattenSingleValue($value); @@ -2848,11 +2848,11 @@ class PHPExcel_Calculation } elseif ((($opCharacter == '~') || ($opCharacter == '|')) && (!$isOperandOrFunction)) { // We have to explicitly deny a tilde or pipe, because they are legal return $this->_raiseFormulaError("Formula Error: Illegal character '~'"); // on the stack but not in the input expression - } elseif ((isset(self::$_operators[$opCharacter]) or $isOperandOrFunction) && $expectingOperator) { // Are we putting an operator on the stack? + } elseif ((isset(self::$operators[$opCharacter]) or $isOperandOrFunction) && $expectingOperator) { // Are we putting an operator on the stack? //echo 'Element with value '.$opCharacter.' is an Operator', PHP_EOL; while ($stack->count() > 0 && ($o2 = $stack->last()) && - isset(self::$_operators[$o2['value']]) && + isset(self::$operators[$o2['value']]) && @(self::$_operatorAssociativity[$opCharacter] ? self::$_operatorPrecedence[$opCharacter] < self::$_operatorPrecedence[$o2['value']] : self::$_operatorPrecedence[$opCharacter] <= self::$_operatorPrecedence[$o2['value']])) { $output[] = $stack->pop(); // Swap operands and higher precedence operators from the stack to the output } @@ -2885,14 +2885,14 @@ class PHPExcel_Calculation //} $output[] = $d; // Dump the argument count on the output $output[] = $stack->pop(); // Pop the function and push onto the output - if (isset(self::$_controlFunctions[$functionName])) { + if (isset(self::$controlFunctions[$functionName])) { //echo 'Built-in function '.$functionName, PHP_EOL; - $expectedArgumentCount = self::$_controlFunctions[$functionName]['argumentCount']; - $functionCall = self::$_controlFunctions[$functionName]['functionCall']; - } elseif (isset(self::$_PHPExcelFunctions[$functionName])) { + $expectedArgumentCount = self::$controlFunctions[$functionName]['argumentCount']; + $functionCall = self::$controlFunctions[$functionName]['functionCall']; + } elseif (isset(self::$PHPExcelFunctions[$functionName])) { //echo 'PHPExcel function '.$functionName, PHP_EOL; - $expectedArgumentCount = self::$_PHPExcelFunctions[$functionName]['argumentCount']; - $functionCall = self::$_PHPExcelFunctions[$functionName]['functionCall']; + $expectedArgumentCount = self::$PHPExcelFunctions[$functionName]['argumentCount']; + $functionCall = self::$PHPExcelFunctions[$functionName]['functionCall']; } else { // did we somehow push a non-function on the stack? this should never happen return $this->_raiseFormulaError("Formula Error: Internal error, non-function on stack"); } @@ -2955,7 +2955,7 @@ class PHPExcel_Calculation // If we've a comma when we're expecting an operand, then what we actually have is a null operand; // so push a null onto the stack if (($expectingOperand) || (!$expectingOperator)) { - $output[] = array('type' => 'NULL Value', 'value' => self::$_ExcelConstants['NULL'], 'reference' => null); + $output[] = array('type' => 'NULL Value', 'value' => self::$excelConstants['NULL'], 'reference' => null); } // make sure there was a function $d = $stack->last(2); @@ -2984,7 +2984,7 @@ class PHPExcel_Calculation if (preg_match('/^'.self::CALCULATION_REGEXP_FUNCTION.'$/i', $val, $matches)) { $val = preg_replace('/\s/u', '', $val); // echo 'Element '.$val.' is a Function
'; - if (isset(self::$_PHPExcelFunctions[strtoupper($matches[1])]) || isset(self::$_controlFunctions[strtoupper($matches[1])])) { // it's a function + if (isset(self::$PHPExcelFunctions[strtoupper($matches[1])]) || isset(self::$controlFunctions[strtoupper($matches[1])])) { // it's a function $stack->push('Function', strtoupper($val)); $ax = preg_match('/^\s*(\s*\))/ui', substr($formula, $index+$length), $amatch); if ($ax) { @@ -3071,13 +3071,13 @@ class PHPExcel_Calculation // echo 'Casting '.$val.' to integer
'; $val = (integer) $val; } - } elseif (isset(self::$_ExcelConstants[trim(strtoupper($val))])) { + } elseif (isset(self::$excelConstants[trim(strtoupper($val))])) { $excelConstant = trim(strtoupper($val)); // echo 'Element '.$excelConstant.' is an Excel Constant
'; - $val = self::$_ExcelConstants[$excelConstant]; - } elseif (($localeConstant = array_search(trim(strtoupper($val)), self::$_localeBoolean)) !== false) { + $val = self::$excelConstants[$excelConstant]; + } elseif (($localeConstant = array_search(trim(strtoupper($val)), self::$localeBoolean)) !== false) { // echo 'Element '.$localeConstant.' is an Excel Constant
'; - $val = self::$_ExcelConstants[$localeConstant]; + $val = self::$excelConstants[$localeConstant]; } $details = array('type' => 'Value', 'value' => $val, 'reference' => null); if ($localeConstant) { @@ -3091,13 +3091,13 @@ class PHPExcel_Calculation ++$index; } elseif ($opCharacter == ')') { // miscellaneous error checking if ($expectingOperand) { - $output[] = array('type' => 'NULL Value', 'value' => self::$_ExcelConstants['NULL'], 'reference' => null); + $output[] = array('type' => 'NULL Value', 'value' => self::$excelConstants['NULL'], 'reference' => null); $expectingOperand = false; $expectingOperator = true; } else { return $this->_raiseFormulaError("Formula Error: Unexpected ')'"); } - } elseif (isset(self::$_operators[$opCharacter]) && !$expectingOperator) { + } elseif (isset(self::$operators[$opCharacter]) && !$expectingOperator) { return $this->_raiseFormulaError("Formula Error: Unexpected operator '$opCharacter'"); } else { // I don't even want to know what you did to get here return $this->_raiseFormulaError("Formula Error: An unexpected error occured"); @@ -3106,7 +3106,7 @@ class PHPExcel_Calculation if ($index == strlen($formula)) { // Did we end with an operator?. // Only valid for the % unary operator - if ((isset(self::$_operators[$opCharacter])) && ($opCharacter != '%')) { + if ((isset(self::$operators[$opCharacter])) && ($opCharacter != '%')) { return $this->_raiseFormulaError("Formula Error: Operator '$opCharacter' has no operands"); } else { break; @@ -3128,7 +3128,7 @@ class PHPExcel_Calculation // echo 'Element is an Intersect Operator
'; while ($stack->count() > 0 && ($o2 = $stack->last()) && - isset(self::$_operators[$o2['value']]) && + isset(self::$operators[$o2['value']]) && @(self::$_operatorAssociativity[$opCharacter] ? self::$_operatorPrecedence[$opCharacter] < self::$_operatorPrecedence[$o2['value']] : self::$_operatorPrecedence[$opCharacter] <= self::$_operatorPrecedence[$o2['value']])) { $output[] = $stack->pop(); // Swap operands and higher precedence operators from the stack to the output } @@ -3183,7 +3183,7 @@ class PHPExcel_Calculation $token = $tokenData['value']; // echo 'Token is '.$token.'
'; // if the token is a binary operator, pop the top two values off the stack, do the operation, and push the result back on the stack - if (isset(self::$_binaryOperators[$token])) { + if (isset(self::$binaryOperators[$token])) { // echo 'Token is a binary operator
'; // We must have two operands, error if we don't if (($operand2Data = $stack->pop()) === null) { @@ -3256,7 +3256,7 @@ class PHPExcel_Calculation } $cellRef = PHPExcel_Cell::stringFromColumnIndex(min($oCol)).min($oRow).':'.PHPExcel_Cell::stringFromColumnIndex(max($oCol)).max($oRow); if ($pCellParent !== null) { - $cellValue = $this->extractCellRange($cellRef, $this->_workbook->getSheetByName($sheet1), false); + $cellValue = $this->extractCellRange($cellRef, $this->workbook->getSheetByName($sheet1), false); } else { return $this->_raiseFormulaError('Unable to access Cell Reference'); } @@ -3285,10 +3285,10 @@ class PHPExcel_Calculation // (converting the other operand to a matrix if need be); then perform the required // matrix operation if (is_bool($operand1)) { - $operand1 = ($operand1) ? self::$_localeBoolean['TRUE'] : self::$_localeBoolean['FALSE']; + $operand1 = ($operand1) ? self::$localeBoolean['TRUE'] : self::$localeBoolean['FALSE']; } if (is_bool($operand2)) { - $operand2 = ($operand2) ? self::$_localeBoolean['TRUE'] : self::$_localeBoolean['FALSE']; + $operand2 = ($operand2) ? self::$localeBoolean['TRUE'] : self::$localeBoolean['FALSE']; } if ((is_array($operand1)) || (is_array($operand2))) { // Ensure that both operands are arrays/matrices @@ -3377,7 +3377,7 @@ class PHPExcel_Calculation // echo '$cellRef='.$cellRef.' in worksheet '.$matches[2].'
'; $this->_debugLog->writeDebugLog('Evaluating Cell Range ', $cellRef, ' in worksheet ', $matches[2]); if ($pCellParent !== null) { - $cellValue = $this->extractCellRange($cellRef, $this->_workbook->getSheetByName($matches[2]), false); + $cellValue = $this->extractCellRange($cellRef, $this->workbook->getSheetByName($matches[2]), false); } else { return $this->_raiseFormulaError('Unable to access Cell Reference'); } @@ -3410,9 +3410,9 @@ class PHPExcel_Calculation // echo '$cellRef='.$cellRef.' in worksheet '.$matches[2].'
'; $this->_debugLog->writeDebugLog('Evaluating Cell ', $cellRef, ' in worksheet ', $matches[2]); if ($pCellParent !== null) { - $cellSheet = $this->_workbook->getSheetByName($matches[2]); + $cellSheet = $this->workbook->getSheetByName($matches[2]); if ($cellSheet && $cellSheet->cellExists($cellRef)) { - $cellValue = $this->extractCellRange($cellRef, $this->_workbook->getSheetByName($matches[2]), false); + $cellValue = $this->extractCellRange($cellRef, $this->workbook->getSheetByName($matches[2]), false); $pCell->attach($pCellParent); } else { $cellValue = null; @@ -3444,17 +3444,17 @@ class PHPExcel_Calculation $argCount = $stack->pop(); $argCount = $argCount['value']; if ($functionName != 'MKMATRIX') { - $this->_debugLog->writeDebugLog('Evaluating Function ', self::_localeFunc($functionName), '() with ', (($argCount == 0) ? 'no' : $argCount), ' argument', (($argCount == 1) ? '' : 's')); + $this->_debugLog->writeDebugLog('Evaluating Function ', self::localeFunc($functionName), '() with ', (($argCount == 0) ? 'no' : $argCount), ' argument', (($argCount == 1) ? '' : 's')); } - if ((isset(self::$_PHPExcelFunctions[$functionName])) || (isset(self::$_controlFunctions[$functionName]))) { // function - if (isset(self::$_PHPExcelFunctions[$functionName])) { - $functionCall = self::$_PHPExcelFunctions[$functionName]['functionCall']; - $passByReference = isset(self::$_PHPExcelFunctions[$functionName]['passByReference']); - $passCellReference = isset(self::$_PHPExcelFunctions[$functionName]['passCellReference']); - } elseif (isset(self::$_controlFunctions[$functionName])) { - $functionCall = self::$_controlFunctions[$functionName]['functionCall']; - $passByReference = isset(self::$_controlFunctions[$functionName]['passByReference']); - $passCellReference = isset(self::$_controlFunctions[$functionName]['passCellReference']); + if ((isset(self::$PHPExcelFunctions[$functionName])) || (isset(self::$controlFunctions[$functionName]))) { // function + if (isset(self::$PHPExcelFunctions[$functionName])) { + $functionCall = self::$PHPExcelFunctions[$functionName]['functionCall']; + $passByReference = isset(self::$PHPExcelFunctions[$functionName]['passByReference']); + $passCellReference = isset(self::$PHPExcelFunctions[$functionName]['passCellReference']); + } elseif (isset(self::$controlFunctions[$functionName])) { + $functionCall = self::$controlFunctions[$functionName]['functionCall']; + $passByReference = isset(self::$controlFunctions[$functionName]['passByReference']); + $passCellReference = isset(self::$controlFunctions[$functionName]['passCellReference']); } // get the arguments for this function // echo 'Function '.$functionName.' expects '.$argCount.' arguments
'; @@ -3463,8 +3463,8 @@ class PHPExcel_Calculation $arg = $stack->pop(); $a = $argCount - $i - 1; if (($passByReference) && - (isset(self::$_PHPExcelFunctions[$functionName]['passByReference'][$a])) && - (self::$_PHPExcelFunctions[$functionName]['passByReference'][$a])) { + (isset(self::$PHPExcelFunctions[$functionName]['passByReference'][$a])) && + (self::$PHPExcelFunctions[$functionName]['passByReference'][$a])) { if ($arg['reference'] === null) { $args[] = $cellID; if ($functionName != 'MKMATRIX') { @@ -3495,7 +3495,7 @@ class PHPExcel_Calculation if ($functionName != 'MKMATRIX') { if ($this->_debugLog->getWriteDebugLog()) { krsort($argArrayVals); - $this->_debugLog->writeDebugLog('Evaluating ', self::_localeFunc($functionName), '( ', implode(self::$_localeArgumentSeparator.' ', PHPExcel_Calculation_Functions::flattenArray($argArrayVals)), ' )'); + $this->_debugLog->writeDebugLog('Evaluating ', self::localeFunc($functionName), '( ', implode(self::$localeArgumentSeparator.' ', PHPExcel_Calculation_Functions::flattenArray($argArrayVals)), ' )'); } } // Process each argument in turn, building the return value as an array @@ -3507,16 +3507,16 @@ class PHPExcel_Calculation // foreach($operand1 as $args) { // if (is_array($args)) { // foreach($args as $arg) { -// $this->_debugLog->writeDebugLog('Evaluating ', self::_localeFunc($functionName), '( ', $this->_showValue($arg), ' )'); +// $this->_debugLog->writeDebugLog('Evaluating ', self::localeFunc($functionName), '( ', $this->_showValue($arg), ' )'); // $r = call_user_func_array($functionCall, $arg); -// $this->_debugLog->writeDebugLog('Evaluation Result for ', self::_localeFunc($functionName), '() function call is ', $this->_showTypeDetails($r)); +// $this->_debugLog->writeDebugLog('Evaluation Result for ', self::localeFunc($functionName), '() function call is ', $this->_showTypeDetails($r)); // $result[$row][] = $r; // } // ++$row; // } else { -// $this->_debugLog->writeDebugLog('Evaluating ', self::_localeFunc($functionName), '( ', $this->_showValue($args), ' )'); +// $this->_debugLog->writeDebugLog('Evaluating ', self::localeFunc($functionName), '( ', $this->_showValue($args), ' )'); // $r = call_user_func_array($functionCall, $args); -// $this->_debugLog->writeDebugLog('Evaluation Result for ', self::_localeFunc($functionName), '() function call is ', $this->_showTypeDetails($r)); +// $this->_debugLog->writeDebugLog('Evaluation Result for ', self::localeFunc($functionName), '() function call is ', $this->_showTypeDetails($r)); // $result[] = $r; // } // } @@ -3535,18 +3535,18 @@ class PHPExcel_Calculation $result = call_user_func_array($functionCall, $args); } if ($functionName != 'MKMATRIX') { - $this->_debugLog->writeDebugLog('Evaluation Result for ', self::_localeFunc($functionName), '() function call is ', $this->_showTypeDetails($result)); + $this->_debugLog->writeDebugLog('Evaluation Result for ', self::localeFunc($functionName), '() function call is ', $this->_showTypeDetails($result)); } $stack->push('Value', self::_wrapResult($result)); } } else { // if the token is a number, boolean, string or an Excel error, push it onto the stack - if (isset(self::$_ExcelConstants[strtoupper($token)])) { + if (isset(self::$excelConstants[strtoupper($token)])) { $excelConstant = strtoupper($token); // echo 'Token is a PHPExcel constant: '.$excelConstant.'
'; - $stack->push('Constant Value', self::$_ExcelConstants[$excelConstant]); - $this->_debugLog->writeDebugLog('Evaluating Constant ', $excelConstant, ' as ', $this->_showTypeDetails(self::$_ExcelConstants[$excelConstant])); + $stack->push('Constant Value', self::$excelConstants[$excelConstant]); + $this->_debugLog->writeDebugLog('Evaluating Constant ', $excelConstant, ' as ', $this->_showTypeDetails(self::$excelConstants[$excelConstant])); } elseif ((is_numeric($token)) || ($token === null) || (is_bool($token)) || ($token == '') || ($token{0} == '"') || ($token{0} == '#')) { // echo 'Token is a number, boolean, string, null or an Excel error
'; $stack->push('Value', $token); @@ -3828,7 +3828,7 @@ class PHPExcel_Calculation protected function _raiseFormulaError($errorMessage) { $this->formulaError = $errorMessage; - $this->_cyclicReferenceStack->clear(); + $this->cyclicReferenceStack->clear(); if (!$this->suppressFormulaErrors) { throw new PHPExcel_Calculation_Exception($errorMessage); } @@ -3860,7 +3860,7 @@ class PHPExcel_Calculation list($pSheetName, $pRange) = PHPExcel_Worksheet::extractSheetTitle($pRange, true); // echo 'New sheet name is '.$pSheetName, PHP_EOL; // echo 'Adjusted Range reference is '.$pRange, PHP_EOL; - $pSheet = $this->_workbook->getSheetByName($pSheetName); + $pSheet = $this->workbook->getSheetByName($pSheetName); } // Extract range @@ -3918,7 +3918,7 @@ class PHPExcel_Calculation list($pSheetName, $pRange) = PHPExcel_Worksheet::extractSheetTitle($pRange, true); // echo 'New sheet name is '.$pSheetName, PHP_EOL; // echo 'Adjusted Range reference is '.$pRange, PHP_EOL; - $pSheet = $this->_workbook->getSheetByName($pSheetName); + $pSheet = $this->workbook->getSheetByName($pSheetName); } // Named range? @@ -3990,8 +3990,8 @@ class PHPExcel_Calculation public function isImplemented($pFunction = '') { $pFunction = strtoupper($pFunction); - if (isset(self::$_PHPExcelFunctions[$pFunction])) { - return (self::$_PHPExcelFunctions[$pFunction]['functionCall'] != 'PHPExcel_Calculation_Functions::DUMMY'); + if (isset(self::$PHPExcelFunctions[$pFunction])) { + return (self::$PHPExcelFunctions[$pFunction]['functionCall'] != 'PHPExcel_Calculation_Functions::DUMMY'); } else { return false; } @@ -4007,7 +4007,7 @@ class PHPExcel_Calculation { $returnValue = array(); - foreach (self::$_PHPExcelFunctions as $functionName => $function) { + foreach (self::$PHPExcelFunctions as $functionName => $function) { if ($function['functionCall'] != 'PHPExcel_Calculation_Functions::DUMMY') { $returnValue[$functionName] = new PHPExcel_Calculation_Function( $function['category'], @@ -4028,7 +4028,7 @@ class PHPExcel_Calculation */ public function listAllFunctionNames() { - return array_keys(self::$_PHPExcelFunctions); + return array_keys(self::$PHPExcelFunctions); } /** @@ -4039,7 +4039,7 @@ class PHPExcel_Calculation public function listFunctionNames() { $returnValue = array(); - foreach (self::$_PHPExcelFunctions as $functionName => $function) { + foreach (self::$PHPExcelFunctions as $functionName => $function) { if ($function['functionCall'] != 'PHPExcel_Calculation_Functions::DUMMY') { $returnValue[] = $functionName; } diff --git a/Classes/PHPExcel/Calculation/Token/Stack.php b/Classes/PHPExcel/Calculation/Token/Stack.php index 13f446ab..02ed5aaf 100644 --- a/Classes/PHPExcel/Calculation/Token/Stack.php +++ b/Classes/PHPExcel/Calculation/Token/Stack.php @@ -66,7 +66,7 @@ class PHPExcel_Calculation_Token_Stack 'reference' => $reference ); if ($type == 'Function') { - $localeFunction = PHPExcel_Calculation::_localeFunc($value); + $localeFunction = PHPExcel_Calculation::localeFunc($value); if ($localeFunction != $value) { $this->stack[($this->count - 1)]['localeValue'] = $localeFunction; } diff --git a/Classes/PHPExcel/Cell.php b/Classes/PHPExcel/Cell.php index 5250cba5..8bc5dac9 100644 --- a/Classes/PHPExcel/Cell.php +++ b/Classes/PHPExcel/Cell.php @@ -40,14 +40,14 @@ class PHPExcel_Cell * * @var PHPExcel_Cell_IValueBinder */ - private static $_valueBinder; + private static $valueBinder; /** * Value of the cell * * @var mixed */ - private $_value; + private $value; /** * Calculated value of the cell (used for caching) @@ -59,34 +59,34 @@ class PHPExcel_Cell * * @var mixed */ - private $_calculatedValue; + private $calculatedValue; /** * Type of the cell data * * @var string */ - private $_dataType; + private $dataType; /** * Parent worksheet * * @var PHPExcel_CachedObjectStorage_CacheBase */ - private $_parent; + private $parent; /** * Index to cellXf * * @var int */ - private $_xfIndex = 0; + private $xfIndex = 0; /** * Attributes of the formula * */ - private $_formulaAttributes; + private $formulaAttributes; /** @@ -96,19 +96,19 @@ class PHPExcel_Cell **/ public function notifyCacheController() { - $this->_parent->updateCacheData($this); + $this->parent->updateCacheData($this); return $this; } public function detach() { - $this->_parent = null; + $this->parent = null; } public function attach(PHPExcel_CachedObjectStorage_CacheBase $parent) { - $this->_parent = $parent; + $this->parent = $parent; } @@ -123,17 +123,17 @@ class PHPExcel_Cell public function __construct($pValue = null, $pDataType = null, PHPExcel_Worksheet $pSheet = null) { // Initialise cell value - $this->_value = $pValue; + $this->value = $pValue; // Set worksheet cache - $this->_parent = $pSheet->getCellCacheController(); + $this->parent = $pSheet->getCellCacheController(); // Set datatype? if ($pDataType !== null) { if ($pDataType == PHPExcel_Cell_DataType::TYPE_STRING2) { $pDataType = PHPExcel_Cell_DataType::TYPE_STRING; } - $this->_dataType = $pDataType; + $this->dataType = $pDataType; } elseif (!self::getValueBinder()->bindValue($this, $pValue)) { throw new PHPExcel_Exception("Value could not be bound to cell."); } @@ -146,7 +146,7 @@ class PHPExcel_Cell */ public function getColumn() { - return $this->_parent->getCurrentColumn(); + return $this->parent->getCurrentColumn(); } /** @@ -156,7 +156,7 @@ class PHPExcel_Cell */ public function getRow() { - return $this->_parent->getCurrentRow(); + return $this->parent->getCurrentRow(); } /** @@ -166,7 +166,7 @@ class PHPExcel_Cell */ public function getCoordinate() { - return $this->_parent->getCurrentAddress(); + return $this->parent->getCurrentAddress(); } /** @@ -176,7 +176,7 @@ class PHPExcel_Cell */ public function getValue() { - return $this->_value; + return $this->value; } /** @@ -223,7 +223,7 @@ class PHPExcel_Cell // set the value according to data type switch ($pDataType) { case PHPExcel_Cell_DataType::TYPE_NULL: - $this->_value = $pValue; + $this->value = $pValue; break; case PHPExcel_Cell_DataType::TYPE_STRING2: $pDataType = PHPExcel_Cell_DataType::TYPE_STRING; @@ -231,19 +231,19 @@ class PHPExcel_Cell // Synonym for string case PHPExcel_Cell_DataType::TYPE_INLINE: // Rich text - $this->_value = PHPExcel_Cell_DataType::checkString($pValue); + $this->value = PHPExcel_Cell_DataType::checkString($pValue); break; case PHPExcel_Cell_DataType::TYPE_NUMERIC: - $this->_value = (float) $pValue; + $this->value = (float) $pValue; break; case PHPExcel_Cell_DataType::TYPE_FORMULA: - $this->_value = (string) $pValue; + $this->value = (string) $pValue; break; case PHPExcel_Cell_DataType::TYPE_BOOL: - $this->_value = (bool) $pValue; + $this->value = (bool) $pValue; break; case PHPExcel_Cell_DataType::TYPE_ERROR: - $this->_value = PHPExcel_Cell_DataType::checkErrorCode($pValue); + $this->value = PHPExcel_Cell_DataType::checkErrorCode($pValue); break; default: throw new PHPExcel_Exception('Invalid datatype: ' . $pDataType); @@ -251,7 +251,7 @@ class PHPExcel_Cell } // set the datatype - $this->_dataType = $pDataType; + $this->dataType = $pDataType; return $this->notifyCacheController(); } @@ -267,8 +267,8 @@ class PHPExcel_Cell */ public function getCalculatedValue($resetLog = true) { -//echo 'Cell '.$this->getCoordinate().' value is a '.$this->_dataType.' with a value of '.$this->getValue().PHP_EOL; - if ($this->_dataType == PHPExcel_Cell_DataType::TYPE_FORMULA) { +//echo 'Cell '.$this->getCoordinate().' value is a '.$this->dataType.' with a value of '.$this->getValue().PHP_EOL; + if ($this->dataType == PHPExcel_Cell_DataType::TYPE_FORMULA) { try { //echo 'Cell value for '.$this->getCoordinate().' is a formula: Calculating value'.PHP_EOL; $result = PHPExcel_Calculation::getInstance( @@ -282,9 +282,9 @@ class PHPExcel_Cell } } } catch (PHPExcel_Exception $ex) { - if (($ex->getMessage() === 'Unable to access External Workbook') && ($this->_calculatedValue !== null)) { -//echo 'Returning fallback value of '.$this->_calculatedValue.' for cell '.$this->getCoordinate().PHP_EOL; - return $this->_calculatedValue; // Fallback for calculations referencing external files. + if (($ex->getMessage() === 'Unable to access External Workbook') && ($this->calculatedValue !== null)) { +//echo 'Returning fallback value of '.$this->calculatedValue.' for cell '.$this->getCoordinate().PHP_EOL; + return $this->calculatedValue; // Fallback for calculations referencing external files. } //echo 'Calculation Exception: '.$ex->getMessage().PHP_EOL; $result = '#N/A'; @@ -294,17 +294,17 @@ class PHPExcel_Cell } if ($result === '#Not Yet Implemented') { -//echo 'Returning fallback value of '.$this->_calculatedValue.' for cell '.$this->getCoordinate().PHP_EOL; - return $this->_calculatedValue; // Fallback if calculation engine does not support the formula. +//echo 'Returning fallback value of '.$this->calculatedValue.' for cell '.$this->getCoordinate().PHP_EOL; + return $this->calculatedValue; // Fallback if calculation engine does not support the formula. } //echo 'Returning calculated value of '.$result.' for cell '.$this->getCoordinate().PHP_EOL; return $result; - } elseif ($this->_value instanceof PHPExcel_RichText) { -// echo 'Cell value for '.$this->getCoordinate().' is rich text: Returning data value of '.$this->_value.'
'; - return $this->_value->getPlainText(); + } elseif ($this->value instanceof PHPExcel_RichText) { +// echo 'Cell value for '.$this->getCoordinate().' is rich text: Returning data value of '.$this->value.'
'; + return $this->value->getPlainText(); } -// echo 'Cell value for '.$this->getCoordinate().' is not a formula: Returning data value of '.$this->_value.'
'; - return $this->_value; +// echo 'Cell value for '.$this->getCoordinate().' is not a formula: Returning data value of '.$this->value.'
'; + return $this->value; } /** @@ -316,7 +316,7 @@ class PHPExcel_Cell public function setCalculatedValue($pValue = null) { if ($pValue !== null) { - $this->_calculatedValue = (is_numeric($pValue)) ? (float) $pValue : $pValue; + $this->calculatedValue = (is_numeric($pValue)) ? (float) $pValue : $pValue; } return $this->notifyCacheController(); @@ -334,7 +334,7 @@ class PHPExcel_Cell */ public function getOldCalculatedValue() { - return $this->_calculatedValue; + return $this->calculatedValue; } /** @@ -344,7 +344,7 @@ class PHPExcel_Cell */ public function getDataType() { - return $this->_dataType; + return $this->dataType; } /** @@ -358,7 +358,7 @@ class PHPExcel_Cell if ($pDataType == PHPExcel_Cell_DataType::TYPE_STRING2) { $pDataType = PHPExcel_Cell_DataType::TYPE_STRING; } - $this->_dataType = $pDataType; + $this->dataType = $pDataType; return $this->notifyCacheController(); } @@ -370,7 +370,7 @@ class PHPExcel_Cell */ public function isFormula() { - return $this->_dataType == PHPExcel_Cell_DataType::TYPE_FORMULA; + return $this->dataType == PHPExcel_Cell_DataType::TYPE_FORMULA; } /** @@ -381,7 +381,7 @@ class PHPExcel_Cell */ public function hasDataValidation() { - if (!isset($this->_parent)) { + if (!isset($this->parent)) { throw new PHPExcel_Exception('Cannot check for data validation when cell is not bound to a worksheet'); } @@ -396,7 +396,7 @@ class PHPExcel_Cell */ public function getDataValidation() { - if (!isset($this->_parent)) { + if (!isset($this->parent)) { throw new PHPExcel_Exception('Cannot get data validation for cell that is not bound to a worksheet'); } @@ -412,7 +412,7 @@ class PHPExcel_Cell */ public function setDataValidation(PHPExcel_Cell_DataValidation $pDataValidation = null) { - if (!isset($this->_parent)) { + if (!isset($this->parent)) { throw new PHPExcel_Exception('Cannot set data validation for cell that is not bound to a worksheet'); } @@ -429,7 +429,7 @@ class PHPExcel_Cell */ public function hasHyperlink() { - if (!isset($this->_parent)) { + if (!isset($this->parent)) { throw new PHPExcel_Exception('Cannot check for hyperlink when cell is not bound to a worksheet'); } @@ -444,7 +444,7 @@ class PHPExcel_Cell */ public function getHyperlink() { - if (!isset($this->_parent)) { + if (!isset($this->parent)) { throw new PHPExcel_Exception('Cannot get hyperlink for cell that is not bound to a worksheet'); } @@ -460,7 +460,7 @@ class PHPExcel_Cell */ public function setHyperlink(PHPExcel_Cell_Hyperlink $pHyperlink = null) { - if (!isset($this->_parent)) { + if (!isset($this->parent)) { throw new PHPExcel_Exception('Cannot set hyperlink for cell that is not bound to a worksheet'); } @@ -476,7 +476,7 @@ class PHPExcel_Cell */ public function getParent() { - return $this->_parent; + return $this->parent; } /** @@ -486,7 +486,7 @@ class PHPExcel_Cell */ public function getWorksheet() { - return $this->_parent->getParent(); + return $this->parent->getParent(); } /** @@ -549,7 +549,7 @@ class PHPExcel_Cell */ public function rebindParent(PHPExcel_Worksheet $parent) { - $this->_parent = $parent->getCellCacheController(); + $this->parent = $parent->getCellCacheController(); return $this->notifyCacheController(); } @@ -943,11 +943,11 @@ class PHPExcel_Cell */ public static function getValueBinder() { - if (self::$_valueBinder === null) { - self::$_valueBinder = new PHPExcel_Cell_DefaultValueBinder(); + if (self::$valueBinder === null) { + self::$valueBinder = new PHPExcel_Cell_DefaultValueBinder(); } - return self::$_valueBinder; + return self::$valueBinder; } /** @@ -962,7 +962,7 @@ class PHPExcel_Cell throw new PHPExcel_Exception("A PHPExcel_Cell_IValueBinder is required for PHPExcel to function correctly."); } - self::$_valueBinder = $binder; + self::$valueBinder = $binder; } /** @@ -972,7 +972,7 @@ class PHPExcel_Cell { $vars = get_object_vars($this); foreach ($vars as $key => $value) { - if ((is_object($value)) && ($key != '_parent')) { + if ((is_object($value)) && ($key != 'parent')) { $this->$key = clone $value; } else { $this->$key = $value; @@ -987,7 +987,7 @@ class PHPExcel_Cell */ public function getXfIndex() { - return $this->_xfIndex; + return $this->xfIndex; } /** @@ -998,7 +998,7 @@ class PHPExcel_Cell */ public function setXfIndex($pValue = 0) { - $this->_xfIndex = $pValue; + $this->xfIndex = $pValue; return $this->notifyCacheController(); } @@ -1008,7 +1008,7 @@ class PHPExcel_Cell */ public function setFormulaAttributes($pAttributes) { - $this->_formulaAttributes = $pAttributes; + $this->formulaAttributes = $pAttributes; return $this; } @@ -1017,7 +1017,7 @@ class PHPExcel_Cell */ public function getFormulaAttributes() { - return $this->_formulaAttributes; + return $this->formulaAttributes; } /** diff --git a/Classes/PHPExcel/Chart/Renderer/jpgraph.php b/Classes/PHPExcel/Chart/Renderer/jpgraph.php index a62f0b79..b95f3b28 100644 --- a/Classes/PHPExcel/Chart/Renderer/jpgraph.php +++ b/Classes/PHPExcel/Chart/Renderer/jpgraph.php @@ -1,846 +1,874 @@ - MARK_DIAMOND, - 'square' => MARK_SQUARE, - 'triangle' => MARK_UTRIANGLE, - 'x' => MARK_X, - 'star' => MARK_STAR, - 'dot' => MARK_FILLEDCIRCLE, - 'dash' => MARK_DTRIANGLE, - 'circle' => MARK_CIRCLE, - 'plus' => MARK_CROSS - ); - - - private $chart; - - private $graph; - - private static $_plotColour = 0; - - private static $_plotMark = 0; - - - private function formatPointMarker($seriesPlot, $markerID) { - $plotMarkKeys = array_keys(self::$markSet); - if (is_null($markerID)) { - // Use default plot marker (next marker in the series) - self::$_plotMark %= count(self::$markSet); - $seriesPlot->mark->SetType(self::$markSet[$plotMarkKeys[self::$_plotMark++]]); - } elseif ($markerID !== 'none') { - // Use specified plot marker (if it exists) - if (isset(self::$markSet[$markerID])) { - $seriesPlot->mark->SetType(self::$markSet[$markerID]); - } else { - // If the specified plot marker doesn't exist, use default plot marker (next marker in the series) - self::$_plotMark %= count(self::$markSet); - $seriesPlot->mark->SetType(self::$markSet[$plotMarkKeys[self::$_plotMark++]]); - } - } else { - // Hide plot marker - $seriesPlot->mark->Hide(); - } - $seriesPlot->mark->SetColor(self::$colourSet[self::$_plotColour]); - $seriesPlot->mark->SetFillColor(self::$colourSet[self::$_plotColour]); - $seriesPlot->SetColor(self::$colourSet[self::$_plotColour++]); - - return $seriesPlot; - } - - - private function formatDataSetLabels($groupID, $datasetLabels, $labelCount, $rotation = '') { - $datasetLabelFormatCode = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex(0)->getFormatCode(); - if (!is_null($datasetLabelFormatCode)) { - // Retrieve any label formatting code - $datasetLabelFormatCode = stripslashes($datasetLabelFormatCode); - } - - $testCurrentIndex = 0; - foreach ($datasetLabels as $i => $datasetLabel) { - if (is_array($datasetLabel)) { - if ($rotation == 'bar') { - $datasetLabels[$i] = implode(" ", $datasetLabel); - } else { - $datasetLabel = array_reverse($datasetLabel); - $datasetLabels[$i] = implode("\n", $datasetLabel); - } - } else { - // Format labels according to any formatting code - if (!is_null($datasetLabelFormatCode)) { - $datasetLabels[$i] = PHPExcel_Style_NumberFormat::toFormattedString($datasetLabel, $datasetLabelFormatCode); - } - } - ++$testCurrentIndex; - } - - return $datasetLabels; - } - - - private function _percentageSumCalculation($groupID, $seriesCount) { - // Adjust our values to a percentage value across all series in the group - for($i = 0; $i < $seriesCount; ++$i) { - if ($i == 0) { - $sumValues = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getDataValues(); - } else { - $nextValues = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getDataValues(); - foreach ($nextValues as $k => $value) { - if (isset($sumValues[$k])) { - $sumValues[$k] += $value; - } else { - $sumValues[$k] = $value; - } - } - } - } - - return $sumValues; - } // function _percentageSumCalculation() - - - private function _percentageAdjustValues($dataValues, $sumValues) { - foreach ($dataValues as $k => $dataValue) { - $dataValues[$k] = $dataValue / $sumValues[$k] * 100; - } - - return $dataValues; - } // function _percentageAdjustValues() - - - private function _getCaption($captionElement) { - // Read any caption - $caption = (!is_null($captionElement)) ? $captionElement->getCaption() : NULL; - // Test if we have a title caption to display - if (!is_null($caption)) { - // If we do, it could be a plain string or an array - if (is_array($caption)) { - // Implode an array to a plain string - $caption = implode('', $caption); - } - } - return $caption; - } // function _getCaption() - - - private function _renderTitle() { - $title = $this->_getCaption($this->chart->getTitle()); - if (!is_null($title)) { - $this->graph->title->Set($title); - } - } // function _renderTitle() - - - private function _renderLegend() { - $legend = $this->chart->getLegend(); - if (!is_null($legend)) { - $legendPosition = $legend->getPosition(); - $legendOverlay = $legend->getOverlay(); - switch ($legendPosition) { - case 'r' : - $this->graph->legend->SetPos(0.01,0.5,'right','center'); // right - $this->graph->legend->SetColumns(1); - break; - case 'l' : - $this->graph->legend->SetPos(0.01,0.5,'left','center'); // left - $this->graph->legend->SetColumns(1); - break; - case 't' : - $this->graph->legend->SetPos(0.5,0.01,'center','top'); // top - break; - case 'b' : - $this->graph->legend->SetPos(0.5,0.99,'center','bottom'); // bottom - break; - default : - $this->graph->legend->SetPos(0.01,0.01,'right','top'); // top-right - $this->graph->legend->SetColumns(1); - break; - } - } else { - $this->graph->legend->Hide(); - } - } // function _renderLegend() - - - private function _renderCartesianPlotArea($type='textlin') { - $this->graph = new Graph(self::$width,self::$height); - $this->graph->SetScale($type); - - $this->_renderTitle(); - - // Rotate for bar rather than column chart - $rotation = $this->chart->getPlotArea()->getPlotGroupByIndex(0)->getPlotDirection(); - $reverse = ($rotation == 'bar') ? true : false; - - $xAxisLabel = $this->chart->getXAxisLabel(); - if (!is_null($xAxisLabel)) { - $title = $this->_getCaption($xAxisLabel); - if (!is_null($title)) { - $this->graph->xaxis->SetTitle($title,'center'); - $this->graph->xaxis->title->SetMargin(35); - if ($reverse) { - $this->graph->xaxis->title->SetAngle(90); - $this->graph->xaxis->title->SetMargin(90); - } - } - } - - $yAxisLabel = $this->chart->getYAxisLabel(); - if (!is_null($yAxisLabel)) { - $title = $this->_getCaption($yAxisLabel); - if (!is_null($title)) { - $this->graph->yaxis->SetTitle($title,'center'); - if ($reverse) { - $this->graph->yaxis->title->SetAngle(0); - $this->graph->yaxis->title->SetMargin(-55); - } - } - } - } // function _renderCartesianPlotArea() - - - private function _renderPiePlotArea($doughnut = False) { - $this->graph = new PieGraph(self::$width,self::$height); - - $this->_renderTitle(); - } // function _renderPiePlotArea() - - - private function _renderRadarPlotArea() { - $this->graph = new RadarGraph(self::$width,self::$height); - $this->graph->SetScale('lin'); - - $this->_renderTitle(); - } // function _renderRadarPlotArea() - - - private function _renderPlotLine($groupID, $filled = false, $combination = false, $dimensions = '2d') { - $grouping = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotGrouping(); - - $labelCount = count($this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex(0)->getPointCount()); - if ($labelCount > 0) { - $datasetLabels = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex(0)->getDataValues(); - $datasetLabels = $this->formatDataSetLabels($groupID, $datasetLabels, $labelCount); - $this->graph->xaxis->SetTickLabels($datasetLabels); - } - - $seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); - $seriesPlots = array(); - if ($grouping == 'percentStacked') { - $sumValues = $this->_percentageSumCalculation($groupID, $seriesCount); - } - - // Loop through each data series in turn - for($i = 0; $i < $seriesCount; ++$i) { - $dataValues = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getDataValues(); - $marker = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getPointMarker(); - - if ($grouping == 'percentStacked') { - $dataValues = $this->_percentageAdjustValues($dataValues, $sumValues); - } - - // Fill in any missing values in the $dataValues array - $testCurrentIndex = 0; - foreach ($dataValues as $k => $dataValue) { - while ($k != $testCurrentIndex) { - $dataValues[$testCurrentIndex] = null; - ++$testCurrentIndex; - } - ++$testCurrentIndex; - } - - $seriesPlot = new LinePlot($dataValues); - if ($combination) { - $seriesPlot->SetBarCenter(); - } - - if ($filled) { - $seriesPlot->SetFilled(true); - $seriesPlot->SetColor('black'); - $seriesPlot->SetFillColor(self::$colourSet[self::$_plotColour++]); - } else { - // Set the appropriate plot marker - $this->formatPointMarker($seriesPlot, $marker); - } - $dataLabel = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotLabelByIndex($i)->getDataValue(); - $seriesPlot->SetLegend($dataLabel); - - $seriesPlots[] = $seriesPlot; - } - - if ($grouping == 'standard') { - $groupPlot = $seriesPlots; - } else { - $groupPlot = new AccLinePlot($seriesPlots); - } - $this->graph->Add($groupPlot); - } // function _renderPlotLine() - - - private function _renderPlotBar($groupID, $dimensions = '2d') { - $rotation = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotDirection(); - // Rotate for bar rather than column chart - if (($groupID == 0) && ($rotation == 'bar')) { - $this->graph->Set90AndMargin(); - } - $grouping = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotGrouping(); - - $labelCount = count($this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex(0)->getPointCount()); - if ($labelCount > 0) { - $datasetLabels = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex(0)->getDataValues(); - $datasetLabels = $this->formatDataSetLabels($groupID, $datasetLabels, $labelCount, $rotation); - // Rotate for bar rather than column chart - if ($rotation == 'bar') { - $datasetLabels = array_reverse($datasetLabels); - $this->graph->yaxis->SetPos('max'); - $this->graph->yaxis->SetLabelAlign('center','top'); - $this->graph->yaxis->SetLabelSide(SIDE_RIGHT); - } - $this->graph->xaxis->SetTickLabels($datasetLabels); - } - - - $seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); - $seriesPlots = array(); - if ($grouping == 'percentStacked') { - $sumValues = $this->_percentageSumCalculation($groupID, $seriesCount); - } - - // Loop through each data series in turn - for($j = 0; $j < $seriesCount; ++$j) { - $dataValues = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($j)->getDataValues(); - if ($grouping == 'percentStacked') { - $dataValues = $this->_percentageAdjustValues($dataValues, $sumValues); - } - - // Fill in any missing values in the $dataValues array - $testCurrentIndex = 0; - foreach ($dataValues as $k => $dataValue) { - while ($k != $testCurrentIndex) { - $dataValues[$testCurrentIndex] = null; - ++$testCurrentIndex; - } - ++$testCurrentIndex; - } - - // Reverse the $dataValues order for bar rather than column chart - if ($rotation == 'bar') { - $dataValues = array_reverse($dataValues); - } - $seriesPlot = new BarPlot($dataValues); - $seriesPlot->SetColor('black'); - $seriesPlot->SetFillColor(self::$colourSet[self::$_plotColour++]); - if ($dimensions == '3d') { - $seriesPlot->SetShadow(); - } - if (!$this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotLabelByIndex($j)) { - $dataLabel = ''; - } else { - $dataLabel = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotLabelByIndex($j)->getDataValue(); - } - $seriesPlot->SetLegend($dataLabel); - - $seriesPlots[] = $seriesPlot; - } - // Reverse the plot order for bar rather than column chart - if (($rotation == 'bar') && (!($grouping == 'percentStacked'))) { - $seriesPlots = array_reverse($seriesPlots); - } - - if ($grouping == 'clustered') { - $groupPlot = new GroupBarPlot($seriesPlots); - } elseif ($grouping == 'standard') { - $groupPlot = new GroupBarPlot($seriesPlots); - } else { - $groupPlot = new AccBarPlot($seriesPlots); - if ($dimensions == '3d') { - $groupPlot->SetShadow(); - } - } - - $this->graph->Add($groupPlot); - } // function _renderPlotBar() - - - private function _renderPlotScatter($groupID, $bubble) { - $grouping = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotGrouping(); - $scatterStyle = $bubbleSize = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotStyle(); - - $seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); - $seriesPlots = array(); - - // Loop through each data series in turn - for($i = 0; $i < $seriesCount; ++$i) { - $dataValuesY = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex($i)->getDataValues(); - $dataValuesX = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getDataValues(); - - foreach ($dataValuesY as $k => $dataValueY) { - $dataValuesY[$k] = $k; - } - - $seriesPlot = new ScatterPlot($dataValuesX, $dataValuesY); - if ($scatterStyle == 'lineMarker') { - $seriesPlot->SetLinkPoints(); - $seriesPlot->link->SetColor(self::$colourSet[self::$_plotColour]); - } elseif ($scatterStyle == 'smoothMarker') { - $spline = new Spline($dataValuesY, $dataValuesX); - list($splineDataY, $splineDataX) = $spline->Get(count($dataValuesX) * self::$width / 20); - $lplot = new LinePlot($splineDataX, $splineDataY); - $lplot->SetColor(self::$colourSet[self::$_plotColour]); - - $this->graph->Add($lplot); - } - - if ($bubble) { - $this->formatPointMarker($seriesPlot,'dot'); - $seriesPlot->mark->SetColor('black'); - $seriesPlot->mark->SetSize($bubbleSize); - } else { - $marker = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getPointMarker(); - $this->formatPointMarker($seriesPlot, $marker); - } - $dataLabel = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotLabelByIndex($i)->getDataValue(); - $seriesPlot->SetLegend($dataLabel); - - $this->graph->Add($seriesPlot); - } - } // function _renderPlotScatter() - - - private function _renderPlotRadar($groupID) { - $radarStyle = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotStyle(); - - $seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); - $seriesPlots = array(); - - // Loop through each data series in turn - for($i = 0; $i < $seriesCount; ++$i) { - $dataValuesY = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex($i)->getDataValues(); - $dataValuesX = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getDataValues(); - $marker = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getPointMarker(); - - $dataValues = array(); - foreach ($dataValuesY as $k => $dataValueY) { - $dataValues[$k] = implode(' ',array_reverse($dataValueY)); - } - $tmp = array_shift($dataValues); - $dataValues[] = $tmp; - $tmp = array_shift($dataValuesX); - $dataValuesX[] = $tmp; - - $this->graph->SetTitles(array_reverse($dataValues)); - - $seriesPlot = new RadarPlot(array_reverse($dataValuesX)); - - $dataLabel = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotLabelByIndex($i)->getDataValue(); - $seriesPlot->SetColor(self::$colourSet[self::$_plotColour++]); - if ($radarStyle == 'filled') { - $seriesPlot->SetFillColor(self::$colourSet[self::$_plotColour]); - } - $this->formatPointMarker($seriesPlot, $marker); - $seriesPlot->SetLegend($dataLabel); - - $this->graph->Add($seriesPlot); - } - } // function _renderPlotRadar() - - - private function _renderPlotContour($groupID) { - $contourStyle = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotStyle(); - - $seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); - $seriesPlots = array(); - - $dataValues = array(); - // Loop through each data series in turn - for($i = 0; $i < $seriesCount; ++$i) { - $dataValuesY = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex($i)->getDataValues(); - $dataValuesX = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getDataValues(); - - $dataValues[$i] = $dataValuesX; - } - $seriesPlot = new ContourPlot($dataValues); - - $this->graph->Add($seriesPlot); - } // function _renderPlotContour() - - - private function _renderPlotStock($groupID) { - $seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); - $plotOrder = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotOrder(); - - $dataValues = array(); - // Loop through each data series in turn and build the plot arrays - foreach ($plotOrder as $i => $v) { - $dataValuesX = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($v)->getDataValues(); - foreach ($dataValuesX as $j => $dataValueX) { - $dataValues[$plotOrder[$i]][$j] = $dataValueX; - } - } - if (empty($dataValues)) { - return; - } - - $dataValuesPlot = array(); - // Flatten the plot arrays to a single dimensional array to work with jpgraph - for($j = 0; $j < count($dataValues[0]); $j++) { - for($i = 0; $i < $seriesCount; $i++) { - $dataValuesPlot[] = $dataValues[$i][$j]; - } - } - - // Set the x-axis labels - $labelCount = count($this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex(0)->getPointCount()); - if ($labelCount > 0) { - $datasetLabels = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex(0)->getDataValues(); - $datasetLabels = $this->formatDataSetLabels($groupID, $datasetLabels, $labelCount); - $this->graph->xaxis->SetTickLabels($datasetLabels); - } - - $seriesPlot = new StockPlot($dataValuesPlot); - $seriesPlot->SetWidth(20); - - $this->graph->Add($seriesPlot); - } // function _renderPlotStock() - - - private function _renderAreaChart($groupCount, $dimensions = '2d') { - require_once(PHPExcel_Settings::getChartRendererPath().'jpgraph_line.php'); - - $this->_renderCartesianPlotArea(); - - for($i = 0; $i < $groupCount; ++$i) { - $this->_renderPlotLine($i,True,False, $dimensions); - } - } // function _renderAreaChart() - - - private function _renderLineChart($groupCount, $dimensions = '2d') { - require_once(PHPExcel_Settings::getChartRendererPath().'jpgraph_line.php'); - - $this->_renderCartesianPlotArea(); - - for($i = 0; $i < $groupCount; ++$i) { - $this->_renderPlotLine($i,False,False, $dimensions); - } - } // function _renderLineChart() - - - private function _renderBarChart($groupCount, $dimensions = '2d') { - require_once(PHPExcel_Settings::getChartRendererPath().'jpgraph_bar.php'); - - $this->_renderCartesianPlotArea(); - - for($i = 0; $i < $groupCount; ++$i) { - $this->_renderPlotBar($i, $dimensions); - } - } // function _renderBarChart() - - - private function _renderScatterChart($groupCount) { - require_once(PHPExcel_Settings::getChartRendererPath().'jpgraph_scatter.php'); - require_once(PHPExcel_Settings::getChartRendererPath().'jpgraph_regstat.php'); - require_once(PHPExcel_Settings::getChartRendererPath().'jpgraph_line.php'); - - $this->_renderCartesianPlotArea('linlin'); - - for($i = 0; $i < $groupCount; ++$i) { - $this->_renderPlotScatter($i,false); - } - } // function _renderScatterChart() - - - private function _renderBubbleChart($groupCount) { - require_once(PHPExcel_Settings::getChartRendererPath().'jpgraph_scatter.php'); - - $this->_renderCartesianPlotArea('linlin'); - - for($i = 0; $i < $groupCount; ++$i) { - $this->_renderPlotScatter($i,true); - } - } // function _renderBubbleChart() - - - private function _renderPieChart($groupCount, $dimensions = '2d', $doughnut = False, $multiplePlots = False) { - require_once(PHPExcel_Settings::getChartRendererPath().'jpgraph_pie.php'); - if ($dimensions == '3d') { - require_once(PHPExcel_Settings::getChartRendererPath().'jpgraph_pie3d.php'); - } - - $this->_renderPiePlotArea($doughnut); - - $iLimit = ($multiplePlots) ? $groupCount : 1; - for($groupID = 0; $groupID < $iLimit; ++$groupID) { - $grouping = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotGrouping(); - $exploded = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotStyle(); - if ($groupID == 0) { - $labelCount = count($this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex(0)->getPointCount()); - if ($labelCount > 0) { - $datasetLabels = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex(0)->getDataValues(); - $datasetLabels = $this->formatDataSetLabels($groupID, $datasetLabels, $labelCount); - } - } - - $seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); - $seriesPlots = array(); - // For pie charts, we only display the first series: doughnut charts generally display all series - $jLimit = ($multiplePlots) ? $seriesCount : 1; - // Loop through each data series in turn - for($j = 0; $j < $jLimit; ++$j) { - $dataValues = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($j)->getDataValues(); - - // Fill in any missing values in the $dataValues array - $testCurrentIndex = 0; - foreach ($dataValues as $k => $dataValue) { - while ($k != $testCurrentIndex) { - $dataValues[$testCurrentIndex] = null; - ++$testCurrentIndex; - } - ++$testCurrentIndex; - } - - if ($dimensions == '3d') { - $seriesPlot = new PiePlot3D($dataValues); - } else { - if ($doughnut) { - $seriesPlot = new PiePlotC($dataValues); - } else { - $seriesPlot = new PiePlot($dataValues); - } - } - - if ($multiplePlots) { - $seriesPlot->SetSize(($jLimit-$j) / ($jLimit * 4)); - } - - if ($doughnut) { - $seriesPlot->SetMidColor('white'); - } - - $seriesPlot->SetColor(self::$colourSet[self::$_plotColour++]); - if (count($datasetLabels) > 0) - $seriesPlot->SetLabels(array_fill(0,count($datasetLabels),'')); - if ($dimensions != '3d') { - $seriesPlot->SetGuideLines(false); - } - if ($j == 0) { - if ($exploded) { - $seriesPlot->ExplodeAll(); - } - $seriesPlot->SetLegends($datasetLabels); - } - - $this->graph->Add($seriesPlot); - } - } - } // function _renderPieChart() - - - private function _renderRadarChart($groupCount) { - require_once(PHPExcel_Settings::getChartRendererPath().'jpgraph_radar.php'); - - $this->_renderRadarPlotArea(); - - for($groupID = 0; $groupID < $groupCount; ++$groupID) { - $this->_renderPlotRadar($groupID); - } - } // function _renderRadarChart() - - - private function _renderStockChart($groupCount) { - require_once(PHPExcel_Settings::getChartRendererPath().'jpgraph_stock.php'); - - $this->_renderCartesianPlotArea('intint'); - - for($groupID = 0; $groupID < $groupCount; ++$groupID) { - $this->_renderPlotStock($groupID); - } - } // function _renderStockChart() - - - private function _renderContourChart($groupCount, $dimensions) { - require_once(PHPExcel_Settings::getChartRendererPath().'jpgraph_contour.php'); - - $this->_renderCartesianPlotArea('intint'); - - for($i = 0; $i < $groupCount; ++$i) { - $this->_renderPlotContour($i); - } - } // function _renderContourChart() - - - private function _renderCombinationChart($groupCount, $dimensions, $outputDestination) { - require_once(PHPExcel_Settings::getChartRendererPath().'jpgraph_line.php'); - require_once(PHPExcel_Settings::getChartRendererPath().'jpgraph_bar.php'); - require_once(PHPExcel_Settings::getChartRendererPath().'jpgraph_scatter.php'); - require_once(PHPExcel_Settings::getChartRendererPath().'jpgraph_regstat.php'); - require_once(PHPExcel_Settings::getChartRendererPath().'jpgraph_line.php'); - - $this->_renderCartesianPlotArea(); - - for($i = 0; $i < $groupCount; ++$i) { - $dimensions = null; - $chartType = $this->chart->getPlotArea()->getPlotGroupByIndex($i)->getPlotType(); - switch ($chartType) { - case 'area3DChart' : - $dimensions = '3d'; - case 'areaChart' : - $this->_renderPlotLine($i,True,True, $dimensions); - break; - case 'bar3DChart' : - $dimensions = '3d'; - case 'barChart' : - $this->_renderPlotBar($i, $dimensions); - break; - case 'line3DChart' : - $dimensions = '3d'; - case 'lineChart' : - $this->_renderPlotLine($i,False,True, $dimensions); - break; - case 'scatterChart' : - $this->_renderPlotScatter($i,false); - break; - case 'bubbleChart' : - $this->_renderPlotScatter($i,true); - break; - default : - $this->graph = null; - return false; - } - } - - $this->_renderLegend(); - - $this->graph->Stroke($outputDestination); - return true; - } // function _renderCombinationChart() - - - public function render($outputDestination) { - self::$_plotColour = 0; - - $groupCount = $this->chart->getPlotArea()->getPlotGroupCount(); - - $dimensions = null; - if ($groupCount == 1) { - $chartType = $this->chart->getPlotArea()->getPlotGroupByIndex(0)->getPlotType(); - } else { - $chartTypes = array(); - for($i = 0; $i < $groupCount; ++$i) { - $chartTypes[] = $this->chart->getPlotArea()->getPlotGroupByIndex($i)->getPlotType(); - } - $chartTypes = array_unique($chartTypes); - if (count($chartTypes) == 1) { - $chartType = array_pop($chartTypes); - } elseif (count($chartTypes) == 0) { - echo 'Chart is not yet implemented
'; - return false; - } else { - return $this->_renderCombinationChart($groupCount, $dimensions, $outputDestination); - } - } - - switch ($chartType) { - case 'area3DChart' : - $dimensions = '3d'; - case 'areaChart' : - $this->_renderAreaChart($groupCount, $dimensions); - break; - case 'bar3DChart' : - $dimensions = '3d'; - case 'barChart' : - $this->_renderBarChart($groupCount, $dimensions); - break; - case 'line3DChart' : - $dimensions = '3d'; - case 'lineChart' : - $this->_renderLineChart($groupCount, $dimensions); - break; - case 'pie3DChart' : - $dimensions = '3d'; - case 'pieChart' : - $this->_renderPieChart($groupCount, $dimensions,False,False); - break; - case 'doughnut3DChart' : - $dimensions = '3d'; - case 'doughnutChart' : - $this->_renderPieChart($groupCount, $dimensions,True,True); - break; - case 'scatterChart' : - $this->_renderScatterChart($groupCount); - break; - case 'bubbleChart' : - $this->_renderBubbleChart($groupCount); - break; - case 'radarChart' : - $this->_renderRadarChart($groupCount); - break; - case 'surface3DChart' : - $dimensions = '3d'; - case 'surfaceChart' : - $this->_renderContourChart($groupCount, $dimensions); - break; - case 'stockChart' : - $this->_renderStockChart($groupCount, $dimensions); - break; - default : - echo $chartType.' is not yet implemented
'; - return false; - } - $this->_renderLegend(); - - $this->graph->Stroke($outputDestination); - return true; - } - - - /** - * Create a new PHPExcel_Chart_Renderer_jpgraph - */ - public function __construct(PHPExcel_Chart $chart) - { - $this->graph = null; - $this->chart = $chart; - } -} + MARK_DIAMOND, + 'square' => MARK_SQUARE, + 'triangle' => MARK_UTRIANGLE, + 'x' => MARK_X, + 'star' => MARK_STAR, + 'dot' => MARK_FILLEDCIRCLE, + 'dash' => MARK_DTRIANGLE, + 'circle' => MARK_CIRCLE, + 'plus' => MARK_CROSS + ); + + + private $chart; + + private $graph; + + private static $plotColour = 0; + + private static $plotMark = 0; + + + private function formatPointMarker($seriesPlot, $markerID) + { + $plotMarkKeys = array_keys(self::$markSet); + if (is_null($markerID)) { + // Use default plot marker (next marker in the series) + self::$plotMark %= count(self::$markSet); + $seriesPlot->mark->SetType(self::$markSet[$plotMarkKeys[self::$plotMark++]]); + } elseif ($markerID !== 'none') { + // Use specified plot marker (if it exists) + if (isset(self::$markSet[$markerID])) { + $seriesPlot->mark->SetType(self::$markSet[$markerID]); + } else { + // If the specified plot marker doesn't exist, use default plot marker (next marker in the series) + self::$plotMark %= count(self::$markSet); + $seriesPlot->mark->SetType(self::$markSet[$plotMarkKeys[self::$plotMark++]]); + } + } else { + // Hide plot marker + $seriesPlot->mark->Hide(); + } + $seriesPlot->mark->SetColor(self::$colourSet[self::$plotColour]); + $seriesPlot->mark->SetFillColor(self::$colourSet[self::$plotColour]); + $seriesPlot->SetColor(self::$colourSet[self::$plotColour++]); + + return $seriesPlot; + } + + + private function formatDataSetLabels($groupID, $datasetLabels, $labelCount, $rotation = '') + { + $datasetLabelFormatCode = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex(0)->getFormatCode(); + if (!is_null($datasetLabelFormatCode)) { + // Retrieve any label formatting code + $datasetLabelFormatCode = stripslashes($datasetLabelFormatCode); + } + + $testCurrentIndex = 0; + foreach ($datasetLabels as $i => $datasetLabel) { + if (is_array($datasetLabel)) { + if ($rotation == 'bar') { + $datasetLabels[$i] = implode(" ", $datasetLabel); + } else { + $datasetLabel = array_reverse($datasetLabel); + $datasetLabels[$i] = implode("\n", $datasetLabel); + } + } else { + // Format labels according to any formatting code + if (!is_null($datasetLabelFormatCode)) { + $datasetLabels[$i] = PHPExcel_Style_NumberFormat::toFormattedString($datasetLabel, $datasetLabelFormatCode); + } + } + ++$testCurrentIndex; + } + + return $datasetLabels; + } + + + private function percentageSumCalculation($groupID, $seriesCount) + { + // Adjust our values to a percentage value across all series in the group + for ($i = 0; $i < $seriesCount; ++$i) { + if ($i == 0) { + $sumValues = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getDataValues(); + } else { + $nextValues = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getDataValues(); + foreach ($nextValues as $k => $value) { + if (isset($sumValues[$k])) { + $sumValues[$k] += $value; + } else { + $sumValues[$k] = $value; + } + } + } + } + + return $sumValues; + } + + + private function percentageAdjustValues($dataValues, $sumValues) + { + foreach ($dataValues as $k => $dataValue) { + $dataValues[$k] = $dataValue / $sumValues[$k] * 100; + } + + return $dataValues; + } + + + private function getCaption($captionElement) + { + // Read any caption + $caption = (!is_null($captionElement)) ? $captionElement->getCaption() : null; + // Test if we have a title caption to display + if (!is_null($caption)) { + // If we do, it could be a plain string or an array + if (is_array($caption)) { + // Implode an array to a plain string + $caption = implode('', $caption); + } + } + return $caption; + } + + + private function renderTitle() + { + $title = $this->getCaption($this->chart->getTitle()); + if (!is_null($title)) { + $this->graph->title->Set($title); + } + } + + + private function renderLegend() + { + $legend = $this->chart->getLegend(); + if (!is_null($legend)) { + $legendPosition = $legend->getPosition(); + $legendOverlay = $legend->getOverlay(); + switch ($legendPosition) { + case 'r': + $this->graph->legend->SetPos(0.01, 0.5, 'right', 'center'); // right + $this->graph->legend->SetColumns(1); + break; + case 'l': + $this->graph->legend->SetPos(0.01, 0.5, 'left', 'center'); // left + $this->graph->legend->SetColumns(1); + break; + case 't': + $this->graph->legend->SetPos(0.5, 0.01, 'center', 'top'); // top + break; + case 'b': + $this->graph->legend->SetPos(0.5, 0.99, 'center', 'bottom'); // bottom + break; + default: + $this->graph->legend->SetPos(0.01, 0.01, 'right', 'top'); // top-right + $this->graph->legend->SetColumns(1); + break; + } + } else { + $this->graph->legend->Hide(); + } + } + + + private function renderCartesianPlotArea($type = 'textlin') + { + $this->graph = new Graph(self::$width, self::$height); + $this->graph->SetScale($type); + + $this->renderTitle(); + + // Rotate for bar rather than column chart + $rotation = $this->chart->getPlotArea()->getPlotGroupByIndex(0)->getPlotDirection(); + $reverse = ($rotation == 'bar') ? true : false; + + $xAxisLabel = $this->chart->getXAxisLabel(); + if (!is_null($xAxisLabel)) { + $title = $this->getCaption($xAxisLabel); + if (!is_null($title)) { + $this->graph->xaxis->SetTitle($title, 'center'); + $this->graph->xaxis->title->SetMargin(35); + if ($reverse) { + $this->graph->xaxis->title->SetAngle(90); + $this->graph->xaxis->title->SetMargin(90); + } + } + } + + $yAxisLabel = $this->chart->getYAxisLabel(); + if (!is_null($yAxisLabel)) { + $title = $this->getCaption($yAxisLabel); + if (!is_null($title)) { + $this->graph->yaxis->SetTitle($title, 'center'); + if ($reverse) { + $this->graph->yaxis->title->SetAngle(0); + $this->graph->yaxis->title->SetMargin(-55); + } + } + } + } + + + private function renderPiePlotArea($doughnut = false) + { + $this->graph = new PieGraph(self::$width, self::$height); + + $this->renderTitle(); + } + + + private function renderRadarPlotArea() + { + $this->graph = new RadarGraph(self::$width, self::$height); + $this->graph->SetScale('lin'); + + $this->renderTitle(); + } + + + private function renderPlotLine($groupID, $filled = false, $combination = false, $dimensions = '2d') + { + $grouping = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotGrouping(); + + $labelCount = count($this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex(0)->getPointCount()); + if ($labelCount > 0) { + $datasetLabels = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex(0)->getDataValues(); + $datasetLabels = $this->formatDataSetLabels($groupID, $datasetLabels, $labelCount); + $this->graph->xaxis->SetTickLabels($datasetLabels); + } + + $seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); + $seriesPlots = array(); + if ($grouping == 'percentStacked') { + $sumValues = $this->percentageSumCalculation($groupID, $seriesCount); + } + + // Loop through each data series in turn + for ($i = 0; $i < $seriesCount; ++$i) { + $dataValues = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getDataValues(); + $marker = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getPointMarker(); + + if ($grouping == 'percentStacked') { + $dataValues = $this->percentageAdjustValues($dataValues, $sumValues); + } + + // Fill in any missing values in the $dataValues array + $testCurrentIndex = 0; + foreach ($dataValues as $k => $dataValue) { + while ($k != $testCurrentIndex) { + $dataValues[$testCurrentIndex] = null; + ++$testCurrentIndex; + } + ++$testCurrentIndex; + } + + $seriesPlot = new LinePlot($dataValues); + if ($combination) { + $seriesPlot->SetBarCenter(); + } + + if ($filled) { + $seriesPlot->SetFilled(true); + $seriesPlot->SetColor('black'); + $seriesPlot->SetFillColor(self::$colourSet[self::$plotColour++]); + } else { + // Set the appropriate plot marker + $this->formatPointMarker($seriesPlot, $marker); + } + $dataLabel = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotLabelByIndex($i)->getDataValue(); + $seriesPlot->SetLegend($dataLabel); + + $seriesPlots[] = $seriesPlot; + } + + if ($grouping == 'standard') { + $groupPlot = $seriesPlots; + } else { + $groupPlot = new AccLinePlot($seriesPlots); + } + $this->graph->Add($groupPlot); + } + + + private function renderPlotBar($groupID, $dimensions = '2d') + { + $rotation = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotDirection(); + // Rotate for bar rather than column chart + if (($groupID == 0) && ($rotation == 'bar')) { + $this->graph->Set90AndMargin(); + } + $grouping = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotGrouping(); + + $labelCount = count($this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex(0)->getPointCount()); + if ($labelCount > 0) { + $datasetLabels = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex(0)->getDataValues(); + $datasetLabels = $this->formatDataSetLabels($groupID, $datasetLabels, $labelCount, $rotation); + // Rotate for bar rather than column chart + if ($rotation == 'bar') { + $datasetLabels = array_reverse($datasetLabels); + $this->graph->yaxis->SetPos('max'); + $this->graph->yaxis->SetLabelAlign('center', 'top'); + $this->graph->yaxis->SetLabelSide(SIDE_RIGHT); + } + $this->graph->xaxis->SetTickLabels($datasetLabels); + } + + + $seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); + $seriesPlots = array(); + if ($grouping == 'percentStacked') { + $sumValues = $this->percentageSumCalculation($groupID, $seriesCount); + } + + // Loop through each data series in turn + for ($j = 0; $j < $seriesCount; ++$j) { + $dataValues = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($j)->getDataValues(); + if ($grouping == 'percentStacked') { + $dataValues = $this->percentageAdjustValues($dataValues, $sumValues); + } + + // Fill in any missing values in the $dataValues array + $testCurrentIndex = 0; + foreach ($dataValues as $k => $dataValue) { + while ($k != $testCurrentIndex) { + $dataValues[$testCurrentIndex] = null; + ++$testCurrentIndex; + } + ++$testCurrentIndex; + } + + // Reverse the $dataValues order for bar rather than column chart + if ($rotation == 'bar') { + $dataValues = array_reverse($dataValues); + } + $seriesPlot = new BarPlot($dataValues); + $seriesPlot->SetColor('black'); + $seriesPlot->SetFillColor(self::$colourSet[self::$plotColour++]); + if ($dimensions == '3d') { + $seriesPlot->SetShadow(); + } + if (!$this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotLabelByIndex($j)) { + $dataLabel = ''; + } else { + $dataLabel = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotLabelByIndex($j)->getDataValue(); + } + $seriesPlot->SetLegend($dataLabel); + + $seriesPlots[] = $seriesPlot; + } + // Reverse the plot order for bar rather than column chart + if (($rotation == 'bar') && (!($grouping == 'percentStacked'))) { + $seriesPlots = array_reverse($seriesPlots); + } + + if ($grouping == 'clustered') { + $groupPlot = new GroupBarPlot($seriesPlots); + } elseif ($grouping == 'standard') { + $groupPlot = new GroupBarPlot($seriesPlots); + } else { + $groupPlot = new AccBarPlot($seriesPlots); + if ($dimensions == '3d') { + $groupPlot->SetShadow(); + } + } + + $this->graph->Add($groupPlot); + } + + + private function renderPlotScatter($groupID, $bubble) + { + $grouping = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotGrouping(); + $scatterStyle = $bubbleSize = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotStyle(); + + $seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); + $seriesPlots = array(); + + // Loop through each data series in turn + for ($i = 0; $i < $seriesCount; ++$i) { + $dataValuesY = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex($i)->getDataValues(); + $dataValuesX = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getDataValues(); + + foreach ($dataValuesY as $k => $dataValueY) { + $dataValuesY[$k] = $k; + } + + $seriesPlot = new ScatterPlot($dataValuesX, $dataValuesY); + if ($scatterStyle == 'lineMarker') { + $seriesPlot->SetLinkPoints(); + $seriesPlot->link->SetColor(self::$colourSet[self::$plotColour]); + } elseif ($scatterStyle == 'smoothMarker') { + $spline = new Spline($dataValuesY, $dataValuesX); + list($splineDataY, $splineDataX) = $spline->Get(count($dataValuesX) * self::$width / 20); + $lplot = new LinePlot($splineDataX, $splineDataY); + $lplot->SetColor(self::$colourSet[self::$plotColour]); + + $this->graph->Add($lplot); + } + + if ($bubble) { + $this->formatPointMarker($seriesPlot, 'dot'); + $seriesPlot->mark->SetColor('black'); + $seriesPlot->mark->SetSize($bubbleSize); + } else { + $marker = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getPointMarker(); + $this->formatPointMarker($seriesPlot, $marker); + } + $dataLabel = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotLabelByIndex($i)->getDataValue(); + $seriesPlot->SetLegend($dataLabel); + + $this->graph->Add($seriesPlot); + } + } + + + private function renderPlotRadar($groupID) + { + $radarStyle = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotStyle(); + + $seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); + $seriesPlots = array(); + + // Loop through each data series in turn + for ($i = 0; $i < $seriesCount; ++$i) { + $dataValuesY = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex($i)->getDataValues(); + $dataValuesX = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getDataValues(); + $marker = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getPointMarker(); + + $dataValues = array(); + foreach ($dataValuesY as $k => $dataValueY) { + $dataValues[$k] = implode(' ', array_reverse($dataValueY)); + } + $tmp = array_shift($dataValues); + $dataValues[] = $tmp; + $tmp = array_shift($dataValuesX); + $dataValuesX[] = $tmp; + + $this->graph->SetTitles(array_reverse($dataValues)); + + $seriesPlot = new RadarPlot(array_reverse($dataValuesX)); + + $dataLabel = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotLabelByIndex($i)->getDataValue(); + $seriesPlot->SetColor(self::$colourSet[self::$plotColour++]); + if ($radarStyle == 'filled') { + $seriesPlot->SetFillColor(self::$colourSet[self::$plotColour]); + } + $this->formatPointMarker($seriesPlot, $marker); + $seriesPlot->SetLegend($dataLabel); + + $this->graph->Add($seriesPlot); + } + } + + + private function renderPlotContour($groupID) + { + $contourStyle = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotStyle(); + + $seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); + $seriesPlots = array(); + + $dataValues = array(); + // Loop through each data series in turn + for ($i = 0; $i < $seriesCount; ++$i) { + $dataValuesY = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex($i)->getDataValues(); + $dataValuesX = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getDataValues(); + + $dataValues[$i] = $dataValuesX; + } + $seriesPlot = new ContourPlot($dataValues); + + $this->graph->Add($seriesPlot); + } + + + private function renderPlotStock($groupID) + { + $seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); + $plotOrder = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotOrder(); + + $dataValues = array(); + // Loop through each data series in turn and build the plot arrays + foreach ($plotOrder as $i => $v) { + $dataValuesX = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($v)->getDataValues(); + foreach ($dataValuesX as $j => $dataValueX) { + $dataValues[$plotOrder[$i]][$j] = $dataValueX; + } + } + if (empty($dataValues)) { + return; + } + + $dataValuesPlot = array(); + // Flatten the plot arrays to a single dimensional array to work with jpgraph + for ($j = 0; $j < count($dataValues[0]); ++$j) { + for ($i = 0; $i < $seriesCount; ++$i) { + $dataValuesPlot[] = $dataValues[$i][$j]; + } + } + + // Set the x-axis labels + $labelCount = count($this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex(0)->getPointCount()); + if ($labelCount > 0) { + $datasetLabels = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex(0)->getDataValues(); + $datasetLabels = $this->formatDataSetLabels($groupID, $datasetLabels, $labelCount); + $this->graph->xaxis->SetTickLabels($datasetLabels); + } + + $seriesPlot = new StockPlot($dataValuesPlot); + $seriesPlot->SetWidth(20); + + $this->graph->Add($seriesPlot); + } + + + private function renderAreaChart($groupCount, $dimensions = '2d') + { + require_once(PHPExcel_Settings::getChartRendererPath().'jpgraph_line.php'); + + $this->renderCartesianPlotArea(); + + for ($i = 0; $i < $groupCount; ++$i) { + $this->renderPlotLine($i, true, false, $dimensions); + } + } + + + private function renderLineChart($groupCount, $dimensions = '2d') + { + require_once(PHPExcel_Settings::getChartRendererPath().'jpgraph_line.php'); + + $this->renderCartesianPlotArea(); + + for ($i = 0; $i < $groupCount; ++$i) { + $this->renderPlotLine($i, false, false, $dimensions); + } + } + + + private function renderBarChart($groupCount, $dimensions = '2d') + { + require_once(PHPExcel_Settings::getChartRendererPath().'jpgraph_bar.php'); + + $this->renderCartesianPlotArea(); + + for ($i = 0; $i < $groupCount; ++$i) { + $this->renderPlotBar($i, $dimensions); + } + } + + + private function renderScatterChart($groupCount) + { + require_once(PHPExcel_Settings::getChartRendererPath().'jpgraph_scatter.php'); + require_once(PHPExcel_Settings::getChartRendererPath().'jpgraph_regstat.php'); + require_once(PHPExcel_Settings::getChartRendererPath().'jpgraph_line.php'); + + $this->renderCartesianPlotArea('linlin'); + + for ($i = 0; $i < $groupCount; ++$i) { + $this->renderPlotScatter($i, false); + } + } + + + private function renderBubbleChart($groupCount) + { + require_once(PHPExcel_Settings::getChartRendererPath().'jpgraph_scatter.php'); + + $this->renderCartesianPlotArea('linlin'); + + for ($i = 0; $i < $groupCount; ++$i) { + $this->renderPlotScatter($i, true); + } + } + + + private function renderPieChart($groupCount, $dimensions = '2d', $doughnut = false, $multiplePlots = false) + { + require_once(PHPExcel_Settings::getChartRendererPath().'jpgraph_pie.php'); + if ($dimensions == '3d') { + require_once(PHPExcel_Settings::getChartRendererPath().'jpgraph_pie3d.php'); + } + + $this->renderPiePlotArea($doughnut); + + $iLimit = ($multiplePlots) ? $groupCount : 1; + for ($groupID = 0; $groupID < $iLimit; ++$groupID) { + $grouping = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotGrouping(); + $exploded = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotStyle(); + if ($groupID == 0) { + $labelCount = count($this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex(0)->getPointCount()); + if ($labelCount > 0) { + $datasetLabels = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex(0)->getDataValues(); + $datasetLabels = $this->formatDataSetLabels($groupID, $datasetLabels, $labelCount); + } + } + + $seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); + $seriesPlots = array(); + // For pie charts, we only display the first series: doughnut charts generally display all series + $jLimit = ($multiplePlots) ? $seriesCount : 1; + // Loop through each data series in turn + for ($j = 0; $j < $jLimit; ++$j) { + $dataValues = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($j)->getDataValues(); + + // Fill in any missing values in the $dataValues array + $testCurrentIndex = 0; + foreach ($dataValues as $k => $dataValue) { + while ($k != $testCurrentIndex) { + $dataValues[$testCurrentIndex] = null; + ++$testCurrentIndex; + } + ++$testCurrentIndex; + } + + if ($dimensions == '3d') { + $seriesPlot = new PiePlot3D($dataValues); + } else { + if ($doughnut) { + $seriesPlot = new PiePlotC($dataValues); + } else { + $seriesPlot = new PiePlot($dataValues); + } + } + + if ($multiplePlots) { + $seriesPlot->SetSize(($jLimit-$j) / ($jLimit * 4)); + } + + if ($doughnut) { + $seriesPlot->SetMidColor('white'); + } + + $seriesPlot->SetColor(self::$colourSet[self::$plotColour++]); + if (count($datasetLabels) > 0) { + $seriesPlot->SetLabels(array_fill(0, count($datasetLabels), '')); + } + if ($dimensions != '3d') { + $seriesPlot->SetGuideLines(false); + } + if ($j == 0) { + if ($exploded) { + $seriesPlot->ExplodeAll(); + } + $seriesPlot->SetLegends($datasetLabels); + } + + $this->graph->Add($seriesPlot); + } + } + } + + + private function renderRadarChart($groupCount) + { + require_once(PHPExcel_Settings::getChartRendererPath().'jpgraph_radar.php'); + + $this->renderRadarPlotArea(); + + for ($groupID = 0; $groupID < $groupCount; ++$groupID) { + $this->renderPlotRadar($groupID); + } + } + + + private function renderStockChart($groupCount) + { + require_once(PHPExcel_Settings::getChartRendererPath().'jpgraph_stock.php'); + + $this->renderCartesianPlotArea('intint'); + + for ($groupID = 0; $groupID < $groupCount; ++$groupID) { + $this->renderPlotStock($groupID); + } + } + + + private function renderContourChart($groupCount, $dimensions) + { + require_once(PHPExcel_Settings::getChartRendererPath().'jpgraph_contour.php'); + + $this->renderCartesianPlotArea('intint'); + + for ($i = 0; $i < $groupCount; ++$i) { + $this->renderPlotContour($i); + } + } + + + private function renderCombinationChart($groupCount, $dimensions, $outputDestination) + { + require_once(PHPExcel_Settings::getChartRendererPath().'jpgraph_line.php'); + require_once(PHPExcel_Settings::getChartRendererPath().'jpgraph_bar.php'); + require_once(PHPExcel_Settings::getChartRendererPath().'jpgraph_scatter.php'); + require_once(PHPExcel_Settings::getChartRendererPath().'jpgraph_regstat.php'); + require_once(PHPExcel_Settings::getChartRendererPath().'jpgraph_line.php'); + + $this->renderCartesianPlotArea(); + + for ($i = 0; $i < $groupCount; ++$i) { + $dimensions = null; + $chartType = $this->chart->getPlotArea()->getPlotGroupByIndex($i)->getPlotType(); + switch ($chartType) { + case 'area3DChart': + $dimensions = '3d'; + case 'areaChart': + $this->renderPlotLine($i, true, true, $dimensions); + break; + case 'bar3DChart': + $dimensions = '3d'; + case 'barChart': + $this->renderPlotBar($i, $dimensions); + break; + case 'line3DChart': + $dimensions = '3d'; + case 'lineChart': + $this->renderPlotLine($i, false, true, $dimensions); + break; + case 'scatterChart': + $this->renderPlotScatter($i, false); + break; + case 'bubbleChart': + $this->renderPlotScatter($i, true); + break; + default: + $this->graph = null; + return false; + } + } + + $this->renderLegend(); + + $this->graph->Stroke($outputDestination); + return true; + } + + + public function render($outputDestination) + { + self::$plotColour = 0; + + $groupCount = $this->chart->getPlotArea()->getPlotGroupCount(); + + $dimensions = null; + if ($groupCount == 1) { + $chartType = $this->chart->getPlotArea()->getPlotGroupByIndex(0)->getPlotType(); + } else { + $chartTypes = array(); + for ($i = 0; $i < $groupCount; ++$i) { + $chartTypes[] = $this->chart->getPlotArea()->getPlotGroupByIndex($i)->getPlotType(); + } + $chartTypes = array_unique($chartTypes); + if (count($chartTypes) == 1) { + $chartType = array_pop($chartTypes); + } elseif (count($chartTypes) == 0) { + echo 'Chart is not yet implemented
'; + return false; + } else { + return $this->renderCombinationChart($groupCount, $dimensions, $outputDestination); + } + } + + switch ($chartType) { + case 'area3DChart': + $dimensions = '3d'; + case 'areaChart': + $this->renderAreaChart($groupCount, $dimensions); + break; + case 'bar3DChart': + $dimensions = '3d'; + case 'barChart': + $this->renderBarChart($groupCount, $dimensions); + break; + case 'line3DChart': + $dimensions = '3d'; + case 'lineChart': + $this->renderLineChart($groupCount, $dimensions); + break; + case 'pie3DChart': + $dimensions = '3d'; + case 'pieChart': + $this->renderPieChart($groupCount, $dimensions, false, false); + break; + case 'doughnut3DChart': + $dimensions = '3d'; + case 'doughnutChart': + $this->renderPieChart($groupCount, $dimensions, true, true); + break; + case 'scatterChart': + $this->renderScatterChart($groupCount); + break; + case 'bubbleChart': + $this->renderBubbleChart($groupCount); + break; + case 'radarChart': + $this->renderRadarChart($groupCount); + break; + case 'surface3DChart': + $dimensions = '3d'; + case 'surfaceChart': + $this->renderContourChart($groupCount, $dimensions); + break; + case 'stockChart': + $this->renderStockChart($groupCount, $dimensions); + break; + default: + echo $chartType.' is not yet implemented
'; + return false; + } + $this->renderLegend(); + + $this->graph->Stroke($outputDestination); + return true; + } + + + /** + * Create a new PHPExcel_Chart_Renderer_jpgraph + */ + public function __construct(PHPExcel_Chart $chart) + { + $this->graph = null; + $this->chart = $chart; + } +} diff --git a/Classes/PHPExcel/Shared/PCLZip/pclzip.lib.php b/Classes/PHPExcel/Shared/PCLZip/pclzip.lib.php index effb8dd7..0805a03c 100644 --- a/Classes/PHPExcel/Shared/PCLZip/pclzip.lib.php +++ b/Classes/PHPExcel/Shared/PCLZip/pclzip.lib.php @@ -25,170 +25,170 @@ // $Id: pclzip.lib.php,v 1.60 2009/09/30 21:01:04 vblavet Exp $ // -------------------------------------------------------------------------------- -// ----- Constants -if (!defined('PCLZIP_READ_BLOCK_SIZE')) { - define('PCLZIP_READ_BLOCK_SIZE', 2048); -} + // ----- Constants + if (!defined('PCLZIP_READ_BLOCK_SIZE')) { + define( 'PCLZIP_READ_BLOCK_SIZE', 2048 ); + } + + // ----- File list separator + // In version 1.x of PclZip, the separator for file list is a space + // (which is not a very smart choice, specifically for windows paths !). + // A better separator should be a comma (,). This constant gives you the + // abilty to change that. + // However notice that changing this value, may have impact on existing + // scripts, using space separated filenames. + // Recommanded values for compatibility with older versions : + //define( 'PCLZIP_SEPARATOR', ' ' ); + // Recommanded values for smart separation of filenames. + if (!defined('PCLZIP_SEPARATOR')) { + define( 'PCLZIP_SEPARATOR', ',' ); + } -// ----- File list separator -// In version 1.x of PclZip, the separator for file list is a space -// (which is not a very smart choice, specifically for windows paths !). -// A better separator should be a comma (,). This constant gives you the -// abilty to change that. -// However notice that changing this value, may have impact on existing -// scripts, using space separated filenames. -// Recommanded values for compatibility with older versions : -//define('PCLZIP_SEPARATOR', ' '); -// Recommanded values for smart separation of filenames. -if (!defined('PCLZIP_SEPARATOR')) { - define('PCLZIP_SEPARATOR', ','); -} + // ----- Error configuration + // 0 : PclZip Class integrated error handling + // 1 : PclError external library error handling. By enabling this + // you must ensure that you have included PclError library. + // [2,...] : reserved for futur use + if (!defined('PCLZIP_ERROR_EXTERNAL')) { + define( 'PCLZIP_ERROR_EXTERNAL', 0 ); + } -// ----- Error configuration -// 0 : PclZip Class integrated error handling -// 1 : PclError external library error handling. By enabling this -// you must ensure that you have included PclError library. -// [2,...] : reserved for futur use -if (!defined('PCLZIP_ERROR_EXTERNAL')) { - define('PCLZIP_ERROR_EXTERNAL', 0); -} + // ----- Optional static temporary directory + // By default temporary files are generated in the script current + // path. + // If defined : + // - MUST BE terminated by a '/'. + // - MUST be a valid, already created directory + // Samples : + // define( 'PCLZIP_TEMPORARY_DIR', '/temp/' ); + // define( 'PCLZIP_TEMPORARY_DIR', 'C:/Temp/' ); + if (!defined('PCLZIP_TEMPORARY_DIR')) { + define( 'PCLZIP_TEMPORARY_DIR', '' ); + } -// ----- Optional static temporary directory -// By default temporary files are generated in the script current -// path. -// If defined : -// - MUST BE terminated by a '/'. -// - MUST be a valid, already created directory -// Samples : -// define('PCLZIP_TEMPORARY_DIR', '/temp/'); -// define('PCLZIP_TEMPORARY_DIR', 'C:/Temp/'); -if (!defined('PCLZIP_TEMPORARY_DIR')) { - define('PCLZIP_TEMPORARY_DIR', ''); -} - -// ----- Optional threshold ratio for use of temporary files -// Pclzip sense the size of the file to add/extract and decide to -// use or not temporary file. The algorythm is looking for -// memory_limit of PHP and apply a ratio. -// threshold = memory_limit * ratio. -// Recommended values are under 0.5. Default 0.47. -// Samples : -// define('PCLZIP_TEMPORARY_FILE_RATIO', 0.5); -if (!defined('PCLZIP_TEMPORARY_FILE_RATIO')) { - define('PCLZIP_TEMPORARY_FILE_RATIO', 0.47); -} + // ----- Optional threshold ratio for use of temporary files + // Pclzip sense the size of the file to add/extract and decide to + // use or not temporary file. The algorythm is looking for + // memory_limit of PHP and apply a ratio. + // threshold = memory_limit * ratio. + // Recommended values are under 0.5. Default 0.47. + // Samples : + // define( 'PCLZIP_TEMPORARY_FILE_RATIO', 0.5 ); + if (!defined('PCLZIP_TEMPORARY_FILE_RATIO')) { + define( 'PCLZIP_TEMPORARY_FILE_RATIO', 0.47 ); + } // -------------------------------------------------------------------------------- // ***** UNDER THIS LINE NOTHING NEEDS TO BE MODIFIED ***** // -------------------------------------------------------------------------------- -// ----- Global variables -$g_pclzip_version = "2.8.2"; + // ----- Global variables + $g_pclzip_version = "2.8.2"; -// ----- Error codes -// -1 : Unable to open file in binary write mode -// -2 : Unable to open file in binary read mode -// -3 : Invalid parameters -// -4 : File does not exist -// -5 : Filename is too long (max. 255) -// -6 : Not a valid zip file -// -7 : Invalid extracted file size -// -8 : Unable to create directory -// -9 : Invalid archive extension -// -10 : Invalid archive format -// -11 : Unable to delete file (unlink) -// -12 : Unable to rename file (rename) -// -13 : Invalid header checksum -// -14 : Invalid archive size -define('PCLZIP_ERR_USER_ABORTED', 2); -define('PCLZIP_ERR_NO_ERROR', 0); -define('PCLZIP_ERR_WRITE_OPEN_FAIL', -1); -define('PCLZIP_ERR_READ_OPEN_FAIL', -2); -define('PCLZIP_ERR_INVALID_PARAMETER', -3); -define('PCLZIP_ERR_MISSING_FILE', -4); -define('PCLZIP_ERR_FILENAME_TOO_LONG', -5); -define('PCLZIP_ERR_INVALID_ZIP', -6); -define('PCLZIP_ERR_BAD_EXTRACTED_FILE', -7); -define('PCLZIP_ERR_DIR_CREATE_FAIL', -8); -define('PCLZIP_ERR_BAD_EXTENSION', -9); -define('PCLZIP_ERR_BAD_FORMAT', -10); -define('PCLZIP_ERR_DELETE_FILE_FAIL', -11); -define('PCLZIP_ERR_RENAME_FILE_FAIL', -12); -define('PCLZIP_ERR_BAD_CHECKSUM', -13); -define('PCLZIP_ERR_INVALID_ARCHIVE_ZIP', -14); -define('PCLZIP_ERR_MISSING_OPTION_VALUE', -15); -define('PCLZIP_ERR_INVALID_OPTION_VALUE', -16); -define('PCLZIP_ERR_ALREADY_A_DIRECTORY', -17); -define('PCLZIP_ERR_UNSUPPORTED_COMPRESSION', -18); -define('PCLZIP_ERR_UNSUPPORTED_ENCRYPTION', -19); -define('PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE', -20); -define('PCLZIP_ERR_DIRECTORY_RESTRICTION', -21); + // ----- Error codes + // -1 : Unable to open file in binary write mode + // -2 : Unable to open file in binary read mode + // -3 : Invalid parameters + // -4 : File does not exist + // -5 : Filename is too long (max. 255) + // -6 : Not a valid zip file + // -7 : Invalid extracted file size + // -8 : Unable to create directory + // -9 : Invalid archive extension + // -10 : Invalid archive format + // -11 : Unable to delete file (unlink) + // -12 : Unable to rename file (rename) + // -13 : Invalid header checksum + // -14 : Invalid archive size + define( 'PCLZIP_ERR_USER_ABORTED', 2 ); + define( 'PCLZIP_ERR_NO_ERROR', 0 ); + define( 'PCLZIP_ERR_WRITE_OPEN_FAIL', -1 ); + define( 'PCLZIP_ERR_READ_OPEN_FAIL', -2 ); + define( 'PCLZIP_ERR_INVALID_PARAMETER', -3 ); + define( 'PCLZIP_ERR_MISSING_FILE', -4 ); + define( 'PCLZIP_ERR_FILENAME_TOO_LONG', -5 ); + define( 'PCLZIP_ERR_INVALID_ZIP', -6 ); + define( 'PCLZIP_ERR_BAD_EXTRACTED_FILE', -7 ); + define( 'PCLZIP_ERR_DIR_CREATE_FAIL', -8 ); + define( 'PCLZIP_ERR_BAD_EXTENSION', -9 ); + define( 'PCLZIP_ERR_BAD_FORMAT', -10 ); + define( 'PCLZIP_ERR_DELETE_FILE_FAIL', -11 ); + define( 'PCLZIP_ERR_RENAME_FILE_FAIL', -12 ); + define( 'PCLZIP_ERR_BAD_CHECKSUM', -13 ); + define( 'PCLZIP_ERR_INVALID_ARCHIVE_ZIP', -14 ); + define( 'PCLZIP_ERR_MISSING_OPTION_VALUE', -15 ); + define( 'PCLZIP_ERR_INVALID_OPTION_VALUE', -16 ); + define( 'PCLZIP_ERR_ALREADY_A_DIRECTORY', -17 ); + define( 'PCLZIP_ERR_UNSUPPORTED_COMPRESSION', -18 ); + define( 'PCLZIP_ERR_UNSUPPORTED_ENCRYPTION', -19 ); + define( 'PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE', -20 ); + define( 'PCLZIP_ERR_DIRECTORY_RESTRICTION', -21 ); -// ----- Options values -define('PCLZIP_OPT_PATH', 77001); -define('PCLZIP_OPT_ADD_PATH', 77002); -define('PCLZIP_OPT_REMOVE_PATH', 77003); -define('PCLZIP_OPT_REMOVE_ALL_PATH', 77004); -define('PCLZIP_OPT_SET_CHMOD', 77005); -define('PCLZIP_OPT_EXTRACT_AS_STRING', 77006); -define('PCLZIP_OPT_NO_COMPRESSION', 77007); -define('PCLZIP_OPT_BY_NAME', 77008); -define('PCLZIP_OPT_BY_INDEX', 77009); -define('PCLZIP_OPT_BY_EREG', 77010); -define('PCLZIP_OPT_BY_PREG', 77011); -define('PCLZIP_OPT_COMMENT', 77012); -define('PCLZIP_OPT_ADD_COMMENT', 77013); -define('PCLZIP_OPT_PREPEND_COMMENT', 77014); -define('PCLZIP_OPT_EXTRACT_IN_OUTPUT', 77015); -define('PCLZIP_OPT_REPLACE_NEWER', 77016); -define('PCLZIP_OPT_STOP_ON_ERROR', 77017); -// Having big trouble with crypt. Need to multiply 2 long int -// which is not correctly supported by PHP ... -//define('PCLZIP_OPT_CRYPT', 77018); -define('PCLZIP_OPT_EXTRACT_DIR_RESTRICTION', 77019); -define('PCLZIP_OPT_TEMP_FILE_THRESHOLD', 77020); -define('PCLZIP_OPT_ADD_TEMP_FILE_THRESHOLD', 77020); // alias -define('PCLZIP_OPT_TEMP_FILE_ON', 77021); -define('PCLZIP_OPT_ADD_TEMP_FILE_ON', 77021); // alias -define('PCLZIP_OPT_TEMP_FILE_OFF', 77022); -define('PCLZIP_OPT_ADD_TEMP_FILE_OFF', 77022); // alias + // ----- Options values + define( 'PCLZIP_OPT_PATH', 77001 ); + define( 'PCLZIP_OPT_ADD_PATH', 77002 ); + define( 'PCLZIP_OPT_REMOVE_PATH', 77003 ); + define( 'PCLZIP_OPT_REMOVE_ALL_PATH', 77004 ); + define( 'PCLZIP_OPT_SET_CHMOD', 77005 ); + define( 'PCLZIP_OPT_EXTRACT_AS_STRING', 77006 ); + define( 'PCLZIP_OPT_NO_COMPRESSION', 77007 ); + define( 'PCLZIP_OPT_BY_NAME', 77008 ); + define( 'PCLZIP_OPT_BY_INDEX', 77009 ); + define( 'PCLZIP_OPT_BY_EREG', 77010 ); + define( 'PCLZIP_OPT_BY_PREG', 77011 ); + define( 'PCLZIP_OPT_COMMENT', 77012 ); + define( 'PCLZIP_OPT_ADD_COMMENT', 77013 ); + define( 'PCLZIP_OPT_PREPEND_COMMENT', 77014 ); + define( 'PCLZIP_OPT_EXTRACT_IN_OUTPUT', 77015 ); + define( 'PCLZIP_OPT_REPLACE_NEWER', 77016 ); + define( 'PCLZIP_OPT_STOP_ON_ERROR', 77017 ); + // Having big trouble with crypt. Need to multiply 2 long int + // which is not correctly supported by PHP ... + //define( 'PCLZIP_OPT_CRYPT', 77018 ); + define( 'PCLZIP_OPT_EXTRACT_DIR_RESTRICTION', 77019 ); + define( 'PCLZIP_OPT_TEMP_FILE_THRESHOLD', 77020 ); + define( 'PCLZIP_OPT_ADD_TEMP_FILE_THRESHOLD', 77020 ); // alias + define( 'PCLZIP_OPT_TEMP_FILE_ON', 77021 ); + define( 'PCLZIP_OPT_ADD_TEMP_FILE_ON', 77021 ); // alias + define( 'PCLZIP_OPT_TEMP_FILE_OFF', 77022 ); + define( 'PCLZIP_OPT_ADD_TEMP_FILE_OFF', 77022 ); // alias + + // ----- File description attributes + define( 'PCLZIP_ATT_FILE_NAME', 79001 ); + define( 'PCLZIP_ATT_FILE_NEW_SHORT_NAME', 79002 ); + define( 'PCLZIP_ATT_FILE_NEW_FULL_NAME', 79003 ); + define( 'PCLZIP_ATT_FILE_MTIME', 79004 ); + define( 'PCLZIP_ATT_FILE_CONTENT', 79005 ); + define( 'PCLZIP_ATT_FILE_COMMENT', 79006 ); -// ----- File description attributes -define('PCLZIP_ATT_FILE_NAME', 79001); -define('PCLZIP_ATT_FILE_NEW_SHORT_NAME', 79002); -define('PCLZIP_ATT_FILE_NEW_FULL_NAME', 79003); -define('PCLZIP_ATT_FILE_MTIME', 79004); -define('PCLZIP_ATT_FILE_CONTENT', 79005); -define('PCLZIP_ATT_FILE_COMMENT', 79006); + // ----- Call backs values + define( 'PCLZIP_CB_PRE_EXTRACT', 78001 ); + define( 'PCLZIP_CB_POST_EXTRACT', 78002 ); + define( 'PCLZIP_CB_PRE_ADD', 78003 ); + define( 'PCLZIP_CB_POST_ADD', 78004 ); + /* For futur use + define( 'PCLZIP_CB_PRE_LIST', 78005 ); + define( 'PCLZIP_CB_POST_LIST', 78006 ); + define( 'PCLZIP_CB_PRE_DELETE', 78007 ); + define( 'PCLZIP_CB_POST_DELETE', 78008 ); + */ -// ----- Call backs values -define('PCLZIP_CB_PRE_EXTRACT', 78001); -define('PCLZIP_CB_POST_EXTRACT', 78002); -define('PCLZIP_CB_PRE_ADD', 78003); -define('PCLZIP_CB_POST_ADD', 78004); -/* For futur use -define('PCLZIP_CB_PRE_LIST', 78005); -define('PCLZIP_CB_POST_LIST', 78006); -define('PCLZIP_CB_PRE_DELETE', 78007); -define('PCLZIP_CB_POST_DELETE', 78008); -*/ - -// -------------------------------------------------------------------------------- -// Class : PclZip -// Description : -// PclZip is the class that represent a Zip archive. -// The public methods allow the manipulation of the archive. -// Attributes : -// Attributes must not be accessed directly. -// Methods : -// PclZip() : Object creator -// create() : Creates the Zip archive -// listContent() : List the content of the Zip archive -// extract() : Extract the content of the archive -// properties() : List the properties of the archive -// -------------------------------------------------------------------------------- -class PclZip -{ + // -------------------------------------------------------------------------------- + // Class : PclZip + // Description : + // PclZip is the class that represent a Zip archive. + // The public methods allow the manipulation of the archive. + // Attributes : + // Attributes must not be accessed directly. + // Methods : + // PclZip() : Object creator + // create() : Creates the Zip archive + // listContent() : List the content of the Zip archive + // extract() : Extract the content of the archive + // properties() : List the properties of the archive + // -------------------------------------------------------------------------------- + class PclZip + { // ----- Filename of the zip file var $zipname = ''; @@ -198,1101 +198,1154 @@ class PclZip // ----- Internal error handling var $error_code = 1; var $error_string = ''; - + // ----- Current status of the magic_quotes_runtime // This value store the php configuration for magic_quotes // The class can then disable the magic_quotes and reset it after var $magic_quotes_status; - // -------------------------------------------------------------------------------- - // Function : PclZip() - // Description : - // Creates a PclZip object and set the name of the associated Zip archive - // filename. - // Note that no real action is taken, if the archive does not exist it is not - // created. Use create() for that. - // -------------------------------------------------------------------------------- - function PclZip($p_zipname) - { - // ----- Tests the zlib - if (!function_exists('gzopen')) { - die('Abort '.basename(__FILE__).' : Missing zlib extensions'); - } - - // ----- Set the attributes - $this->zipname = $p_zipname; - $this->zip_fd = 0; - $this->magic_quotes_status = -1; - - // ----- Return - return; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : - // create($p_filelist, $p_add_dir="", $p_remove_dir="") - // create($p_filelist, $p_option, $p_option_value, ...) - // Description : - // This method supports two different synopsis. The first one is historical. - // This method creates a Zip Archive. The Zip file is created in the - // filesystem. The files and directories indicated in $p_filelist - // are added in the archive. See the parameters description for the - // supported format of $p_filelist. - // When a directory is in the list, the directory and its content is added - // in the archive. - // In this synopsis, the function takes an optional variable list of - // options. See bellow the supported options. - // Parameters : - // $p_filelist : An array containing file or directory names, or - // a string containing one filename or one directory name, or - // a string containing a list of filenames and/or directory - // names separated by spaces. - // $p_add_dir : A path to add before the real path of the archived file, - // in order to have it memorized in the archive. - // $p_remove_dir : A path to remove from the real path of the file to archive, - // in order to have a shorter path memorized in the archive. - // When $p_add_dir and $p_remove_dir are set, $p_remove_dir - // is removed first, before $p_add_dir is added. - // Options : - // PCLZIP_OPT_ADD_PATH : - // PCLZIP_OPT_REMOVE_PATH : - // PCLZIP_OPT_REMOVE_ALL_PATH : - // PCLZIP_OPT_COMMENT : - // PCLZIP_CB_PRE_ADD : - // PCLZIP_CB_POST_ADD : - // Return Values : - // 0 on failure, - // The list of the added files, with a status of the add action. - // (see PclZip::listContent() for list entry format) - // -------------------------------------------------------------------------------- - function create($p_filelist) { - $v_result=1; - - // ----- Reset the error handler - $this->privErrorReset(); - - // ----- Set default values - $v_options = array(); - $v_options[PCLZIP_OPT_NO_COMPRESSION] = false; - - // ----- Look for variable options arguments - $v_size = func_num_args(); - - // ----- Look for arguments - if ($v_size > 1) { - // ----- Get the arguments - $v_arg_list = func_get_args(); - - // ----- Remove from the options list the first argument - array_shift($v_arg_list); - $v_size--; - - // ----- Look for first arg - if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) { - // ----- Parse the options - $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, array( - PCLZIP_OPT_REMOVE_PATH => 'optional', - PCLZIP_OPT_REMOVE_ALL_PATH => 'optional', - PCLZIP_OPT_ADD_PATH => 'optional', - PCLZIP_CB_PRE_ADD => 'optional', - PCLZIP_CB_POST_ADD => 'optional', - PCLZIP_OPT_NO_COMPRESSION => 'optional', - PCLZIP_OPT_COMMENT => 'optional', - PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional', - PCLZIP_OPT_TEMP_FILE_ON => 'optional', - PCLZIP_OPT_TEMP_FILE_OFF => 'optional' - //, PCLZIP_OPT_CRYPT => 'optional' - ))); - if ($v_result != 1) { - return 0; - } - } else { - // ----- Look for 2 args - // Here we need to support the first historic synopsis of the - // method. - - // ----- Get the first argument - $v_options[PCLZIP_OPT_ADD_PATH] = $v_arg_list[0]; - - // ----- Look for the optional second argument - if ($v_size == 2) { - $v_options[PCLZIP_OPT_REMOVE_PATH] = $v_arg_list[1]; - } else if ($v_size > 2) { - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments"); - return 0; - } - } - } - - // ----- Look for default option values - $this->privOptionDefaultThreshold($v_options); - - // ----- Init - $v_string_list = array(); - $v_att_list = array(); - $v_filedescr_list = array(); - $p_result_list = array(); - - // ----- Look if the $p_filelist is really an array - if (is_array($p_filelist)) { - // ----- Look if the first element is also an array - // This will mean that this is a file description entry - if (isset($p_filelist[0]) && is_array($p_filelist[0])) { - $v_att_list = $p_filelist; - } else { - // ----- The list is a list of string names - $v_string_list = $p_filelist; - } - } else if (is_string($p_filelist)) { - // ----- Look if the $p_filelist is a string - // ----- Create a list from the string - $v_string_list = explode(PCLZIP_SEPARATOR, $p_filelist); - } else { - // ----- Invalid variable type for $p_filelist - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_filelist"); - return 0; - } - // ----- Reformat the string list - if (sizeof($v_string_list) != 0) { - foreach ($v_string_list as $v_string) { - if ($v_string != '') { - $v_att_list[][PCLZIP_ATT_FILE_NAME] = $v_string; - } - } - } - - // ----- For each file in the list check the attributes - $v_supported_attributes = array( - PCLZIP_ATT_FILE_NAME => 'mandatory', - PCLZIP_ATT_FILE_NEW_SHORT_NAME => 'optional', - PCLZIP_ATT_FILE_NEW_FULL_NAME => 'optional', - PCLZIP_ATT_FILE_MTIME => 'optional', - PCLZIP_ATT_FILE_CONTENT => 'optional', - PCLZIP_ATT_FILE_COMMENT => 'optional', - )); - foreach ($v_att_list as $v_entry) { - $v_result = $this->privFileDescrParseAtt($v_entry, $v_filedescr_list[], $v_options, $v_supported_attributes); - if ($v_result != 1) { - return 0; - } - } - // ----- Expand the filelist (expand directories) - $v_result = $this->privFileDescrExpand($v_filedescr_list, $v_options); - if ($v_result != 1) { - return 0; - } - - // ----- Call the create fct - $v_result = $this->privCreate($v_filedescr_list, $p_result_list, $v_options); - if ($v_result != 1) { - return 0; - } - - // ----- Return - return $p_result_list; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : - // add($p_filelist, $p_add_dir="", $p_remove_dir="") - // add($p_filelist, $p_option, $p_option_value, ...) - // Description : - // This method supports two synopsis. The first one is historical. - // This methods add the list of files in an existing archive. - // If a file with the same name already exists, it is added at the end of the - // archive, the first one is still present. - // If the archive does not exist, it is created. - // Parameters : - // $p_filelist : An array containing file or directory names, or - // a string containing one filename or one directory name, or - // a string containing a list of filenames and/or directory - // names separated by spaces. - // $p_add_dir : A path to add before the real path of the archived file, - // in order to have it memorized in the archive. - // $p_remove_dir : A path to remove from the real path of the file to archive, - // in order to have a shorter path memorized in the archive. - // When $p_add_dir and $p_remove_dir are set, $p_remove_dir - // is removed first, before $p_add_dir is added. - // Options : - // PCLZIP_OPT_ADD_PATH : - // PCLZIP_OPT_REMOVE_PATH : - // PCLZIP_OPT_REMOVE_ALL_PATH : - // PCLZIP_OPT_COMMENT : - // PCLZIP_OPT_ADD_COMMENT : - // PCLZIP_OPT_PREPEND_COMMENT : - // PCLZIP_CB_PRE_ADD : - // PCLZIP_CB_POST_ADD : - // Return Values : - // 0 on failure, - // The list of the added files, with a status of the add action. - // (see PclZip::listContent() for list entry format) - // -------------------------------------------------------------------------------- - function add($p_filelist) - { - $v_result=1; - - // ----- Reset the error handler - $this->privErrorReset(); - - // ----- Set default values - $v_options = array(); - $v_options[PCLZIP_OPT_NO_COMPRESSION] = false; - - // ----- Look for variable options arguments - $v_size = func_num_args(); - - // ----- Look for arguments - if ($v_size > 1) { - // ----- Get the arguments - $v_arg_list = func_get_args(); - - // ----- Remove form the options list the first argument - array_shift($v_arg_list); - $v_size--; - - // ----- Look for first arg - if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) { - // ----- Parse the options - $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, array( - PCLZIP_OPT_REMOVE_PATH => 'optional', - PCLZIP_OPT_REMOVE_ALL_PATH => 'optional', - PCLZIP_OPT_ADD_PATH => 'optional', - PCLZIP_CB_PRE_ADD => 'optional', - PCLZIP_CB_POST_ADD => 'optional', - PCLZIP_OPT_NO_COMPRESSION => 'optional', - PCLZIP_OPT_COMMENT => 'optional', - PCLZIP_OPT_ADD_COMMENT => 'optional', - PCLZIP_OPT_PREPEND_COMMENT => 'optional', - PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional', - PCLZIP_OPT_TEMP_FILE_ON => 'optional', - PCLZIP_OPT_TEMP_FILE_OFF => 'optional' - //, PCLZIP_OPT_CRYPT => 'optional' - ))); - if ($v_result != 1) { - return 0; - } - } else { - // ----- Look for 2 args - // Here we need to support the first historic synopsis of the method. - - // ----- Get the first argument - $v_options[PCLZIP_OPT_ADD_PATH] = $v_add_path = $v_arg_list[0]; - - // ----- Look for the optional second argument - if ($v_size == 2) { - $v_options[PCLZIP_OPT_REMOVE_PATH] = $v_arg_list[1]; - } else if ($v_size > 2) { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments"); - // ----- Return - return 0; - } - } - } - - // ----- Look for default option values - $this->privOptionDefaultThreshold($v_options); - - // ----- Init - $v_string_list = array(); - $v_att_list = array(); - $v_filedescr_list = array(); - $p_result_list = array(); - - // ----- Look if the $p_filelist is really an array - if (is_array($p_filelist)) { - // ----- Look if the first element is also an array - // This will mean that this is a file description entry - if (isset($p_filelist[0]) && is_array($p_filelist[0])) { - $v_att_list = $p_filelist; - } else { - // ----- The list is a list of string names - $v_string_list = $p_filelist; - } - } else if (is_string($p_filelist)) { - // ----- Look if the $p_filelist is a string - // ----- Create a list from the string - $v_string_list = explode(PCLZIP_SEPARATOR, $p_filelist); - } else { - // ----- Invalid variable type for $p_filelist - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type '".gettype($p_filelist)."' for p_filelist"); - return 0; - } - - // ----- Reformat the string list - if (sizeof($v_string_list) != 0) { - foreach ($v_string_list as $v_string) { - $v_att_list[][PCLZIP_ATT_FILE_NAME] = $v_string; - } - } - - // ----- For each file in the list check the attributes - $v_supported_attributes = array( - PCLZIP_ATT_FILE_NAME => 'mandatory', - PCLZIP_ATT_FILE_NEW_SHORT_NAME => 'optional', - PCLZIP_ATT_FILE_NEW_FULL_NAME => 'optional', - PCLZIP_ATT_FILE_MTIME => 'optional', - PCLZIP_ATT_FILE_CONTENT => 'optional', - PCLZIP_ATT_FILE_COMMENT => 'optional', - )); - foreach ($v_att_list as $v_entry) { - $v_result = $this->privFileDescrParseAtt($v_entry, $v_filedescr_list[], $v_options, $v_supported_attributes); - if ($v_result != 1) { - return 0; - } - } - - // ----- Expand the filelist (expand directories) - $v_result = $this->privFileDescrExpand($v_filedescr_list, $v_options); - if ($v_result != 1) { - return 0; - } - - // ----- Call the create fct - $v_result = $this->privAdd($v_filedescr_list, $p_result_list, $v_options); - if ($v_result != 1) { - return 0; - } - - // ----- Return - return $p_result_list; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : listContent() - // Description : - // This public method, gives the list of the files and directories, with their - // properties. - // The properties of each entries in the list are (used also in other functions) : - // filename : Name of the file. For a create or add action it is the filename - // given by the user. For an extract function it is the filename - // of the extracted file. - // stored_filename : Name of the file / directory stored in the archive. - // size : Size of the stored file. - // compressed_size : Size of the file's data compressed in the archive - // (without the headers overhead) - // mtime : Last known modification date of the file (UNIX timestamp) - // comment : Comment associated with the file - // folder : true | false - // index : index of the file in the archive - // status : status of the action (depending of the action) : - // Values are : - // ok : OK ! - // filtered : the file / dir is not extracted (filtered by user) - // already_a_directory : the file can not be extracted because a - // directory with the same name already exists - // write_protected : the file can not be extracted because a file - // with the same name already exists and is - // write protected - // newer_exist : the file was not extracted because a newer file exists - // path_creation_fail : the file is not extracted because the folder - // does not exist and can not be created - // write_error : the file was not extracted because there was a - // error while writing the file - // read_error : the file was not extracted because there was a error - // while reading the file - // invalid_header : the file was not extracted because of an archive - // format error (bad file header) - // Note that each time a method can continue operating when there - // is an action error on a file, the error is only logged in the file status. - // Return Values : - // 0 on an unrecoverable failure, - // The list of the files in the archive. - // -------------------------------------------------------------------------------- - function listContent() - { - $v_result=1; - - // ----- Reset the error handler - $this->privErrorReset(); - - // ----- Check archive - if (!$this->privCheckFormat()) { - return(0); - } - - // ----- Call the extracting fct - $p_list = array(); - if (($v_result = $this->privList($p_list)) != 1) { - unset($p_list); - return(0); - } - - // ----- Return - return $p_list; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : - // extract($p_path="./", $p_remove_path="") - // extract([$p_option, $p_option_value, ...]) - // Description : - // This method supports two synopsis. The first one is historical. - // This method extract all the files / directories from the archive to the - // folder indicated in $p_path. - // If you want to ignore the 'root' part of path of the memorized files - // you can indicate this in the optional $p_remove_path parameter. - // By default, if a newer file with the same name already exists, the - // file is not extracted. - // - // If both PCLZIP_OPT_PATH and PCLZIP_OPT_ADD_PATH aoptions - // are used, the path indicated in PCLZIP_OPT_ADD_PATH is append - // at the end of the path value of PCLZIP_OPT_PATH. - // Parameters : - // $p_path : Path where the files and directories are to be extracted - // $p_remove_path : First part ('root' part) of the memorized path - // (if any similar) to remove while extracting. - // Options : - // PCLZIP_OPT_PATH : - // PCLZIP_OPT_ADD_PATH : - // PCLZIP_OPT_REMOVE_PATH : - // PCLZIP_OPT_REMOVE_ALL_PATH : - // PCLZIP_CB_PRE_EXTRACT : - // PCLZIP_CB_POST_EXTRACT : - // Return Values : - // 0 or a negative value on failure, - // The list of the extracted files, with a status of the action. - // (see PclZip::listContent() for list entry format) - // -------------------------------------------------------------------------------- - function extract() - { - $v_result=1; - - // ----- Reset the error handler - $this->privErrorReset(); - - // ----- Check archive - if (!$this->privCheckFormat()) { - return(0); - } - - // ----- Set default values - $v_options = array(); - // $v_path = "./"; - $v_path = ''; - $v_remove_path = ""; - $v_remove_all_path = false; - - // ----- Look for variable options arguments - $v_size = func_num_args(); - - // ----- Default values for option - $v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = false; - - // ----- Look for arguments - if ($v_size > 0) { - // ----- Get the arguments - $v_arg_list = func_get_args(); - - // ----- Look for first arg - if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) { - // ----- Parse the options - $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, array( - PCLZIP_OPT_PATH => 'optional', - PCLZIP_OPT_REMOVE_PATH => 'optional', - PCLZIP_OPT_REMOVE_ALL_PATH => 'optional', - PCLZIP_OPT_ADD_PATH => 'optional', - PCLZIP_CB_PRE_EXTRACT => 'optional', - PCLZIP_CB_POST_EXTRACT => 'optional', - PCLZIP_OPT_SET_CHMOD => 'optional', - PCLZIP_OPT_BY_NAME => 'optional', - PCLZIP_OPT_BY_EREG => 'optional', - PCLZIP_OPT_BY_PREG => 'optional', - PCLZIP_OPT_BY_INDEX => 'optional', - PCLZIP_OPT_EXTRACT_AS_STRING => 'optional', - PCLZIP_OPT_EXTRACT_IN_OUTPUT => 'optional', - PCLZIP_OPT_REPLACE_NEWER => 'optional', - PCLZIP_OPT_STOP_ON_ERROR => 'optional', - PCLZIP_OPT_EXTRACT_DIR_RESTRICTION => 'optional', - PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional', - PCLZIP_OPT_TEMP_FILE_ON => 'optional', - PCLZIP_OPT_TEMP_FILE_OFF => 'optional' - ))); - if ($v_result != 1) { - return 0; - } - - // ----- Set the arguments - if (isset($v_options[PCLZIP_OPT_PATH])) { - $v_path = $v_options[PCLZIP_OPT_PATH]; - } - if (isset($v_options[PCLZIP_OPT_REMOVE_PATH])) { - $v_remove_path = $v_options[PCLZIP_OPT_REMOVE_PATH]; - } - if (isset($v_options[PCLZIP_OPT_REMOVE_ALL_PATH])) { - $v_remove_all_path = $v_options[PCLZIP_OPT_REMOVE_ALL_PATH]; - } - if (isset($v_options[PCLZIP_OPT_ADD_PATH])) { - // ----- Check for '/' in last path char - if ((strlen($v_path) > 0) && (substr($v_path, -1) != '/')) { - $v_path .= '/'; - } - $v_path .= $v_options[PCLZIP_OPT_ADD_PATH]; - } - } else { - // ----- Look for 2 args - // Here we need to support the first historic synopsis of the method. - // ----- Get the first argument - $v_path = $v_arg_list[0]; - - // ----- Look for the optional second argument - if ($v_size == 2) { - $v_remove_path = $v_arg_list[1]; - } else if ($v_size > 2) { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments"); - // ----- Return - return 0; - } - } - } - - // ----- Look for default option values - $this->privOptionDefaultThreshold($v_options); - - // ----- Trace - - // ----- Call the extracting fct - $p_list = array(); - $v_result = $this->privExtractByRule($p_list, $v_path, $v_remove_path, - $v_remove_all_path, $v_options); - if ($v_result < 1) { - unset($p_list); - return(0); - } - - // ----- Return - return $p_list; - } - // -------------------------------------------------------------------------------- - - - // -------------------------------------------------------------------------------- - // Function : - // extractByIndex($p_index, $p_path="./", $p_remove_path="") - // extractByIndex($p_index, [$p_option, $p_option_value, ...]) - // Description : - // This method supports two synopsis. The first one is historical. - // This method is doing a partial extract of the archive. - // The extracted files or folders are identified by their index in the - // archive (from 0 to n). - // Note that if the index identify a folder, only the folder entry is - // extracted, not all the files included in the archive. - // Parameters : - // $p_index : A single index (integer) or a string of indexes of files to - // extract. The form of the string is "0,4-6,8-12" with only numbers - // and '-' for range or ',' to separate ranges. No spaces or ';' - // are allowed. - // $p_path : Path where the files and directories are to be extracted - // $p_remove_path : First part ('root' part) of the memorized path - // (if any similar) to remove while extracting. - // Options : - // PCLZIP_OPT_PATH : - // PCLZIP_OPT_ADD_PATH : - // PCLZIP_OPT_REMOVE_PATH : - // PCLZIP_OPT_REMOVE_ALL_PATH : - // PCLZIP_OPT_EXTRACT_AS_STRING : The files are extracted as strings and - // not as files. - // The resulting content is in a new field 'content' in the file - // structure. - // This option must be used alone (any other options are ignored). - // PCLZIP_CB_PRE_EXTRACT : - // PCLZIP_CB_POST_EXTRACT : - // Return Values : - // 0 on failure, - // The list of the extracted files, with a status of the action. - // (see PclZip::listContent() for list entry format) - // -------------------------------------------------------------------------------- - //function extractByIndex($p_index, options...) - function extractByIndex($p_index) - { - $v_result=1; - - // ----- Reset the error handler - $this->privErrorReset(); - - // ----- Check archive - if (!$this->privCheckFormat()) { - return(0); - } - - // ----- Set default values - $v_options = array(); - // $v_path = "./"; - $v_path = ''; - $v_remove_path = ""; - $v_remove_all_path = false; - - // ----- Look for variable options arguments - $v_size = func_num_args(); - - // ----- Default values for option - $v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = false; - - // ----- Look for arguments - if ($v_size > 1) { - // ----- Get the arguments - $v_arg_list = func_get_args(); - - // ----- Remove form the options list the first argument - array_shift($v_arg_list); - $v_size--; - - // ----- Look for first arg - if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) { - // ----- Parse the options - $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, array( - PCLZIP_OPT_PATH => 'optional', - PCLZIP_OPT_REMOVE_PATH => 'optional', - PCLZIP_OPT_REMOVE_ALL_PATH => 'optional', - PCLZIP_OPT_EXTRACT_AS_STRING => 'optional', - PCLZIP_OPT_ADD_PATH => 'optional', - PCLZIP_CB_PRE_EXTRACT => 'optional', - PCLZIP_CB_POST_EXTRACT => 'optional', - PCLZIP_OPT_SET_CHMOD => 'optional', - PCLZIP_OPT_REPLACE_NEWER => 'optional', - PCLZIP_OPT_STOP_ON_ERROR => 'optional', - PCLZIP_OPT_EXTRACT_DIR_RESTRICTION => 'optional', - PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional', - PCLZIP_OPT_TEMP_FILE_ON => 'optional', - PCLZIP_OPT_TEMP_FILE_OFF => 'optional' - ))); - if ($v_result != 1) { - return 0; - } - - // ----- Set the arguments - if (isset($v_options[PCLZIP_OPT_PATH])) { - $v_path = $v_options[PCLZIP_OPT_PATH]; - } - if (isset($v_options[PCLZIP_OPT_REMOVE_PATH])) { - $v_remove_path = $v_options[PCLZIP_OPT_REMOVE_PATH]; - } - if (isset($v_options[PCLZIP_OPT_REMOVE_ALL_PATH])) { - $v_remove_all_path = $v_options[PCLZIP_OPT_REMOVE_ALL_PATH]; - } - if (isset($v_options[PCLZIP_OPT_ADD_PATH])) { - // ----- Check for '/' in last path char - if ((strlen($v_path) > 0) && (substr($v_path, -1) != '/')) { - $v_path .= '/'; - } - $v_path .= $v_options[PCLZIP_OPT_ADD_PATH]; - } - if (!isset($v_options[PCLZIP_OPT_EXTRACT_AS_STRING])) { - $v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = false; - } - } else { - // ----- Look for 2 args - // Here we need to support the first historic synopsis of the method. - - // ----- Get the first argument - $v_path = $v_arg_list[0]; - - // ----- Look for the optional second argument - if ($v_size == 2) { - $v_remove_path = $v_arg_list[1]; - } else if ($v_size > 2) { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments"); - - // ----- Return - return 0; - } - } - } - - // ----- Trace - - // ----- Trick - // Here I want to reuse extractByRule(), so I need to parse the $p_index - // with privParseOptions() - $v_arg_trick = array (PCLZIP_OPT_BY_INDEX, $p_index); - $v_options_trick = array(); - $v_result = $this->privParseOptions($v_arg_trick, sizeof($v_arg_trick), $v_options_trick, - array (PCLZIP_OPT_BY_INDEX => 'optional')); - if ($v_result != 1) { - return 0; - } - $v_options[PCLZIP_OPT_BY_INDEX] = $v_options_trick[PCLZIP_OPT_BY_INDEX]; - - // ----- Look for default option values - $this->privOptionDefaultThreshold($v_options); - - // ----- Call the extracting fct - if (($v_result = $this->privExtractByRule($p_list, $v_path, $v_remove_path, $v_remove_all_path, $v_options)) < 1) { - return(0); - } - - // ----- Return - return $p_list; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : - // delete([$p_option, $p_option_value, ...]) - // Description : - // This method removes files from the archive. - // If no parameters are given, then all the archive is emptied. - // Parameters : - // None or optional arguments. - // Options : - // PCLZIP_OPT_BY_INDEX : - // PCLZIP_OPT_BY_NAME : - // PCLZIP_OPT_BY_EREG : - // PCLZIP_OPT_BY_PREG : - // Return Values : - // 0 on failure, - // The list of the files which are still present in the archive. - // (see PclZip::listContent() for list entry format) - // -------------------------------------------------------------------------------- - function delete() -{ -$v_result=1; - -// ----- Reset the error handler -$this->privErrorReset(); - -// ----- Check archive -if (!$this->privCheckFormat()) { - return(0); -} - -// ----- Set default values -$v_options = array(); - -// ----- Look for variable options arguments -$v_size = func_num_args(); - -// ----- Look for arguments -if ($v_size > 0) { - // ----- Get the arguments - $v_arg_list = func_get_args(); - - // ----- Parse the options - $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, - array (PCLZIP_OPT_BY_NAME => 'optional', - PCLZIP_OPT_BY_EREG => 'optional', - PCLZIP_OPT_BY_PREG => 'optional', - PCLZIP_OPT_BY_INDEX => 'optional')); - if ($v_result != 1) { - return 0; - } -} - -// ----- Magic quotes trick -$this->privDisableMagicQuotes(); - -// ----- Call the delete fct -$v_list = array(); -if (($v_result = $this->privDeleteByRule($v_list, $v_options)) != 1) { - $this->privSwapBackMagicQuotes(); - unset($v_list); - return(0); -} - -// ----- Magic quotes trick -$this->privSwapBackMagicQuotes(); - -// ----- Return -return $v_list; -} -// -------------------------------------------------------------------------------- - -// -------------------------------------------------------------------------------- -// Function : deleteByIndex() -// Description : -// ***** Deprecated ***** -// delete(PCLZIP_OPT_BY_INDEX, $p_index) should be prefered. -// -------------------------------------------------------------------------------- -function deleteByIndex($p_index) -{ - -$p_list = $this->delete(PCLZIP_OPT_BY_INDEX, $p_index); - -// ----- Return -return $p_list; -} -// -------------------------------------------------------------------------------- - -// -------------------------------------------------------------------------------- -// Function : properties() -// Description : -// This method gives the properties of the archive. -// The properties are : -// nb : Number of files in the archive -// comment : Comment associated with the archive file -// status : not_exist, ok -// Parameters : -// None -// Return Values : -// 0 on failure, -// An array with the archive properties. -// -------------------------------------------------------------------------------- -function properties() -{ - -// ----- Reset the error handler -$this->privErrorReset(); - -// ----- Magic quotes trick -$this->privDisableMagicQuotes(); - -// ----- Check archive -if (!$this->privCheckFormat()) { - $this->privSwapBackMagicQuotes(); - return(0); -} - -// ----- Default properties -$v_prop = array(); -$v_prop['comment'] = ''; -$v_prop['nb'] = 0; -$v_prop['status'] = 'not_exist'; - -// ----- Look if file exists -if (@is_file($this->zipname)) -{ - // ----- Open the zip file - if (($this->zip_fd = @fopen($this->zipname, 'rb')) == 0) + // -------------------------------------------------------------------------------- + // Function : PclZip() + // Description : + // Creates a PclZip object and set the name of the associated Zip archive + // filename. + // Note that no real action is taken, if the archive does not exist it is not + // created. Use create() for that. + // -------------------------------------------------------------------------------- + function PclZip($p_zipname) { - $this->privSwapBackMagicQuotes(); - - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \''.$this->zipname.'\' in binary read mode'); + + // ----- Tests the zlib + if (!function_exists('gzopen')) + { + die('Abort '.basename(__FILE__).' : Missing zlib extensions'); + } + + // ----- Set the attributes + $this->zipname = $p_zipname; + $this->zip_fd = 0; + $this->magic_quotes_status = -1; // ----- Return - return 0; + return; } + // -------------------------------------------------------------------------------- - // ----- Read the central directory informations - $v_central_dir = array(); - if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) + // -------------------------------------------------------------------------------- + // Function : + // create($p_filelist, $p_add_dir="", $p_remove_dir="") + // create($p_filelist, $p_option, $p_option_value, ...) + // Description : + // This method supports two different synopsis. The first one is historical. + // This method creates a Zip Archive. The Zip file is created in the + // filesystem. The files and directories indicated in $p_filelist + // are added in the archive. See the parameters description for the + // supported format of $p_filelist. + // When a directory is in the list, the directory and its content is added + // in the archive. + // In this synopsis, the function takes an optional variable list of + // options. See bellow the supported options. + // Parameters : + // $p_filelist : An array containing file or directory names, or + // a string containing one filename or one directory name, or + // a string containing a list of filenames and/or directory + // names separated by spaces. + // $p_add_dir : A path to add before the real path of the archived file, + // in order to have it memorized in the archive. + // $p_remove_dir : A path to remove from the real path of the file to archive, + // in order to have a shorter path memorized in the archive. + // When $p_add_dir and $p_remove_dir are set, $p_remove_dir + // is removed first, before $p_add_dir is added. + // Options : + // PCLZIP_OPT_ADD_PATH : + // PCLZIP_OPT_REMOVE_PATH : + // PCLZIP_OPT_REMOVE_ALL_PATH : + // PCLZIP_OPT_COMMENT : + // PCLZIP_CB_PRE_ADD : + // PCLZIP_CB_POST_ADD : + // Return Values : + // 0 on failure, + // The list of the added files, with a status of the add action. + // (see PclZip::listContent() for list entry format) + // -------------------------------------------------------------------------------- + function create($p_filelist) { + $v_result=1; + + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Set default values + $v_options = array(); + $v_options[PCLZIP_OPT_NO_COMPRESSION] = FALSE; + + // ----- Look for variable options arguments + $v_size = func_num_args(); + + // ----- Look for arguments + if ($v_size > 1) { + // ----- Get the arguments + $v_arg_list = func_get_args(); + + // ----- Remove from the options list the first argument + array_shift($v_arg_list); + $v_size--; + + // ----- Look for first arg + if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) { + + // ----- Parse the options + $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, + array (PCLZIP_OPT_REMOVE_PATH => 'optional', + PCLZIP_OPT_REMOVE_ALL_PATH => 'optional', + PCLZIP_OPT_ADD_PATH => 'optional', + PCLZIP_CB_PRE_ADD => 'optional', + PCLZIP_CB_POST_ADD => 'optional', + PCLZIP_OPT_NO_COMPRESSION => 'optional', + PCLZIP_OPT_COMMENT => 'optional', + PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional', + PCLZIP_OPT_TEMP_FILE_ON => 'optional', + PCLZIP_OPT_TEMP_FILE_OFF => 'optional' + //, PCLZIP_OPT_CRYPT => 'optional' + )); + if ($v_result != 1) { + return 0; + } + } + + // ----- Look for 2 args + // Here we need to support the first historic synopsis of the + // method. + else { + + // ----- Get the first argument + $v_options[PCLZIP_OPT_ADD_PATH] = $v_arg_list[0]; + + // ----- Look for the optional second argument + if ($v_size == 2) { + $v_options[PCLZIP_OPT_REMOVE_PATH] = $v_arg_list[1]; + } + else if ($v_size > 2) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, + "Invalid number / type of arguments"); + return 0; + } + } + } + + // ----- Look for default option values + $this->privOptionDefaultThreshold($v_options); + + // ----- Init + $v_string_list = array(); + $v_att_list = array(); + $v_filedescr_list = array(); + $p_result_list = array(); + + // ----- Look if the $p_filelist is really an array + if (is_array($p_filelist)) { + + // ----- Look if the first element is also an array + // This will mean that this is a file description entry + if (isset($p_filelist[0]) && is_array($p_filelist[0])) { + $v_att_list = $p_filelist; + } + + // ----- The list is a list of string names + else { + $v_string_list = $p_filelist; + } + } + + // ----- Look if the $p_filelist is a string + else if (is_string($p_filelist)) { + // ----- Create a list from the string + $v_string_list = explode(PCLZIP_SEPARATOR, $p_filelist); + } + + // ----- Invalid variable type for $p_filelist + else { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_filelist"); + return 0; + } + + // ----- Reformat the string list + if (sizeof($v_string_list) != 0) { + foreach ($v_string_list as $v_string) { + if ($v_string != '') { + $v_att_list[][PCLZIP_ATT_FILE_NAME] = $v_string; + } + else { + } + } + } + + // ----- For each file in the list check the attributes + $v_supported_attributes + = array ( PCLZIP_ATT_FILE_NAME => 'mandatory' + ,PCLZIP_ATT_FILE_NEW_SHORT_NAME => 'optional' + ,PCLZIP_ATT_FILE_NEW_FULL_NAME => 'optional' + ,PCLZIP_ATT_FILE_MTIME => 'optional' + ,PCLZIP_ATT_FILE_CONTENT => 'optional' + ,PCLZIP_ATT_FILE_COMMENT => 'optional' + ); + foreach ($v_att_list as $v_entry) { + $v_result = $this->privFileDescrParseAtt($v_entry, + $v_filedescr_list[], + $v_options, + $v_supported_attributes); + if ($v_result != 1) { + return 0; + } + } + + // ----- Expand the filelist (expand directories) + $v_result = $this->privFileDescrExpand($v_filedescr_list, $v_options); + if ($v_result != 1) { + return 0; + } + + // ----- Call the create fct + $v_result = $this->privCreate($v_filedescr_list, $p_result_list, $v_options); + if ($v_result != 1) { + return 0; + } + + // ----- Return + return $p_result_list; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : + // add($p_filelist, $p_add_dir="", $p_remove_dir="") + // add($p_filelist, $p_option, $p_option_value, ...) + // Description : + // This method supports two synopsis. The first one is historical. + // This methods add the list of files in an existing archive. + // If a file with the same name already exists, it is added at the end of the + // archive, the first one is still present. + // If the archive does not exist, it is created. + // Parameters : + // $p_filelist : An array containing file or directory names, or + // a string containing one filename or one directory name, or + // a string containing a list of filenames and/or directory + // names separated by spaces. + // $p_add_dir : A path to add before the real path of the archived file, + // in order to have it memorized in the archive. + // $p_remove_dir : A path to remove from the real path of the file to archive, + // in order to have a shorter path memorized in the archive. + // When $p_add_dir and $p_remove_dir are set, $p_remove_dir + // is removed first, before $p_add_dir is added. + // Options : + // PCLZIP_OPT_ADD_PATH : + // PCLZIP_OPT_REMOVE_PATH : + // PCLZIP_OPT_REMOVE_ALL_PATH : + // PCLZIP_OPT_COMMENT : + // PCLZIP_OPT_ADD_COMMENT : + // PCLZIP_OPT_PREPEND_COMMENT : + // PCLZIP_CB_PRE_ADD : + // PCLZIP_CB_POST_ADD : + // Return Values : + // 0 on failure, + // The list of the added files, with a status of the add action. + // (see PclZip::listContent() for list entry format) + // -------------------------------------------------------------------------------- + function add($p_filelist) + { + $v_result=1; + + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Set default values + $v_options = array(); + $v_options[PCLZIP_OPT_NO_COMPRESSION] = FALSE; + + // ----- Look for variable options arguments + $v_size = func_num_args(); + + // ----- Look for arguments + if ($v_size > 1) { + // ----- Get the arguments + $v_arg_list = func_get_args(); + + // ----- Remove form the options list the first argument + array_shift($v_arg_list); + $v_size--; + + // ----- Look for first arg + if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) { + + // ----- Parse the options + $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, + array (PCLZIP_OPT_REMOVE_PATH => 'optional', + PCLZIP_OPT_REMOVE_ALL_PATH => 'optional', + PCLZIP_OPT_ADD_PATH => 'optional', + PCLZIP_CB_PRE_ADD => 'optional', + PCLZIP_CB_POST_ADD => 'optional', + PCLZIP_OPT_NO_COMPRESSION => 'optional', + PCLZIP_OPT_COMMENT => 'optional', + PCLZIP_OPT_ADD_COMMENT => 'optional', + PCLZIP_OPT_PREPEND_COMMENT => 'optional', + PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional', + PCLZIP_OPT_TEMP_FILE_ON => 'optional', + PCLZIP_OPT_TEMP_FILE_OFF => 'optional' + //, PCLZIP_OPT_CRYPT => 'optional' + )); + if ($v_result != 1) { + return 0; + } + } + + // ----- Look for 2 args + // Here we need to support the first historic synopsis of the + // method. + else { + + // ----- Get the first argument + $v_options[PCLZIP_OPT_ADD_PATH] = $v_add_path = $v_arg_list[0]; + + // ----- Look for the optional second argument + if ($v_size == 2) { + $v_options[PCLZIP_OPT_REMOVE_PATH] = $v_arg_list[1]; + } + else if ($v_size > 2) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments"); + + // ----- Return + return 0; + } + } + } + + // ----- Look for default option values + $this->privOptionDefaultThreshold($v_options); + + // ----- Init + $v_string_list = array(); + $v_att_list = array(); + $v_filedescr_list = array(); + $p_result_list = array(); + + // ----- Look if the $p_filelist is really an array + if (is_array($p_filelist)) { + + // ----- Look if the first element is also an array + // This will mean that this is a file description entry + if (isset($p_filelist[0]) && is_array($p_filelist[0])) { + $v_att_list = $p_filelist; + } + + // ----- The list is a list of string names + else { + $v_string_list = $p_filelist; + } + } + + // ----- Look if the $p_filelist is a string + else if (is_string($p_filelist)) { + // ----- Create a list from the string + $v_string_list = explode(PCLZIP_SEPARATOR, $p_filelist); + } + + // ----- Invalid variable type for $p_filelist + else { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type '".gettype($p_filelist)."' for p_filelist"); + return 0; + } + + // ----- Reformat the string list + if (sizeof($v_string_list) != 0) { + foreach ($v_string_list as $v_string) { + $v_att_list[][PCLZIP_ATT_FILE_NAME] = $v_string; + } + } + + // ----- For each file in the list check the attributes + $v_supported_attributes + = array ( PCLZIP_ATT_FILE_NAME => 'mandatory' + ,PCLZIP_ATT_FILE_NEW_SHORT_NAME => 'optional' + ,PCLZIP_ATT_FILE_NEW_FULL_NAME => 'optional' + ,PCLZIP_ATT_FILE_MTIME => 'optional' + ,PCLZIP_ATT_FILE_CONTENT => 'optional' + ,PCLZIP_ATT_FILE_COMMENT => 'optional' + ); + foreach ($v_att_list as $v_entry) { + $v_result = $this->privFileDescrParseAtt($v_entry, + $v_filedescr_list[], + $v_options, + $v_supported_attributes); + if ($v_result != 1) { + return 0; + } + } + + // ----- Expand the filelist (expand directories) + $v_result = $this->privFileDescrExpand($v_filedescr_list, $v_options); + if ($v_result != 1) { + return 0; + } + + // ----- Call the create fct + $v_result = $this->privAdd($v_filedescr_list, $p_result_list, $v_options); + if ($v_result != 1) { + return 0; + } + + // ----- Return + return $p_result_list; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : listContent() + // Description : + // This public method, gives the list of the files and directories, with their + // properties. + // The properties of each entries in the list are (used also in other functions) : + // filename : Name of the file. For a create or add action it is the filename + // given by the user. For an extract function it is the filename + // of the extracted file. + // stored_filename : Name of the file / directory stored in the archive. + // size : Size of the stored file. + // compressed_size : Size of the file's data compressed in the archive + // (without the headers overhead) + // mtime : Last known modification date of the file (UNIX timestamp) + // comment : Comment associated with the file + // folder : true | false + // index : index of the file in the archive + // status : status of the action (depending of the action) : + // Values are : + // ok : OK ! + // filtered : the file / dir is not extracted (filtered by user) + // already_a_directory : the file can not be extracted because a + // directory with the same name already exists + // write_protected : the file can not be extracted because a file + // with the same name already exists and is + // write protected + // newer_exist : the file was not extracted because a newer file exists + // path_creation_fail : the file is not extracted because the folder + // does not exist and can not be created + // write_error : the file was not extracted because there was a + // error while writing the file + // read_error : the file was not extracted because there was a error + // while reading the file + // invalid_header : the file was not extracted because of an archive + // format error (bad file header) + // Note that each time a method can continue operating when there + // is an action error on a file, the error is only logged in the file status. + // Return Values : + // 0 on an unrecoverable failure, + // The list of the files in the archive. + // -------------------------------------------------------------------------------- + function listContent() + { + $v_result=1; + + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Check archive + if (!$this->privCheckFormat()) { + return(0); + } + + // ----- Call the extracting fct + $p_list = array(); + if (($v_result = $this->privList($p_list)) != 1) + { + unset($p_list); + return(0); + } + + // ----- Return + return $p_list; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : + // extract($p_path="./", $p_remove_path="") + // extract([$p_option, $p_option_value, ...]) + // Description : + // This method supports two synopsis. The first one is historical. + // This method extract all the files / directories from the archive to the + // folder indicated in $p_path. + // If you want to ignore the 'root' part of path of the memorized files + // you can indicate this in the optional $p_remove_path parameter. + // By default, if a newer file with the same name already exists, the + // file is not extracted. + // + // If both PCLZIP_OPT_PATH and PCLZIP_OPT_ADD_PATH aoptions + // are used, the path indicated in PCLZIP_OPT_ADD_PATH is append + // at the end of the path value of PCLZIP_OPT_PATH. + // Parameters : + // $p_path : Path where the files and directories are to be extracted + // $p_remove_path : First part ('root' part) of the memorized path + // (if any similar) to remove while extracting. + // Options : + // PCLZIP_OPT_PATH : + // PCLZIP_OPT_ADD_PATH : + // PCLZIP_OPT_REMOVE_PATH : + // PCLZIP_OPT_REMOVE_ALL_PATH : + // PCLZIP_CB_PRE_EXTRACT : + // PCLZIP_CB_POST_EXTRACT : + // Return Values : + // 0 or a negative value on failure, + // The list of the extracted files, with a status of the action. + // (see PclZip::listContent() for list entry format) + // -------------------------------------------------------------------------------- + function extract() + { + $v_result=1; + + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Check archive + if (!$this->privCheckFormat()) { + return(0); + } + + // ----- Set default values + $v_options = array(); +// $v_path = "./"; + $v_path = ''; + $v_remove_path = ""; + $v_remove_all_path = false; + + // ----- Look for variable options arguments + $v_size = func_num_args(); + + // ----- Default values for option + $v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = FALSE; + + // ----- Look for arguments + if ($v_size > 0) { + // ----- Get the arguments + $v_arg_list = func_get_args(); + + // ----- Look for first arg + if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) { + + // ----- Parse the options + $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, + array (PCLZIP_OPT_PATH => 'optional', + PCLZIP_OPT_REMOVE_PATH => 'optional', + PCLZIP_OPT_REMOVE_ALL_PATH => 'optional', + PCLZIP_OPT_ADD_PATH => 'optional', + PCLZIP_CB_PRE_EXTRACT => 'optional', + PCLZIP_CB_POST_EXTRACT => 'optional', + PCLZIP_OPT_SET_CHMOD => 'optional', + PCLZIP_OPT_BY_NAME => 'optional', + PCLZIP_OPT_BY_EREG => 'optional', + PCLZIP_OPT_BY_PREG => 'optional', + PCLZIP_OPT_BY_INDEX => 'optional', + PCLZIP_OPT_EXTRACT_AS_STRING => 'optional', + PCLZIP_OPT_EXTRACT_IN_OUTPUT => 'optional', + PCLZIP_OPT_REPLACE_NEWER => 'optional' + ,PCLZIP_OPT_STOP_ON_ERROR => 'optional' + ,PCLZIP_OPT_EXTRACT_DIR_RESTRICTION => 'optional', + PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional', + PCLZIP_OPT_TEMP_FILE_ON => 'optional', + PCLZIP_OPT_TEMP_FILE_OFF => 'optional' + )); + if ($v_result != 1) { + return 0; + } + + // ----- Set the arguments + if (isset($v_options[PCLZIP_OPT_PATH])) { + $v_path = $v_options[PCLZIP_OPT_PATH]; + } + if (isset($v_options[PCLZIP_OPT_REMOVE_PATH])) { + $v_remove_path = $v_options[PCLZIP_OPT_REMOVE_PATH]; + } + if (isset($v_options[PCLZIP_OPT_REMOVE_ALL_PATH])) { + $v_remove_all_path = $v_options[PCLZIP_OPT_REMOVE_ALL_PATH]; + } + if (isset($v_options[PCLZIP_OPT_ADD_PATH])) { + // ----- Check for '/' in last path char + if ((strlen($v_path) > 0) && (substr($v_path, -1) != '/')) { + $v_path .= '/'; + } + $v_path .= $v_options[PCLZIP_OPT_ADD_PATH]; + } + } + + // ----- Look for 2 args + // Here we need to support the first historic synopsis of the + // method. + else { + + // ----- Get the first argument + $v_path = $v_arg_list[0]; + + // ----- Look for the optional second argument + if ($v_size == 2) { + $v_remove_path = $v_arg_list[1]; + } + else if ($v_size > 2) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments"); + + // ----- Return + return 0; + } + } + } + + // ----- Look for default option values + $this->privOptionDefaultThreshold($v_options); + + // ----- Trace + + // ----- Call the extracting fct + $p_list = array(); + $v_result = $this->privExtractByRule($p_list, $v_path, $v_remove_path, + $v_remove_all_path, $v_options); + if ($v_result < 1) { + unset($p_list); + return(0); + } + + // ----- Return + return $p_list; + } + // -------------------------------------------------------------------------------- + + + // -------------------------------------------------------------------------------- + // Function : + // extractByIndex($p_index, $p_path="./", $p_remove_path="") + // extractByIndex($p_index, [$p_option, $p_option_value, ...]) + // Description : + // This method supports two synopsis. The first one is historical. + // This method is doing a partial extract of the archive. + // The extracted files or folders are identified by their index in the + // archive (from 0 to n). + // Note that if the index identify a folder, only the folder entry is + // extracted, not all the files included in the archive. + // Parameters : + // $p_index : A single index (integer) or a string of indexes of files to + // extract. The form of the string is "0,4-6,8-12" with only numbers + // and '-' for range or ',' to separate ranges. No spaces or ';' + // are allowed. + // $p_path : Path where the files and directories are to be extracted + // $p_remove_path : First part ('root' part) of the memorized path + // (if any similar) to remove while extracting. + // Options : + // PCLZIP_OPT_PATH : + // PCLZIP_OPT_ADD_PATH : + // PCLZIP_OPT_REMOVE_PATH : + // PCLZIP_OPT_REMOVE_ALL_PATH : + // PCLZIP_OPT_EXTRACT_AS_STRING : The files are extracted as strings and + // not as files. + // The resulting content is in a new field 'content' in the file + // structure. + // This option must be used alone (any other options are ignored). + // PCLZIP_CB_PRE_EXTRACT : + // PCLZIP_CB_POST_EXTRACT : + // Return Values : + // 0 on failure, + // The list of the extracted files, with a status of the action. + // (see PclZip::listContent() for list entry format) + // -------------------------------------------------------------------------------- + //function extractByIndex($p_index, options...) + function extractByIndex($p_index) + { + $v_result=1; + + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Check archive + if (!$this->privCheckFormat()) { + return(0); + } + + // ----- Set default values + $v_options = array(); +// $v_path = "./"; + $v_path = ''; + $v_remove_path = ""; + $v_remove_all_path = false; + + // ----- Look for variable options arguments + $v_size = func_num_args(); + + // ----- Default values for option + $v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = FALSE; + + // ----- Look for arguments + if ($v_size > 1) { + // ----- Get the arguments + $v_arg_list = func_get_args(); + + // ----- Remove form the options list the first argument + array_shift($v_arg_list); + $v_size--; + + // ----- Look for first arg + if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) { + + // ----- Parse the options + $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, + array (PCLZIP_OPT_PATH => 'optional', + PCLZIP_OPT_REMOVE_PATH => 'optional', + PCLZIP_OPT_REMOVE_ALL_PATH => 'optional', + PCLZIP_OPT_EXTRACT_AS_STRING => 'optional', + PCLZIP_OPT_ADD_PATH => 'optional', + PCLZIP_CB_PRE_EXTRACT => 'optional', + PCLZIP_CB_POST_EXTRACT => 'optional', + PCLZIP_OPT_SET_CHMOD => 'optional', + PCLZIP_OPT_REPLACE_NEWER => 'optional' + ,PCLZIP_OPT_STOP_ON_ERROR => 'optional' + ,PCLZIP_OPT_EXTRACT_DIR_RESTRICTION => 'optional', + PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional', + PCLZIP_OPT_TEMP_FILE_ON => 'optional', + PCLZIP_OPT_TEMP_FILE_OFF => 'optional' + )); + if ($v_result != 1) { + return 0; + } + + // ----- Set the arguments + if (isset($v_options[PCLZIP_OPT_PATH])) { + $v_path = $v_options[PCLZIP_OPT_PATH]; + } + if (isset($v_options[PCLZIP_OPT_REMOVE_PATH])) { + $v_remove_path = $v_options[PCLZIP_OPT_REMOVE_PATH]; + } + if (isset($v_options[PCLZIP_OPT_REMOVE_ALL_PATH])) { + $v_remove_all_path = $v_options[PCLZIP_OPT_REMOVE_ALL_PATH]; + } + if (isset($v_options[PCLZIP_OPT_ADD_PATH])) { + // ----- Check for '/' in last path char + if ((strlen($v_path) > 0) && (substr($v_path, -1) != '/')) { + $v_path .= '/'; + } + $v_path .= $v_options[PCLZIP_OPT_ADD_PATH]; + } + if (!isset($v_options[PCLZIP_OPT_EXTRACT_AS_STRING])) { + $v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = FALSE; + } + else { + } + } + + // ----- Look for 2 args + // Here we need to support the first historic synopsis of the + // method. + else { + + // ----- Get the first argument + $v_path = $v_arg_list[0]; + + // ----- Look for the optional second argument + if ($v_size == 2) { + $v_remove_path = $v_arg_list[1]; + } + else if ($v_size > 2) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments"); + + // ----- Return + return 0; + } + } + } + + // ----- Trace + + // ----- Trick + // Here I want to reuse extractByRule(), so I need to parse the $p_index + // with privParseOptions() + $v_arg_trick = array (PCLZIP_OPT_BY_INDEX, $p_index); + $v_options_trick = array(); + $v_result = $this->privParseOptions($v_arg_trick, sizeof($v_arg_trick), $v_options_trick, + array (PCLZIP_OPT_BY_INDEX => 'optional' )); + if ($v_result != 1) { + return 0; + } + $v_options[PCLZIP_OPT_BY_INDEX] = $v_options_trick[PCLZIP_OPT_BY_INDEX]; + + // ----- Look for default option values + $this->privOptionDefaultThreshold($v_options); + + // ----- Call the extracting fct + if (($v_result = $this->privExtractByRule($p_list, $v_path, $v_remove_path, $v_remove_all_path, $v_options)) < 1) { + return(0); + } + + // ----- Return + return $p_list; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : + // delete([$p_option, $p_option_value, ...]) + // Description : + // This method removes files from the archive. + // If no parameters are given, then all the archive is emptied. + // Parameters : + // None or optional arguments. + // Options : + // PCLZIP_OPT_BY_INDEX : + // PCLZIP_OPT_BY_NAME : + // PCLZIP_OPT_BY_EREG : + // PCLZIP_OPT_BY_PREG : + // Return Values : + // 0 on failure, + // The list of the files which are still present in the archive. + // (see PclZip::listContent() for list entry format) + // -------------------------------------------------------------------------------- + function delete() + { + $v_result=1; + + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Check archive + if (!$this->privCheckFormat()) { + return(0); + } + + // ----- Set default values + $v_options = array(); + + // ----- Look for variable options arguments + $v_size = func_num_args(); + + // ----- Look for arguments + if ($v_size > 0) { + // ----- Get the arguments + $v_arg_list = func_get_args(); + + // ----- Parse the options + $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, + array (PCLZIP_OPT_BY_NAME => 'optional', + PCLZIP_OPT_BY_EREG => 'optional', + PCLZIP_OPT_BY_PREG => 'optional', + PCLZIP_OPT_BY_INDEX => 'optional' )); + if ($v_result != 1) { + return 0; + } + } + + // ----- Magic quotes trick + $this->privDisableMagicQuotes(); + + // ----- Call the delete fct + $v_list = array(); + if (($v_result = $this->privDeleteByRule($v_list, $v_options)) != 1) { + $this->privSwapBackMagicQuotes(); + unset($v_list); + return(0); + } + + // ----- Magic quotes trick $this->privSwapBackMagicQuotes(); - return 0; + + // ----- Return + return $v_list; } + // -------------------------------------------------------------------------------- - // ----- Close the zip file - $this->privCloseFd(); + // -------------------------------------------------------------------------------- + // Function : deleteByIndex() + // Description : + // ***** Deprecated ***** + // delete(PCLZIP_OPT_BY_INDEX, $p_index) should be prefered. + // -------------------------------------------------------------------------------- + function deleteByIndex($p_index) + { + + $p_list = $this->delete(PCLZIP_OPT_BY_INDEX, $p_index); - // ----- Set the user attributes - $v_prop['comment'] = $v_central_dir['comment']; - $v_prop['nb'] = $v_central_dir['entries']; - $v_prop['status'] = 'ok'; -} - -// ----- Magic quotes trick -$this->privSwapBackMagicQuotes(); - -// ----- Return -return $v_prop; -} -// -------------------------------------------------------------------------------- - -// -------------------------------------------------------------------------------- -// Function : duplicate() -// Description : -// This method creates an archive by copying the content of an other one. If -// the archive already exist, it is replaced by the new one without any warning. -// Parameters : -// $p_archive : The filename of a valid archive, or -// a valid PclZip object. -// Return Values : -// 1 on success. -// 0 or a negative value on error (error code). -// -------------------------------------------------------------------------------- -function duplicate($p_archive) -{ -$v_result = 1; - -// ----- Reset the error handler -$this->privErrorReset(); - -// ----- Look if the $p_archive is a PclZip object -if ((is_object($p_archive)) && (get_class($p_archive) == 'pclzip')) -{ - - // ----- Duplicate the archive - $v_result = $this->privDuplicate($p_archive->zipname); -} - -// ----- Look if the $p_archive is a string (so a filename) -else if (is_string($p_archive)) -{ - - // ----- Check that $p_archive is a valid zip file - // TBC : Should also check the archive format - if (!is_file($p_archive)) { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_MISSING_FILE, "No file with filename '".$p_archive."'"); - $v_result = PCLZIP_ERR_MISSING_FILE; + // ----- Return + return $p_list; } - else { - // ----- Duplicate the archive - $v_result = $this->privDuplicate($p_archive); + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : properties() + // Description : + // This method gives the properties of the archive. + // The properties are : + // nb : Number of files in the archive + // comment : Comment associated with the archive file + // status : not_exist, ok + // Parameters : + // None + // Return Values : + // 0 on failure, + // An array with the archive properties. + // -------------------------------------------------------------------------------- + function properties() + { + + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Magic quotes trick + $this->privDisableMagicQuotes(); + + // ----- Check archive + if (!$this->privCheckFormat()) { + $this->privSwapBackMagicQuotes(); + return(0); + } + + // ----- Default properties + $v_prop = array(); + $v_prop['comment'] = ''; + $v_prop['nb'] = 0; + $v_prop['status'] = 'not_exist'; + + // ----- Look if file exists + if (@is_file($this->zipname)) + { + // ----- Open the zip file + if (($this->zip_fd = @fopen($this->zipname, 'rb')) == 0) + { + $this->privSwapBackMagicQuotes(); + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \''.$this->zipname.'\' in binary read mode'); + + // ----- Return + return 0; + } + + // ----- Read the central directory informations + $v_central_dir = array(); + if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) + { + $this->privSwapBackMagicQuotes(); + return 0; + } + + // ----- Close the zip file + $this->privCloseFd(); + + // ----- Set the user attributes + $v_prop['comment'] = $v_central_dir['comment']; + $v_prop['nb'] = $v_central_dir['entries']; + $v_prop['status'] = 'ok'; + } + + // ----- Magic quotes trick + $this->privSwapBackMagicQuotes(); + + // ----- Return + return $v_prop; } -} + // -------------------------------------------------------------------------------- -// ----- Invalid variable -else -{ - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_archive_to_add"); - $v_result = PCLZIP_ERR_INVALID_PARAMETER; -} + // -------------------------------------------------------------------------------- + // Function : duplicate() + // Description : + // This method creates an archive by copying the content of an other one. If + // the archive already exist, it is replaced by the new one without any warning. + // Parameters : + // $p_archive : The filename of a valid archive, or + // a valid PclZip object. + // Return Values : + // 1 on success. + // 0 or a negative value on error (error code). + // -------------------------------------------------------------------------------- + function duplicate($p_archive) + { + $v_result = 1; -// ----- Return -return $v_result; -} -// -------------------------------------------------------------------------------- + // ----- Reset the error handler + $this->privErrorReset(); -// -------------------------------------------------------------------------------- -// Function : merge() -// Description : -// This method merge the $p_archive_to_add archive at the end of the current -// one ($this). -// If the archive ($this) does not exist, the merge becomes a duplicate. -// If the $p_archive_to_add archive does not exist, the merge is a success. -// Parameters : -// $p_archive_to_add : It can be directly the filename of a valid zip archive, -// or a PclZip object archive. -// Return Values : -// 1 on success, -// 0 or negative values on error (see below). -// -------------------------------------------------------------------------------- -function merge($p_archive_to_add) -{ -$v_result = 1; + // ----- Look if the $p_archive is a PclZip object + if ((is_object($p_archive)) && (get_class($p_archive) == 'pclzip')) + { -// ----- Reset the error handler -$this->privErrorReset(); + // ----- Duplicate the archive + $v_result = $this->privDuplicate($p_archive->zipname); + } -// ----- Check archive -if (!$this->privCheckFormat()) { - return(0); -} + // ----- Look if the $p_archive is a string (so a filename) + else if (is_string($p_archive)) + { -// ----- Look if the $p_archive_to_add is a PclZip object -if ((is_object($p_archive_to_add)) && (get_class($p_archive_to_add) == 'pclzip')) -{ + // ----- Check that $p_archive is a valid zip file + // TBC : Should also check the archive format + if (!is_file($p_archive)) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_FILE, "No file with filename '".$p_archive."'"); + $v_result = PCLZIP_ERR_MISSING_FILE; + } + else { + // ----- Duplicate the archive + $v_result = $this->privDuplicate($p_archive); + } + } - // ----- Merge the archive - $v_result = $this->privMerge($p_archive_to_add); -} + // ----- Invalid variable + else + { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_archive_to_add"); + $v_result = PCLZIP_ERR_INVALID_PARAMETER; + } -// ----- Look if the $p_archive_to_add is a string (so a filename) -else if (is_string($p_archive_to_add)) -{ - - // ----- Create a temporary archive - $v_object_archive = new PclZip($p_archive_to_add); - - // ----- Merge the archive - $v_result = $this->privMerge($v_object_archive); -} - -// ----- Invalid variable -else -{ - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_archive_to_add"); - $v_result = PCLZIP_ERR_INVALID_PARAMETER; -} - -// ----- Return -return $v_result; -} -// -------------------------------------------------------------------------------- - - - -// -------------------------------------------------------------------------------- -// Function : errorCode() -// Description : -// Parameters : -// -------------------------------------------------------------------------------- -function errorCode() -{ -if (PCLZIP_ERROR_EXTERNAL == 1) { - return(PclErrorCode()); -} -else { - return($this->error_code); -} -} -// -------------------------------------------------------------------------------- - -// -------------------------------------------------------------------------------- -// Function : errorName() -// Description : -// Parameters : -// -------------------------------------------------------------------------------- -function errorName($p_with_code=false) -{ -$v_name = array (PCLZIP_ERR_NO_ERROR => 'PCLZIP_ERR_NO_ERROR', - PCLZIP_ERR_WRITE_OPEN_FAIL => 'PCLZIP_ERR_WRITE_OPEN_FAIL', - PCLZIP_ERR_READ_OPEN_FAIL => 'PCLZIP_ERR_READ_OPEN_FAIL', - PCLZIP_ERR_INVALID_PARAMETER => 'PCLZIP_ERR_INVALID_PARAMETER', - PCLZIP_ERR_MISSING_FILE => 'PCLZIP_ERR_MISSING_FILE', - PCLZIP_ERR_FILENAME_TOO_LONG => 'PCLZIP_ERR_FILENAME_TOO_LONG', - PCLZIP_ERR_INVALID_ZIP => 'PCLZIP_ERR_INVALID_ZIP', - PCLZIP_ERR_BAD_EXTRACTED_FILE => 'PCLZIP_ERR_BAD_EXTRACTED_FILE', - PCLZIP_ERR_DIR_CREATE_FAIL => 'PCLZIP_ERR_DIR_CREATE_FAIL', - PCLZIP_ERR_BAD_EXTENSION => 'PCLZIP_ERR_BAD_EXTENSION', - PCLZIP_ERR_BAD_FORMAT => 'PCLZIP_ERR_BAD_FORMAT', - PCLZIP_ERR_DELETE_FILE_FAIL => 'PCLZIP_ERR_DELETE_FILE_FAIL', - PCLZIP_ERR_RENAME_FILE_FAIL => 'PCLZIP_ERR_RENAME_FILE_FAIL', - PCLZIP_ERR_BAD_CHECKSUM => 'PCLZIP_ERR_BAD_CHECKSUM', - PCLZIP_ERR_INVALID_ARCHIVE_ZIP => 'PCLZIP_ERR_INVALID_ARCHIVE_ZIP', - PCLZIP_ERR_MISSING_OPTION_VALUE => 'PCLZIP_ERR_MISSING_OPTION_VALUE', - PCLZIP_ERR_INVALID_OPTION_VALUE => 'PCLZIP_ERR_INVALID_OPTION_VALUE', - PCLZIP_ERR_UNSUPPORTED_COMPRESSION => 'PCLZIP_ERR_UNSUPPORTED_COMPRESSION', - PCLZIP_ERR_UNSUPPORTED_ENCRYPTION => 'PCLZIP_ERR_UNSUPPORTED_ENCRYPTION' - ,PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE => 'PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE' - ,PCLZIP_ERR_DIRECTORY_RESTRICTION => 'PCLZIP_ERR_DIRECTORY_RESTRICTION' - ) ); - -if (isset($v_name[$this->error_code])) { - $v_value = $v_name[$this->error_code]; -} -else { - $v_value = 'NoName'; -} - -if ($p_with_code) { - return($v_value.' ('.$this->error_code.')'); -} -else { - return($v_value); -} -} -// -------------------------------------------------------------------------------- - -// -------------------------------------------------------------------------------- -// Function : errorInfo() -// Description : -// Parameters : -// -------------------------------------------------------------------------------- -function errorInfo($p_full=false) -{ -if (PCLZIP_ERROR_EXTERNAL == 1) { - return(PclErrorString()); -} -else { - if ($p_full) { - return($this->errorName(true)." : ".$this->error_string); + // ----- Return + return $v_result; } - else { - return($this->error_string." [code ".$this->error_code."]"); + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : merge() + // Description : + // This method merge the $p_archive_to_add archive at the end of the current + // one ($this). + // If the archive ($this) does not exist, the merge becomes a duplicate. + // If the $p_archive_to_add archive does not exist, the merge is a success. + // Parameters : + // $p_archive_to_add : It can be directly the filename of a valid zip archive, + // or a PclZip object archive. + // Return Values : + // 1 on success, + // 0 or negative values on error (see below). + // -------------------------------------------------------------------------------- + function merge($p_archive_to_add) + { + $v_result = 1; + + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Check archive + if (!$this->privCheckFormat()) { + return(0); + } + + // ----- Look if the $p_archive_to_add is a PclZip object + if ((is_object($p_archive_to_add)) && (get_class($p_archive_to_add) == 'pclzip')) + { + + // ----- Merge the archive + $v_result = $this->privMerge($p_archive_to_add); + } + + // ----- Look if the $p_archive_to_add is a string (so a filename) + else if (is_string($p_archive_to_add)) + { + + // ----- Create a temporary archive + $v_object_archive = new PclZip($p_archive_to_add); + + // ----- Merge the archive + $v_result = $this->privMerge($v_object_archive); + } + + // ----- Invalid variable + else + { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_archive_to_add"); + $v_result = PCLZIP_ERR_INVALID_PARAMETER; + } + + // ----- Return + return $v_result; } -} -} -// -------------------------------------------------------------------------------- + // -------------------------------------------------------------------------------- + + + + // -------------------------------------------------------------------------------- + // Function : errorCode() + // Description : + // Parameters : + // -------------------------------------------------------------------------------- + function errorCode() + { + if (PCLZIP_ERROR_EXTERNAL == 1) { + return(PclErrorCode()); + } + else { + return($this->error_code); + } + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : errorName() + // Description : + // Parameters : + // -------------------------------------------------------------------------------- + function errorName($p_with_code=false) + { + $v_name = array ( PCLZIP_ERR_NO_ERROR => 'PCLZIP_ERR_NO_ERROR', + PCLZIP_ERR_WRITE_OPEN_FAIL => 'PCLZIP_ERR_WRITE_OPEN_FAIL', + PCLZIP_ERR_READ_OPEN_FAIL => 'PCLZIP_ERR_READ_OPEN_FAIL', + PCLZIP_ERR_INVALID_PARAMETER => 'PCLZIP_ERR_INVALID_PARAMETER', + PCLZIP_ERR_MISSING_FILE => 'PCLZIP_ERR_MISSING_FILE', + PCLZIP_ERR_FILENAME_TOO_LONG => 'PCLZIP_ERR_FILENAME_TOO_LONG', + PCLZIP_ERR_INVALID_ZIP => 'PCLZIP_ERR_INVALID_ZIP', + PCLZIP_ERR_BAD_EXTRACTED_FILE => 'PCLZIP_ERR_BAD_EXTRACTED_FILE', + PCLZIP_ERR_DIR_CREATE_FAIL => 'PCLZIP_ERR_DIR_CREATE_FAIL', + PCLZIP_ERR_BAD_EXTENSION => 'PCLZIP_ERR_BAD_EXTENSION', + PCLZIP_ERR_BAD_FORMAT => 'PCLZIP_ERR_BAD_FORMAT', + PCLZIP_ERR_DELETE_FILE_FAIL => 'PCLZIP_ERR_DELETE_FILE_FAIL', + PCLZIP_ERR_RENAME_FILE_FAIL => 'PCLZIP_ERR_RENAME_FILE_FAIL', + PCLZIP_ERR_BAD_CHECKSUM => 'PCLZIP_ERR_BAD_CHECKSUM', + PCLZIP_ERR_INVALID_ARCHIVE_ZIP => 'PCLZIP_ERR_INVALID_ARCHIVE_ZIP', + PCLZIP_ERR_MISSING_OPTION_VALUE => 'PCLZIP_ERR_MISSING_OPTION_VALUE', + PCLZIP_ERR_INVALID_OPTION_VALUE => 'PCLZIP_ERR_INVALID_OPTION_VALUE', + PCLZIP_ERR_UNSUPPORTED_COMPRESSION => 'PCLZIP_ERR_UNSUPPORTED_COMPRESSION', + PCLZIP_ERR_UNSUPPORTED_ENCRYPTION => 'PCLZIP_ERR_UNSUPPORTED_ENCRYPTION' + ,PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE => 'PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE' + ,PCLZIP_ERR_DIRECTORY_RESTRICTION => 'PCLZIP_ERR_DIRECTORY_RESTRICTION' + ); + + if (isset($v_name[$this->error_code])) { + $v_value = $v_name[$this->error_code]; + } + else { + $v_value = 'NoName'; + } + + if ($p_with_code) { + return($v_value.' ('.$this->error_code.')'); + } + else { + return($v_value); + } + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : errorInfo() + // Description : + // Parameters : + // -------------------------------------------------------------------------------- + function errorInfo($p_full=false) + { + if (PCLZIP_ERROR_EXTERNAL == 1) { + return(PclErrorString()); + } + else { + if ($p_full) { + return($this->errorName(true)." : ".$this->error_string); + } + else { + return($this->error_string." [code ".$this->error_code."]"); + } + } + } + // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- @@ -1303,3491 +1356,966 @@ else { -// -------------------------------------------------------------------------------- -// Function : privCheckFormat() -// Description : -// This method check that the archive exists and is a valid zip archive. -// Several level of check exists. (futur) -// Parameters : -// $p_level : Level of check. Default 0. -// 0 : Check the first bytes (magic codes) (default value)) -// 1 : 0 + Check the central directory (futur) -// 2 : 1 + Check each file header (futur) -// Return Values : -// true on success, -// false on error, the error code is set. -// -------------------------------------------------------------------------------- -function privCheckFormat($p_level=0) -{ -$v_result = true; + // -------------------------------------------------------------------------------- + // Function : privCheckFormat() + // Description : + // This method check that the archive exists and is a valid zip archive. + // Several level of check exists. (futur) + // Parameters : + // $p_level : Level of check. Default 0. + // 0 : Check the first bytes (magic codes) (default value)) + // 1 : 0 + Check the central directory (futur) + // 2 : 1 + Check each file header (futur) + // Return Values : + // true on success, + // false on error, the error code is set. + // -------------------------------------------------------------------------------- + function privCheckFormat($p_level=0) + { + $v_result = true; -// ----- Reset the file system cache -clearstatcache(); + // ----- Reset the file system cache + clearstatcache(); -// ----- Reset the error handler -$this->privErrorReset(); + // ----- Reset the error handler + $this->privErrorReset(); -// ----- Look if the file exits -if (!is_file($this->zipname)) { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_MISSING_FILE, "Missing archive file '".$this->zipname."'"); - return(false); -} + // ----- Look if the file exits + if (!is_file($this->zipname)) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_FILE, "Missing archive file '".$this->zipname."'"); + return(false); + } -// ----- Check that the file is readeable -if (!is_readable($this->zipname)) { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, "Unable to read archive '".$this->zipname."'"); - return(false); -} + // ----- Check that the file is readeable + if (!is_readable($this->zipname)) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, "Unable to read archive '".$this->zipname."'"); + return(false); + } -// ----- Check the magic code -// TBC + // ----- Check the magic code + // TBC -// ----- Check the central header -// TBC + // ----- Check the central header + // TBC -// ----- Check each file header -// TBC - -// ----- Return -return $v_result; -} -// -------------------------------------------------------------------------------- - -// -------------------------------------------------------------------------------- -// Function : privParseOptions() -// Description : -// This internal methods reads the variable list of arguments ($p_options_list, -// $p_size) and generate an array with the options and values ($v_result_list). -// $v_requested_options contains the options that can be present and those that -// must be present. -// $v_requested_options is an array, with the option value as key, and 'optional', -// or 'mandatory' as value. -// Parameters : -// See above. -// Return Values : -// 1 on success. -// 0 on failure. -// -------------------------------------------------------------------------------- -function privParseOptions(&$p_options_list, $p_size, &$v_result_list, $v_requested_options=false) -{ -$v_result=1; - -// ----- Read the options -$i=0; -while ($i<$p_size) { - - // ----- Check if the option is supported - if (!isset($v_requested_options[$p_options_list[$i]])) { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid optional parameter '".$p_options_list[$i]."' for this method"); + // ----- Check each file header + // TBC // ----- Return - return PclZip::errorCode(); + return $v_result; } + // -------------------------------------------------------------------------------- - // ----- Look for next option - switch ($p_options_list[$i]) { - // ----- Look for options that request a path value - case PCLZIP_OPT_PATH : - case PCLZIP_OPT_REMOVE_PATH : - case PCLZIP_OPT_ADD_PATH : - // ----- Check the number of parameters - if (($i+1) >= $p_size) { + // -------------------------------------------------------------------------------- + // Function : privParseOptions() + // Description : + // This internal methods reads the variable list of arguments ($p_options_list, + // $p_size) and generate an array with the options and values ($v_result_list). + // $v_requested_options contains the options that can be present and those that + // must be present. + // $v_requested_options is an array, with the option value as key, and 'optional', + // or 'mandatory' as value. + // Parameters : + // See above. + // Return Values : + // 1 on success. + // 0 on failure. + // -------------------------------------------------------------------------------- + function privParseOptions(&$p_options_list, $p_size, &$v_result_list, $v_requested_options=false) + { + $v_result=1; + + // ----- Read the options + $i=0; + while ($i<$p_size) { + + // ----- Check if the option is supported + if (!isset($v_requested_options[$p_options_list[$i]])) { // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid optional parameter '".$p_options_list[$i]."' for this method"); // ----- Return return PclZip::errorCode(); } - // ----- Get the value - $v_result_list[$p_options_list[$i]] = PclZipUtilTranslateWinPath($p_options_list[$i+1], false); - $i++; - break; + // ----- Look for next option + switch ($p_options_list[$i]) { + // ----- Look for options that request a path value + case PCLZIP_OPT_PATH : + case PCLZIP_OPT_REMOVE_PATH : + case PCLZIP_OPT_ADD_PATH : + // ----- Check the number of parameters + if (($i+1) >= $p_size) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); - case PCLZIP_OPT_TEMP_FILE_THRESHOLD : - // ----- Check the number of parameters - if (($i+1) >= $p_size) { - PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); - return PclZip::errorCode(); - } - - // ----- Check for incompatible options - if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_OFF])) { - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_OFF'"); - return PclZip::errorCode(); - } - - // ----- Check the value - $v_value = $p_options_list[$i+1]; - if ((!is_integer($v_value)) || ($v_value<0)) { - PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Integer expected for option '".PclZipUtilOptionText($p_options_list[$i])."'"); - return PclZip::errorCode(); - } - - // ----- Get the value (and convert it in bytes) - $v_result_list[$p_options_list[$i]] = $v_value*1048576; - $i++; - break; - - case PCLZIP_OPT_TEMP_FILE_ON : - // ----- Check for incompatible options - if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_OFF])) { - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_OFF'"); - return PclZip::errorCode(); - } - - $v_result_list[$p_options_list[$i]] = true; - break; - - case PCLZIP_OPT_TEMP_FILE_OFF : - // ----- Check for incompatible options - if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_ON])) { - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_ON'"); - return PclZip::errorCode(); - } - // ----- Check for incompatible options - if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_THRESHOLD])) { - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_THRESHOLD'"); - return PclZip::errorCode(); - } - - $v_result_list[$p_options_list[$i]] = true; - break; - - case PCLZIP_OPT_EXTRACT_DIR_RESTRICTION : - // ----- Check the number of parameters - if (($i+1) >= $p_size) { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); - - // ----- Return - return PclZip::errorCode(); - } - - // ----- Get the value - if (is_string($p_options_list[$i+1]) - && ($p_options_list[$i+1] != '')) { - $v_result_list[$p_options_list[$i]] = PclZipUtilTranslateWinPath($p_options_list[$i+1], false); - $i++; - } - else { - } - break; - - // ----- Look for options that request an array of string for value - case PCLZIP_OPT_BY_NAME : - // ----- Check the number of parameters - if (($i+1) >= $p_size) { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); - - // ----- Return - return PclZip::errorCode(); - } - - // ----- Get the value - if (is_string($p_options_list[$i+1])) { - $v_result_list[$p_options_list[$i]][0] = $p_options_list[$i+1]; - } - else if (is_array($p_options_list[$i+1])) { - $v_result_list[$p_options_list[$i]] = $p_options_list[$i+1]; - } - else { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Wrong parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); - - // ----- Return - return PclZip::errorCode(); - } - $i++; - break; - - // ----- Look for options that request an EREG or PREG expression - case PCLZIP_OPT_BY_EREG : - // ereg() is deprecated starting with PHP 5.3. Move PCLZIP_OPT_BY_EREG - // to PCLZIP_OPT_BY_PREG - $p_options_list[$i] = PCLZIP_OPT_BY_PREG; - case PCLZIP_OPT_BY_PREG : - //case PCLZIP_OPT_CRYPT : - // ----- Check the number of parameters - if (($i+1) >= $p_size) { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); - - // ----- Return - return PclZip::errorCode(); - } - - // ----- Get the value - if (is_string($p_options_list[$i+1])) { - $v_result_list[$p_options_list[$i]] = $p_options_list[$i+1]; - } - else { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Wrong parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); - - // ----- Return - return PclZip::errorCode(); - } - $i++; - break; - - // ----- Look for options that takes a string - case PCLZIP_OPT_COMMENT : - case PCLZIP_OPT_ADD_COMMENT : - case PCLZIP_OPT_PREPEND_COMMENT : - // ----- Check the number of parameters - if (($i+1) >= $p_size) { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, - "Missing parameter value for option '" - .PclZipUtilOptionText($p_options_list[$i]) - ."'"); - - // ----- Return - return PclZip::errorCode(); - } - - // ----- Get the value - if (is_string($p_options_list[$i+1])) { - $v_result_list[$p_options_list[$i]] = $p_options_list[$i+1]; - } - else { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, - "Wrong parameter value for option '" - .PclZipUtilOptionText($p_options_list[$i]) - ."'"); - - // ----- Return - return PclZip::errorCode(); - } - $i++; - break; - - // ----- Look for options that request an array of index - case PCLZIP_OPT_BY_INDEX : - // ----- Check the number of parameters - if (($i+1) >= $p_size) { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); - - // ----- Return - return PclZip::errorCode(); - } - - // ----- Get the value - $v_work_list = array(); - if (is_string($p_options_list[$i+1])) { - - // ----- Remove spaces - $p_options_list[$i+1] = strtr($p_options_list[$i+1], ' ', ''); - - // ----- Parse items - $v_work_list = explode(",", $p_options_list[$i+1]); - } - else if (is_integer($p_options_list[$i+1])) { - $v_work_list[0] = $p_options_list[$i+1].'-'.$p_options_list[$i+1]; - } - else if (is_array($p_options_list[$i+1])) { - $v_work_list = $p_options_list[$i+1]; - } - else { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Value must be integer, string or array for option '".PclZipUtilOptionText($p_options_list[$i])."'"); - - // ----- Return - return PclZip::errorCode(); - } - - // ----- Reduce the index list - // each index item in the list must be a couple with a start and - // an end value : [0,3], [5-5], [8-10], ... - // ----- Check the format of each item - $v_sort_flag=false; - $v_sort_value=0; - for ($j=0; $j= $p_size) { + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + return PclZip::errorCode(); + } + + // ----- Check for incompatible options + if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_OFF])) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_OFF'"); + return PclZip::errorCode(); + } + + // ----- Check the value + $v_value = $p_options_list[$i+1]; + if ((!is_integer($v_value)) || ($v_value<0)) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Integer expected for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + return PclZip::errorCode(); + } + + // ----- Get the value (and convert it in bytes) + $v_result_list[$p_options_list[$i]] = $v_value*1048576; + $i++; + break; + + case PCLZIP_OPT_TEMP_FILE_ON : + // ----- Check for incompatible options + if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_OFF])) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_OFF'"); + return PclZip::errorCode(); + } + + $v_result_list[$p_options_list[$i]] = true; + break; + + case PCLZIP_OPT_TEMP_FILE_OFF : + // ----- Check for incompatible options + if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_ON])) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_ON'"); + return PclZip::errorCode(); + } + // ----- Check for incompatible options + if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_THRESHOLD])) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_THRESHOLD'"); + return PclZip::errorCode(); + } + + $v_result_list[$p_options_list[$i]] = true; + break; + + case PCLZIP_OPT_EXTRACT_DIR_RESTRICTION : + // ----- Check the number of parameters + if (($i+1) >= $p_size) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Get the value + if ( is_string($p_options_list[$i+1]) + && ($p_options_list[$i+1] != '')) { + $v_result_list[$p_options_list[$i]] = PclZipUtilTranslateWinPath($p_options_list[$i+1], FALSE); + $i++; } else { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Too many values in index range for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + } + break; - // ----- Return - return PclZip::errorCode(); + // ----- Look for options that request an array of string for value + case PCLZIP_OPT_BY_NAME : + // ----- Check the number of parameters + if (($i+1) >= $p_size) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + + // ----- Return + return PclZip::errorCode(); } - - // ----- Look for list sort - if ($v_result_list[$p_options_list[$i]][$j]['start'] < $v_sort_value) { - $v_sort_flag=true; - - // ----- TBC : An automatic sort should be writen ... - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Invalid order of index range for option '".PclZipUtilOptionText($p_options_list[$i])."'"); - - // ----- Return - return PclZip::errorCode(); + // ----- Get the value + if (is_string($p_options_list[$i+1])) { + $v_result_list[$p_options_list[$i]][0] = $p_options_list[$i+1]; } - $v_sort_value = $v_result_list[$p_options_list[$i]][$j]['start']; - } - - // ----- Sort the items - if ($v_sort_flag) { - // TBC : To Be Completed - } - - // ----- Next option - $i++; - break; - - // ----- Look for options that request no value - case PCLZIP_OPT_REMOVE_ALL_PATH : - case PCLZIP_OPT_EXTRACT_AS_STRING : - case PCLZIP_OPT_NO_COMPRESSION : - case PCLZIP_OPT_EXTRACT_IN_OUTPUT : - case PCLZIP_OPT_REPLACE_NEWER : - case PCLZIP_OPT_STOP_ON_ERROR : - $v_result_list[$p_options_list[$i]] = true; - break; - - // ----- Look for options that request an octal value - case PCLZIP_OPT_SET_CHMOD : - // ----- Check the number of parameters - if (($i+1) >= $p_size) { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); - - // ----- Return - return PclZip::errorCode(); - } - - // ----- Get the value - $v_result_list[$p_options_list[$i]] = $p_options_list[$i+1]; - $i++; - break; - - // ----- Look for options that request a call-back - case PCLZIP_CB_PRE_EXTRACT : - case PCLZIP_CB_POST_EXTRACT : - case PCLZIP_CB_PRE_ADD : - case PCLZIP_CB_POST_ADD : - /* for futur use - case PCLZIP_CB_PRE_DELETE : - case PCLZIP_CB_POST_DELETE : - case PCLZIP_CB_PRE_LIST : - case PCLZIP_CB_POST_LIST : - */ - // ----- Check the number of parameters - if (($i+1) >= $p_size) { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); - - // ----- Return - return PclZip::errorCode(); - } - - // ----- Get the value - $v_function_name = $p_options_list[$i+1]; - - // ----- Check that the value is a valid existing function - if (!function_exists($v_function_name)) { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VA )); - if ($v_result != 1) { - return 0; - } - } - - // ----- Look for 2 args - // Here we need to support the first historic synopsis of the - // method. - else { - - // ----- Get the first argument - $v_options[PCLZIP_OPT_ADD_PATH] = $v_arg_list[0]; - - // ----- Look for the optional second argument - if ($v_size == 2) { - $v_options[PCLZIP_OPT_REMOVE_PATH] = $v_arg_list[1]; - } - else if ($v_size > 2) { - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, - "Invalid number / type of arguments"); - return 0; - } - } -} - -// ----- Look for default option values -$this->privOptionDefaultThreshold($v_options); - -// ----- Init -$v_string_list = array(); -$v_att_list = array(); -$v_filedescr_list = array(); -$p_result_list = array(); - -// ----- Look if the $p_filelist is really an array -if (is_array($p_filelist)) { - - // ----- Look if the first element is also an array - // This will mean that this is a file description entry - if (isset($p_filelist[0]) && is_array($p_filelist[0])) { - $v_att_list = $p_filelist; - } - - // ----- The list is a list of string names - else { - $v_string_list = $p_filelist; - } -} - -// ----- Look if the $p_filelist is a string -else if (is_string($p_filelist)) { - // ----- Create a list from the string - $v_string_list = explode(PCLZIP_SEPARATOR, $p_filelist); -} - -// ----- Invalid variable type for $p_filelist -else { - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_filelist"); - return 0; -} - -// ----- Reformat the string list -if (sizeof($v_string_list) != 0) { - foreach ($v_string_list as $v_string) { - if ($v_string != '') { - $v_att_list[][PCLZIP_ATT_FILE_NAME] = $v_string; - } - else { - } - } -} - -// ----- For each file in the list check the attributes -$v_supported_attributes -= array (PCLZIP_ATT_FILE_NAME => 'mandatory' - ,PCLZIP_ATT_FILE_NEW_SHORT_NAME => 'optional' - ,PCLZIP_ATT_FILE_NEW_FULL_NAME => 'optional' - ,PCLZIP_ATT_FILE_MTIME => 'optional' - ,PCLZIP_ATT_FILE_CONTENT => 'optional' - ,PCLZIP_ATT_FILE_COMMENT => 'optional' - ); -foreach ($v_att_list as $v_entry) { - $v_result = $this->privFileDescrParseAtt($v_entry, - $v_filedescr_list[], - $v_options, - $v_supported_attributes); - if ($v_result != 1) { - return 0; - } -} - -// ----- Expand the filelist (expand directories) -$v_result = $this->privFileDescrExpand($v_filedescr_list, $v_options); -if ($v_result != 1) { - return 0; -} - -// ----- Call the create fct -$v_result = $this->privCreate($v_filedescr_list, $p_result_list, $v_options); -if ($v_result != 1) { - return 0; -} - -// ----- Return -return $p_result_list; -} -// -------------------------------------------------------------------------------- - -// -------------------------------------------------------------------------------- -// Function : -// add($p_filelist, $p_add_dir="", $p_remove_dir="") -// add($p_filelist, $p_option, $p_option_value, ...) -// Description : -// This method supports two synopsis. The first one is historical. -// This methods add the list of files in an existing archive. -// If a file with the same name already exists, it is added at the end of the -// archive, the first one is still present. -// If the archive does not exist, it is created. -// Parameters : -// $p_filelist : An array containing file or directory names, or -// a string containing one filename or one directory name, or -// a string containing a list of filenames and/or directory -// names separated by spaces. -// $p_add_dir : A path to add before the real path of the archived file, -// in order to have it memorized in the archive. -// $p_remove_dir : A path to remove from the real path of the file to archive, -// in order to have a shorter path memorized in the archive. -// When $p_add_dir and $p_remove_dir are set, $p_remove_dir -// is removed first, before $p_add_dir is added. -// Options : -// PCLZIP_OPT_ADD_PATH : -// PCLZIP_OPT_REMOVE_PATH : -// PCLZIP_OPT_REMOVE_ALL_PATH : -// PCLZIP_OPT_COMMENT : -// PCLZIP_OPT_ADD_COMMENT : -// PCLZIP_OPT_PREPEND_COMMENT : -// PCLZIP_CB_PRE_ADD : -// PCLZIP_CB_POST_ADD : -// Return Values : -// 0 on failure, -// The list of the added files, with a status of the add action. -// (see PclZip::listContent() for list entry format) -// -------------------------------------------------------------------------------- -function add($p_filelist) -{ -$v_result=1; - -// ----- Reset the error handler -$this->privErrorReset(); - -// ----- Set default values -$v_options = array(); -$v_options[PCLZIP_OPT_NO_COMPRESSION] = false; - -// ----- Look for variable options arguments -$v_size = func_num_args(); - -// ----- Look for arguments -if ($v_size > 1) { - // ----- Get the arguments - $v_arg_list = func_get_args(); - - // ----- Remove form the options list the first argument - array_shift($v_arg_list); - $v_size--; - - // ----- Look for first arg - if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) { - - // ----- Parse the options - $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, - array (PCLZIP_OPT_REMOVE_PATH => 'optional', - PCLZIP_OPT_REMOVE_ALL_PATH => 'optional', - PCLZIP_OPT_ADD_PATH => 'optional', - PCLZIP_CB_PRE_ADD => 'optional', - PCLZIP_CB_POST_ADD => 'optional', - PCLZIP_OPT_NO_COMPRESSION => 'optional', - PCLZIP_OPT_COMMENT => 'optional', - PCLZIP_OPT_ADD_COMMENT => 'optional', - PCLZIP_OPT_PREPEND_COMMENT => 'optional', - PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional', - PCLZIP_OPT_TEMP_FILE_ON => 'optional', - PCLZIP_OPT_TEMP_FILE_OFF => 'optional' - //, PCLZIP_OPT_CRYPT => 'optional' - )); - if ($v_result != 1) { - return 0; - } - } - - // ----- Look for 2 args - // Here we need to support the first historic synopsis of the - // method. - else { - - // ----- Get the first argument - $v_options[PCLZIP_OPT_ADD_PATH] = $v_add_path = $v_arg_list[0]; - - // ----- Look for the optional second argument - if ($v_size == 2) { - $v_options[PCLZIP_OPT_REMOVE_PATH] = $v_arg_list[1]; - } - else if ($v_size > 2) { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments"); - - // ----- Return - return 0; - } - } -} - -// ----- Look for default option values -$this->privOptionDefaultThreshold($v_options); - -// ----- Init -$v_string_list = array(); -$v_att_list = array(); -$v_filedescr_list = array(); -$p_result_list = array(); - -// ----- Look if the $p_filelist is really an array -if (is_array($p_filelist)) { - - // ----- Look if the first element is also an array - // This will mean that this is a file description entry - if (isset($p_filelist[0]) && is_array($p_filelist[0])) { - $v_att_list = $p_filelist; - } - - // ----- The list is a list of string names - else { - $v_string_list = $p_filelist; - } -} - -// ----- Look if the $p_filelist is a string -else if (is_string($p_filelist)) { - // ----- Create a list from the string - $v_string_list = explode(PCLZIP_SEPARATOR, $p_filelist); -} - -// ----- Invalid variable type for $p_filelist -else { - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type '".gettype($p_filelist)."' for p_filelist"); - return 0; -} - -// ----- Reformat the string list -if (sizeof($v_string_list) != 0) { - foreach ($v_string_list as $v_string) { - $v_att_list[][PCLZIP_ATT_FILE_NAME] = $v_string; - } -} - -// ----- For each file in the list check the attributes -$v_supported_attributes -= array (PCLZIP_ATT_FILE_NAME => 'mandatory' - ,PCLZIP_ATT_FILE_NEW_SHORT_NAME => 'optional' - ,PCLZIP_ATT_FILE_NEW_FULL_NAME => 'optional' - ,PCLZIP_ATT_FILE_MTIME => 'optional' - ,PCLZIP_ATT_FILE_CONTENT => 'optional' - ,PCLZIP_ATT_FILE_COMMENT => 'optional' - ); -foreach ($v_att_list as $v_entry) { - $v_result = $this->privFileDescrParseAtt($v_entry, - $v_filedescr_list[], - $v_options, - $v_supported_attributes); - if ($v_result != 1) { - return 0; - } -} - -// ----- Expand the filelist (expand directories) -$v_result = $this->privFileDescrExpand($v_filedescr_list, $v_options); -if ($v_result != 1) { - return 0; -} - -// ----- Call the create fct -$v_result = $this->privAdd($v_filedescr_list, $p_result_list, $v_options); -if ($v_result != 1) { - return 0; -} - -// ----- Return -return $p_result_list; -} -// -------------------------------------------------------------------------------- - -// -------------------------------------------------------------------------------- -// Function : listContent() -// Description : -// This public method, gives the list of the files and directories, with their -// properties. -// The properties of each entries in the list are (used also in other functions) : -// filename : Name of the file. For a create or add action it is the filename -// given by the user. For an extract function it is the filename -// of the extracted file. -// stored_filename : Name of the file / directory stored in the archive. -// size : Size of the stored file. -// compressed_size : Size of the file's data compressed in the archive -// (without the headers overhead) -// mtime : Last known modification date of the file (UNIX timestamp) -// comment : Comment associated with the file -// folder : true | false -// index : index of the file in the archive -// status : status of the action (depending of the action) : -// Values are : -// ok : OK ! -// filtered : the file / dir is not extracted (filtered by user) -// already_a_directory : the file can not be extracted because a -// directory with the same name already exists -// write_protected : the file can not be extracted because a file -// with the same name already exists and is -// write protected -// newer_exist : the file was not extracted because a newer file exists -// path_creation_fail : the file is not extracted because the folder -// does not exist and can not be created -// write_error : the file was not extracted because there was a -// error while writing the file -// read_error : the file was not extracted because there was a error -// while reading the file -// invalid_header : the file was not extracted because of an archive -// format error (bad file header) -// Note that each time a method can continue operating when there -// is an action error on a file, the error is only logged in the file status. -// Return Values : -// 0 on an unrecoverable failure, -// The list of the files in the archive. -// -------------------------------------------------------------------------------- -function listContent() -{ -$v_result=1; - -// ----- Reset the error handler -$this->privErrorReset(); - -// ----- Check archive -if (!$this->privCheckFormat()) { - return(0); -} - -// ----- Call the extracting fct -$p_list = array(); -if (($v_result = $this->privList($p_list)) != 1) -{ - unset($p_list); - return(0); -} - -// ----- Return -return $p_list; -} -// -------------------------------------------------------------------------------- - -// -------------------------------------------------------------------------------- -// Function : -// extract($p_path="./", $p_remove_path="") -// extract([$p_option, $p_option_value, ...]) -// Description : -// This method supports two synopsis. The first one is historical. -// This method extract all the files / directories from the archive to the -// folder indicated in $p_path. -// If you want to ignore the 'root' part of path of the memorized files -// you can indicate this in the optional $p_remove_path parameter. -// By default, if a newer file with the same name already exists, the -// file is not extracted. -// -// If both PCLZIP_OPT_PATH and PCLZIP_OPT_ADD_PATH aoptions -// are used, the path indicated in PCLZIP_OPT_ADD_PATH is append -// at the end of the path value of PCLZIP_OPT_PATH. -// Parameters : -// $p_path : Path where the files and directories are to be extracted -// $p_remove_path : First part ('root' part) of the memorized path -// (if any similar) to remove while extracting. -// Options : -// PCLZIP_OPT_PATH : -// PCLZIP_OPT_ADD_PATH : -// PCLZIP_OPT_REMOVE_PATH : -// PCLZIP_OPT_REMOVE_ALL_PATH : -// PCLZIP_CB_PRE_EXTRACT : -// PCLZIP_CB_POST_EXTRACT : -// Return Values : -// 0 or a negative value on failure, -// The list of the extracted files, with a status of the action. -// (see PclZip::listContent() for list entry format) -// -------------------------------------------------------------------------------- -function extract() -{ -$v_result=1; - -// ----- Reset the error handler -$this->privErrorReset(); - -// ----- Check archive -if (!$this->privCheckFormat()) { - return(0); -} - -// ----- Set default values -$v_options = array(); -// $v_path = "./"; -$v_path = ''; -$v_remove_path = ""; -$v_remove_all_path = false; - -// ----- Look for variable options arguments -$v_size = func_num_args(); - -// ----- Default values for option -$v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = false; - -// ----- Look for arguments -if ($v_size > 0) { - // ----- Get the arguments - $v_arg_list = func_get_args(); - - // ----- Look for first arg - if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) { - - // ----- Parse the options - $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, - array (PCLZIP_OPT_PATH => 'optional', - PCLZIP_OPT_REMOVE_PATH => 'optional', - PCLZIP_OPT_REMOVE_ALL_PATH => 'optional', - PCLZIP_OPT_ADD_PATH => 'optional', - PCLZIP_CB_PRE_EXTRACT => 'optional', - PCLZIP_CB_POST_EXTRACT => 'optional', - PCLZIP_OPT_SET_CHMOD => 'optional', - PCLZIP_OPT_BY_NAME => 'optional', - PCLZIP_OPT_BY_EREG => 'optional', - PCLZIP_OPT_BY_PREG => 'optional', - PCLZIP_OPT_BY_INDEX => 'optional', - PCLZIP_OPT_EXTRACT_AS_STRING => 'optional', - PCLZIP_OPT_EXTRACT_IN_OUTPUT => 'optional', - PCLZIP_OPT_REPLACE_NEWER => 'optional' - ,PCLZIP_OPT_STOP_ON_ERROR => 'optional' - ,PCLZIP_OPT_EXTRACT_DIR_RESTRICTION => 'optional', - PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional', - PCLZIP_OPT_TEMP_FILE_ON => 'optional', - PCLZIP_OPT_TEMP_FILE_OFF => 'optional' - )); - if ($v_result != 1) { - return 0; - } - - // ----- Set the arguments - if (isset($v_options[PCLZIP_OPT_PATH])) { - $v_path = $v_options[PCLZIP_OPT_PATH]; - } - if (isset($v_options[PCLZIP_OPT_REMOVE_PATH])) { - $v_remove_path = $v_options[PCLZIP_OPT_REMOVE_PATH]; - } - if (isset($v_options[PCLZIP_OPT_REMOVE_ALL_PATH])) { - $v_remove_all_path = $v_options[PCLZIP_OPT_REMOVE_ALL_PATH]; - } - if (isset($v_options[PCLZIP_OPT_ADD_PATH])) { - // ----- Check for '/' in last path char - if ((strlen($v_path) > 0) && (substr($v_path, -1) != '/')) { - $v_path .= '/'; - } - $v_path .= $v_options[PCLZIP_OPT_ADD_PATH]; - } - } - - // ----- Look for 2 args - // Here we need to support the first historic synopsis of the - // method. - else { - - // ----- Get the first argument - $v_path = $v_arg_list[0]; - - // ----- Look for the optional second argument - if ($v_size == 2) { - $v_remove_path = $v_arg_list[1]; - } - else if ($v_size > 2) { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments"); - - // ----- Return - return 0; - } - } -} - -// ----- Look for default option values -$this->privOptionDefaultThreshold($v_options); - -// ----- Trace - -// ----- Call the extracting fct -$p_list = array(); -$v_result = $this->privExtractByRule($p_list, $v_path, $v_remove_path, - $v_remove_all_path, $v_options); -if ($v_result < 1) { - unset($p_list); - return(0); -} - -// ----- Return -return $p_list; -} -// -------------------------------------------------------------------------------- - - -// -------------------------------------------------------------------------------- -// Function : -// extractByIndex($p_index, $p_path="./", $p_remove_path="") -// extractByIndex($p_index, [$p_option, $p_option_value, ...]) -// Description : -// This method supports two synopsis. The first one is historical. -// This method is doing a partial extract of the archive. -// The extracted files or folders are identified by their index in the -// archive (from 0 to n). -// Note that if the index identify a folder, only the folder entry is -// extracted, not all the files included in the archive. -// Parameters : -// $p_index : A single index (integer) or a string of indexes of files to -// extract. The form of the string is "0,4-6,8-12" with only numbers -// and '-' for range or ',' to separate ranges. No spaces or ';' -// are allowed. -// $p_path : Path where the files and directories are to be extracted -// $p_remove_path : First part ('root' part) of the memorized path -// (if any similar) to remove while extracting. -// Options : -// PCLZIP_OPT_PATH : -// PCLZIP_OPT_ADD_PATH : -// PCLZIP_OPT_REMOVE_PATH : -// PCLZIP_OPT_REMOVE_ALL_PATH : -// PCLZIP_OPT_EXTRACT_AS_STRING : The files are extracted as strings and -// not as files. -// The resulting content is in a new field 'content' in the file -// structure. -// This option must be used alone (any other options are ignored). -// PCLZIP_CB_PRE_EXTRACT : -// PCLZIP_CB_POST_EXTRACT : -// Return Values : -// 0 on failure, -// The list of the extracted files, with a status of the action. -// (see PclZip::listContent() for list entry format) -// -------------------------------------------------------------------------------- -//function extractByIndex($p_index, options...) -function extractByIndex($p_index) -{ -$v_result=1; - -// ----- Reset the error handler -$this->privErrorReset(); - -// ----- Check archive -if (!$this->privCheckFormat()) { - return(0); -} - -// ----- Set default values -$v_options = array(); -// $v_path = "./"; -$v_path = ''; -$v_remove_path = ""; -$v_remove_all_path = false; - -// ----- Look for variable options arguments -$v_size = func_num_args(); - -// ----- Default values for option -$v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = false; - -// ----- Look for arguments -if ($v_size > 1) { - // ----- Get the arguments - $v_arg_list = func_get_args(); - - // ----- Remove form the options list the first argument - array_shift($v_arg_list); - $v_size--; - - // ----- Look for first arg - if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) { - - // ----- Parse the options - $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, - array (PCLZIP_OPT_PATH => 'optional', - PCLZIP_OPT_REMOVE_PATH => 'optional', - PCLZIP_OPT_REMOVE_ALL_PATH => 'optional', - PCLZIP_OPT_EXTRACT_AS_STRING => 'optional', - PCLZIP_OPT_ADD_PATH => 'optional', - PCLZIP_CB_PRE_EXTRACT => 'optional', - PCLZIP_CB_POST_EXTRACT => 'optional', - PCLZIP_OPT_SET_CHMOD => 'optional', - PCLZIP_OPT_REPLACE_NEWER => 'optional' - ,PCLZIP_OPT_STOP_ON_ERROR => 'optional' - ,PCLZIP_OPT_EXTRACT_DIR_RESTRICTION => 'optional', - PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional', - PCLZIP_OPT_TEMP_FILE_ON => 'optional', - PCLZIP_OPT_TEMP_FILE_OFF => 'optional' - )); - if ($v_result != 1) { - return 0; - } - - // ----- Set the arguments - if (isset($v_options[PCLZIP_OPT_PATH])) { - $v_path = $v_options[PCLZIP_OPT_PATH]; - } - if (isset($v_options[PCLZIP_OPT_REMOVE_PATH])) { - $v_remove_path = $v_options[PCLZIP_OPT_REMOVE_PATH]; - } - if (isset($v_options[PCLZIP_OPT_REMOVE_ALL_PATH])) { - $v_remove_all_path = $v_options[PCLZIP_OPT_REMOVE_ALL_PATH]; - } - if (isset($v_options[PCLZIP_OPT_ADD_PATH])) { - // ----- Check for '/' in last path char - if ((strlen($v_path) > 0) && (substr($v_path, -1) != '/')) { - $v_path .= '/'; - } - $v_path .= $v_options[PCLZIP_OPT_ADD_PATH]; - } - if (!isset($v_options[PCLZIP_OPT_EXTRACT_AS_STRING])) { - $v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = false; - } - else { - } - } - - // ----- Look for 2 args - // Here we need to support the first historic synopsis of the - // method. - else ){ - - // ----- Get the first argument - $v_path = $v_arg_list[0]; - - // ----- Look for the optional second argument - if ($v_size == 2) { - $v_remove_path = $v_arg_list[1]; - } - else if ($v_size > 2) { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments"); - - // ----- Return - return 0; - } - } -} - -// ----- Trace - -// ----- Trick -// Here I want to reuse extractByRule(), so I need to parse the $p_index -// with privParseOptions() -$v_arg_trick = array (PCLZIP_OPT_BY_INDEX, $p_index); -$v_options_trick = array(); -$v_result = $this->privParseOptions($v_arg_trick, sizeof($v_arg_trick), $v_options_trick, - array (PCLZIP_OPT_BY_INDEX => 'optional')); -if ($v_result != 1) { - return 0; -} -$v_options[PCLZIP_OPT_BY_INDEX] = $v_options_trick[PCLZIP_OPT_BY_INDEX]; - -// ----- Look for default option values -$this->privOptionDefaultThreshold($v_options); - -// ----- Call the extracting fct -if (($v_result = $this->privExtractByRule($p_list, $v_path, $v_remove_path, $v_remove_all_path, $v_options)) < 1) { - return(0); -} - -// ----- Return -return $p_list; -} -// -------------------------------------------------------------------------------- - -// -------------------------------------------------------------------------------- -// Function : -// delete([$p_option, $p_option_value, ...]) -// Description : -// This method removes files from the archive. -// If no parameters are given, then all the archive is emptied. -// Parameters : -// None or optional arguments. -// Options : -// PCLZIP_OPT_BY_INDEX : -// PCLZIP_OPT_BY_NAME : -// PCLZIP_OPT_BY_EREG : -// PCLZIP_OPT_BY_PREG : -// Return Values : -// 0 on failure, -// The list of the files which are still present in the archive. -// (see PclZip::listContent() for list entry format) -// -------------------------------------------------------------------------------- -function delete() -{ -$v_result=1; - -// ----- Reset the error handler -$this->privErrorReset(); - -// ----- Check archive -if (!$this->privCheckFormat()) { - return(0); -} - -// ----- Set default values -$v_options = array(); - -// ----- Look for variable options arguments -$v_size = func_num_args(); - -// ----- Look for arguments -if ($v_size > 0) { - // ----- Get the arguments - $v_arg_list = func_get_args(); - - // ----- Parse the options - $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, - array (PCLZIP_OPT_BY_NAME => 'optional', - PCLZIP_OPT_BY_EREG => 'optional', - PCLZIP_OPT_BY_PREG => 'optional', - PCLZIP_OPT_BY_INDEX => 'optional')); - if ($v_result != 1) { - return 0; - } -} - -// ----- Magic quotes trick -$this->privDisableMagicQuotes(); - -// ----- Call the delete fct -$v_list = array(); -if (($v_result = $this->privDeleteByRule($v_list, $v_options)) != 1) { - $this->privSwapBackMagicQuotes(); - unset($v_list); - return(0); -} - -// ----- Magic quotes trick -$this->privSwapBackMagicQuotes(); - -// ----- Return -return $v_list; -} -// -------------------------------------------------------------------------------- - -// -------------------------------------------------------------------------------- -// Function : deleteByIndex() -// Description : -// ***** Deprecated ***** -// delete(PCLZIP_OPT_BY_INDEX, $p_index) should be prefered. -// -------------------------------------------------------------------------------- -function deleteByIndex($p_index) -{ - -$p_list = $this->delete(PCLZIP_OPT_BY_INDEX, $p_index); - -// ----- Return -return $p_list; -} -// -------------------------------------------------------------------------------- - -// -------------------------------------------------------------------------------- -// Function : properties() -// Description : -// This method gives the properties of the archive. -// The properties are : -// nb : Number of files in the archive -// comment : Comment associated with the archive file -// status : not_exist, ok -// Parameters : -// None -// Return Values : -// 0 on failure, -// An array with the archive properties. -// -------------------------------------------------------------------------------- -function properties() -{ - -// ----- Reset the error handler -$this->privErrorReset(); - -// ----- Magic quotes trick -$this->privDisableMagicQuotes(); - -// ----- Check archive -if (!$this->privCheckFormat()) { - $this->privSwapBackMagicQuotes(); - return(0); -} - -// ----- Default properties -$v_prop = array(); -$v_prop['comment'] = ''; -$v_prop['nb'] = 0; -$v_prop['status'] = 'not_exist'; - -// ----- Look if file exists -if (@is_file($this->zipname)) -{ - // ----- Open the zip file - if (($this->zip_fd = @fopen($this->zipname, 'rb')) == 0) - { - $this->privSwapBackMagicQuotes(); - - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \''.$this->zipname.'\' in binary read mode'); - - // ----- Return - return 0; - } - - // ----- Read the central directory informations - $v_central_dir = array(); - if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) - { - $this->privSwapBackMagicQuotes(); - return 0; - } - - // ----- Close the zip file - $this->privCloseFd(); - - // ----- Set the user attributes - $v_prop['comment'] = $v_central_dir['comment']; - $v_prop['nb'] = $v_central_dir['entries']; - $v_prop['status'] = 'ok'; -} - -// ----- Magic quotes trick -$this->privSwapBackMagicQuotes(); - -// ----- Return -return $v_prop; -} -// -------------------------------------------------------------------------------- - -// -------------------------------------------------------------------------------- -// Function : duplicate() -// Description : -// This method creates an archive by copying the content of an other one. If -// the archive already exist, it is replaced by the new one without any warning. -// Parameters : -// $p_archive : The filename of a valid archive, or -// a valid PclZip object. -// Return Values : -// 1 on success. -// 0 or a negative value on error (error code). -// -------------------------------------------------------------------------------- -function duplicate($p_archive) -{ -$v_result = 1; - -// ----- Reset the error handler -$this->privErrorReset(); - -// ----- Look if the $p_archive is a PclZip object -if ((is_object($p_archive)) && (get_class($p_archive) == 'pclzip')) -{ - - // ----- Duplicate the archive - $v_result = $this->privDuplicate($p_archive->zipname); -} - -// ----- Look if the $p_archive is a string (so a filename) -else if (is_string($p_archive)) -{ - - // ----- Check that $p_archive is a valid zip file - // TBC : Should also check the archive format - if (!is_file($p_archive)) { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_MISSING_FILE, "No file with filename '".$p_archive."'"); - $v_result = PCLZIP_ERR_MISSING_FILE; - } - else { - // ----- Duplicate the archive - $v_result = $this->privDuplicate($p_archive); - } -} - -// ----- Invalid variable -else -{ - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_archive_to_add"); - $v_result = PCLZIP_ERR_INVALID_PARAMETER; -} - -// ----- Return -return $v_result; -} -// -------------------------------------------------------------------------------- - -// -------------------------------------------------------------------------------- -// Function : merge() -// Description : -// This method merge the $p_archive_to_add archive at the end of the current -// one ($this). -// If the archive ($this) does not exist, the merge becomes a duplicate. -// If the $p_archive_to_add archive does not exist, the merge is a success. -// Parameters : -// $p_archive_to_add : It can be directly the filename of a valid zip archive, -// or a PclZip object archive. -// Return Values : -// 1 on success, -// 0 or negative values on error (see below). -// -------------------------------------------------------------------------------- -function merge($p_archive_to_add) -{ -$v_result = 1; - -// ----- Reset the error handler -$this->privErrorReset(); - -// ----- Check archive -if (!$this->privCheckFormat()) { - return(0); -} - -// ----- Look if the $p_archive_to_add is a PclZip object -if ((is_object($p_archive_to_add)) && (get_class($p_archive_to_add) == 'pclzip')) -{ - - // ----- Merge the archive - $v_result = $this->privMerge($p_archive_to_add); -} - -// ----- Look if the $p_archive_to_add is a string (so a filename) -else if (is_string($p_archive_to_add)) -{ - - // ----- Create a temporary archive - $v_object_archive = new PclZip($p_archive_to_add); - - // ----- Merge the archive - $v_result = $this->privMerge($v_object_archive); -} - -// ----- Invalid variable -else -{ - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_archive_to_add"); - $v_result = PCLZIP_ERR_INVALID_PARAMETER; -} - -// ----- Return -return $v_result; -} -// -------------------------------------------------------------------------------- - - - -// -------------------------------------------------------------------------------- -// Function : errorCode() -// Description : -// Parameters : -// -------------------------------------------------------------------------------- -function errorCode() -{ -if (PCLZIP_ERROR_EXTERNAL == 1) { - return(PclErrorCode()); -} -else { - return($this->error_code); -} -} -// -------------------------------------------------------------------------------- - -// -------------------------------------------------------------------------------- -// Function : errorName() -// Description : -// Parameters : -// -------------------------------------------------------------------------------- -function errorName($p_with_code=false) -{ -$v_name = array (PCLZIP_ERR_NO_ERROR => 'PCLZIP_ERR_NO_ERROR', - PCLZIP_ERR_WRITE_OPEN_FAIL => 'PCLZIP_ERR_WRITE_OPEN_FAIL', - PCLZIP_ERR_READ_OPEN_FAIL => 'PCLZIP_ERR_READ_OPEN_FAIL', - PCLZIP_ERR_INVALID_PARAMETER => 'PCLZIP_ERR_INVALID_PARAMETER', - PCLZIP_ERR_MISSING_FILE => 'PCLZIP_ERR_MISSING_FILE', - PCLZIP_ERR_FILENAME_TOO_LONG => 'PCLZIP_ERR_FILENAME_TOO_LONG', - PCLZIP_ERR_INVALID_ZIP => 'PCLZIP_ERR_INVALID_ZIP', - PCLZIP_ERR_BAD_EXTRACTED_FILE => 'PCLZIP_ERR_BAD_EXTRACTED_FILE', - PCLZIP_ERR_DIR_CREATE_FAIL => 'PCLZIP_ERR_DIR_CREATE_FAIL', - PCLZIP_ERR_BAD_EXTENSION => 'PCLZIP_ERR_BAD_EXTENSION', - PCLZIP_ERR_BAD_FORMAT => 'PCLZIP_ERR_BAD_FORMAT', - PCLZIP_ERR_DELETE_FILE_FAIL => 'PCLZIP_ERR_DELETE_FILE_FAIL', - PCLZIP_ERR_RENAME_FILE_FAIL => 'PCLZIP_ERR_RENAME_FILE_FAIL', - PCLZIP_ERR_BAD_CHECKSUM => 'PCLZIP_ERR_BAD_CHECKSUM', - PCLZIP_ERR_INVALID_ARCHIVE_ZIP => 'PCLZIP_ERR_INVALID_ARCHIVE_ZIP', - PCLZIP_ERR_MISSING_OPTION_VALUE => 'PCLZIP_ERR_MISSING_OPTION_VALUE', - PCLZIP_ERR_INVALID_OPTION_VALUE => 'PCLZIP_ERR_INVALID_OPTION_VALUE', - PCLZIP_ERR_UNSUPPORTED_COMPRESSION => 'PCLZIP_ERR_UNSUPPORTED_COMPRESSION', - PCLZIP_ERR_UNSUPPORTED_ENCRYPTION => 'PCLZIP_ERR_UNSUPPORTED_ENCRYPTION' - ,PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE => 'PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE' - ,PCLZIP_ERR_DIRECTORY_RESTRICTION => 'PCLZIP_ERR_DIRECTORY_RESTRICTION' - ) == 0) -{ - PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary read mode'); - return PclZip::errorCode(); -} - -// ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks -fseek($v_file_compressed, 10); -$v_size = $p_header['compressed_size']; -while ($v_size != 0) -{ - $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); - $v_buffer = @fread($v_file_compressed, $v_read_size); - //$v_binary_data = pack('a'.$v_read_size, $v_buffer); - @fwrite($this->zip_fd, $v_buffer, $v_read_size); - $v_size -= $v_read_size; -} - -// ----- Close the file -@fclose($v_file_compressed); - -// ----- Unlink the temporary file -@unlink($v_gzip_temp_name); - -// ----- Return -return $v_result; -} -// -------------------------------------------------------------------------------- - -// -------------------------------------------------------------------------------- -// Function : privCalculateStoredFilename() -// Description : -// Based on file descriptor properties and global options, this method -// calculate the filename that will be stored in the archive. -// Parameters : -// Return Values : -// -------------------------------------------------------------------------------- -function privCalculateStoredFilename(&$p_filedescr, &$p_options) -{ -$v_result=1; - -// ----- Working variables -$p_filename = $p_filedescr['filename']; -if (isset($p_options[PCLZIP_OPT_ADD_PATH])) { - $p_add_dir = $p_options[PCLZIP_OPT_ADD_PATH]; -} -else { - $p_add_dir = ''; -} -if (isset($p_options[PCLZIP_OPT_REMOVE_PATH])) { - $p_remove_dir = $p_options[PCLZIP_OPT_REMOVE_PATH]; -} -else { - $p_remove_dir = ''; -} -if (isset($p_options[PCLZIP_OPT_REMOVE_ALL_PATH])) { - $p_remove_all_dir = $p_options[PCLZIP_OPT_REMOVE_ALL_PATH]; -} -else { - $p_remove_all_dir = 0; -} - - -// ----- Look for full name change -if (isset($p_filedescr['new_full_name'])) { - // ----- Remove drive letter if any - $v_stored_filename = PclZipUtilTranslateWinPath($p_filedescr['new_full_name']); -} - -// ----- Look for path and/or short name change -else { - - // ----- Look for short name change - // Its when we cahnge just the filename but not the path - if (isset($p_filedescr['new_short_name'])) { - $v_path_info = pathinfo($p_filename); - $v_dir = ''; - if ($v_path_info['dirname'] != '') { - $v_dir = $v_path_info['dirname'].'/'; - } - $v_stored_filename = $v_dir.$p_filedescr['new_short_name']; - } - else { - // ----- Calculate the stored filename - $v_stored_filename = $p_filename; - } - - // ----- Look for all path to remove - if ($p_remove_all_dir) { - $v_stored_filename = basename($p_filename); - } - // ----- Look for partial path remove - else if ($p_remove_dir != "") { - if (substr($p_remove_dir, -1) != '/') - $p_remove_dir .= "/"; - - if ((substr($p_filename, 0, 2) == "./") - || (substr($p_remove_dir, 0, 2) == "./")) { - - if ((substr($p_filename, 0, 2) == "./") - && (substr($p_remove_dir, 0, 2) != "./")) { - $p_remove_dir = "./".$p_remove_dir; - } - if ((substr($p_filename, 0, 2) != "./") - && (substr($p_remove_dir, 0, 2) == "./")) { - $p_remove_dir = substr($p_remove_dir, 2); - } - } - - $v_compare = PclZipUtilPathInclusion($p_remove_dir, - $v_stored_filename); - if ($v_compare > 0) { - if ($v_compare == 2) { - $v_stored_filename = ""; - } - else { - $v_stored_filename = substr($v_stored_filename, - strlen($p_remove_dir)); - } - } - } - - // ----- Remove drive letter if any - $v_stored_filename = PclZipUtilTranslateWinPath($v_stored_filename); - - // ----- Look for path to add - if ($p_add_dir != "") { - if (substr($p_add_dir, -1) == "/") - $v_stored_filename = $p_add_dir.$v_stored_filename; - else - $v_stored_filename = $p_add_dir."/".$v_stored_filename; - } -} - -// ----- Filename (reduce the path of stored name) -$v_stored_filename = PclZipUtilPathReduction($v_stored_filename); -$p_filedescr['stored_filename'] = $v_stored_filename; - -// ----- Return -return $v_result; -} -// -------------------------------------------------------------------------------- - -// -------------------------------------------------------------------------------- -// Function : privWriteFileHeader() -// Description : -// Parameters : -// Return Values : -// -------------------------------------------------------------------------------- -function privWriteFileHeader(&$p_header) -{ -$v_result=1; - -// ----- Store the offset position of the file -$p_header['offset'] = ftell($this->zip_fd); - -// ----- Transform UNIX mtime to DOS format mdate/mtime -$v_date = getdate($p_header['mtime']); -$v_mtime = ($v_date['hours']<<11) + ($v_date['minutes']<<5) + $v_date['seconds']/2; -$v_mdate = (($v_date['year']-1980)<<9) + ($v_date['mon']<<5) + $v_date['mday']; - -// ----- Packed data -$v_binary_data = pack("VvvvvvVVVvv", 0x04034b50, - $p_header['version_extracted'], $p_header['flag'], - $p_header['compression'], $v_mtime, $v_mdate, - $p_header['crc'], $p_header['compressed_size'], - $p_header['size'], - strlen($p_header['stored_filename']), - $p_header['extra_len']); - -// ----- Write the first 148 bytes of the header in the archive -fputs($this->zip_fd, $v_binary_data, 30); - -// ----- Write the variable fields -if (strlen($p_header['stored_filename']) != 0) -{ - fputs($this->zip_fd, $p_header['stored_filename'], strlen($p_header['stored_filename'])); -} -if ($p_header['extra_len'] != 0) -{ - fputs($this->zip_fd, $p_header['extra'], $p_header['extra_len']); -} - -// ----- Return -return $v_result; -} -// -------------------------------------------------------------------------------- - -// -------------------------------------------------------------------------------- -// Function : privWriteCentralFileHeader() -// Description : -// Parameters : -// Return Values : -// -------------------------------------------------------------------------------- -function privWriteCentralFileHeader(&$p_header) -{ -$v_result=1; - -// TBC -//for(reset($p_header); $key = key($p_header); next($p_header)) { -//} - -// ----- Transform UNIX mtime to DOS format mdate/mtime -$v_date = getdate($p_header['mtime']); -$v_mtime = ($v_date['hours']<<11) + ($v_date['minutes']<<5) + $v_date['seconds']/2; -$v_mdate = (($v_date['year']-1980)<<9) + ($v_date['mon']<<5) + $v_date['mday']; - - -// ----- Packed data -$v_binary_data = pack("VvvvvvvVVVvvvvvVV", 0x02014b50, - $p_header['version'], $p_header['version_extracted'], - $p_header['flag'], $p_header['compression'], - $v_mtime, $v_mdate, $p_header['crc'], - $p_header['compressed_size'], $p_header['size'], - strlen($p_header['stored_filename']), - $p_header['extra_len'], $p_header['comment_len'], - $p_header['disk'], $p_header['internal'], - $p_header['external'], $p_header['offset']); - -// ----- Write the 42 bytes of the header in the zip file -fputs($this->zip_fd, $v_binary_data, 46); - -// ----- Write the variable fields -if (strlen($p_header['stored_filename']) != 0) -{ - fputs($this->zip_fd, $p_header['stored_filename'], strlen($p_header['stored_filename'])); -} -if ($p_header['extra_len'] != 0) -{ - fputs($this->zip_fd, $p_header['extra'], $p_header['extra_len']); -} -if ($p_header['comment_len'] != 0) -{ - fputs($this->zip_fd, $p_header['comment'], $p_header['comment_len']); -} - -// ----- Return -return $v_result; -} -// -------------------------------------------------------------------------------- - -// -------------------------------------------------------------------------------- -// Function : privWriteCentralHeader() -// Description : -// Parameters : -// Return Values : -// -------------------------------------------------------------------------------- -function privWriteCentralHeader($p_nb_entries, $p_size, $p_offset, $p_comment) -{ -$v_result=1; - -// ----- Packed data -$v_binary_data = pack("VvvvvVVv", 0x06054b50, 0, 0, $p_nb_entries, - $p_nb_entries, $p_size, - $p_offset, strlen($p_comment)); - -// ----- Write the 22 bytes of the header in the zip file -fputs($this->zip_fd, $v_binary_data, 22); - -// ----- Write the variable fields -if (strlen($p_comment) != 0) -{ - fputs($this->zip_fd, $p_comment, strlen($p_comment)); -} - -// ----- Return -return $v_result; -} -// -------------------------------------------------------------------------------- - -// -------------------------------------------------------------------------------- -// Function : privList() -// Description : -// Parameters : -// Return Values : -// -------------------------------------------------------------------------------- -function privList(&$p_list) -{ -$v_result=1; - -// ----- Magic quotes trick -$this->privDisableMagicQuotes(); - -// ----- Open the zip file -if (($this->zip_fd = @fopen($this->zipname, 'rb')) == 0) -{ - // ----- Magic quotes trick - $this->privSwapBackMagicQuotes(); - - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \''.$this->zipname.'\' in binary read mode'); - - // ----- Return - return PclZip::errorCode(); -} - -// ----- Read the central directory informations -$v_central_dir = array(); -if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) -{ - $this->privSwapBackMagicQuotes(); - return $v_result; -} - -// ----- Go to beginning of Central Dir -@rewind($this->zip_fd); -if (@fseek($this->zip_fd, $v_central_dir['offset'])) -{ - $this->privSwapBackMagicQuotes(); - - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); - - // ----- Return - return PclZip::errorCode(); -} - -// ----- Read each entry -for ($i=0; $i<$v_central_dir['entries']; $i++) -{ - // ----- Read the file header - if (($v_result = $this->privReadCentralFileHeader($v_header)) != 1) - { - $this->privSwapBackMagicQuotes(); - return $v_result; - } - $v_header['index'] = $i; - - // ----- Get the only interesting attributes - $this->privConvertHeader2FileInfo($v_header, $p_list[$i]); - unset($v_header); -} - -// ----- Close the zip file -$this->privCloseFd(); - -// ----- Magic quotes trick -$this->privSwapBackMagicQuotes(); - -// ----- Return -return $v_result; -} -// -------------------------------------------------------------------------------- - -// -------------------------------------------------------------------------------- -// Function : privConvertHeader2FileInfo() -// Description : -// This function takes the file informations from the central directory -// entries and extract the interesting parameters that will be given back. -// The resulting file infos are set in the array $p_info -// $p_info['filename'] : Filename with full path. Given by user (add), -// extracted in the filesystem (extract). -// $p_info['stored_filename'] : Stored filename in the archive. -// $p_info['size'] = Size of the file. -// $p_info['compressed_size'] = Compressed size of the file. -// $p_info['mtime'] = Last modification date of the file. -// $p_info['comment'] = Comment associated with the file. -// $p_info['folder'] = true/false : indicates if the entry is a folder or not. -// $p_info['status'] = status of the action on the file. -// $p_info['crc'] = CRC of the file content. -// Parameters : -// Return Values : -// -------------------------------------------------------------------------------- -function privConvertHeader2FileInfo($p_header, &$p_info) -{ -$v_result=1; - -// ----- Get the interesting attributes -$v_temp_path = PclZipUtilPathReduction($p_header['filename']); -$p_info['filename'] = $v_temp_path; -$v_temp_path = PclZipUtilPathReduction($p_header['stored_filename']); -$p_info['stored_filename'] = $v_temp_path; -$p_info['size'] = $p_header['size']; -$p_info['compressed_size'] = $p_header['compressed_size']; -$p_info['mtime'] = $p_header['mtime']; -$p_info['comment'] = $p_header['comment']; -$p_info['folder'] = (($p_header['external']&0x00000010)==0x00000010); -$p_info['index'] = $p_header['index']; -$p_info['status'] = $p_header['status']; -$p_info['crc'] = $p_header['crc']; - -// ----- Return -return $v_result; -} -// -------------------------------------------------------------------------------- - -// -------------------------------------------------------------------------------- -// Function : privExtractByRule() -// Description : -// Extract a file or directory depending of rules (by index, by name, ...) -// Parameters : -// $p_file_list : An array where will be placed the properties of each -// extracted file -// $p_path : Path to add while writing the extracted files -// $p_remove_path : Path to remove (from the file memorized path) while writing the -// extracted files. If the path does not match the file path, -// the file is extracted with its memorized path. -// $p_remove_path does not apply to 'list' mode. -// $p_path and $p_remove_path are commulative. -// Return Values : -// 1 on success,0 or less on error (see error code list) -// -------------------------------------------------------------------------------- -function privExtractByRule(&$p_file_list, $p_path, $p_remove_path, $p_remove_all_path, &$p_options) -{ -$v_result=1; - -// ----- Magic quotes trick -$this->privDisableMagicQuotes(); - -// ----- Check the path -if (($p_path == "") - || ((substr($p_path, 0, 1) != "/") - && (substr($p_path, 0, 3) != "../") - && (substr($p_path,1,2)!=":/"))) - $p_path = "./".$p_path; - -// ----- Reduce the path last (and duplicated) '/' -if (($p_path != "./") && ($p_path != "/")) -{ - // ----- Look for the path end '/' - while (substr($p_path, -1) == "/") - { - $p_path = substr($p_path, 0, strlen($p_path)-1); - } -} - -// ----- Look for path to remove format (should end by /) -if (($p_remove_path != "") && (substr($p_remove_path, -1) != '/')) -{ - $p_remove_path .= '/'; -} -$p_remove_path_size = strlen($p_remove_path); - -// ----- Open the zip file -if (($v_result = $this->privOpenFd('rb')) != 1) -{ - $this->privSwapBackMagicQuotes(); - return $v_result; -} - -// ----- Read the central directory informations -$v_central_dir = array(); -if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) -{ - // ----- Close the zip file - $this->privCloseFd(); - $this->privSwapBackMagicQuotes(); - - return $v_result; -} - -// ----- Start at beginning of Central Dir -$v_pos_entry = $v_central_dir['offset']; - -// ----- Read each entry -$j_start = 0; -for ($i=0, $v_nb_extracted=0; $i<$v_central_dir['entries']; $i++) -{ - - // ----- Read next Central dir entry - @rewind($this->zip_fd); - if (@fseek($this->zip_fd, $v_pos_entry)) - { - // ----- Close the zip file - $this->privCloseFd(); - $this->privSwapBackMagicQuotes(); - - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); - - // ----- Return - return PclZip::errorCode(); - } - - // ----- Read the file header - $v_header = array(); - if (($v_result = $this->privReadCentralFileHeader($v_header)) != 1) - { - // ----- Close the zip file - $this->privCloseFd(); - $this->privSwapBackMagicQuotes(); - - return $v_result; - } - - // ----- Store the index - $v_header['index'] = $i; - - // ----- Store the file position - $v_pos_entry = ftell($this->zip_fd); - - // ----- Look for the specific extract rules - $v_extract = false; - - // ----- Look for extract by name rule - if ((isset($p_options[PCLZIP_OPT_BY_NAME])) - && ($p_options[PCLZIP_OPT_BY_NAME] != 0)) { - - // ----- Look if the filename is in the list - for ($j=0; ($j strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) - && (substr($v_header['stored_filename'], 0, strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) == $p_options[PCLZIP_OPT_BY_NAME][$j])) { - $v_extract = true; - } + else if (is_array($p_options_list[$i+1])) { + $v_result_list[$p_options_list[$i]] = $p_options_list[$i+1]; } - // ----- Look for a filename - elseif ($v_header['stored_filename'] == $p_options[PCLZIP_OPT_BY_NAME][$j]) { - $v_extract = true; + else { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Wrong parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + + // ----- Return + return PclZip::errorCode(); } - } - } + $i++; + break; - // ----- Look for extract by ereg rule - // ereg() is deprecated with PHP 5.3 - /* - else if ((isset($p_options[PCLZIP_OPT_BY_EREG])) - && ($p_options[PCLZIP_OPT_BY_EREG] != "")) { + // ----- Look for options that request an EREG or PREG expression + case PCLZIP_OPT_BY_EREG : + // ereg() is deprecated starting with PHP 5.3. Move PCLZIP_OPT_BY_EREG + // to PCLZIP_OPT_BY_PREG + $p_options_list[$i] = PCLZIP_OPT_BY_PREG; + case PCLZIP_OPT_BY_PREG : + //case PCLZIP_OPT_CRYPT : + // ----- Check the number of parameters + if (($i+1) >= $p_size) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); - if (ereg($p_options[PCLZIP_OPT_BY_EREG], $v_header['stored_filename'])) { - $v_extract = true; - } - } - */ - - // ----- Look for extract by preg rule - else if ((isset($p_options[PCLZIP_OPT_BY_PREG])) - && ($p_options[PCLZIP_OPT_BY_PREG] != "")) { - - if (preg_match($p_options[PCLZIP_OPT_BY_PREG], $v_header['stored_filename'])) { - $v_extract = true; - } - } - - // ----- Look for extract by index rule - else if ((isset($p_options[PCLZIP_OPT_BY_INDEX])) - && ($p_options[PCLZIP_OPT_BY_INDEX] != 0)) { - - // ----- Look if the index is in the list - for ($j=$j_start; ($j=$p_options[PCLZIP_OPT_BY_INDEX][$j]['start']) && ($i<=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end'])) { - $v_extract = true; - } - if ($i>=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end']) { - $j_start = $j+1; + // ----- Return + return PclZip::errorCode(); } - if ($p_options[PCLZIP_OPT_BY_INDEX][$j]['start']>$i) { - break; + // ----- Get the value + if (is_string($p_options_list[$i+1])) { + $v_result_list[$p_options_list[$i]] = $p_options_list[$i+1]; } - } - } + else { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Wrong parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); - // ----- Look for no rule, which means extract all the archive - else { - $v_extract = true; - } + // ----- Return + return PclZip::errorCode(); + } + $i++; + break; - // ----- Check compression method - if (($v_extract) - && (($v_header['compression'] != 8) - && ($v_header['compression'] != 0))) { - $v_header['status'] = 'unsupported_compression'; + // ----- Look for options that takes a string + case PCLZIP_OPT_COMMENT : + case PCLZIP_OPT_ADD_COMMENT : + case PCLZIP_OPT_PREPEND_COMMENT : + // ----- Check the number of parameters + if (($i+1) >= $p_size) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, + "Missing parameter value for option '" + .PclZipUtilOptionText($p_options_list[$i]) + ."'"); - // ----- Look for PCLZIP_OPT_STOP_ON_ERROR - if ((isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) - && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) { + // ----- Return + return PclZip::errorCode(); + } - $this->privSwapBackMagicQuotes(); + // ----- Get the value + if (is_string($p_options_list[$i+1])) { + $v_result_list[$p_options_list[$i]] = $p_options_list[$i+1]; + } + else { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, + "Wrong parameter value for option '" + .PclZipUtilOptionText($p_options_list[$i]) + ."'"); + + // ----- Return + return PclZip::errorCode(); + } + $i++; + break; + + // ----- Look for options that request an array of index + case PCLZIP_OPT_BY_INDEX : + // ----- Check the number of parameters + if (($i+1) >= $p_size) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Get the value + $v_work_list = array(); + if (is_string($p_options_list[$i+1])) { + + // ----- Remove spaces + $p_options_list[$i+1] = strtr($p_options_list[$i+1], ' ', ''); + + // ----- Parse items + $v_work_list = explode(",", $p_options_list[$i+1]); + } + else if (is_integer($p_options_list[$i+1])) { + $v_work_list[0] = $p_options_list[$i+1].'-'.$p_options_list[$i+1]; + } + else if (is_array($p_options_list[$i+1])) { + $v_work_list = $p_options_list[$i+1]; + } + else { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Value must be integer, string or array for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + + // ----- Return + return PclZip::errorCode(); + } - PclZip::privErrorLog(PCLZIP_ERR_UNSUPPORTED_COMPRESSION, - "Filename '".$v_header['stored_filename']."' is " - ."compressed by an unsupported compression " - ."method (".$v_header['compression'].") "); + // ----- Reduce the index list + // each index item in the list must be a couple with a start and + // an end value : [0,3], [5-5], [8-10], ... + // ----- Check the format of each item + $v_sort_flag=false; + $v_sort_value=0; + for ($j=0; $j= $p_size) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Get the value + $v_result_list[$p_options_list[$i]] = $p_options_list[$i+1]; + $i++; + break; + + // ----- Look for options that request a call-back + case PCLZIP_CB_PRE_EXTRACT : + case PCLZIP_CB_POST_EXTRACT : + case PCLZIP_CB_PRE_ADD : + case PCLZIP_CB_POST_ADD : + /* for futur use + case PCLZIP_CB_PRE_DELETE : + case PCLZIP_CB_POST_DELETE : + case PCLZIP_CB_PRE_LIST : + case PCLZIP_CB_POST_LIST : + */ + // ----- Check the number of parameters + if (($i+1) >= $p_size) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Get the value + $v_function_name = $p_options_list[$i+1]; + + // ----- Check that the value is a valid existing function + if (!function_exists($v_function_name)) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Function '".$v_function_name."()' is not an existing function for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Set the attribute + $v_result_list[$p_options_list[$i]] = $v_function_name; + $i++; + break; + + default : + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, + "Unknown parameter '" + .$p_options_list[$i]."'"); + + // ----- Return return PclZip::errorCode(); } - } - - // ----- Check encrypted files - if (($v_extract) && (($v_header['flag'] & 1) == 1)) { - $v_header['status'] = 'unsupported_encryption'; - // ----- Look for PCLZIP_OPT_STOP_ON_ERROR - if ((isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) - && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) { + // ----- Next options + $i++; + } - $this->privSwapBackMagicQuotes(); + // ----- Look for mandatory options + if ($v_requested_options !== false) { + for ($key=reset($v_requested_options); $key=key($v_requested_options); $key=next($v_requested_options)) { + // ----- Look for mandatory option + if ($v_requested_options[$key] == 'mandatory') { + // ----- Look if present + if (!isset($v_result_list[$key])) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Missing mandatory parameter ".PclZipUtilOptionText($key)."(".$key.")"); - PclZip::privErrorLog(PCLZIP_ERR_UNSUPPORTED_ENCRYPTION, - "Unsupported encryption for " - ." filename '".$v_header['stored_filename'] - ."'"); - - return PclZip::errorCode(); + // ----- Return + return PclZip::errorCode(); + } + } } -} + } + + // ----- Look for default values + if (!isset($v_result_list[PCLZIP_OPT_TEMP_FILE_THRESHOLD])) { + + } - // ----- Look for real extraction - if (($v_extract) && ($v_header['status'] != 'ok')) { - $v_result = $this->privConvertHeader2FileInfo($v_header, - $p_file_list[$v_nb_extracted++]); - if ($v_result != 1) { - $this->privCloseFd(); - $this->privSwapBackMagicQuotes(); - return $v_result; - } - - $v_extract = false; + // ----- Return + return $v_result; } - - // ----- Look for real extraction - if ($v_extract) + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privOptionDefaultThreshold() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privOptionDefaultThreshold(&$p_options) { + $v_result=1; + + if (isset($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD]) + || isset($p_options[PCLZIP_OPT_TEMP_FILE_OFF])) { + return $v_result; + } + + // ----- Get 'memory_limit' configuration value + $v_memory_limit = ini_get('memory_limit'); + $v_memory_limit = trim($v_memory_limit); + $last = strtolower(substr($v_memory_limit, -1)); + + if ($last == 'g') + //$v_memory_limit = $v_memory_limit*1024*1024*1024; + $v_memory_limit = $v_memory_limit*1073741824; + if ($last == 'm') + //$v_memory_limit = $v_memory_limit*1024*1024; + $v_memory_limit = $v_memory_limit*1048576; + if ($last == 'k') + $v_memory_limit = $v_memory_limit*1024; + + $p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD] = floor($v_memory_limit*PCLZIP_TEMPORARY_FILE_RATIO); + - // ----- Go to the file position - @rewind($this->zip_fd); - if (@fseek($this->zip_fd, $v_header['offset'])) + // ----- Sanity check : No threshold if value lower than 1M + if ($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD] < 1048576) { + unset($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD]); + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privFileDescrParseAtt() + // Description : + // Parameters : + // Return Values : + // 1 on success. + // 0 on failure. + // -------------------------------------------------------------------------------- + function privFileDescrParseAtt(&$p_file_list, &$p_filedescr, $v_options, $v_requested_options=false) + { + $v_result=1; + + // ----- For each file in the list check the attributes + foreach ($p_file_list as $v_key => $v_value) { + + // ----- Check if the option is supported + if (!isset($v_requested_options[$v_key])) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid file attribute '".$v_key."' for this file"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Look for attribute + switch ($v_key) { + case PCLZIP_ATT_FILE_NAME : + if (!is_string($v_value)) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".PclZipUtilOptionText($v_key)."'"); + return PclZip::errorCode(); + } + + $p_filedescr['filename'] = PclZipUtilPathReduction($v_value); + + if ($p_filedescr['filename'] == '') { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid empty filename for attribute '".PclZipUtilOptionText($v_key)."'"); + return PclZip::errorCode(); + } + + break; + + case PCLZIP_ATT_FILE_NEW_SHORT_NAME : + if (!is_string($v_value)) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".PclZipUtilOptionText($v_key)."'"); + return PclZip::errorCode(); + } + + $p_filedescr['new_short_name'] = PclZipUtilPathReduction($v_value); + + if ($p_filedescr['new_short_name'] == '') { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid empty short filename for attribute '".PclZipUtilOptionText($v_key)."'"); + return PclZip::errorCode(); + } + break; + + case PCLZIP_ATT_FILE_NEW_FULL_NAME : + if (!is_string($v_value)) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".PclZipUtilOptionText($v_key)."'"); + return PclZip::errorCode(); + } + + $p_filedescr['new_full_name'] = PclZipUtilPathReduction($v_value); + + if ($p_filedescr['new_full_name'] == '') { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid empty full filename for attribute '".PclZipUtilOptionText($v_key)."'"); + return PclZip::errorCode(); + } + break; + + // ----- Look for options that takes a string + case PCLZIP_ATT_FILE_COMMENT : + if (!is_string($v_value)) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".PclZipUtilOptionText($v_key)."'"); + return PclZip::errorCode(); + } + + $p_filedescr['comment'] = $v_value; + break; + + case PCLZIP_ATT_FILE_MTIME : + if (!is_integer($v_value)) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". Integer expected for attribute '".PclZipUtilOptionText($v_key)."'"); + return PclZip::errorCode(); + } + + $p_filedescr['mtime'] = $v_value; + break; + + case PCLZIP_ATT_FILE_CONTENT : + $p_filedescr['content'] = $v_value; + break; + + default : + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, + "Unknown parameter '".$v_key."'"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Look for mandatory options + if ($v_requested_options !== false) { + for ($key=reset($v_requested_options); $key=key($v_requested_options); $key=next($v_requested_options)) { + // ----- Look for mandatory option + if ($v_requested_options[$key] == 'mandatory') { + // ----- Look if present + if (!isset($p_file_list[$key])) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Missing mandatory parameter ".PclZipUtilOptionText($key)."(".$key.")"); + return PclZip::errorCode(); + } + } + } + } + + // end foreach + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privFileDescrExpand() + // Description : + // This method look for each item of the list to see if its a file, a folder + // or a string to be added as file. For any other type of files (link, other) + // just ignore the item. + // Then prepare the information that will be stored for that file. + // When its a folder, expand the folder with all the files that are in that + // folder (recursively). + // Parameters : + // Return Values : + // 1 on success. + // 0 on failure. + // -------------------------------------------------------------------------------- + function privFileDescrExpand(&$p_filedescr_list, &$p_options) + { + $v_result=1; + + // ----- Create a result list + $v_result_list = array(); + + // ----- Look each entry + for ($i=0; $iprivCalculateStoredFilename($v_descr, $p_options); + + // ----- Add the descriptor in result list + $v_result_list[sizeof($v_result_list)] = $v_descr; + + // ----- Look for folder + if ($v_descr['type'] == 'folder') { + // ----- List of items in folder + $v_dirlist_descr = array(); + $v_dirlist_nb = 0; + if ($v_folder_handler = @opendir($v_descr['filename'])) { + while (($v_item_handler = @readdir($v_folder_handler)) !== false) { + + // ----- Skip '.' and '..' + if (($v_item_handler == '.') || ($v_item_handler == '..')) { + continue; + } + + // ----- Compose the full filename + $v_dirlist_descr[$v_dirlist_nb]['filename'] = $v_descr['filename'].'/'.$v_item_handler; + + // ----- Look for different stored filename + // Because the name of the folder was changed, the name of the + // files/sub-folders also change + if (($v_descr['stored_filename'] != $v_descr['filename']) + && (!isset($p_options[PCLZIP_OPT_REMOVE_ALL_PATH]))) { + if ($v_descr['stored_filename'] != '') { + $v_dirlist_descr[$v_dirlist_nb]['new_full_name'] = $v_descr['stored_filename'].'/'.$v_item_handler; + } + else { + $v_dirlist_descr[$v_dirlist_nb]['new_full_name'] = $v_item_handler; + } + } + + $v_dirlist_nb++; + } + + @closedir($v_folder_handler); + } + else { + // TBC : unable to open folder in read mode + } + + // ----- Expand each element of the list + if ($v_dirlist_nb != 0) { + // ----- Expand + if (($v_result = $this->privFileDescrExpand($v_dirlist_descr, $p_options)) != 1) { + return $v_result; + } + + // ----- Concat the resulting list + $v_result_list = array_merge($v_result_list, $v_dirlist_descr); + } + else { + } + + // ----- Free local array + unset($v_dirlist_descr); + } + } + + // ----- Get the result list + $p_filedescr_list = $v_result_list; + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privCreate() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privCreate($p_filedescr_list, &$p_result_list, &$p_options) + { + $v_result=1; + $v_list_detail = array(); + + // ----- Magic quotes trick + $this->privDisableMagicQuotes(); + + // ----- Open the file in write mode + if (($v_result = $this->privOpenFd('wb')) != 1) { - // ----- Close the zip file - $this->privCloseFd(); + // ----- Return + return $v_result; + } + // ----- Add the list of files + $v_result = $this->privAddList($p_filedescr_list, $p_result_list, $p_options); + + // ----- Close + $this->privCloseFd(); + + // ----- Magic quotes trick + $this->privSwapBackMagicQuotes(); + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privAdd() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privAdd($p_filedescr_list, &$p_result_list, &$p_options) + { + $v_result=1; + $v_list_detail = array(); + + // ----- Look if the archive exists or is empty + if ((!is_file($this->zipname)) || (filesize($this->zipname) == 0)) + { + + // ----- Do a create + $v_result = $this->privCreate($p_filedescr_list, $p_result_list, $p_options); + + // ----- Return + return $v_result; + } + // ----- Magic quotes trick + $this->privDisableMagicQuotes(); + + // ----- Open the zip file + if (($v_result=$this->privOpenFd('rb')) != 1) + { + // ----- Magic quotes trick $this->privSwapBackMagicQuotes(); - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); + // ----- Return + return $v_result; + } + + // ----- Read the central directory informations + $v_central_dir = array(); + if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) + { + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + return $v_result; + } + + // ----- Go to beginning of File + @rewind($this->zip_fd); + + // ----- Creates a temporay file + $v_zip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.tmp'; + + // ----- Open the temporary file in write mode + if (($v_zip_temp_fd = @fopen($v_zip_temp_name, 'wb')) == 0) + { + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_zip_temp_name.'\' in binary write mode'); // ----- Return return PclZip::errorCode(); } - // ----- Look for extraction as string - if ($p_options[PCLZIP_OPT_EXTRACT_AS_STRING]) { - - $v_string = ''; - - // ----- Extracting the file - $v_result1 = $this->privExtractFileAsString($v_header, $v_string, $p_options); - if ($v_result1 < 1) { - $this->privCloseFd(); - $this->privSwapBackMagicQuotes(); - return $v_result1; - } - - // ----- Get the only interesting attributes - if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted])) != 1) - { - // ----- Close the zip file - $this->privCloseFd(); - $this->privSwapBackMagicQuotes(); - - return $v_result; - } - - // ----- Set the file content - $p_file_list[$v_nb_extracted]['content'] = $v_string; - - // ----- Next extracted file - $v_nb_extracted++; - - // ----- Look for user callback abort - if ($v_result1 == 2) { - break; - } - } - // ----- Look for extraction in standard output - elseif ((isset($p_options[PCLZIP_OPT_EXTRACT_IN_OUTPUT])) - && ($p_options[PCLZIP_OPT_EXTRACT_IN_OUTPUT])) { - // ----- Extracting the file in standard output - $v_result1 = $this->privExtractFileInOutput($v_header, $p_options); - if ($v_result1 < 1) { - $this->privCloseFd(); - $this->privSwapBackMagicQuotes(); - return $v_result1; - } - - // ----- Get the only interesting attributes - if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted++])) != 1) { - $this->privCloseFd(); - $this->privSwapBackMagicQuotes(); - return $v_result; - } - - // ----- Look for user callback abort - if ($v_result1 == 2) { - break; - } - } - // ----- Look for normal extraction - else { - // ----- Extracting the file - $v_result1 = $this->privExtractFile($v_header, - $p_path, $p_remove_path, - $p_remove_all_path, - $p_options); - if ($v_result1 < 1) { - $this->privCloseFd(); - $this->privSwapBackMagicQuotes(); - return $v_result1; - } - - // ----- Get the only interesting attributes - if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted++])) != 1) - { - // ----- Close the zip file - $this->privCloseFd(); - $this->privSwapBackMagicQuotes(); - - return $v_result; - } - - // ----- Look for user callback abort - if ($v_result1 == 2) { - break; - } - } - } -} - -// ----- Close the zip file -$this->privCloseFd(); -$this->privSwapBackMagicQuotes(); - -// ----- Return -return $v_result; -} -// -------------------------------------------------------------------------------- - -// -------------------------------------------------------------------------------- -// Function : privExtractFile() -// Description : -// Parameters : -// Return Values : -// -// 1 : ... ? -// PCLZIP_ERR_USER_ABORTED(2) : User ask for extraction stop in callback -// -------------------------------------------------------------------------------- -function privExtractFile(&$p_entry, $p_path, $p_remove_path, $p_remove_all_path, &$p_options) -{ -$v_result=1; - -// ----- Read the file header -if (($v_result = $this->privReadFileHeader($v_header)) != 1) -{ - // ----- Return - return $v_result; -} - - -// ----- Check that the file header is coherent with $p_entry info -if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) { - // TBC -} - -// ----- Look for all path to remove -if ($p_remove_all_path == true) { - // ----- Look for folder entry that not need to be extracted - if (($p_entry['external']&0x00000010)==0x00000010) { - - $p_entry['status'] = "filtered"; - - return $v_result; + // ----- Copy the files from the archive to the temporary file + // TBC : Here I should better append the file and go back to erase the central dir + $v_size = $v_central_dir['offset']; + while ($v_size != 0) + { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = fread($this->zip_fd, $v_read_size); + @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); + $v_size -= $v_read_size; } - // ----- Get the basename of the path - $p_entry['filename'] = basename($p_entry['filename']); -} + // ----- Swap the file descriptor + // Here is a trick : I swap the temporary fd with the zip fd, in order to use + // the following methods on the temporary fil and not the real archive + $v_swap = $this->zip_fd; + $this->zip_fd = $v_zip_temp_fd; + $v_zip_temp_fd = $v_swap; -// ----- Look for path to remove -else if ($p_remove_path != "") -{ - if (PclZipUtilPathInclusion($p_remove_path, $p_entry['filename']) == 2) - { - - // ----- Change the file status - $p_entry['status'] = "filtered"; - - // ----- Return - return $v_result; - } - - $p_remove_path_size = strlen($p_remove_path); - if (substr($p_entry['filename'], 0, $p_remove_path_size) == $p_remove_path) - { - - // ----- Remove the path - $p_entry['filename'] = substr($p_entry['filename'], $p_remove_path_size); - - } -} - -// ----- Add the path -if ($p_path != '') { - $p_entry['filename'] = $p_path."/".$p_entry['filename']; -} - -// ----- Check a base_dir_restriction -if (isset($p_options[PCLZIP_OPT_EXTRACT_DIR_RESTRICTION])) { - $v_inclusion - = PclZipUtilPathInclusion($p_options[PCLZIP_OPT_EXTRACT_DIR_RESTRICTION], - $p_entry['filename']); - if ($v_inclusion == 0) { - - PclZip::privErrorLog(PCLZIP_ERR_DIRECTORY_RESTRICTION, - "Filename '".$p_entry['filename']."' is " - ."outside PCLZIP_OPT_EXTRACT_DIR_RESTRICTION"); - - return PclZip::errorCode(); - } -} - -// ----- Look for pre-extract callback -if (isset($p_options[PCLZIP_CB_PRE_EXTRACT])) { - - // ----- Generate a local information - $v_local_header = array(); - $this->privConvertHeader2FileInfo($p_entry, $v_local_header); - - // ----- Call the callback - // Here I do not use call_user_func() because I need to send a reference to the - // header. -// eval('$v_result = '.$p_options[PCLZIP_CB_PRE_EXTRACT].'(PCLZIP_CB_PRE_EXTRACT, $v_local_header);'); - $v_result = $p_options[PCLZIP_CB_PRE_EXTRACT](PCLZIP_CB_PRE_EXTRACT, $v_local_header); - if ($v_result == 0) { - // ----- Change the file status - $p_entry['status'] = "skipped"; - $v_result = 1; - } - - // ----- Look for abort result - if ($v_result == 2) { - // ----- This status is internal and will be changed in 'skipped' - $p_entry['status'] = "aborted"; - $v_result = PCLZIP_ERR_USER_ABORTED; - } - - // ----- Update the informations - // Only some fields can be modified - $p_entry['filename'] = $v_local_header['filename']; -} - - -// ----- Look if extraction should be done -if ($p_entry['status'] == 'ok') { - -// ----- Look for specific actions while the file exist -if (file_exists($p_entry['filename'])) -{ - - // ----- Look if file is a directory - if (is_dir($p_entry['filename'])) - { - - // ----- Change the file status - $p_entry['status'] = "already_a_directory"; - - // ----- Look for PCLZIP_OPT_STOP_ON_ERROR - // For historical reason first PclZip implementation does not stop - // when this kind of error occurs. - if ((isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) - && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) { - - PclZip::privErrorLog(PCLZIP_ERR_ALREADY_A_DIRECTORY, - "Filename '".$p_entry['filename']."' is " - ."already used by an existing directory"); - - return PclZip::errorCode(); - } - } - // ----- Look if file is write protected - else if (!is_writeable($p_entry['filename'])) - { - - // ----- Change the file status - $p_entry['status'] = "write_protected"; - - // ----- Look for PCLZIP_OPT_STOP_ON_ERROR - // For historical reason first PclZip implementation does not stop - // when this kind of error occurs. - if ((isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) - && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) { - - PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, - "Filename '".$p_entry['filename']."' exists " - ."and is write protected"); - - return PclZip::errorCode(); - } - } - - // ----- Look if the extracted file is older - else if (filemtime($p_entry['filename']) > $p_entry['mtime']) - { - // ----- Change the file status - if ((isset($p_options[PCLZIP_OPT_REPLACE_NEWER])) - && ($p_options[PCLZIP_OPT_REPLACE_NEWER]===true)) { - } - else { - $p_entry['status'] = "newer_exist"; - - // ----- Look for PCLZIP_OPT_STOP_ON_ERROR - // For historical reason first PclZip implementation does not stop - // when this kind of error occurs. - if ((isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) - && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) { - - PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, - "Newer version of '".$p_entry['filename']."' exists " - ."and option PCLZIP_OPT_REPLACE_NEWER is not selected"); - - return PclZip::errorCode(); - } - } - } - else { - } -} - -// ----- Check the directory availability and create it if necessary -else { - if ((($p_entry['external']&0x00000010)==0x00000010) || (substr($p_entry['filename'], -1) == '/')) - $v_dir_to_check = $p_entry['filename']; - else if (!strstr($p_entry['filename'], "/")) - $v_dir_to_check = ""; - else - $v_dir_to_check = dirname($p_entry['filename']); - - if (($v_result = $this->privDirCheck($v_dir_to_check, (($p_entry['external']&0x00000010)==0x00000010))) != 1) { - - // ----- Change the file status - $p_entry['status'] = "path_creation_fail"; + // ----- Add the files + $v_header_list = array(); + if (($v_result = $this->privAddFileList($p_filedescr_list, $v_header_list, $p_options)) != 1) + { + fclose($v_zip_temp_fd); + $this->privCloseFd(); + @unlink($v_zip_temp_name); + $this->privSwapBackMagicQuotes(); // ----- Return - //return $v_result; - $v_result = 1; - } - } -} - -// ----- Look if extraction should be done -if ($p_entry['status'] == 'ok') { - - // ----- Do the extraction (if not a folder) - if (!(($p_entry['external']&0x00000010)==0x00000010)) - { - // ----- Look for not compressed file - if ($p_entry['compression'] == 0) { - - // ----- Opening destination file - if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0) - { - - // ----- Change the file status - $p_entry['status'] = "write_error"; - - // ----- Return - return $v_result; - } - - - // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks - $v_size = $p_entry['compressed_size']; - while ($v_size != 0) - { - $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); - $v_buffer = @fread($this->zip_fd, $v_read_size); - /* Try to speed up the code - $v_binary_data = pack('a'.$v_read_size, $v_buffer); - @fwrite($v_dest_file, $v_binary_data, $v_read_size); - */ - @fwrite($v_dest_file, $v_buffer, $v_read_size); - $v_size -= $v_read_size; - } - - // ----- Closing the destination file - fclose($v_dest_file); - - // ----- Change the file mtime - touch($p_entry['filename'], $p_entry['mtime']); - - - } - else { - // ----- TBC - // Need to be finished - if (($p_entry['flag'] & 1) == 1) { - PclZip::privErrorLog(PCLZIP_ERR_UNSUPPORTED_ENCRYPTION, 'File \''.$p_entry['filename'].'\' is encrypted. Encrypted files are not supported.'); - return PclZip::errorCode(); - } - - - // ----- Look for using temporary file to unzip - if ((!isset($p_options[PCLZIP_OPT_TEMP_FILE_OFF])) - && (isset($p_options[PCLZIP_OPT_TEMP_FILE_ON]) - || (isset($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD]) - && ($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD] <= $p_entry['size'])))) { - $v_result = $this->privExtractFileUsingTempFile($p_entry, $p_options); - if ($v_result < PCLZIP_ERR_NO_ERROR) { - return $v_result; - } - } - - // ----- Look for extract in memory - else { - - - // ----- Read the compressed file in a buffer (one shot) - $v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']); - - // ----- Decompress the file - $v_file_content = @gzinflate($v_buffer); - unset($v_buffer); - if ($v_file_content === false) { - - // ----- Change the file status - // TBC - $p_entry['status'] = "error"; - - return $v_result; - } - - // ----- Opening destination file - if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0) { - - // ----- Change the file status - $p_entry['status'] = "write_error"; - - return $v_result; - } - - // ----- Write the uncompressed data - @fwrite($v_dest_file, $v_file_content, $p_entry['size']); - unset($v_file_content); - - // ----- Closing the destination file - @fclose($v_dest_file); - - } - - // ----- Change the file mtime - @touch($p_entry['filename'], $p_entry['mtime']); - } - - // ----- Look for chmod option - if (isset($p_options[PCLZIP_OPT_SET_CHMOD])) { - - // ----- Change the mode of the file - @chmod($p_entry['filename'], $p_options[PCLZIP_OPT_SET_CHMOD]); - } - - } -} - - // ----- Change abort status - if ($p_entry['status'] == "aborted") { - $p_entry['status'] = "skipped"; - } - -// ----- Look for post-extract callback -elseif (isset($p_options[PCLZIP_CB_POST_EXTRACT])) { - - // ----- Generate a local information - $v_local_header = array(); - $this->privConvertHeader2FileInfo($p_entry, $v_local_header); - - // ----- Call the callback - // Here I do not use call_user_func() because I need to send a reference to the - // header. -// eval('$v_result = '.$p_options[PCLZIP_CB_POST_EXTRACT].'(PCLZIP_CB_POST_EXTRACT, $v_local_header);'); - $v_result = $p_options[PCLZIP_CB_POST_EXTRACT](PCLZIP_CB_POST_EXTRACT, $v_local_header); - - // ----- Look for abort result - if ($v_result == 2) { - $v_result = PCLZIP_ERR_USER_ABORTED; - } -} - -// ----- Return -return $v_result; -} -// -------------------------------------------------------------------------------- - -// -------------------------------------------------------------------------------- -// Function : privExtractFileUsingTempFile() -// Description : -// Parameters : -// Return Values : -// -------------------------------------------------------------------------------- -function privExtractFileUsingTempFile(&$p_entry, &$p_options) -{ -$v_result=1; - -// ----- Creates a temporary file -$v_gzip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.gz'; -if (($v_dest_file = @fopen($v_gzip_temp_name, "wb")) == 0) { - fclose($v_file); - PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary write mode'); - return PclZip::errorCode(); -} - - -// ----- Write gz file format header -$v_binary_data = pack('va1a1Va1a1', 0x8b1f, Chr($p_entry['compression']), Chr(0x00), time(), Chr(0x00), Chr(3)); -@fwrite($v_dest_file, $v_binary_data, 10); - -// ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks -$v_size = $p_entry['compressed_size']; -while ($v_size != 0) -{ - $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); - $v_buffer = @fread($this->zip_fd, $v_read_size); - //$v_binary_data = pack('a'.$v_read_size, $v_buffer); - @fwrite($v_dest_file, $v_buffer, $v_read_size); - $v_size -= $v_read_size; -} - -// ----- Write gz file format footer -$v_binary_data = pack('VV', $p_entry['crc'], $p_entry['size']); -@fwrite($v_dest_file, $v_binary_data, 8); - -// ----- Close the temporary file -@fclose($v_dest_file); - -// ----- Opening destination file -if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0) { - $p_entry['status'] = "write_error"; - return $v_result; -} - -// ----- Open the temporary gz file -if (($v_src_file = @gzopen($v_gzip_temp_name, 'rb')) == 0) { - @fclose($v_dest_file); - $p_entry['status'] = "read_error"; - PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary read mode'); - return PclZip::errorCode(); -} - - -// ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks -$v_size = $p_entry['size']; -while ($v_size != 0) { - $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); - $v_buffer = @gzread($v_src_file, $v_read_size); - //$v_binary_data = pack('a'.$v_read_size, $v_buffer); - @fwrite($v_dest_file, $v_buffer, $v_read_size); - $v_size -= $v_read_size; -} -@fclose($v_dest_file); -@gzclose($v_src_file); - -// ----- Delete the temporary file -@unlink($v_gzip_temp_name); - -// ----- Return -return $v_result; -} -// -------------------------------------------------------------------------------- - -// -------------------------------------------------------------------------------- -// Function : privExtractFileInOutput() -// Description : -// Parameters : -// Return Values : -// -------------------------------------------------------------------------------- -function privExtractFileInOutput(&$p_entry, &$p_options) -{ -$v_result=1; - -// ----- Read the file header -if (($v_result = $this->privReadFileHeader($v_header)) != 1) { - return $v_result; -} - - -// ----- Check that the file header is coherent with $p_entry info -if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) { - // TBC -} - -// ----- Look for pre-extract callback -if (isset($p_options[PCLZIP_CB_PRE_EXTRACT])) { - - // ----- Generate a local information - $v_local_header = array(); - $this->privConvertHeader2FileInfo($p_entry, $v_local_header); - - // ----- Call the callback - // Here I do not use call_user_func() because I need to send a reference to the - // header. -// eval('$v_result = '.$p_options[PCLZIP_CB_PRE_EXTRACT].'(PCLZIP_CB_PRE_EXTRACT, $v_local_header);'); - $v_result = $p_options[PCLZIP_CB_PRE_EXTRACT](PCLZIP_CB_PRE_EXTRACT, $v_local_header); - if ($v_result == 0) { - // ----- Change the file status - $p_entry['status'] = "skipped"; - $v_result = 1; - } - - // ----- Look for abort result - if ($v_result == 2) { - // ----- This status is internal and will be changed in 'skipped' - $p_entry['status'] = "aborted"; - $v_result = PCLZIP_ERR_USER_ABORTED; - } - - // ----- Update the informations - // Only some fields can be modified - $p_entry['filename'] = $v_local_header['filename']; -} - -// ----- Trace - -// ----- Look if extraction should be done -if ($p_entry['status'] == 'ok') { - - // ----- Do the extraction (if not a folder) - if (!(($p_entry['external']&0x00000010)==0x00000010)) { - // ----- Look for not compressed file - if ($p_entry['compressed_size'] == $p_entry['size']) { - - // ----- Read the file in a buffer (one shot) - $v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']); - - // ----- Send the file to the output - echo $v_buffer; - unset($v_buffer); - } - else { - - // ----- Read the compressed file in a buffer (one shot) - $v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']); - - // ----- Decompress the file - $v_file_content = gzinflate($v_buffer); - unset($v_buffer); - - // ----- Send the file to the output - echo $v_file_content; - unset($v_file_content); - } - } -} - -// ----- Change abort status -if ($p_entry['status'] == "aborted") { - $p_entry['status'] = "skipped"; -} - -// ----- Look for post-extract callback -elseif (isset($p_options[PCLZIP_CB_POST_EXTRACT])) { - - // ----- Generate a local information - $v_local_header = array(); - $this->privConvertHeader2FileInfo($p_entry, $v_local_header); - - // ----- Call the callback - // Here I do not use call_user_func() because I need to send a reference to the - // header. -// eval('$v_result = '.$p_options[PCLZIP_CB_POST_EXTRACT].'(PCLZIP_CB_POST_EXTRACT, $v_local_header);'); - $v_result = $p_options[PCLZIP_CB_POST_EXTRACT](PCLZIP_CB_POST_EXTRACT, $v_local_header); - - // ----- Look for abort result - if ($v_result == 2) { - $v_result = PCLZIP_ERR_USER_ABORTED; - } -} - -return $v_result; -} -// -------------------------------------------------------------------------------- - -// -------------------------------------------------------------------------------- -// Function : privExtractFileAsString() -// Description : -// Parameters : -// Return Values : -// -------------------------------------------------------------------------------- -function privExtractFileAsString(&$p_entry, &$p_string, &$p_options) -{ -$v_result=1; - -// ----- Read the file header -$v_header = array(); -if (($v_result = $this->privReadFileHeader($v_header)) != 1) -{ - // ----- Return - return $v_result; -} - - -// ----- Check that the file header is coherent with $p_entry info -if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) { - // TBC -} - -// ----- Look for pre-extract callback -if (isset($p_options[PCLZIP_CB_PRE_EXTRACT])) { - - // ----- Generate a local information - $v_local_header = array(); - $this->privConvertHeader2FileInfo($p_entry, $v_local_header); - - // ----- Call the callback - // Here I do not use call_user_func() because I need to send a reference to the - // header. -// eval('$v_result = '.$p_options[PCLZIP_CB_PRE_EXTRACT].'(PCLZIP_CB_PRE_EXTRACT, $v_local_header);'); - $v_result = $p_options[PCLZIP_CB_PRE_EXTRACT](PCLZIP_CB_PRE_EXTRACT, $v_local_header); - if ($v_result == 0) { - // ----- Change the file status - $p_entry['status'] = "skipped"; - $v_result = 1; - } - - // ----- Look for abort result - if ($v_result == 2) { - // ----- This status is internal and will be changed in 'skipped' - $p_entry['status'] = "aborted"; - $v_result = PCLZIP_ERR_USER_ABORTED; - } - - // ----- Update the informations - // Only some fields can be modified - $p_entry['filename'] = $v_local_header['filename']; -} - - -// ----- Look if extraction should be done -if ($p_entry['status'] == 'ok') { - - // ----- Do the extraction (if not a folder) - if (!(($p_entry['external']&0x00000010)==0x00000010)) { - // ----- Look for not compressed file -// if ($p_entry['compressed_size'] == $p_entry['size']) - if ($p_entry['compression'] == 0) { - - // ----- Reading the file - $p_string = @fread($this->zip_fd, $p_entry['compressed_size']); - } - else { - - // ----- Reading the file - $v_data = @fread($this->zip_fd, $p_entry['compressed_size']); - - // ----- Decompress the file - if (($p_string = @gzinflate($v_data)) === false) { - // TBC - } - } - - // ----- Trace - } - else { - // TBC : error : can not extract a folder in a string - } - -} - - // ----- Change abort status - if ($p_entry['status'] == "aborted") { - $p_entry['status'] = "skipped"; - } - -// ----- Look for post-extract callback -elseif (isset($p_options[PCLZIP_CB_POST_EXTRACT])) { - - // ----- Generate a local information - $v_local_header = array(); - $this->privConvertHeader2FileInfo($p_entry, $v_local_header); - - // ----- Swap the content to header - $v_local_header['content'] = $p_string; - $p_string = ''; - - // ----- Call the callback - // Here I do not use call_user_func() because I need to send a reference to the - // header. -// eval('$v_result = '.$p_options[PCLZIP_CB_POST_EXTRACT].'(PCLZIP_CB_POST_EXTRACT, $v_local_header);'); - $v_result = $p_options[PCLZIP_CB_POST_EXTRACT](PCLZIP_CB_POST_EXTRACT, $v_local_header); - - // ----- Swap back the content to header - $p_string = $v_local_header['content']; - unset($v_local_header['content']); - - // ----- Look for abort result - if ($v_result == 2) { - $v_result = PCLZIP_ERR_USER_ABORTED; - } -} - -// ----- Return -return $v_result; -} -// -------------------------------------------------------------------------------- - -// -------------------------------------------------------------------------------- -// Function : privReadFileHeader() -// Description : -// Parameters : -// Return Values : -// -------------------------------------------------------------------------------- -function privReadFileHeader(&$p_header) -{ -$v_result=1; - -// ----- Read the 4 bytes signature -$v_binary_data = @fread($this->zip_fd, 4); -$v_data = unpack('Vid', $v_binary_data); - -// ----- Check signature -if ($v_data['id'] != 0x04034b50) -{ - - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Invalid archive structure'); - - // ----- Return - return PclZip::errorCode(); -} - -// ----- Read the first 42 bytes of the header -$v_binary_data = fread($this->zip_fd, 26); - -// ----- Look for invalid block size -if (strlen($v_binary_data) != 26) -{ - $p_header['filename'] = ""; - $p_header['status'] = "invalid_header"; - - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Invalid block size : ".strlen($v_binary_data)); - - // ----- Return - return PclZip::errorCode(); -} - -// ----- Extract the values -$v_data = unpack('vversion/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len', $v_binary_data); - -// ----- Get filename -$p_header['filename'] = fread($this->zip_fd, $v_data['filename_len']); - -// ----- Get extra_fields -if ($v_data['extra_len'] != 0) { - $p_header['extra'] = fread($this->zip_fd, $v_data['extra_len']); -} -else { - $p_header['extra'] = ''; -} - -// ----- Extract properties -$p_header['version_extracted'] = $v_data['version']; -$p_header['compression'] = $v_data['compression']; -$p_header['size'] = $v_data['size']; -$p_header['compressed_size'] = $v_data['compressed_size']; -$p_header['crc'] = $v_data['crc']; -$p_header['flag'] = $v_data['flag']; -$p_header['filename_len'] = $v_data['filename_len']; - -// ----- Recuperate date in UNIX format -$p_header['mdate'] = $v_data['mdate']; -$p_header['mtime'] = $v_data['mtime']; -if ($p_header['mdate'] && $p_header['mtime']) -{ - // ----- Extract time - $v_hour = ($p_header['mtime'] & 0xF800) >> 11; - $v_minute = ($p_header['mtime'] & 0x07E0) >> 5; - $v_seconde = ($p_header['mtime'] & 0x001F)*2; - - // ----- Extract date - $v_year = (($p_header['mdate'] & 0xFE00) >> 9) + 1980; - $v_month = ($p_header['mdate'] & 0x01E0) >> 5; - $v_day = $p_header['mdate'] & 0x001F; - - // ----- Get UNIX date format - $p_header['mtime'] = @mktime($v_hour, $v_minute, $v_seconde, $v_month, $v_day, $v_year); - -} -else -{ - $p_header['mtime'] = time(); -} - -// TBC -//for(reset($v_data); $key = key($v_data); next($v_data)) { -//} - -// ----- Set the stored filename -$p_header['stored_filename'] = $p_header['filename']; - -// ----- Set the status field -$p_header['status'] = "ok"; - -// ----- Return -return $v_result; -} -// -------------------------------------------------------------------------------- - -// -------------------------------------------------------------------------------- -// Function : privReadCentralFileHeader() -// Description : -// Parameters : -// Return Values : -// -------------------------------------------------------------------------------- -function privReadCentralFileHeader(&$p_header) -{ -$v_result=1; - -// ----- Read the 4 bytes signature -$v_binary_data = @fread($this->zip_fd, 4); -$v_data = unpack('Vid', $v_binary_data); - -// ----- Check signature -if ($v_data['id'] != 0x02014b50) -{ - - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Invalid archive structure'); - - // ----- Return - return PclZip::errorCode(); -} - -// ----- Read the first 42 bytes of the header -$v_binary_data = fread($this->zip_fd, 42); - -// ----- Look for invalid block size -if (strlen($v_binary_data) != 42) -{ - $p_header['filename'] = ""; - $p_header['status'] = "invalid_header"; - - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Invalid block size : ".strlen($v_binary_data)); - - // ----- Return - return PclZip::errorCode(); -} - -// ----- Extract the values -$p_header = unpack('vversion/vversion_extracted/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len/vcomment_len/vdisk/vinternal/Vexternal/Voffset', $v_binary_data); - -// ----- Get filename -if ($p_header['filename_len'] != 0) - $p_header['filename'] = fread($this->zip_fd, $p_header['filename_len']); -else - $p_header['filename'] = ''; - -// ----- Get extra -if ($p_header['extra_len'] != 0) - $p_header['extra'] = fread($this->zip_fd, $p_header['extra_len']); -else - $p_header['extra'] = ''; - -// ----- Get comment -if ($p_header['comment_len'] != 0) - $p_header['comment'] = fread($this->zip_fd, $p_header['comment_len']); -else - $p_header['comment'] = ''; - -// ----- Extract properties - -// ----- Recuperate date in UNIX format -//if ($p_header['mdate'] && $p_header['mtime']) -// TBC : bug : this was ignoring time with 0/0/0 -if (1) -{ - // ----- Extract time - $v_hour = ($p_header['mtime'] & 0xF800) >> 11; - $v_minute = ($p_header['mtime'] & 0x07E0) >> 5; - $v_seconde = ($p_header['mtime'] & 0x001F)*2; - - // ----- Extract date - $v_year = (($p_header['mdate'] & 0xFE00) >> 9) + 1980; - $v_month = ($p_header['mdate'] & 0x01E0) >> 5; - $v_day = $p_header['mdate'] & 0x001F; - - // ----- Get UNIX date format - $p_header['mtime'] = @mktime($v_hour, $v_minute, $v_seconde, $v_month, $v_day, $v_year); - -} -else -{ - $p_header['mtime'] = time(); -} - -// ----- Set the stored filename -$p_header['stored_filename'] = $p_header['filename']; - -// ----- Set default status to ok -$p_header['status'] = 'ok'; - -// ----- Look if it is a directory -if (substr($p_header['filename'], -1) == '/') { - //$p_header['external'] = 0x41FF0010; - $p_header['external'] = 0x00000010; -} - - -// ----- Return -return $v_result; -} -// -------------------------------------------------------------------------------- - -// -------------------------------------------------------------------------------- -// Function : privCheckFileHeaders() -// Description : -// Parameters : -// Return Values : -// 1 on success, -// 0 on error; -// -------------------------------------------------------------------------------- -function privCheckFileHeaders(&$p_local_header, &$p_central_header) -{ -$v_result=1; - - // ----- Check the static values - // TBC - if ($p_local_header['filename'] != $p_central_header['filename']) { - } - if ($p_local_header['version_extracted'] != $p_central_header['version_extracted']) { - } - if ($p_local_header['flag'] != $p_central_header['flag']) { - } - if ($p_local_header['compression'] != $p_central_header['compression']) { - } - if ($p_local_header['mtime'] != $p_central_header['mtime']) { - } - if ($p_local_header['filename_len'] != $p_central_header['filename_len']) { - } - - // ----- Look for flag bit 3 - if (($p_local_header['flag'] & 8) == 8) { - $p_local_header['size'] = $p_central_header['size']; - $p_local_header['compressed_size'] = $p_central_header['compressed_size']; - $p_local_header['crc'] = $p_central_header['crc']; - } - -// ----- Return -return $v_result; -} -// -------------------------------------------------------------------------------- - -// -------------------------------------------------------------------------------- -// Function : privReadEndCentralDir() -// Description : -// Parameters : -// Return Values : -// -------------------------------------------------------------------------------- -function privReadEndCentralDir(&$p_central_dir) -{ -$v_result=1; - -// ----- Go to the end of the zip file -$v_size = filesize($this->zipname); -@fseek($this->zip_fd, $v_size); -if (@ftell($this->zip_fd) != $v_size) -{ - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to go to the end of the archive \''.$this->zipname.'\''); - - // ----- Return - return PclZip::errorCode(); -} - -// ----- First try : look if this is an archive with no commentaries (most of the time) -// in this case the end of central dir is at 22 bytes of the file end -$v_found = 0; -if ($v_size > 26) { - @fseek($this->zip_fd, $v_size-22); - if (($v_pos = @ftell($this->zip_fd)) != ($v_size-22)) - { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to seek back to the middle of the archive \''.$this->zipname.'\''); - - // ----- Return - return PclZip::errorCode(); - } - - // ----- Read for bytes - $v_binary_data = @fread($this->zip_fd, 4); - $v_data = @unpack('Vid', $v_binary_data); - - // ----- Check signature - if ($v_data['id'] == 0x06054b50) { - $v_found = 1; - } - - $v_pos = ftell($this->zip_fd); -} - -// ----- Go back to the maximum possible size of the Central Dir End Record -if (!$v_found) { - $v_maximum_size = 65557; // 0xFFFF + 22; - if ($v_maximum_size > $v_size) - $v_maximum_size = $v_size; - @fseek($this->zip_fd, $v_size-$v_maximum_size); - if (@ftell($this->zip_fd) != ($v_size-$v_maximum_size)) - { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to seek back to the middle of the archive \''.$this->zipname.'\''); - - // ----- Return - return PclZip::errorCode(); - } - - // ----- Read byte per byte in order to find the signature - $v_pos = ftell($this->zip_fd); - $v_bytes = 0x00000000; - while ($v_pos < $v_size) - { - // ----- Read a byte - $v_byte = @fread($this->zip_fd, 1); - - // ----- Add the byte - //$v_bytes = ($v_bytes << 8) | Ord($v_byte); - // Note we mask the old value down such that once shifted we can never end up with more than a 32bit number - // Otherwise on systems where we have 64bit integers the check below for the magic number will fail. - $v_bytes = (($v_bytes & 0xFFFFFF) << 8) | Ord($v_byte); - - // ----- Compare the bytes - if ($v_bytes == 0x504b0506) - { - $v_pos++; - break; - } - - $v_pos++; - } - - // ----- Look if not found end of central dir - if ($v_pos == $v_size) - { - - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Unable to find End of Central Dir Record signature"); - - // ----- Return - return PclZip::errorCode(); - } -} - -// ----- Read the first 18 bytes of the header -$v_binary_data = fread($this->zip_fd, 18); - -// ----- Look for invalid block size -if (strlen($v_binary_data) != 18) -{ - - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Invalid End of Central Dir Record size : ".strlen($v_binary_data)); - - // ----- Return - return PclZip::errorCode(); -} - -// ----- Extract the values -$v_data = unpack('vdisk/vdisk_start/vdisk_entries/ventries/Vsize/Voffset/vcomment_size', $v_binary_data); - -// ----- Check the global size -if (($v_pos + $v_data['comment_size'] + 18) != $v_size) { - - // ----- Removed in release 2.2 see readme file - // The check of the file size is a little too strict. - // Some bugs where found when a zip is encrypted/decrypted with 'crypt'. - // While decrypted, zip has training 0 bytes - if (0) { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, - 'The central dir is not at the end of the archive.' - .' Some trailing bytes exists after the archive.'); - - // ----- Return - return PclZip::errorCode(); - } -} - -// ----- Get comment -if ($v_data['comment_size'] != 0) { - $p_central_dir['comment'] = fread($this->zip_fd, $v_data['comment_size']); -} -else - $p_central_dir['comment'] = ''; - -$p_central_dir['entries'] = $v_data['entries']; -$p_central_dir['disk_entries'] = $v_data['disk_entries']; -$p_central_dir['offset'] = $v_data['offset']; -$p_central_dir['size'] = $v_data['size']; -$p_central_dir['disk'] = $v_data['disk']; -$p_central_dir['disk_start'] = $v_data['disk_start']; - -// TBC -//for(reset($p_central_dir); $key = key($p_central_dir); next($p_central_dir)) { -//} - -// ----- Return -return $v_result; -} -// -------------------------------------------------------------------------------- - -// -------------------------------------------------------------------------------- -// Function : privDeleteByRule() -// Description : -// Parameters : -// Return Values : -// -------------------------------------------------------------------------------- -function privDeleteByRule(&$p_result_list, &$p_options) -{ -$v_result=1; -$v_list_detail = array(); - -// ----- Open the zip file -if (($v_result=$this->privOpenFd('rb')) != 1) -{ - // ----- Return - return $v_result; -} - -// ----- Read the central directory informations -$v_central_dir = array(); -if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) -{ - $this->privCloseFd(); - return $v_result; -} - -// ----- Go to beginning of File -@rewind($this->zip_fd); - -// ----- Scan all the files -// ----- Start at beginning of Central Dir -$v_pos_entry = $v_central_dir['offset']; -@rewind($this->zip_fd); -if (@fseek($this->zip_fd, $v_pos_entry)) -{ - // ----- Close the zip file - $this->privCloseFd(); - - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); - - // ----- Return - return PclZip::errorCode(); -} - -// ----- Read each entry -$v_header_list = array(); -$j_start = 0; -for ($i=0, $v_nb_extracted=0; $i<$v_central_dir['entries']; $i++) -{ - - // ----- Read the file header - $v_header_list[$v_nb_extracted] = array(); - if (($v_result = $this->privReadCentralFileHeader($v_header_list[$v_nb_extracted])) != 1) - { - // ----- Close the zip file - $this->privCloseFd(); - - return $v_result; - } - - - // ----- Store the index - $v_header_list[$v_nb_extracted]['index'] = $i; - - // ----- Look for the specific extract rules - $v_found = false; - - // ----- Look for extract by name rule - if ((isset($p_options[PCLZIP_OPT_BY_NAME])) - && ($p_options[PCLZIP_OPT_BY_NAME] != 0)) { - - // ----- Look if the filename is in the list - for ($j=0; ($j strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) - && (substr($v_header_list[$v_nb_extracted]['stored_filename'], 0, strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) == $p_options[PCLZIP_OPT_BY_NAME][$j])) { - $v_found = true; - } - elseif ((($v_header_list[$v_nb_extracted]['external']&0x00000010)==0x00000010) /* Indicates a folder */ - && ($v_header_list[$v_nb_extracted]['stored_filename'].'/' == $p_options[PCLZIP_OPT_BY_NAME][$j])) { - $v_found = true; - } - } - // ----- Look for a filename - elseif ($v_header_list[$v_nb_extracted]['stored_filename'] == $p_options[PCLZIP_OPT_BY_NAME][$j]) { - $v_found = true; - } - } - } - - // ----- Look for extract by ereg rule - // ereg() is deprecated with PHP 5.3 - /* - else if ((isset($p_options[PCLZIP_OPT_BY_EREG])) - && ($p_options[PCLZIP_OPT_BY_EREG] != "")) { - - if (ereg($p_options[PCLZIP_OPT_BY_EREG], $v_header_list[$v_nb_extracted]['stored_filename'])) { - $v_found = true; - } - } - */ - - // ----- Look for extract by preg rule - else if ((isset($p_options[PCLZIP_OPT_BY_PREG])) - && ($p_options[PCLZIP_OPT_BY_PREG] != "")) { - - if (preg_match($p_options[PCLZIP_OPT_BY_PREG], $v_header_list[$v_nb_extracted]['stored_filename'])) { - $v_found = true; - } - } - - // ----- Look for extract by index rule - else if ((isset($p_options[PCLZIP_OPT_BY_INDEX])) - && ($p_options[PCLZIP_OPT_BY_INDEX] != 0)) { - - // ----- Look if the index is in the list - for ($j=$j_start; ($j=$p_options[PCLZIP_OPT_BY_INDEX][$j]['start']) && ($i<=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end'])) { - $v_found = true; - } - if ($i>=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end']) { - $j_start = $j+1; - } - - if ($p_options[PCLZIP_OPT_BY_INDEX][$j]['start']>$i) { - break; - } - } - } - else { - $v_found = true; - } - - // ----- Look for deletion - if ($v_found) - { - unset($v_header_list[$v_nb_extracted]); - } - else - { - $v_nb_extracted++; - } -} - -// ----- Look if something need to be deleted -if ($v_nb_extracted > 0) { - - // ----- Creates a temporay file - $v_zip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.tmp'; - - // ----- Creates a temporary zip archive - $v_temp_zip = new PclZip($v_zip_temp_name); - - // ----- Open the temporary zip file in write mode - if (($v_result = $v_temp_zip->privOpenFd('wb')) != 1) { - $this->privCloseFd(); - - // ----- Return - return $v_result; - } - - // ----- Look which file need to be kept - for ($i=0; $izip_fd); - if (@fseek($this->zip_fd, $v_header_list[$i]['offset'])) { - // ----- Close the zip file - $this->privCloseFd(); - $v_temp_zip->privCloseFd(); - @unlink($v_zip_temp_name); - - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); - - // ----- Return - return PclZip::errorCode(); - } - - // ----- Read the file header - $v_local_header = array(); - if (($v_result = $this->privReadFileHeader($v_local_header)) != 1) { - // ----- Close the zip file - $this->privCloseFd(); - $v_temp_zip->privCloseFd(); - @unlink($v_zip_temp_name); - - // ----- Return - return $v_result; - } - - // ----- Check that local file header is same as central file header - if ($this->privCheckFileHeaders($v_local_header, - $v_header_list[$i]) != 1) { - // TBC - } - unset($v_local_header); - - // ----- Write the file header - if (($v_result = $v_temp_zip->privWriteFileHeader($v_header_list[$i])) != 1) { - // ----- Close the zip file - $this->privCloseFd(); - $v_temp_zip->privCloseFd(); - @unlink($v_zip_temp_name); - - // ----- Return - return $v_result; - } - - // ----- Read/write the data block - if (($v_result = PclZipUtilCopyBlock($this->zip_fd, $v_temp_zip->zip_fd, $v_header_list[$i]['compressed_size'])) != 1) { - // ----- Close the zip file - $this->privCloseFd(); - $v_temp_zip->privCloseFd(); - @unlink($v_zip_temp_name); - - // ----- Return - return $v_result; - } + return $v_result; } // ----- Store the offset of the central dir - $v_offset = @ftell($v_temp_zip->zip_fd); + $v_offset = @ftell($this->zip_fd); - // ----- Re-Create the Central Dir files header - for ($i=0; $iprivWriteCentralFileHeader($v_header_list[$i])) != 1) { - $v_temp_zip->privCloseFd(); - $this->privCloseFd(); - @unlink($v_zip_temp_name); - - // ----- Return - return $v_result; - } - - // ----- Transform the header to a 'usable' info - $v_temp_zip->privConvertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]); + // ----- Copy the block of file headers from the old archive + $v_size = $v_central_dir['size']; + while ($v_size != 0) + { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @fread($v_zip_temp_fd, $v_read_size); + @fwrite($this->zip_fd, $v_buffer, $v_read_size); + $v_size -= $v_read_size; } + // ----- Create the Central Dir files header + for ($i=0, $v_count=0; $iprivWriteCentralFileHeader($v_header_list[$i])) != 1) { + fclose($v_zip_temp_fd); + $this->privCloseFd(); + @unlink($v_zip_temp_name); + $this->privSwapBackMagicQuotes(); + + // ----- Return + return $v_result; + } + $v_count++; + } + + // ----- Transform the header to a 'usable' info + $this->privConvertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]); + } // ----- Zip file comment - $v_comment = ''; + $v_comment = $v_central_dir['comment']; if (isset($p_options[PCLZIP_OPT_COMMENT])) { $v_comment = $p_options[PCLZIP_OPT_COMMENT]; } - - // ----- Calculate the size of the central header - $v_size = @ftell($v_temp_zip->zip_fd)-$v_offset; - - // ----- Create the central dir footer - if (($v_result = $v_temp_zip->privWriteCentralHeader(sizeof($v_header_list), $v_size, $v_offset, $v_comment)) != 1) { - // ----- Reset the file list - unset($v_header_list); - $v_temp_zip->privCloseFd(); - $this->privCloseFd(); - @unlink($v_zip_temp_name); - - // ----- Return - return $v_result; + if (isset($p_options[PCLZIP_OPT_ADD_COMMENT])) { + $v_comment = $v_comment.$p_options[PCLZIP_OPT_ADD_COMMENT]; + } + if (isset($p_options[PCLZIP_OPT_PREPEND_COMMENT])) { + $v_comment = $p_options[PCLZIP_OPT_PREPEND_COMMENT].$v_comment; } + // ----- Calculate the size of the central header + $v_size = @ftell($this->zip_fd)-$v_offset; + + // ----- Create the central dir footer + if (($v_result = $this->privWriteCentralHeader($v_count+$v_central_dir['entries'], $v_size, $v_offset, $v_comment)) != 1) + { + // ----- Reset the file list + unset($v_header_list); + $this->privSwapBackMagicQuotes(); + + // ----- Return + return $v_result; + } + + // ----- Swap back the file descriptor + $v_swap = $this->zip_fd; + $this->zip_fd = $v_zip_temp_fd; + $v_zip_temp_fd = $v_swap; + // ----- Close - $v_temp_zip->privCloseFd(); $this->privCloseFd(); + // ----- Close the temporary file + @fclose($v_zip_temp_fd); + + // ----- Magic quotes trick + $this->privSwapBackMagicQuotes(); + // ----- Delete the zip file // TBC : I should test the result ... @unlink($this->zipname); @@ -4797,738 +2325,3368 @@ if ($v_nb_extracted > 0) { //@rename($v_zip_temp_name, $this->zipname); PclZipUtilRename($v_zip_temp_name, $this->zipname); - // ----- Destroy the temporary archive - unset($v_temp_zip); -} - -// ----- Remove every files : reset the file -else if ($v_central_dir['entries'] != 0) { - $this->privCloseFd(); - - if (($v_result = $this->privOpenFd('wb')) != 1) { - return $v_result; - } - - if (($v_result = $this->privWriteCentralHeader(0, 0, 0, '')) != 1) { - return $v_result; - } - - $this->privCloseFd(); -} - -// ----- Return -return $v_result; -} -// -------------------------------------------------------------------------------- - -// -------------------------------------------------------------------------------- -// Function : privDirCheck() -// Description : -// Check if a directory exists, if not it creates it and all the parents directory -// which may be useful. -// Parameters : -// $p_dir : Directory path to check. -// Return Values : -// 1 : OK -// -1 : Unable to create directory -// -------------------------------------------------------------------------------- -function privDirCheck($p_dir, $p_is_dir=false) -{ -$v_result = 1; - - -// ----- Remove the final '/' -if (($p_is_dir) && (substr($p_dir, -1)=='/')) -{ - $p_dir = substr($p_dir, 0, strlen($p_dir)-1); -} - -// ----- Check the directory availability -if ((is_dir($p_dir)) || ($p_dir == "")) -{ - return 1; -} - -// ----- Extract parent directory -$p_parent_dir = dirname($p_dir); - -// ----- Just a check -if ($p_parent_dir != $p_dir) -{ - // ----- Look for parent directory - if ($p_parent_dir != "") - { - if (($v_result = $this->privDirCheck($p_parent_dir)) != 1) - { - return $v_result; - } + // ----- Return + return $v_result; } -} - -// ----- Create the directory -if (!@mkdir($p_dir, 0777)) -{ - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_DIR_CREATE_FAIL, "Unable to create directory '$p_dir'"); - - // ----- Return - return PclZip::errorCode(); -} - -// ----- Return -return $v_result; -} -// -------------------------------------------------------------------------------- - -// -------------------------------------------------------------------------------- -// Function : privMerge() -// Description : -// If $p_archive_to_add does not exist, the function exit with a success result. -// Parameters : -// Return Values : -// -------------------------------------------------------------------------------- -function privMerge(&$p_archive_to_add) -{ -$v_result=1; - -// ----- Look if the archive_to_add exists -if (!is_file($p_archive_to_add->zipname)) -{ - - // ----- Nothing to merge, so merge is a success - $v_result = 1; - - // ----- Return - return $v_result; -} - -// ----- Look if the archive exists -if (!is_file($this->zipname)) -{ - - // ----- Do a duplicate - $v_result = $this->privDuplicate($p_archive_to_add->zipname); - - // ----- Return - return $v_result; -} - -// ----- Open the zip file -if (($v_result=$this->privOpenFd('rb')) != 1) -{ - // ----- Return - return $v_result; -} - -// ----- Read the central directory informations -$v_central_dir = array(); -if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) -{ - $this->privCloseFd(); - return $v_result; -} - -// ----- Go to beginning of File -@rewind($this->zip_fd); - -// ----- Open the archive_to_add file -if (($v_result=$p_archive_to_add->privOpenFd('rb')) != 1) -{ - $this->privCloseFd(); - - // ----- Return - return $v_result; -} - -// ----- Read the central directory informations -$v_central_dir_to_add = array(); -if (($v_result = $p_archive_to_add->privReadEndCentralDir($v_central_dir_to_add)) != 1) -{ - $this->privCloseFd(); - $p_archive_to_add->privCloseFd(); - - return $v_result; -} - -// ----- Go to beginning of File -@rewind($p_archive_to_add->zip_fd); - -// ----- Creates a temporay file -$v_zip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.tmp'; - -// ----- Open the temporary file in write mode -if (($v_zip_temp_fd = @fopen($v_zip_temp_name, 'wb')) == 0) -{ - $this->privCloseFd(); - $p_archive_to_add->privCloseFd(); - - PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_zip_temp_name.'\' in binary write mode'); - - // ----- Return - return PclZip::errorCode(); -} - -// ----- Copy the files from the archive to the temporary file -// TBC : Here I should better append the file and go back to erase the central dir -$v_size = $v_central_dir['offset']; -while ($v_size != 0) -{ - $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); - $v_buffer = fread($this->zip_fd, $v_read_size); - @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); - $v_size -= $v_read_size; -} - -// ----- Copy the files from the archive_to_add into the temporary file -$v_size = $v_central_dir_to_add['offset']; -while ($v_size != 0) -{ - $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); - $v_buffer = fread($p_archive_to_add->zip_fd, $v_read_size); - @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); - $v_size -= $v_read_size; -} - -// ----- Store the offset of the central dir -$v_offset = @ftell($v_zip_temp_fd); - -// ----- Copy the block of file headers from the old archive -$v_size = $v_central_dir['size']; -while ($v_size != 0) -{ - $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); - $v_buffer = @fread($this->zip_fd, $v_read_size); - @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); - $v_size -= $v_read_size; -} - -// ----- Copy the block of file headers from the archive_to_add -$v_size = $v_central_dir_to_add['size']; -while ($v_size != 0) -{ - $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); - $v_buffer = @fread($p_archive_to_add->zip_fd, $v_read_size); - @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); - $v_size -= $v_read_size; -} - -// ----- Merge the file comments -$v_comment = $v_central_dir['comment'].' '.$v_central_dir_to_add['comment']; - -// ----- Calculate the size of the (new) central header -$v_size = @ftell($v_zip_temp_fd)-$v_offset; - -// ----- Swap the file descriptor -// Here is a trick : I swap the temporary fd with the zip fd, in order to use -// the following methods on the temporary fil and not the real archive fd -$v_swap = $this->zip_fd; -$this->zip_fd = $v_zip_temp_fd; -$v_zip_temp_fd = $v_swap; - -// ----- Create the central dir footer -if (($v_result = $this->privWriteCentralHeader($v_central_dir['entries']+$v_central_dir_to_add['entries'], $v_size, $v_offset, $v_comment)) != 1) -{ - $this->privCloseFd(); - $p_archive_to_add->privCloseFd(); - @fclose($v_zip_temp_fd); - $this->zip_fd = null; - - // ----- Reset the file list - unset($v_header_list); - - // ----- Return - return $v_result; -} - -// ----- Swap back the file descriptor -$v_swap = $this->zip_fd; -$this->zip_fd = $v_zip_temp_fd; -$v_zip_temp_fd = $v_swap; - -// ----- Close -$this->privCloseFd(); -$p_archive_to_add->privCloseFd(); - -// ----- Close the temporary file -@fclose($v_zip_temp_fd); - -// ----- Delete the zip file -// TBC : I should test the result ... -@unlink($this->zipname); - -// ----- Rename the temporary file -// TBC : I should test the result ... -//@rename($v_zip_temp_name, $this->zipname); -PclZipUtilRename($v_zip_temp_name, $this->zipname); - -// ----- Return -return $v_result; -} -// -------------------------------------------------------------------------------- - -// -------------------------------------------------------------------------------- -// Function : privDuplicate() -// Description : -// Parameters : -// Return Values : -// -------------------------------------------------------------------------------- -function privDuplicate($p_archive_filename) -{ -$v_result=1; - -// ----- Look if the $p_archive_filename exists -if (!is_file($p_archive_filename)) -{ - - // ----- Nothing to duplicate, so duplicate is a success. - $v_result = 1; - - // ----- Return - return $v_result; -} - -// ----- Open the zip file -if (($v_result=$this->privOpenFd('wb')) != 1) -{ - // ----- Return - return $v_result; -} - -// ----- Open the temporary file in write mode -if (($v_zip_temp_fd = @fopen($p_archive_filename, 'rb')) == 0) -{ - $this->privCloseFd(); - - PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive file \''.$p_archive_filename.'\' in binary write mode'); - - // ----- Return - return PclZip::errorCode(); -} - -// ----- Copy the files from the archive to the temporary file -// TBC : Here I should better append the file and go back to erase the central dir -$v_size = filesize($p_archive_filename); -while ($v_size != 0) -{ - $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); - $v_buffer = fread($v_zip_temp_fd, $v_read_size); - @fwrite($this->zip_fd, $v_buffer, $v_read_size); - $v_size -= $v_read_size; -} - -// ----- Close -$this->privCloseFd(); - -// ----- Close the temporary file -@fclose($v_zip_temp_fd); - -// ----- Return -return $v_result; -} -// -------------------------------------------------------------------------------- - -// -------------------------------------------------------------------------------- -// Function : privErrorLog() -// Description : -// Parameters : -// -------------------------------------------------------------------------------- -function privErrorLog($p_error_code=0, $p_error_string='') -{ -if (PCLZIP_ERROR_EXTERNAL == 1) { - PclError($p_error_code, $p_error_string); -} -else { - $this->error_code = $p_error_code; - $this->error_string = $p_error_string; -} -} -// -------------------------------------------------------------------------------- - -// -------------------------------------------------------------------------------- -// Function : privErrorReset() -// Description : -// Parameters : -// -------------------------------------------------------------------------------- -function privErrorReset() -{ -if (PCLZIP_ERROR_EXTERNAL == 1) { - PclErrorReset(); -} -else { - $this->error_code = 0; - $this->error_string = ''; -} -} -// -------------------------------------------------------------------------------- - -// -------------------------------------------------------------------------------- -// Function : privDisableMagicQuotes() -// Description : -// Parameters : -// Return Values : -// -------------------------------------------------------------------------------- -function privDisableMagicQuotes() -{ -$v_result=1; - -// ----- Look if function exists -if ((!function_exists("get_magic_quotes_runtime")) - || (!function_exists("set_magic_quotes_runtime"))) { - return $v_result; -} - -// ----- Look if already done -if ($this->magic_quotes_status != -1) { - return $v_result; -} - -// ----- Get and memorize the magic_quote value -$this->magic_quotes_status = @get_magic_quotes_runtime(); - -// ----- Disable magic_quotes -if ($this->magic_quotes_status == 1) { - @set_magic_quotes_runtime(0); -} - -// ----- Return -return $v_result; -} -// -------------------------------------------------------------------------------- - -// -------------------------------------------------------------------------------- -// Function : privSwapBackMagicQuotes() -// Description : -// Parameters : -// Return Values : -// -------------------------------------------------------------------------------- -function privSwapBackMagicQuotes() -{ -$v_result=1; - -// ----- Look if function exists -if ((!function_exists("get_magic_quotes_runtime")) - || (!function_exists("set_magic_quotes_runtime"))) { - return $v_result; -} - -// ----- Look if something to do -if ($this->magic_quotes_status != -1) { - return $v_result; -} - -// ----- Swap back magic_quotes -if ($this->magic_quotes_status == 1) { - @set_magic_quotes_runtime($this->magic_quotes_status); -} - -// ----- Return -return $v_result; -} -// -------------------------------------------------------------------------------- - -} -// End of class -// -------------------------------------------------------------------------------- - -// -------------------------------------------------------------------------------- -// Function : PclZipUtilPathReduction() -// Description : -// Parameters : -// Return Values : -// -------------------------------------------------------------------------------- -function PclZipUtilPathReduction($p_dir) -{ -$v_result = ""; - -// ----- Look for not empty path -if ($p_dir != "") { - // ----- Explode path by directory names - $v_list = explode("/", $p_dir); - - // ----- Study directories from last to first - $v_skip = 0; - for ($i=sizeof($v_list)-1; $i>=0; $i--) { - // ----- Look for current path - if ($v_list[$i] == ".") { - // ----- Ignore this directory - // Should be the first $i=0, but no check is done + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privOpenFd() + // Description : + // Parameters : + // -------------------------------------------------------------------------------- + function privOpenFd($p_mode) + { + $v_result=1; + + // ----- Look if already open + if ($this->zip_fd != 0) + { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Zip file \''.$this->zipname.'\' already open'); + + // ----- Return + return PclZip::errorCode(); } - else if ($v_list[$i] == "..") { - $v_skip++; + + // ----- Open the zip file + if (($this->zip_fd = @fopen($this->zipname, $p_mode)) == 0) + { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \''.$this->zipname.'\' in '.$p_mode.' mode'); + + // ----- Return + return PclZip::errorCode(); } - else if ($v_list[$i] == "") { - // ----- First '/' i.e. root slash - if ($i == 0) { - $v_result = "/".$v_result; - if ($v_skip > 0) { - // ----- It is an invalid path, so the path is not modified - // TBC - $v_result = $p_dir; - $v_skip = 0; + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privCloseFd() + // Description : + // Parameters : + // -------------------------------------------------------------------------------- + function privCloseFd() + { + $v_result=1; + + if ($this->zip_fd != 0) + @fclose($this->zip_fd); + $this->zip_fd = 0; + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privAddList() + // Description : + // $p_add_dir and $p_remove_dir will give the ability to memorize a path which is + // different from the real path of the file. This is usefull if you want to have PclTar + // running in any directory, and memorize relative path from an other directory. + // Parameters : + // $p_list : An array containing the file or directory names to add in the tar + // $p_result_list : list of added files with their properties (specially the status field) + // $p_add_dir : Path to add in the filename path archived + // $p_remove_dir : Path to remove in the filename path archived + // Return Values : + // -------------------------------------------------------------------------------- +// function privAddList($p_list, &$p_result_list, $p_add_dir, $p_remove_dir, $p_remove_all_dir, &$p_options) + function privAddList($p_filedescr_list, &$p_result_list, &$p_options) + { + $v_result=1; + + // ----- Add the files + $v_header_list = array(); + if (($v_result = $this->privAddFileList($p_filedescr_list, $v_header_list, $p_options)) != 1) + { + // ----- Return + return $v_result; + } + + // ----- Store the offset of the central dir + $v_offset = @ftell($this->zip_fd); + + // ----- Create the Central Dir files header + for ($i=0, $v_count=0; $iprivWriteCentralFileHeader($v_header_list[$i])) != 1) { + // ----- Return + return $v_result; } + $v_count++; } - // ----- Last '/' i.e. indicates a directory - else if ($i == (sizeof($v_list)-1)) { - $v_result = $v_list[$i]; + + // ----- Transform the header to a 'usable' info + $this->privConvertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]); + } + + // ----- Zip file comment + $v_comment = ''; + if (isset($p_options[PCLZIP_OPT_COMMENT])) { + $v_comment = $p_options[PCLZIP_OPT_COMMENT]; + } + + // ----- Calculate the size of the central header + $v_size = @ftell($this->zip_fd)-$v_offset; + + // ----- Create the central dir footer + if (($v_result = $this->privWriteCentralHeader($v_count, $v_size, $v_offset, $v_comment)) != 1) + { + // ----- Reset the file list + unset($v_header_list); + + // ----- Return + return $v_result; + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privAddFileList() + // Description : + // Parameters : + // $p_filedescr_list : An array containing the file description + // or directory names to add in the zip + // $p_result_list : list of added files with their properties (specially the status field) + // Return Values : + // -------------------------------------------------------------------------------- + function privAddFileList($p_filedescr_list, &$p_result_list, &$p_options) + { + $v_result=1; + $v_header = array(); + + // ----- Recuperate the current number of elt in list + $v_nb = sizeof($p_result_list); + + // ----- Loop on the files + for ($j=0; ($jprivAddFile($p_filedescr_list[$j], $v_header, + $p_options); + if ($v_result != 1) { + return $v_result; + } + + // ----- Store the file infos + $p_result_list[$v_nb++] = $v_header; + } + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privAddFile() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privAddFile($p_filedescr, &$p_header, &$p_options) + { + $v_result=1; + + // ----- Working variable + $p_filename = $p_filedescr['filename']; + + // TBC : Already done in the fileAtt check ... ? + if ($p_filename == "") { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid file list parameter (invalid or empty list)"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Look for a stored different filename + /* TBC : Removed + if (isset($p_filedescr['stored_filename'])) { + $v_stored_filename = $p_filedescr['stored_filename']; } else { - // ----- Look for item to skip - if ($v_skip > 0) { - $v_skip--; + $v_stored_filename = $p_filedescr['stored_filename']; + } + */ + + // ----- Set the file properties + clearstatcache(); + $p_header['version'] = 20; + $p_header['version_extracted'] = 10; + $p_header['flag'] = 0; + $p_header['compression'] = 0; + $p_header['crc'] = 0; + $p_header['compressed_size'] = 0; + $p_header['filename_len'] = strlen($p_filename); + $p_header['extra_len'] = 0; + $p_header['disk'] = 0; + $p_header['internal'] = 0; + $p_header['offset'] = 0; + $p_header['filename'] = $p_filename; +// TBC : Removed $p_header['stored_filename'] = $v_stored_filename; + $p_header['stored_filename'] = $p_filedescr['stored_filename']; + $p_header['extra'] = ''; + $p_header['status'] = 'ok'; + $p_header['index'] = -1; + + // ----- Look for regular file + if ($p_filedescr['type']=='file') { + $p_header['external'] = 0x00000000; + $p_header['size'] = filesize($p_filename); + } + + // ----- Look for regular folder + else if ($p_filedescr['type']=='folder') { + $p_header['external'] = 0x00000010; + $p_header['mtime'] = filemtime($p_filename); + $p_header['size'] = filesize($p_filename); + } + + // ----- Look for virtual file + else if ($p_filedescr['type'] == 'virtual_file') { + $p_header['external'] = 0x00000000; + $p_header['size'] = strlen($p_filedescr['content']); + } + + + // ----- Look for filetime + if (isset($p_filedescr['mtime'])) { + $p_header['mtime'] = $p_filedescr['mtime']; + } + else if ($p_filedescr['type'] == 'virtual_file') { + $p_header['mtime'] = time(); + } + else { + $p_header['mtime'] = filemtime($p_filename); + } + + // ------ Look for file comment + if (isset($p_filedescr['comment'])) { + $p_header['comment_len'] = strlen($p_filedescr['comment']); + $p_header['comment'] = $p_filedescr['comment']; + } + else { + $p_header['comment_len'] = 0; + $p_header['comment'] = ''; + } + + // ----- Look for pre-add callback + if (isset($p_options[PCLZIP_CB_PRE_ADD])) { + + // ----- Generate a local information + $v_local_header = array(); + $this->privConvertHeader2FileInfo($p_header, $v_local_header); + + // ----- Call the callback + // Here I do not use call_user_func() because I need to send a reference to the + // header. +// eval('$v_result = '.$p_options[PCLZIP_CB_PRE_ADD].'(PCLZIP_CB_PRE_ADD, $v_local_header);'); + $v_result = $p_options[PCLZIP_CB_PRE_ADD](PCLZIP_CB_PRE_ADD, $v_local_header); + if ($v_result == 0) { + // ----- Change the file status + $p_header['status'] = "skipped"; + $v_result = 1; + } + + // ----- Update the informations + // Only some fields can be modified + if ($p_header['stored_filename'] != $v_local_header['stored_filename']) { + $p_header['stored_filename'] = PclZipUtilPathReduction($v_local_header['stored_filename']); + } + } + + // ----- Look for empty stored filename + if ($p_header['stored_filename'] == "") { + $p_header['status'] = "filtered"; + } + + // ----- Check the path length + if (strlen($p_header['stored_filename']) > 0xFF) { + $p_header['status'] = 'filename_too_long'; + } + + // ----- Look if no error, or file not skipped + if ($p_header['status'] == 'ok') { + + // ----- Look for a file + if ($p_filedescr['type'] == 'file') { + // ----- Look for using temporary file to zip + if ( (!isset($p_options[PCLZIP_OPT_TEMP_FILE_OFF])) + && (isset($p_options[PCLZIP_OPT_TEMP_FILE_ON]) + || (isset($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD]) + && ($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD] <= $p_header['size'])) ) ) { + $v_result = $this->privAddFileUsingTempFile($p_filedescr, $p_header, $p_options); + if ($v_result < PCLZIP_ERR_NO_ERROR) { + return $v_result; + } + } + + // ----- Use "in memory" zip algo + else { + + // ----- Open the source file + if (($v_file = @fopen($p_filename, "rb")) == 0) { + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, "Unable to open file '$p_filename' in binary read mode"); + return PclZip::errorCode(); + } + + // ----- Read the file content + $v_content = @fread($v_file, $p_header['size']); + + // ----- Close the file + @fclose($v_file); + + // ----- Calculate the CRC + $p_header['crc'] = @crc32($v_content); + + // ----- Look for no compression + if ($p_options[PCLZIP_OPT_NO_COMPRESSION]) { + // ----- Set header parameters + $p_header['compressed_size'] = $p_header['size']; + $p_header['compression'] = 0; + } + + // ----- Look for normal compression + else { + // ----- Compress the content + $v_content = @gzdeflate($v_content); + + // ----- Set header parameters + $p_header['compressed_size'] = strlen($v_content); + $p_header['compression'] = 8; + } + + // ----- Call the header generation + if (($v_result = $this->privWriteFileHeader($p_header)) != 1) { + @fclose($v_file); + return $v_result; + } + + // ----- Write the compressed (or not) content + @fwrite($this->zip_fd, $v_content, $p_header['compressed_size']); + + } + + } + + // ----- Look for a virtual file (a file from string) + else if ($p_filedescr['type'] == 'virtual_file') { + + $v_content = $p_filedescr['content']; + + // ----- Calculate the CRC + $p_header['crc'] = @crc32($v_content); + + // ----- Look for no compression + if ($p_options[PCLZIP_OPT_NO_COMPRESSION]) { + // ----- Set header parameters + $p_header['compressed_size'] = $p_header['size']; + $p_header['compression'] = 0; + } + + // ----- Look for normal compression + else { + // ----- Compress the content + $v_content = @gzdeflate($v_content); + + // ----- Set header parameters + $p_header['compressed_size'] = strlen($v_content); + $p_header['compression'] = 8; + } + + // ----- Call the header generation + if (($v_result = $this->privWriteFileHeader($p_header)) != 1) { + @fclose($v_file); + return $v_result; + } + + // ----- Write the compressed (or not) content + @fwrite($this->zip_fd, $v_content, $p_header['compressed_size']); + } + + // ----- Look for a directory + else if ($p_filedescr['type'] == 'folder') { + // ----- Look for directory last '/' + if (@substr($p_header['stored_filename'], -1) != '/') { + $p_header['stored_filename'] .= '/'; + } + + // ----- Set the file properties + $p_header['size'] = 0; + //$p_header['external'] = 0x41FF0010; // Value for a folder : to be checked + $p_header['external'] = 0x00000010; // Value for a folder : to be checked + + // ----- Call the header generation + if (($v_result = $this->privWriteFileHeader($p_header)) != 1) + { + return $v_result; + } + } + } + + // ----- Look for post-add callback + if (isset($p_options[PCLZIP_CB_POST_ADD])) { + + // ----- Generate a local information + $v_local_header = array(); + $this->privConvertHeader2FileInfo($p_header, $v_local_header); + + // ----- Call the callback + // Here I do not use call_user_func() because I need to send a reference to the + // header. +// eval('$v_result = '.$p_options[PCLZIP_CB_POST_ADD].'(PCLZIP_CB_POST_ADD, $v_local_header);'); + $v_result = $p_options[PCLZIP_CB_POST_ADD](PCLZIP_CB_POST_ADD, $v_local_header); + if ($v_result == 0) { + // ----- Ignored + $v_result = 1; + } + + // ----- Update the informations + // Nothing can be modified + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privAddFileUsingTempFile() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privAddFileUsingTempFile($p_filedescr, &$p_header, &$p_options) + { + $v_result=PCLZIP_ERR_NO_ERROR; + + // ----- Working variable + $p_filename = $p_filedescr['filename']; + + + // ----- Open the source file + if (($v_file = @fopen($p_filename, "rb")) == 0) { + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, "Unable to open file '$p_filename' in binary read mode"); + return PclZip::errorCode(); + } + + // ----- Creates a compressed temporary file + $v_gzip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.gz'; + if (($v_file_compressed = @gzopen($v_gzip_temp_name, "wb")) == 0) { + fclose($v_file); + PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary write mode'); + return PclZip::errorCode(); + } + + // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks + $v_size = filesize($p_filename); + while ($v_size != 0) { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @fread($v_file, $v_read_size); + //$v_binary_data = pack('a'.$v_read_size, $v_buffer); + @gzputs($v_file_compressed, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + + // ----- Close the file + @fclose($v_file); + @gzclose($v_file_compressed); + + // ----- Check the minimum file size + if (filesize($v_gzip_temp_name) < 18) { + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'gzip temporary file \''.$v_gzip_temp_name.'\' has invalid filesize - should be minimum 18 bytes'); + return PclZip::errorCode(); + } + + // ----- Extract the compressed attributes + if (($v_file_compressed = @fopen($v_gzip_temp_name, "rb")) == 0) { + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary read mode'); + return PclZip::errorCode(); + } + + // ----- Read the gzip file header + $v_binary_data = @fread($v_file_compressed, 10); + $v_data_header = unpack('a1id1/a1id2/a1cm/a1flag/Vmtime/a1xfl/a1os', $v_binary_data); + + // ----- Check some parameters + $v_data_header['os'] = bin2hex($v_data_header['os']); + + // ----- Read the gzip file footer + @fseek($v_file_compressed, filesize($v_gzip_temp_name)-8); + $v_binary_data = @fread($v_file_compressed, 8); + $v_data_footer = unpack('Vcrc/Vcompressed_size', $v_binary_data); + + // ----- Set the attributes + $p_header['compression'] = ord($v_data_header['cm']); + //$p_header['mtime'] = $v_data_header['mtime']; + $p_header['crc'] = $v_data_footer['crc']; + $p_header['compressed_size'] = filesize($v_gzip_temp_name)-18; + + // ----- Close the file + @fclose($v_file_compressed); + + // ----- Call the header generation + if (($v_result = $this->privWriteFileHeader($p_header)) != 1) { + return $v_result; + } + + // ----- Add the compressed data + if (($v_file_compressed = @fopen($v_gzip_temp_name, "rb")) == 0) + { + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary read mode'); + return PclZip::errorCode(); + } + + // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks + fseek($v_file_compressed, 10); + $v_size = $p_header['compressed_size']; + while ($v_size != 0) + { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @fread($v_file_compressed, $v_read_size); + //$v_binary_data = pack('a'.$v_read_size, $v_buffer); + @fwrite($this->zip_fd, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + + // ----- Close the file + @fclose($v_file_compressed); + + // ----- Unlink the temporary file + @unlink($v_gzip_temp_name); + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privCalculateStoredFilename() + // Description : + // Based on file descriptor properties and global options, this method + // calculate the filename that will be stored in the archive. + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privCalculateStoredFilename(&$p_filedescr, &$p_options) + { + $v_result=1; + + // ----- Working variables + $p_filename = $p_filedescr['filename']; + if (isset($p_options[PCLZIP_OPT_ADD_PATH])) { + $p_add_dir = $p_options[PCLZIP_OPT_ADD_PATH]; + } + else { + $p_add_dir = ''; + } + if (isset($p_options[PCLZIP_OPT_REMOVE_PATH])) { + $p_remove_dir = $p_options[PCLZIP_OPT_REMOVE_PATH]; + } + else { + $p_remove_dir = ''; + } + if (isset($p_options[PCLZIP_OPT_REMOVE_ALL_PATH])) { + $p_remove_all_dir = $p_options[PCLZIP_OPT_REMOVE_ALL_PATH]; + } + else { + $p_remove_all_dir = 0; + } + + + // ----- Look for full name change + if (isset($p_filedescr['new_full_name'])) { + // ----- Remove drive letter if any + $v_stored_filename = PclZipUtilTranslateWinPath($p_filedescr['new_full_name']); + } + + // ----- Look for path and/or short name change + else { + + // ----- Look for short name change + // Its when we cahnge just the filename but not the path + if (isset($p_filedescr['new_short_name'])) { + $v_path_info = pathinfo($p_filename); + $v_dir = ''; + if ($v_path_info['dirname'] != '') { + $v_dir = $v_path_info['dirname'].'/'; + } + $v_stored_filename = $v_dir.$p_filedescr['new_short_name']; } else { - $v_result = $v_list[$i].($i!=(sizeof($v_list)-1)?"/".$v_result:""); + // ----- Calculate the stored filename + $v_stored_filename = $p_filename; + } + + // ----- Look for all path to remove + if ($p_remove_all_dir) { + $v_stored_filename = basename($p_filename); + } + // ----- Look for partial path remove + else if ($p_remove_dir != "") { + if (substr($p_remove_dir, -1) != '/') + $p_remove_dir .= "/"; + + if ( (substr($p_filename, 0, 2) == "./") + || (substr($p_remove_dir, 0, 2) == "./")) { + + if ( (substr($p_filename, 0, 2) == "./") + && (substr($p_remove_dir, 0, 2) != "./")) { + $p_remove_dir = "./".$p_remove_dir; + } + if ( (substr($p_filename, 0, 2) != "./") + && (substr($p_remove_dir, 0, 2) == "./")) { + $p_remove_dir = substr($p_remove_dir, 2); + } + } + + $v_compare = PclZipUtilPathInclusion($p_remove_dir, + $v_stored_filename); + if ($v_compare > 0) { + if ($v_compare == 2) { + $v_stored_filename = ""; + } + else { + $v_stored_filename = substr($v_stored_filename, + strlen($p_remove_dir)); + } + } + } + + // ----- Remove drive letter if any + $v_stored_filename = PclZipUtilTranslateWinPath($v_stored_filename); + + // ----- Look for path to add + if ($p_add_dir != "") { + if (substr($p_add_dir, -1) == "/") + $v_stored_filename = $p_add_dir.$v_stored_filename; + else + $v_stored_filename = $p_add_dir."/".$v_stored_filename; } } + + // ----- Filename (reduce the path of stored name) + $v_stored_filename = PclZipUtilPathReduction($v_stored_filename); + $p_filedescr['stored_filename'] = $v_stored_filename; + + // ----- Return + return $v_result; } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privWriteFileHeader() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privWriteFileHeader(&$p_header) + { + $v_result=1; + + // ----- Store the offset position of the file + $p_header['offset'] = ftell($this->zip_fd); + + // ----- Transform UNIX mtime to DOS format mdate/mtime + $v_date = getdate($p_header['mtime']); + $v_mtime = ($v_date['hours']<<11) + ($v_date['minutes']<<5) + $v_date['seconds']/2; + $v_mdate = (($v_date['year']-1980)<<9) + ($v_date['mon']<<5) + $v_date['mday']; + + // ----- Packed data + $v_binary_data = pack("VvvvvvVVVvv", 0x04034b50, + $p_header['version_extracted'], $p_header['flag'], + $p_header['compression'], $v_mtime, $v_mdate, + $p_header['crc'], $p_header['compressed_size'], + $p_header['size'], + strlen($p_header['stored_filename']), + $p_header['extra_len']); + + // ----- Write the first 148 bytes of the header in the archive + fputs($this->zip_fd, $v_binary_data, 30); + + // ----- Write the variable fields + if (strlen($p_header['stored_filename']) != 0) + { + fputs($this->zip_fd, $p_header['stored_filename'], strlen($p_header['stored_filename'])); + } + if ($p_header['extra_len'] != 0) + { + fputs($this->zip_fd, $p_header['extra'], $p_header['extra_len']); + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privWriteCentralFileHeader() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privWriteCentralFileHeader(&$p_header) + { + $v_result=1; + + // TBC + //for(reset($p_header); $key = key($p_header); next($p_header)) { + //} + + // ----- Transform UNIX mtime to DOS format mdate/mtime + $v_date = getdate($p_header['mtime']); + $v_mtime = ($v_date['hours']<<11) + ($v_date['minutes']<<5) + $v_date['seconds']/2; + $v_mdate = (($v_date['year']-1980)<<9) + ($v_date['mon']<<5) + $v_date['mday']; + + + // ----- Packed data + $v_binary_data = pack("VvvvvvvVVVvvvvvVV", 0x02014b50, + $p_header['version'], $p_header['version_extracted'], + $p_header['flag'], $p_header['compression'], + $v_mtime, $v_mdate, $p_header['crc'], + $p_header['compressed_size'], $p_header['size'], + strlen($p_header['stored_filename']), + $p_header['extra_len'], $p_header['comment_len'], + $p_header['disk'], $p_header['internal'], + $p_header['external'], $p_header['offset']); + + // ----- Write the 42 bytes of the header in the zip file + fputs($this->zip_fd, $v_binary_data, 46); + + // ----- Write the variable fields + if (strlen($p_header['stored_filename']) != 0) + { + fputs($this->zip_fd, $p_header['stored_filename'], strlen($p_header['stored_filename'])); + } + if ($p_header['extra_len'] != 0) + { + fputs($this->zip_fd, $p_header['extra'], $p_header['extra_len']); + } + if ($p_header['comment_len'] != 0) + { + fputs($this->zip_fd, $p_header['comment'], $p_header['comment_len']); + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privWriteCentralHeader() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privWriteCentralHeader($p_nb_entries, $p_size, $p_offset, $p_comment) + { + $v_result=1; + + // ----- Packed data + $v_binary_data = pack("VvvvvVVv", 0x06054b50, 0, 0, $p_nb_entries, + $p_nb_entries, $p_size, + $p_offset, strlen($p_comment)); + + // ----- Write the 22 bytes of the header in the zip file + fputs($this->zip_fd, $v_binary_data, 22); + + // ----- Write the variable fields + if (strlen($p_comment) != 0) + { + fputs($this->zip_fd, $p_comment, strlen($p_comment)); + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privList() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privList(&$p_list) + { + $v_result=1; + + // ----- Magic quotes trick + $this->privDisableMagicQuotes(); + + // ----- Open the zip file + if (($this->zip_fd = @fopen($this->zipname, 'rb')) == 0) + { + // ----- Magic quotes trick + $this->privSwapBackMagicQuotes(); + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \''.$this->zipname.'\' in binary read mode'); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Read the central directory informations + $v_central_dir = array(); + if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) + { + $this->privSwapBackMagicQuotes(); + return $v_result; + } + + // ----- Go to beginning of Central Dir + @rewind($this->zip_fd); + if (@fseek($this->zip_fd, $v_central_dir['offset'])) + { + $this->privSwapBackMagicQuotes(); + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Read each entry + for ($i=0; $i<$v_central_dir['entries']; $i++) + { + // ----- Read the file header + if (($v_result = $this->privReadCentralFileHeader($v_header)) != 1) + { + $this->privSwapBackMagicQuotes(); + return $v_result; + } + $v_header['index'] = $i; + + // ----- Get the only interesting attributes + $this->privConvertHeader2FileInfo($v_header, $p_list[$i]); + unset($v_header); + } + + // ----- Close the zip file + $this->privCloseFd(); + + // ----- Magic quotes trick + $this->privSwapBackMagicQuotes(); + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privConvertHeader2FileInfo() + // Description : + // This function takes the file informations from the central directory + // entries and extract the interesting parameters that will be given back. + // The resulting file infos are set in the array $p_info + // $p_info['filename'] : Filename with full path. Given by user (add), + // extracted in the filesystem (extract). + // $p_info['stored_filename'] : Stored filename in the archive. + // $p_info['size'] = Size of the file. + // $p_info['compressed_size'] = Compressed size of the file. + // $p_info['mtime'] = Last modification date of the file. + // $p_info['comment'] = Comment associated with the file. + // $p_info['folder'] = true/false : indicates if the entry is a folder or not. + // $p_info['status'] = status of the action on the file. + // $p_info['crc'] = CRC of the file content. + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privConvertHeader2FileInfo($p_header, &$p_info) + { + $v_result=1; + + // ----- Get the interesting attributes + $v_temp_path = PclZipUtilPathReduction($p_header['filename']); + $p_info['filename'] = $v_temp_path; + $v_temp_path = PclZipUtilPathReduction($p_header['stored_filename']); + $p_info['stored_filename'] = $v_temp_path; + $p_info['size'] = $p_header['size']; + $p_info['compressed_size'] = $p_header['compressed_size']; + $p_info['mtime'] = $p_header['mtime']; + $p_info['comment'] = $p_header['comment']; + $p_info['folder'] = (($p_header['external']&0x00000010)==0x00000010); + $p_info['index'] = $p_header['index']; + $p_info['status'] = $p_header['status']; + $p_info['crc'] = $p_header['crc']; + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privExtractByRule() + // Description : + // Extract a file or directory depending of rules (by index, by name, ...) + // Parameters : + // $p_file_list : An array where will be placed the properties of each + // extracted file + // $p_path : Path to add while writing the extracted files + // $p_remove_path : Path to remove (from the file memorized path) while writing the + // extracted files. If the path does not match the file path, + // the file is extracted with its memorized path. + // $p_remove_path does not apply to 'list' mode. + // $p_path and $p_remove_path are commulative. + // Return Values : + // 1 on success,0 or less on error (see error code list) + // -------------------------------------------------------------------------------- + function privExtractByRule(&$p_file_list, $p_path, $p_remove_path, $p_remove_all_path, &$p_options) + { + $v_result=1; + + // ----- Magic quotes trick + $this->privDisableMagicQuotes(); + + // ----- Check the path + if ( ($p_path == "") + || ( (substr($p_path, 0, 1) != "/") + && (substr($p_path, 0, 3) != "../") + && (substr($p_path,1,2)!=":/"))) + $p_path = "./".$p_path; + + // ----- Reduce the path last (and duplicated) '/' + if (($p_path != "./") && ($p_path != "/")) + { + // ----- Look for the path end '/' + while (substr($p_path, -1) == "/") + { + $p_path = substr($p_path, 0, strlen($p_path)-1); + } + } + + // ----- Look for path to remove format (should end by /) + if (($p_remove_path != "") && (substr($p_remove_path, -1) != '/')) + { + $p_remove_path .= '/'; + } + $p_remove_path_size = strlen($p_remove_path); + + // ----- Open the zip file + if (($v_result = $this->privOpenFd('rb')) != 1) + { + $this->privSwapBackMagicQuotes(); + return $v_result; + } + + // ----- Read the central directory informations + $v_central_dir = array(); + if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) + { + // ----- Close the zip file + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + + return $v_result; + } + + // ----- Start at beginning of Central Dir + $v_pos_entry = $v_central_dir['offset']; + + // ----- Read each entry + $j_start = 0; + for ($i=0, $v_nb_extracted=0; $i<$v_central_dir['entries']; $i++) + { + + // ----- Read next Central dir entry + @rewind($this->zip_fd); + if (@fseek($this->zip_fd, $v_pos_entry)) + { + // ----- Close the zip file + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Read the file header + $v_header = array(); + if (($v_result = $this->privReadCentralFileHeader($v_header)) != 1) + { + // ----- Close the zip file + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + + return $v_result; + } + + // ----- Store the index + $v_header['index'] = $i; + + // ----- Store the file position + $v_pos_entry = ftell($this->zip_fd); + + // ----- Look for the specific extract rules + $v_extract = false; + + // ----- Look for extract by name rule + if ( (isset($p_options[PCLZIP_OPT_BY_NAME])) + && ($p_options[PCLZIP_OPT_BY_NAME] != 0)) { + + // ----- Look if the filename is in the list + for ($j=0; ($j strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) + && (substr($v_header['stored_filename'], 0, strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) == $p_options[PCLZIP_OPT_BY_NAME][$j])) { + $v_extract = true; + } + } + // ----- Look for a filename + elseif ($v_header['stored_filename'] == $p_options[PCLZIP_OPT_BY_NAME][$j]) { + $v_extract = true; + } + } + } + + // ----- Look for extract by ereg rule + // ereg() is deprecated with PHP 5.3 + /* + else if ( (isset($p_options[PCLZIP_OPT_BY_EREG])) + && ($p_options[PCLZIP_OPT_BY_EREG] != "")) { + + if (ereg($p_options[PCLZIP_OPT_BY_EREG], $v_header['stored_filename'])) { + $v_extract = true; + } + } + */ + + // ----- Look for extract by preg rule + else if ( (isset($p_options[PCLZIP_OPT_BY_PREG])) + && ($p_options[PCLZIP_OPT_BY_PREG] != "")) { + + if (preg_match($p_options[PCLZIP_OPT_BY_PREG], $v_header['stored_filename'])) { + $v_extract = true; + } + } + + // ----- Look for extract by index rule + else if ( (isset($p_options[PCLZIP_OPT_BY_INDEX])) + && ($p_options[PCLZIP_OPT_BY_INDEX] != 0)) { + + // ----- Look if the index is in the list + for ($j=$j_start; ($j=$p_options[PCLZIP_OPT_BY_INDEX][$j]['start']) && ($i<=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end'])) { + $v_extract = true; + } + if ($i>=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end']) { + $j_start = $j+1; + } + + if ($p_options[PCLZIP_OPT_BY_INDEX][$j]['start']>$i) { + break; + } + } + } + + // ----- Look for no rule, which means extract all the archive + else { + $v_extract = true; + } + + // ----- Check compression method + if ( ($v_extract) + && ( ($v_header['compression'] != 8) + && ($v_header['compression'] != 0))) { + $v_header['status'] = 'unsupported_compression'; + + // ----- Look for PCLZIP_OPT_STOP_ON_ERROR + if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) + && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) { + + $this->privSwapBackMagicQuotes(); + + PclZip::privErrorLog(PCLZIP_ERR_UNSUPPORTED_COMPRESSION, + "Filename '".$v_header['stored_filename']."' is " + ."compressed by an unsupported compression " + ."method (".$v_header['compression'].") "); + + return PclZip::errorCode(); + } + } + + // ----- Check encrypted files + if (($v_extract) && (($v_header['flag'] & 1) == 1)) { + $v_header['status'] = 'unsupported_encryption'; + + // ----- Look for PCLZIP_OPT_STOP_ON_ERROR + if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) + && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) { + + $this->privSwapBackMagicQuotes(); + + PclZip::privErrorLog(PCLZIP_ERR_UNSUPPORTED_ENCRYPTION, + "Unsupported encryption for " + ." filename '".$v_header['stored_filename'] + ."'"); + + return PclZip::errorCode(); + } + } + + // ----- Look for real extraction + if (($v_extract) && ($v_header['status'] != 'ok')) { + $v_result = $this->privConvertHeader2FileInfo($v_header, + $p_file_list[$v_nb_extracted++]); + if ($v_result != 1) { + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + return $v_result; + } + + $v_extract = false; + } + + // ----- Look for real extraction + if ($v_extract) + { + + // ----- Go to the file position + @rewind($this->zip_fd); + if (@fseek($this->zip_fd, $v_header['offset'])) + { + // ----- Close the zip file + $this->privCloseFd(); + + $this->privSwapBackMagicQuotes(); + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Look for extraction as string + if ($p_options[PCLZIP_OPT_EXTRACT_AS_STRING]) { + + $v_string = ''; + + // ----- Extracting the file + $v_result1 = $this->privExtractFileAsString($v_header, $v_string, $p_options); + if ($v_result1 < 1) { + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + return $v_result1; + } + + // ----- Get the only interesting attributes + if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted])) != 1) + { + // ----- Close the zip file + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + + return $v_result; + } + + // ----- Set the file content + $p_file_list[$v_nb_extracted]['content'] = $v_string; + + // ----- Next extracted file + $v_nb_extracted++; + + // ----- Look for user callback abort + if ($v_result1 == 2) { + break; + } + } + // ----- Look for extraction in standard output + elseif ( (isset($p_options[PCLZIP_OPT_EXTRACT_IN_OUTPUT])) + && ($p_options[PCLZIP_OPT_EXTRACT_IN_OUTPUT])) { + // ----- Extracting the file in standard output + $v_result1 = $this->privExtractFileInOutput($v_header, $p_options); + if ($v_result1 < 1) { + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + return $v_result1; + } + + // ----- Get the only interesting attributes + if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted++])) != 1) { + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + return $v_result; + } + + // ----- Look for user callback abort + if ($v_result1 == 2) { + break; + } + } + // ----- Look for normal extraction + else { + // ----- Extracting the file + $v_result1 = $this->privExtractFile($v_header, + $p_path, $p_remove_path, + $p_remove_all_path, + $p_options); + if ($v_result1 < 1) { + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + return $v_result1; + } + + // ----- Get the only interesting attributes + if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted++])) != 1) + { + // ----- Close the zip file + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + + return $v_result; + } + + // ----- Look for user callback abort + if ($v_result1 == 2) { + break; + } + } + } + } + + // ----- Close the zip file + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privExtractFile() + // Description : + // Parameters : + // Return Values : + // + // 1 : ... ? + // PCLZIP_ERR_USER_ABORTED(2) : User ask for extraction stop in callback + // -------------------------------------------------------------------------------- + function privExtractFile(&$p_entry, $p_path, $p_remove_path, $p_remove_all_path, &$p_options) + { + $v_result=1; + + // ----- Read the file header + if (($v_result = $this->privReadFileHeader($v_header)) != 1) + { + // ----- Return + return $v_result; + } + + + // ----- Check that the file header is coherent with $p_entry info + if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) { + // TBC + } + + // ----- Look for all path to remove + if ($p_remove_all_path == true) { + // ----- Look for folder entry that not need to be extracted + if (($p_entry['external']&0x00000010)==0x00000010) { + + $p_entry['status'] = "filtered"; + + return $v_result; + } + + // ----- Get the basename of the path + $p_entry['filename'] = basename($p_entry['filename']); + } + + // ----- Look for path to remove + else if ($p_remove_path != "") + { + if (PclZipUtilPathInclusion($p_remove_path, $p_entry['filename']) == 2) + { + + // ----- Change the file status + $p_entry['status'] = "filtered"; + + // ----- Return + return $v_result; + } + + $p_remove_path_size = strlen($p_remove_path); + if (substr($p_entry['filename'], 0, $p_remove_path_size) == $p_remove_path) + { + + // ----- Remove the path + $p_entry['filename'] = substr($p_entry['filename'], $p_remove_path_size); + + } + } + + // ----- Add the path + if ($p_path != '') { + $p_entry['filename'] = $p_path."/".$p_entry['filename']; + } + + // ----- Check a base_dir_restriction + if (isset($p_options[PCLZIP_OPT_EXTRACT_DIR_RESTRICTION])) { + $v_inclusion + = PclZipUtilPathInclusion($p_options[PCLZIP_OPT_EXTRACT_DIR_RESTRICTION], + $p_entry['filename']); + if ($v_inclusion == 0) { + + PclZip::privErrorLog(PCLZIP_ERR_DIRECTORY_RESTRICTION, + "Filename '".$p_entry['filename']."' is " + ."outside PCLZIP_OPT_EXTRACT_DIR_RESTRICTION"); + + return PclZip::errorCode(); + } + } + + // ----- Look for pre-extract callback + if (isset($p_options[PCLZIP_CB_PRE_EXTRACT])) { + + // ----- Generate a local information + $v_local_header = array(); + $this->privConvertHeader2FileInfo($p_entry, $v_local_header); + + // ----- Call the callback + // Here I do not use call_user_func() because I need to send a reference to the + // header. +// eval('$v_result = '.$p_options[PCLZIP_CB_PRE_EXTRACT].'(PCLZIP_CB_PRE_EXTRACT, $v_local_header);'); + $v_result = $p_options[PCLZIP_CB_PRE_EXTRACT](PCLZIP_CB_PRE_EXTRACT, $v_local_header); + if ($v_result == 0) { + // ----- Change the file status + $p_entry['status'] = "skipped"; + $v_result = 1; + } + + // ----- Look for abort result + if ($v_result == 2) { + // ----- This status is internal and will be changed in 'skipped' + $p_entry['status'] = "aborted"; + $v_result = PCLZIP_ERR_USER_ABORTED; + } + + // ----- Update the informations + // Only some fields can be modified + $p_entry['filename'] = $v_local_header['filename']; + } + + + // ----- Look if extraction should be done + if ($p_entry['status'] == 'ok') { + + // ----- Look for specific actions while the file exist + if (file_exists($p_entry['filename'])) + { + + // ----- Look if file is a directory + if (is_dir($p_entry['filename'])) + { + + // ----- Change the file status + $p_entry['status'] = "already_a_directory"; + + // ----- Look for PCLZIP_OPT_STOP_ON_ERROR + // For historical reason first PclZip implementation does not stop + // when this kind of error occurs. + if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) + && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) { + + PclZip::privErrorLog(PCLZIP_ERR_ALREADY_A_DIRECTORY, + "Filename '".$p_entry['filename']."' is " + ."already used by an existing directory"); + + return PclZip::errorCode(); + } + } + // ----- Look if file is write protected + else if (!is_writeable($p_entry['filename'])) + { + + // ----- Change the file status + $p_entry['status'] = "write_protected"; + + // ----- Look for PCLZIP_OPT_STOP_ON_ERROR + // For historical reason first PclZip implementation does not stop + // when this kind of error occurs. + if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) + && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) { + + PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, + "Filename '".$p_entry['filename']."' exists " + ."and is write protected"); + + return PclZip::errorCode(); + } + } + + // ----- Look if the extracted file is older + else if (filemtime($p_entry['filename']) > $p_entry['mtime']) + { + // ----- Change the file status + if ( (isset($p_options[PCLZIP_OPT_REPLACE_NEWER])) + && ($p_options[PCLZIP_OPT_REPLACE_NEWER]===true)) { + } + else { + $p_entry['status'] = "newer_exist"; + + // ----- Look for PCLZIP_OPT_STOP_ON_ERROR + // For historical reason first PclZip implementation does not stop + // when this kind of error occurs. + if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) + && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) { + + PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, + "Newer version of '".$p_entry['filename']."' exists " + ."and option PCLZIP_OPT_REPLACE_NEWER is not selected"); + + return PclZip::errorCode(); + } + } + } + else { + } + } + + // ----- Check the directory availability and create it if necessary + else { + if ((($p_entry['external']&0x00000010)==0x00000010) || (substr($p_entry['filename'], -1) == '/')) + $v_dir_to_check = $p_entry['filename']; + else if (!strstr($p_entry['filename'], "/")) + $v_dir_to_check = ""; + else + $v_dir_to_check = dirname($p_entry['filename']); + + if (($v_result = $this->privDirCheck($v_dir_to_check, (($p_entry['external']&0x00000010)==0x00000010))) != 1) { - // ----- Look for skip - if ($v_skip > 0) { - while ($v_skip > 0) { - $v_result = '../'.$v_result; - $v_skip--; + // ----- Change the file status + $p_entry['status'] = "path_creation_fail"; + + // ----- Return + //return $v_result; + $v_result = 1; + } + } + } + + // ----- Look if extraction should be done + if ($p_entry['status'] == 'ok') { + + // ----- Do the extraction (if not a folder) + if (!(($p_entry['external']&0x00000010)==0x00000010)) + { + // ----- Look for not compressed file + if ($p_entry['compression'] == 0) { + + // ----- Opening destination file + if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0) + { + + // ----- Change the file status + $p_entry['status'] = "write_error"; + + // ----- Return + return $v_result; + } + + + // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks + $v_size = $p_entry['compressed_size']; + while ($v_size != 0) + { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @fread($this->zip_fd, $v_read_size); + /* Try to speed up the code + $v_binary_data = pack('a'.$v_read_size, $v_buffer); + @fwrite($v_dest_file, $v_binary_data, $v_read_size); + */ + @fwrite($v_dest_file, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + + // ----- Closing the destination file + fclose($v_dest_file); + + // ----- Change the file mtime + touch($p_entry['filename'], $p_entry['mtime']); + + + } + else { + // ----- TBC + // Need to be finished + if (($p_entry['flag'] & 1) == 1) { + PclZip::privErrorLog(PCLZIP_ERR_UNSUPPORTED_ENCRYPTION, 'File \''.$p_entry['filename'].'\' is encrypted. Encrypted files are not supported.'); + return PclZip::errorCode(); + } + + + // ----- Look for using temporary file to unzip + if ( (!isset($p_options[PCLZIP_OPT_TEMP_FILE_OFF])) + && (isset($p_options[PCLZIP_OPT_TEMP_FILE_ON]) + || (isset($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD]) + && ($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD] <= $p_entry['size'])) ) ) { + $v_result = $this->privExtractFileUsingTempFile($p_entry, $p_options); + if ($v_result < PCLZIP_ERR_NO_ERROR) { + return $v_result; + } + } + + // ----- Look for extract in memory + else { + + + // ----- Read the compressed file in a buffer (one shot) + $v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']); + + // ----- Decompress the file + $v_file_content = @gzinflate($v_buffer); + unset($v_buffer); + if ($v_file_content === FALSE) { + + // ----- Change the file status + // TBC + $p_entry['status'] = "error"; + + return $v_result; + } + + // ----- Opening destination file + if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0) { + + // ----- Change the file status + $p_entry['status'] = "write_error"; + + return $v_result; + } + + // ----- Write the uncompressed data + @fwrite($v_dest_file, $v_file_content, $p_entry['size']); + unset($v_file_content); + + // ----- Closing the destination file + @fclose($v_dest_file); + + } + + // ----- Change the file mtime + @touch($p_entry['filename'], $p_entry['mtime']); + } + + // ----- Look for chmod option + if (isset($p_options[PCLZIP_OPT_SET_CHMOD])) { + + // ----- Change the mode of the file + @chmod($p_entry['filename'], $p_options[PCLZIP_OPT_SET_CHMOD]); + } + + } + } + + // ----- Change abort status + if ($p_entry['status'] == "aborted") { + $p_entry['status'] = "skipped"; + } + + // ----- Look for post-extract callback + elseif (isset($p_options[PCLZIP_CB_POST_EXTRACT])) { + + // ----- Generate a local information + $v_local_header = array(); + $this->privConvertHeader2FileInfo($p_entry, $v_local_header); + + // ----- Call the callback + // Here I do not use call_user_func() because I need to send a reference to the + // header. +// eval('$v_result = '.$p_options[PCLZIP_CB_POST_EXTRACT].'(PCLZIP_CB_POST_EXTRACT, $v_local_header);'); + $v_result = $p_options[PCLZIP_CB_POST_EXTRACT](PCLZIP_CB_POST_EXTRACT, $v_local_header); + + // ----- Look for abort result + if ($v_result == 2) { + $v_result = PCLZIP_ERR_USER_ABORTED; + } + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privExtractFileUsingTempFile() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privExtractFileUsingTempFile(&$p_entry, &$p_options) + { + $v_result=1; + + // ----- Creates a temporary file + $v_gzip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.gz'; + if (($v_dest_file = @fopen($v_gzip_temp_name, "wb")) == 0) { + fclose($v_file); + PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary write mode'); + return PclZip::errorCode(); + } + + + // ----- Write gz file format header + $v_binary_data = pack('va1a1Va1a1', 0x8b1f, Chr($p_entry['compression']), Chr(0x00), time(), Chr(0x00), Chr(3)); + @fwrite($v_dest_file, $v_binary_data, 10); + + // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks + $v_size = $p_entry['compressed_size']; + while ($v_size != 0) + { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @fread($this->zip_fd, $v_read_size); + //$v_binary_data = pack('a'.$v_read_size, $v_buffer); + @fwrite($v_dest_file, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + + // ----- Write gz file format footer + $v_binary_data = pack('VV', $p_entry['crc'], $p_entry['size']); + @fwrite($v_dest_file, $v_binary_data, 8); + + // ----- Close the temporary file + @fclose($v_dest_file); + + // ----- Opening destination file + if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0) { + $p_entry['status'] = "write_error"; + return $v_result; + } + + // ----- Open the temporary gz file + if (($v_src_file = @gzopen($v_gzip_temp_name, 'rb')) == 0) { + @fclose($v_dest_file); + $p_entry['status'] = "read_error"; + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary read mode'); + return PclZip::errorCode(); + } + + + // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks + $v_size = $p_entry['size']; + while ($v_size != 0) { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @gzread($v_src_file, $v_read_size); + //$v_binary_data = pack('a'.$v_read_size, $v_buffer); + @fwrite($v_dest_file, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + @fclose($v_dest_file); + @gzclose($v_src_file); + + // ----- Delete the temporary file + @unlink($v_gzip_temp_name); + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privExtractFileInOutput() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privExtractFileInOutput(&$p_entry, &$p_options) + { + $v_result=1; + + // ----- Read the file header + if (($v_result = $this->privReadFileHeader($v_header)) != 1) { + return $v_result; + } + + + // ----- Check that the file header is coherent with $p_entry info + if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) { + // TBC + } + + // ----- Look for pre-extract callback + if (isset($p_options[PCLZIP_CB_PRE_EXTRACT])) { + + // ----- Generate a local information + $v_local_header = array(); + $this->privConvertHeader2FileInfo($p_entry, $v_local_header); + + // ----- Call the callback + // Here I do not use call_user_func() because I need to send a reference to the + // header. +// eval('$v_result = '.$p_options[PCLZIP_CB_PRE_EXTRACT].'(PCLZIP_CB_PRE_EXTRACT, $v_local_header);'); + $v_result = $p_options[PCLZIP_CB_PRE_EXTRACT](PCLZIP_CB_PRE_EXTRACT, $v_local_header); + if ($v_result == 0) { + // ----- Change the file status + $p_entry['status'] = "skipped"; + $v_result = 1; + } + + // ----- Look for abort result + if ($v_result == 2) { + // ----- This status is internal and will be changed in 'skipped' + $p_entry['status'] = "aborted"; + $v_result = PCLZIP_ERR_USER_ABORTED; + } + + // ----- Update the informations + // Only some fields can be modified + $p_entry['filename'] = $v_local_header['filename']; + } + + // ----- Trace + + // ----- Look if extraction should be done + if ($p_entry['status'] == 'ok') { + + // ----- Do the extraction (if not a folder) + if (!(($p_entry['external']&0x00000010)==0x00000010)) { + // ----- Look for not compressed file + if ($p_entry['compressed_size'] == $p_entry['size']) { + + // ----- Read the file in a buffer (one shot) + $v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']); + + // ----- Send the file to the output + echo $v_buffer; + unset($v_buffer); + } + else { + + // ----- Read the compressed file in a buffer (one shot) + $v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']); + + // ----- Decompress the file + $v_file_content = gzinflate($v_buffer); + unset($v_buffer); + + // ----- Send the file to the output + echo $v_file_content; + unset($v_file_content); + } + } + } + + // ----- Change abort status + if ($p_entry['status'] == "aborted") { + $p_entry['status'] = "skipped"; + } + + // ----- Look for post-extract callback + elseif (isset($p_options[PCLZIP_CB_POST_EXTRACT])) { + + // ----- Generate a local information + $v_local_header = array(); + $this->privConvertHeader2FileInfo($p_entry, $v_local_header); + + // ----- Call the callback + // Here I do not use call_user_func() because I need to send a reference to the + // header. +// eval('$v_result = '.$p_options[PCLZIP_CB_POST_EXTRACT].'(PCLZIP_CB_POST_EXTRACT, $v_local_header);'); + $v_result = $p_options[PCLZIP_CB_POST_EXTRACT](PCLZIP_CB_POST_EXTRACT, $v_local_header); + + // ----- Look for abort result + if ($v_result == 2) { + $v_result = PCLZIP_ERR_USER_ABORTED; + } + } + + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privExtractFileAsString() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privExtractFileAsString(&$p_entry, &$p_string, &$p_options) + { + $v_result=1; + + // ----- Read the file header + $v_header = array(); + if (($v_result = $this->privReadFileHeader($v_header)) != 1) + { + // ----- Return + return $v_result; + } + + + // ----- Check that the file header is coherent with $p_entry info + if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) { + // TBC + } + + // ----- Look for pre-extract callback + if (isset($p_options[PCLZIP_CB_PRE_EXTRACT])) { + + // ----- Generate a local information + $v_local_header = array(); + $this->privConvertHeader2FileInfo($p_entry, $v_local_header); + + // ----- Call the callback + // Here I do not use call_user_func() because I need to send a reference to the + // header. +// eval('$v_result = '.$p_options[PCLZIP_CB_PRE_EXTRACT].'(PCLZIP_CB_PRE_EXTRACT, $v_local_header);'); + $v_result = $p_options[PCLZIP_CB_PRE_EXTRACT](PCLZIP_CB_PRE_EXTRACT, $v_local_header); + if ($v_result == 0) { + // ----- Change the file status + $p_entry['status'] = "skipped"; + $v_result = 1; + } + + // ----- Look for abort result + if ($v_result == 2) { + // ----- This status is internal and will be changed in 'skipped' + $p_entry['status'] = "aborted"; + $v_result = PCLZIP_ERR_USER_ABORTED; + } + + // ----- Update the informations + // Only some fields can be modified + $p_entry['filename'] = $v_local_header['filename']; + } + + + // ----- Look if extraction should be done + if ($p_entry['status'] == 'ok') { + + // ----- Do the extraction (if not a folder) + if (!(($p_entry['external']&0x00000010)==0x00000010)) { + // ----- Look for not compressed file + // if ($p_entry['compressed_size'] == $p_entry['size']) + if ($p_entry['compression'] == 0) { + + // ----- Reading the file + $p_string = @fread($this->zip_fd, $p_entry['compressed_size']); + } + else { + + // ----- Reading the file + $v_data = @fread($this->zip_fd, $p_entry['compressed_size']); + + // ----- Decompress the file + if (($p_string = @gzinflate($v_data)) === FALSE) { + // TBC + } + } + + // ----- Trace + } + else { + // TBC : error : can not extract a folder in a string + } + + } + + // ----- Change abort status + if ($p_entry['status'] == "aborted") { + $p_entry['status'] = "skipped"; + } + + // ----- Look for post-extract callback + elseif (isset($p_options[PCLZIP_CB_POST_EXTRACT])) { + + // ----- Generate a local information + $v_local_header = array(); + $this->privConvertHeader2FileInfo($p_entry, $v_local_header); + + // ----- Swap the content to header + $v_local_header['content'] = $p_string; + $p_string = ''; + + // ----- Call the callback + // Here I do not use call_user_func() because I need to send a reference to the + // header. +// eval('$v_result = '.$p_options[PCLZIP_CB_POST_EXTRACT].'(PCLZIP_CB_POST_EXTRACT, $v_local_header);'); + $v_result = $p_options[PCLZIP_CB_POST_EXTRACT](PCLZIP_CB_POST_EXTRACT, $v_local_header); + + // ----- Swap back the content to header + $p_string = $v_local_header['content']; + unset($v_local_header['content']); + + // ----- Look for abort result + if ($v_result == 2) { + $v_result = PCLZIP_ERR_USER_ABORTED; + } + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privReadFileHeader() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privReadFileHeader(&$p_header) + { + $v_result=1; + + // ----- Read the 4 bytes signature + $v_binary_data = @fread($this->zip_fd, 4); + $v_data = unpack('Vid', $v_binary_data); + + // ----- Check signature + if ($v_data['id'] != 0x04034b50) + { + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Invalid archive structure'); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Read the first 42 bytes of the header + $v_binary_data = fread($this->zip_fd, 26); + + // ----- Look for invalid block size + if (strlen($v_binary_data) != 26) + { + $p_header['filename'] = ""; + $p_header['status'] = "invalid_header"; + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Invalid block size : ".strlen($v_binary_data)); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Extract the values + $v_data = unpack('vversion/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len', $v_binary_data); + + // ----- Get filename + $p_header['filename'] = fread($this->zip_fd, $v_data['filename_len']); + + // ----- Get extra_fields + if ($v_data['extra_len'] != 0) { + $p_header['extra'] = fread($this->zip_fd, $v_data['extra_len']); + } + else { + $p_header['extra'] = ''; + } + + // ----- Extract properties + $p_header['version_extracted'] = $v_data['version']; + $p_header['compression'] = $v_data['compression']; + $p_header['size'] = $v_data['size']; + $p_header['compressed_size'] = $v_data['compressed_size']; + $p_header['crc'] = $v_data['crc']; + $p_header['flag'] = $v_data['flag']; + $p_header['filename_len'] = $v_data['filename_len']; + + // ----- Recuperate date in UNIX format + $p_header['mdate'] = $v_data['mdate']; + $p_header['mtime'] = $v_data['mtime']; + if ($p_header['mdate'] && $p_header['mtime']) + { + // ----- Extract time + $v_hour = ($p_header['mtime'] & 0xF800) >> 11; + $v_minute = ($p_header['mtime'] & 0x07E0) >> 5; + $v_seconde = ($p_header['mtime'] & 0x001F)*2; + + // ----- Extract date + $v_year = (($p_header['mdate'] & 0xFE00) >> 9) + 1980; + $v_month = ($p_header['mdate'] & 0x01E0) >> 5; + $v_day = $p_header['mdate'] & 0x001F; + + // ----- Get UNIX date format + $p_header['mtime'] = @mktime($v_hour, $v_minute, $v_seconde, $v_month, $v_day, $v_year); + + } + else + { + $p_header['mtime'] = time(); + } + + // TBC + //for(reset($v_data); $key = key($v_data); next($v_data)) { + //} + + // ----- Set the stored filename + $p_header['stored_filename'] = $p_header['filename']; + + // ----- Set the status field + $p_header['status'] = "ok"; + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privReadCentralFileHeader() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privReadCentralFileHeader(&$p_header) + { + $v_result=1; + + // ----- Read the 4 bytes signature + $v_binary_data = @fread($this->zip_fd, 4); + $v_data = unpack('Vid', $v_binary_data); + + // ----- Check signature + if ($v_data['id'] != 0x02014b50) + { + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Invalid archive structure'); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Read the first 42 bytes of the header + $v_binary_data = fread($this->zip_fd, 42); + + // ----- Look for invalid block size + if (strlen($v_binary_data) != 42) + { + $p_header['filename'] = ""; + $p_header['status'] = "invalid_header"; + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Invalid block size : ".strlen($v_binary_data)); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Extract the values + $p_header = unpack('vversion/vversion_extracted/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len/vcomment_len/vdisk/vinternal/Vexternal/Voffset', $v_binary_data); + + // ----- Get filename + if ($p_header['filename_len'] != 0) + $p_header['filename'] = fread($this->zip_fd, $p_header['filename_len']); + else + $p_header['filename'] = ''; + + // ----- Get extra + if ($p_header['extra_len'] != 0) + $p_header['extra'] = fread($this->zip_fd, $p_header['extra_len']); + else + $p_header['extra'] = ''; + + // ----- Get comment + if ($p_header['comment_len'] != 0) + $p_header['comment'] = fread($this->zip_fd, $p_header['comment_len']); + else + $p_header['comment'] = ''; + + // ----- Extract properties + + // ----- Recuperate date in UNIX format + //if ($p_header['mdate'] && $p_header['mtime']) + // TBC : bug : this was ignoring time with 0/0/0 + if (1) + { + // ----- Extract time + $v_hour = ($p_header['mtime'] & 0xF800) >> 11; + $v_minute = ($p_header['mtime'] & 0x07E0) >> 5; + $v_seconde = ($p_header['mtime'] & 0x001F)*2; + + // ----- Extract date + $v_year = (($p_header['mdate'] & 0xFE00) >> 9) + 1980; + $v_month = ($p_header['mdate'] & 0x01E0) >> 5; + $v_day = $p_header['mdate'] & 0x001F; + + // ----- Get UNIX date format + $p_header['mtime'] = @mktime($v_hour, $v_minute, $v_seconde, $v_month, $v_day, $v_year); + + } + else + { + $p_header['mtime'] = time(); + } + + // ----- Set the stored filename + $p_header['stored_filename'] = $p_header['filename']; + + // ----- Set default status to ok + $p_header['status'] = 'ok'; + + // ----- Look if it is a directory + if (substr($p_header['filename'], -1) == '/') { + //$p_header['external'] = 0x41FF0010; + $p_header['external'] = 0x00000010; + } + + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privCheckFileHeaders() + // Description : + // Parameters : + // Return Values : + // 1 on success, + // 0 on error; + // -------------------------------------------------------------------------------- + function privCheckFileHeaders(&$p_local_header, &$p_central_header) + { + $v_result=1; + + // ----- Check the static values + // TBC + if ($p_local_header['filename'] != $p_central_header['filename']) { + } + if ($p_local_header['version_extracted'] != $p_central_header['version_extracted']) { + } + if ($p_local_header['flag'] != $p_central_header['flag']) { + } + if ($p_local_header['compression'] != $p_central_header['compression']) { + } + if ($p_local_header['mtime'] != $p_central_header['mtime']) { + } + if ($p_local_header['filename_len'] != $p_central_header['filename_len']) { + } + + // ----- Look for flag bit 3 + if (($p_local_header['flag'] & 8) == 8) { + $p_local_header['size'] = $p_central_header['size']; + $p_local_header['compressed_size'] = $p_central_header['compressed_size']; + $p_local_header['crc'] = $p_central_header['crc']; + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privReadEndCentralDir() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privReadEndCentralDir(&$p_central_dir) + { + $v_result=1; + + // ----- Go to the end of the zip file + $v_size = filesize($this->zipname); + @fseek($this->zip_fd, $v_size); + if (@ftell($this->zip_fd) != $v_size) + { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to go to the end of the archive \''.$this->zipname.'\''); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- First try : look if this is an archive with no commentaries (most of the time) + // in this case the end of central dir is at 22 bytes of the file end + $v_found = 0; + if ($v_size > 26) { + @fseek($this->zip_fd, $v_size-22); + if (($v_pos = @ftell($this->zip_fd)) != ($v_size-22)) + { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to seek back to the middle of the archive \''.$this->zipname.'\''); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Read for bytes + $v_binary_data = @fread($this->zip_fd, 4); + $v_data = @unpack('Vid', $v_binary_data); + + // ----- Check signature + if ($v_data['id'] == 0x06054b50) { + $v_found = 1; + } + + $v_pos = ftell($this->zip_fd); + } + + // ----- Go back to the maximum possible size of the Central Dir End Record + if (!$v_found) { + $v_maximum_size = 65557; // 0xFFFF + 22; + if ($v_maximum_size > $v_size) + $v_maximum_size = $v_size; + @fseek($this->zip_fd, $v_size-$v_maximum_size); + if (@ftell($this->zip_fd) != ($v_size-$v_maximum_size)) + { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to seek back to the middle of the archive \''.$this->zipname.'\''); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Read byte per byte in order to find the signature + $v_pos = ftell($this->zip_fd); + $v_bytes = 0x00000000; + while ($v_pos < $v_size) + { + // ----- Read a byte + $v_byte = @fread($this->zip_fd, 1); + + // ----- Add the byte + //$v_bytes = ($v_bytes << 8) | Ord($v_byte); + // Note we mask the old value down such that once shifted we can never end up with more than a 32bit number + // Otherwise on systems where we have 64bit integers the check below for the magic number will fail. + $v_bytes = ( ($v_bytes & 0xFFFFFF) << 8) | Ord($v_byte); + + // ----- Compare the bytes + if ($v_bytes == 0x504b0506) + { + $v_pos++; + break; + } + + $v_pos++; + } + + // ----- Look if not found end of central dir + if ($v_pos == $v_size) + { + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Unable to find End of Central Dir Record signature"); + + // ----- Return + return PclZip::errorCode(); + } + } + + // ----- Read the first 18 bytes of the header + $v_binary_data = fread($this->zip_fd, 18); + + // ----- Look for invalid block size + if (strlen($v_binary_data) != 18) + { + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Invalid End of Central Dir Record size : ".strlen($v_binary_data)); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Extract the values + $v_data = unpack('vdisk/vdisk_start/vdisk_entries/ventries/Vsize/Voffset/vcomment_size', $v_binary_data); + + // ----- Check the global size + if (($v_pos + $v_data['comment_size'] + 18) != $v_size) { + + // ----- Removed in release 2.2 see readme file + // The check of the file size is a little too strict. + // Some bugs where found when a zip is encrypted/decrypted with 'crypt'. + // While decrypted, zip has training 0 bytes + if (0) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, + 'The central dir is not at the end of the archive.' + .' Some trailing bytes exists after the archive.'); + + // ----- Return + return PclZip::errorCode(); + } + } + + // ----- Get comment + if ($v_data['comment_size'] != 0) { + $p_central_dir['comment'] = fread($this->zip_fd, $v_data['comment_size']); + } + else + $p_central_dir['comment'] = ''; + + $p_central_dir['entries'] = $v_data['entries']; + $p_central_dir['disk_entries'] = $v_data['disk_entries']; + $p_central_dir['offset'] = $v_data['offset']; + $p_central_dir['size'] = $v_data['size']; + $p_central_dir['disk'] = $v_data['disk']; + $p_central_dir['disk_start'] = $v_data['disk_start']; + + // TBC + //for(reset($p_central_dir); $key = key($p_central_dir); next($p_central_dir)) { + //} + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privDeleteByRule() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privDeleteByRule(&$p_result_list, &$p_options) + { + $v_result=1; + $v_list_detail = array(); + + // ----- Open the zip file + if (($v_result=$this->privOpenFd('rb')) != 1) + { + // ----- Return + return $v_result; + } + + // ----- Read the central directory informations + $v_central_dir = array(); + if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) + { + $this->privCloseFd(); + return $v_result; + } + + // ----- Go to beginning of File + @rewind($this->zip_fd); + + // ----- Scan all the files + // ----- Start at beginning of Central Dir + $v_pos_entry = $v_central_dir['offset']; + @rewind($this->zip_fd); + if (@fseek($this->zip_fd, $v_pos_entry)) + { + // ----- Close the zip file + $this->privCloseFd(); + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Read each entry + $v_header_list = array(); + $j_start = 0; + for ($i=0, $v_nb_extracted=0; $i<$v_central_dir['entries']; $i++) + { + + // ----- Read the file header + $v_header_list[$v_nb_extracted] = array(); + if (($v_result = $this->privReadCentralFileHeader($v_header_list[$v_nb_extracted])) != 1) + { + // ----- Close the zip file + $this->privCloseFd(); + + return $v_result; + } + + + // ----- Store the index + $v_header_list[$v_nb_extracted]['index'] = $i; + + // ----- Look for the specific extract rules + $v_found = false; + + // ----- Look for extract by name rule + if ( (isset($p_options[PCLZIP_OPT_BY_NAME])) + && ($p_options[PCLZIP_OPT_BY_NAME] != 0)) { + + // ----- Look if the filename is in the list + for ($j=0; ($j strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) + && (substr($v_header_list[$v_nb_extracted]['stored_filename'], 0, strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) == $p_options[PCLZIP_OPT_BY_NAME][$j])) { + $v_found = true; + } + elseif ( (($v_header_list[$v_nb_extracted]['external']&0x00000010)==0x00000010) /* Indicates a folder */ + && ($v_header_list[$v_nb_extracted]['stored_filename'].'/' == $p_options[PCLZIP_OPT_BY_NAME][$j])) { + $v_found = true; + } + } + // ----- Look for a filename + elseif ($v_header_list[$v_nb_extracted]['stored_filename'] == $p_options[PCLZIP_OPT_BY_NAME][$j]) { + $v_found = true; + } + } + } + + // ----- Look for extract by ereg rule + // ereg() is deprecated with PHP 5.3 + /* + else if ( (isset($p_options[PCLZIP_OPT_BY_EREG])) + && ($p_options[PCLZIP_OPT_BY_EREG] != "")) { + + if (ereg($p_options[PCLZIP_OPT_BY_EREG], $v_header_list[$v_nb_extracted]['stored_filename'])) { + $v_found = true; + } + } + */ + + // ----- Look for extract by preg rule + else if ( (isset($p_options[PCLZIP_OPT_BY_PREG])) + && ($p_options[PCLZIP_OPT_BY_PREG] != "")) { + + if (preg_match($p_options[PCLZIP_OPT_BY_PREG], $v_header_list[$v_nb_extracted]['stored_filename'])) { + $v_found = true; + } + } + + // ----- Look for extract by index rule + else if ( (isset($p_options[PCLZIP_OPT_BY_INDEX])) + && ($p_options[PCLZIP_OPT_BY_INDEX] != 0)) { + + // ----- Look if the index is in the list + for ($j=$j_start; ($j=$p_options[PCLZIP_OPT_BY_INDEX][$j]['start']) && ($i<=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end'])) { + $v_found = true; + } + if ($i>=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end']) { + $j_start = $j+1; + } + + if ($p_options[PCLZIP_OPT_BY_INDEX][$j]['start']>$i) { + break; + } + } + } + else { + $v_found = true; + } + + // ----- Look for deletion + if ($v_found) + { + unset($v_header_list[$v_nb_extracted]); + } + else + { + $v_nb_extracted++; + } + } + + // ----- Look if something need to be deleted + if ($v_nb_extracted > 0) { + + // ----- Creates a temporay file + $v_zip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.tmp'; + + // ----- Creates a temporary zip archive + $v_temp_zip = new PclZip($v_zip_temp_name); + + // ----- Open the temporary zip file in write mode + if (($v_result = $v_temp_zip->privOpenFd('wb')) != 1) { + $this->privCloseFd(); + + // ----- Return + return $v_result; + } + + // ----- Look which file need to be kept + for ($i=0; $izip_fd); + if (@fseek($this->zip_fd, $v_header_list[$i]['offset'])) { + // ----- Close the zip file + $this->privCloseFd(); + $v_temp_zip->privCloseFd(); + @unlink($v_zip_temp_name); + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Read the file header + $v_local_header = array(); + if (($v_result = $this->privReadFileHeader($v_local_header)) != 1) { + // ----- Close the zip file + $this->privCloseFd(); + $v_temp_zip->privCloseFd(); + @unlink($v_zip_temp_name); + + // ----- Return + return $v_result; + } + + // ----- Check that local file header is same as central file header + if ($this->privCheckFileHeaders($v_local_header, + $v_header_list[$i]) != 1) { + // TBC + } + unset($v_local_header); + + // ----- Write the file header + if (($v_result = $v_temp_zip->privWriteFileHeader($v_header_list[$i])) != 1) { + // ----- Close the zip file + $this->privCloseFd(); + $v_temp_zip->privCloseFd(); + @unlink($v_zip_temp_name); + + // ----- Return + return $v_result; + } + + // ----- Read/write the data block + if (($v_result = PclZipUtilCopyBlock($this->zip_fd, $v_temp_zip->zip_fd, $v_header_list[$i]['compressed_size'])) != 1) { + // ----- Close the zip file + $this->privCloseFd(); + $v_temp_zip->privCloseFd(); + @unlink($v_zip_temp_name); + + // ----- Return + return $v_result; + } + } + + // ----- Store the offset of the central dir + $v_offset = @ftell($v_temp_zip->zip_fd); + + // ----- Re-Create the Central Dir files header + for ($i=0; $iprivWriteCentralFileHeader($v_header_list[$i])) != 1) { + $v_temp_zip->privCloseFd(); + $this->privCloseFd(); + @unlink($v_zip_temp_name); + + // ----- Return + return $v_result; + } + + // ----- Transform the header to a 'usable' info + $v_temp_zip->privConvertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]); + } + + + // ----- Zip file comment + $v_comment = ''; + if (isset($p_options[PCLZIP_OPT_COMMENT])) { + $v_comment = $p_options[PCLZIP_OPT_COMMENT]; + } + + // ----- Calculate the size of the central header + $v_size = @ftell($v_temp_zip->zip_fd)-$v_offset; + + // ----- Create the central dir footer + if (($v_result = $v_temp_zip->privWriteCentralHeader(sizeof($v_header_list), $v_size, $v_offset, $v_comment)) != 1) { + // ----- Reset the file list + unset($v_header_list); + $v_temp_zip->privCloseFd(); + $this->privCloseFd(); + @unlink($v_zip_temp_name); + + // ----- Return + return $v_result; + } + + // ----- Close + $v_temp_zip->privCloseFd(); + $this->privCloseFd(); + + // ----- Delete the zip file + // TBC : I should test the result ... + @unlink($this->zipname); + + // ----- Rename the temporary file + // TBC : I should test the result ... + //@rename($v_zip_temp_name, $this->zipname); + PclZipUtilRename($v_zip_temp_name, $this->zipname); + + // ----- Destroy the temporary archive + unset($v_temp_zip); + } + + // ----- Remove every files : reset the file + else if ($v_central_dir['entries'] != 0) { + $this->privCloseFd(); + + if (($v_result = $this->privOpenFd('wb')) != 1) { + return $v_result; + } + + if (($v_result = $this->privWriteCentralHeader(0, 0, 0, '')) != 1) { + return $v_result; + } + + $this->privCloseFd(); + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privDirCheck() + // Description : + // Check if a directory exists, if not it creates it and all the parents directory + // which may be useful. + // Parameters : + // $p_dir : Directory path to check. + // Return Values : + // 1 : OK + // -1 : Unable to create directory + // -------------------------------------------------------------------------------- + function privDirCheck($p_dir, $p_is_dir=false) + { + $v_result = 1; + + + // ----- Remove the final '/' + if (($p_is_dir) && (substr($p_dir, -1)=='/')) + { + $p_dir = substr($p_dir, 0, strlen($p_dir)-1); + } + + // ----- Check the directory availability + if ((is_dir($p_dir)) || ($p_dir == "")) + { + return 1; + } + + // ----- Extract parent directory + $p_parent_dir = dirname($p_dir); + + // ----- Just a check + if ($p_parent_dir != $p_dir) + { + // ----- Look for parent directory + if ($p_parent_dir != "") + { + if (($v_result = $this->privDirCheck($p_parent_dir)) != 1) + { + return $v_result; + } + } + } + + // ----- Create the directory + if (!@mkdir($p_dir, 0777)) + { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_DIR_CREATE_FAIL, "Unable to create directory '$p_dir'"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privMerge() + // Description : + // If $p_archive_to_add does not exist, the function exit with a success result. + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privMerge(&$p_archive_to_add) + { + $v_result=1; + + // ----- Look if the archive_to_add exists + if (!is_file($p_archive_to_add->zipname)) + { + + // ----- Nothing to merge, so merge is a success + $v_result = 1; + + // ----- Return + return $v_result; + } + + // ----- Look if the archive exists + if (!is_file($this->zipname)) + { + + // ----- Do a duplicate + $v_result = $this->privDuplicate($p_archive_to_add->zipname); + + // ----- Return + return $v_result; + } + + // ----- Open the zip file + if (($v_result=$this->privOpenFd('rb')) != 1) + { + // ----- Return + return $v_result; + } + + // ----- Read the central directory informations + $v_central_dir = array(); + if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) + { + $this->privCloseFd(); + return $v_result; + } + + // ----- Go to beginning of File + @rewind($this->zip_fd); + + // ----- Open the archive_to_add file + if (($v_result=$p_archive_to_add->privOpenFd('rb')) != 1) + { + $this->privCloseFd(); + + // ----- Return + return $v_result; + } + + // ----- Read the central directory informations + $v_central_dir_to_add = array(); + if (($v_result = $p_archive_to_add->privReadEndCentralDir($v_central_dir_to_add)) != 1) + { + $this->privCloseFd(); + $p_archive_to_add->privCloseFd(); + + return $v_result; + } + + // ----- Go to beginning of File + @rewind($p_archive_to_add->zip_fd); + + // ----- Creates a temporay file + $v_zip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.tmp'; + + // ----- Open the temporary file in write mode + if (($v_zip_temp_fd = @fopen($v_zip_temp_name, 'wb')) == 0) + { + $this->privCloseFd(); + $p_archive_to_add->privCloseFd(); + + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_zip_temp_name.'\' in binary write mode'); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Copy the files from the archive to the temporary file + // TBC : Here I should better append the file and go back to erase the central dir + $v_size = $v_central_dir['offset']; + while ($v_size != 0) + { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = fread($this->zip_fd, $v_read_size); + @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + + // ----- Copy the files from the archive_to_add into the temporary file + $v_size = $v_central_dir_to_add['offset']; + while ($v_size != 0) + { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = fread($p_archive_to_add->zip_fd, $v_read_size); + @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + + // ----- Store the offset of the central dir + $v_offset = @ftell($v_zip_temp_fd); + + // ----- Copy the block of file headers from the old archive + $v_size = $v_central_dir['size']; + while ($v_size != 0) + { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @fread($this->zip_fd, $v_read_size); + @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + + // ----- Copy the block of file headers from the archive_to_add + $v_size = $v_central_dir_to_add['size']; + while ($v_size != 0) + { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @fread($p_archive_to_add->zip_fd, $v_read_size); + @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + + // ----- Merge the file comments + $v_comment = $v_central_dir['comment'].' '.$v_central_dir_to_add['comment']; + + // ----- Calculate the size of the (new) central header + $v_size = @ftell($v_zip_temp_fd)-$v_offset; + + // ----- Swap the file descriptor + // Here is a trick : I swap the temporary fd with the zip fd, in order to use + // the following methods on the temporary fil and not the real archive fd + $v_swap = $this->zip_fd; + $this->zip_fd = $v_zip_temp_fd; + $v_zip_temp_fd = $v_swap; + + // ----- Create the central dir footer + if (($v_result = $this->privWriteCentralHeader($v_central_dir['entries']+$v_central_dir_to_add['entries'], $v_size, $v_offset, $v_comment)) != 1) + { + $this->privCloseFd(); + $p_archive_to_add->privCloseFd(); + @fclose($v_zip_temp_fd); + $this->zip_fd = null; + + // ----- Reset the file list + unset($v_header_list); + + // ----- Return + return $v_result; + } + + // ----- Swap back the file descriptor + $v_swap = $this->zip_fd; + $this->zip_fd = $v_zip_temp_fd; + $v_zip_temp_fd = $v_swap; + + // ----- Close + $this->privCloseFd(); + $p_archive_to_add->privCloseFd(); + + // ----- Close the temporary file + @fclose($v_zip_temp_fd); + + // ----- Delete the zip file + // TBC : I should test the result ... + @unlink($this->zipname); + + // ----- Rename the temporary file + // TBC : I should test the result ... + //@rename($v_zip_temp_name, $this->zipname); + PclZipUtilRename($v_zip_temp_name, $this->zipname); + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privDuplicate() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privDuplicate($p_archive_filename) + { + $v_result=1; + + // ----- Look if the $p_archive_filename exists + if (!is_file($p_archive_filename)) + { + + // ----- Nothing to duplicate, so duplicate is a success. + $v_result = 1; + + // ----- Return + return $v_result; + } + + // ----- Open the zip file + if (($v_result=$this->privOpenFd('wb')) != 1) + { + // ----- Return + return $v_result; + } + + // ----- Open the temporary file in write mode + if (($v_zip_temp_fd = @fopen($p_archive_filename, 'rb')) == 0) + { + $this->privCloseFd(); + + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive file \''.$p_archive_filename.'\' in binary write mode'); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Copy the files from the archive to the temporary file + // TBC : Here I should better append the file and go back to erase the central dir + $v_size = filesize($p_archive_filename); + while ($v_size != 0) + { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = fread($v_zip_temp_fd, $v_read_size); + @fwrite($this->zip_fd, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + + // ----- Close + $this->privCloseFd(); + + // ----- Close the temporary file + @fclose($v_zip_temp_fd); + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privErrorLog() + // Description : + // Parameters : + // -------------------------------------------------------------------------------- + function privErrorLog($p_error_code=0, $p_error_string='') + { + if (PCLZIP_ERROR_EXTERNAL == 1) { + PclError($p_error_code, $p_error_string); + } + else { + $this->error_code = $p_error_code; + $this->error_string = $p_error_string; } } -} + // -------------------------------------------------------------------------------- -// ----- Return -return $v_result; -} -// -------------------------------------------------------------------------------- - -// -------------------------------------------------------------------------------- -// Function : PclZipUtilPathInclusion() -// Description : -// This function indicates if the path $p_path is under the $p_dir tree. Or, -// said in an other way, if the file or sub-dir $p_path is inside the dir -// $p_dir. -// The function indicates also if the path is exactly the same as the dir. -// This function supports path with duplicated '/' like '//', but does not -// support '.' or '..' statements. -// Parameters : -// Return Values : -// 0 if $p_path is not inside directory $p_dir -// 1 if $p_path is inside directory $p_dir -// 2 if $p_path is exactly the same as $p_dir -// -------------------------------------------------------------------------------- -function PclZipUtilPathInclusion($p_dir, $p_path) -{ -$v_result = 1; - -// ----- Look for path beginning by ./ -if (($p_dir == '.') - || ((strlen($p_dir) >=2) && (substr($p_dir, 0, 2) == './'))) { - $p_dir = PclZipUtilTranslateWinPath(getcwd(), false).'/'.substr($p_dir, 1); -} -if (($p_path == '.') - || ((strlen($p_path) >=2) && (substr($p_path, 0, 2) == './'))) { - $p_path = PclZipUtilTranslateWinPath(getcwd(), false).'/'.substr($p_path, 1); -} - -// ----- Explode dir and path by directory separator -$v_list_dir = explode("/", $p_dir); -$v_list_dir_size = sizeof($v_list_dir); -$v_list_path = explode("/", $p_path); -$v_list_path_size = sizeof($v_list_path); - -// ----- Study directories paths -$i = 0; -$j = 0; -while (($i < $v_list_dir_size) && ($j < $v_list_path_size) && ($v_result)) { - - // ----- Look for empty dir (path reduction) - if ($v_list_dir[$i] == '') { - $i++; - continue; - } - if ($v_list_path[$j] == '') { - $j++; - continue; - } - - // ----- Compare the items - if (($v_list_dir[$i] != $v_list_path[$j]) && ($v_list_dir[$i] != '') && ($v_list_path[$j] != '')) { - $v_result = 0; - } - - // ----- Next items - $i++; - $j++; -} - -// ----- Look if everything seems to be the same -if ($v_result) { - // ----- Skip all the empty items - while (($j < $v_list_path_size) && ($v_list_path[$j] == '')) $j++; - while (($i < $v_list_dir_size) && ($v_list_dir[$i] == '')) $i++; - - if (($i >= $v_list_dir_size) && ($j >= $v_list_path_size)) { - // ----- There are exactly the same - $v_result = 2; - } - else if ($i < $v_list_dir_size) { - // ----- The path is shorter than the dir - $v_result = 0; - } -} - -// ----- Return -return $v_result; -} -// -------------------------------------------------------------------------------- - -// -------------------------------------------------------------------------------- -// Function : PclZipUtilCopyBlock() -// Description : -// Parameters : -// $p_mode : read/write compression mode -// 0 : src & dest normal -// 1 : src gzip, dest normal -// 2 : src normal, dest gzip -// 3 : src & dest gzip -// Return Values : -// -------------------------------------------------------------------------------- -function PclZipUtilCopyBlock($p_src, $p_dest, $p_size, $p_mode=0) -{ -$v_result = 1; - -if ($p_mode==0) -{ - while ($p_size != 0) + // -------------------------------------------------------------------------------- + // Function : privErrorReset() + // Description : + // Parameters : + // -------------------------------------------------------------------------------- + function privErrorReset() { - $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE); - $v_buffer = @fread($p_src, $v_read_size); - @fwrite($p_dest, $v_buffer, $v_read_size); - $p_size -= $v_read_size; - } -} -else if ($p_mode==1) -{ - while ($p_size != 0) - { - $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE); - $v_buffer = @gzread($p_src, $v_read_size); - @fwrite($p_dest, $v_buffer, $v_read_size); - $p_size -= $v_read_size; - } -} -else if ($p_mode==2) -{ - while ($p_size != 0) - { - $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE); - $v_buffer = @fread($p_src, $v_read_size); - @gzwrite($p_dest, $v_buffer, $v_read_size); - $p_size -= $v_read_size; - } -} -else if ($p_mode==3) -{ - while ($p_size != 0) - { - $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE); - $v_buffer = @gzread($p_src, $v_read_size); - @gzwrite($p_dest, $v_buffer, $v_read_size); - $p_size -= $v_read_size; - } -} - -// ----- Return -return $v_result; -} -// -------------------------------------------------------------------------------- - -// -------------------------------------------------------------------------------- -// Function : PclZipUtilRename() -// Description : -// This function tries to do a simple rename() function. If it fails, it -// tries to copy the $p_src file in a new $p_dest file and then unlink the -// first one. -// Parameters : -// $p_src : Old filename -// $p_dest : New filename -// Return Values : -// 1 on success, 0 on failure. -// -------------------------------------------------------------------------------- -function PclZipUtilRename($p_src, $p_dest) -{ -$v_result = 1; - -// ----- Try to rename the files -if (!@rename($p_src, $p_dest)) { - - // ----- Try to copy & unlink the src - if (!@copy($p_src, $p_dest)) { - $v_result = 0; - } - else if (!@unlink($p_src)) { - $v_result = 0; - } -} - -// ----- Return -return $v_result; -} -// -------------------------------------------------------------------------------- - -// -------------------------------------------------------------------------------- -// Function : PclZipUtilOptionText() -// Description : -// Translate option value in text. Mainly for debug purpose. -// Parameters : -// $p_option : the option value. -// Return Values : -// The option text value. -// -------------------------------------------------------------------------------- -function PclZipUtilOptionText($p_option) -{ - -$v_list = get_defined_constants(); -for (reset($v_list); $v_key = key($v_list); next($v_list)) { - $v_prefix = substr($v_key, 0, 10); - if ((($v_prefix == 'PCLZIP_OPT') - || ($v_prefix == 'PCLZIP_CB_') - || ($v_prefix == 'PCLZIP_ATT')) - && ($v_list[$v_key] == $p_option)) { - return $v_key; + if (PCLZIP_ERROR_EXTERNAL == 1) { + PclErrorReset(); + } + else { + $this->error_code = 0; + $this->error_string = ''; } -} - -$v_result = 'Unknown'; - -return $v_result; -} -// -------------------------------------------------------------------------------- - -// -------------------------------------------------------------------------------- -// Function : PclZipUtilTranslateWinPath() -// Description : -// Translate windows path by replacing '\' by '/' and optionally removing -// drive letter. -// Parameters : -// $p_path : path to translate. -// $p_remove_disk_letter : true | false -// Return Values : -// The path translated. -// -------------------------------------------------------------------------------- -function PclZipUtilTranslateWinPath($p_path, $p_remove_disk_letter=true) -{ -if (stristr(php_uname(), 'windows')) { - // ----- Look for potential disk letter - if (($p_remove_disk_letter) && (($v_position = strpos($p_path, ':')) != false)) { - $p_path = substr($p_path, $v_position+1); } - // ----- Change potential windows directory separator - if ((strpos($p_path, '\\') > 0) || (substr($p_path, 0,1) == '\\')) { - $p_path = strtr($p_path, '\\', '/'); + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privDisableMagicQuotes() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privDisableMagicQuotes() + { + $v_result=1; + + // ----- Look if function exists + if ( (!function_exists("get_magic_quotes_runtime")) + || (!function_exists("set_magic_quotes_runtime"))) { + return $v_result; + } + + // ----- Look if already done + if ($this->magic_quotes_status != -1) { + return $v_result; + } + + // ----- Get and memorize the magic_quote value + $this->magic_quotes_status = @get_magic_quotes_runtime(); + + // ----- Disable magic_quotes + if ($this->magic_quotes_status == 1) { + @set_magic_quotes_runtime(0); + } + + // ----- Return + return $v_result; } -} -return $p_path; -} -// -------------------------------------------------------------------------------- \ No newline at end of file + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privSwapBackMagicQuotes() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privSwapBackMagicQuotes() + { + $v_result=1; + + // ----- Look if function exists + if ( (!function_exists("get_magic_quotes_runtime")) + || (!function_exists("set_magic_quotes_runtime"))) { + return $v_result; + } + + // ----- Look if something to do + if ($this->magic_quotes_status != -1) { + return $v_result; + } + + // ----- Swap back magic_quotes + if ($this->magic_quotes_status == 1) { + @set_magic_quotes_runtime($this->magic_quotes_status); + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + } + // End of class + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : PclZipUtilPathReduction() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function PclZipUtilPathReduction($p_dir) + { + $v_result = ""; + + // ----- Look for not empty path + if ($p_dir != "") { + // ----- Explode path by directory names + $v_list = explode("/", $p_dir); + + // ----- Study directories from last to first + $v_skip = 0; + for ($i=sizeof($v_list)-1; $i>=0; $i--) { + // ----- Look for current path + if ($v_list[$i] == ".") { + // ----- Ignore this directory + // Should be the first $i=0, but no check is done + } + else if ($v_list[$i] == "..") { + $v_skip++; + } + else if ($v_list[$i] == "") { + // ----- First '/' i.e. root slash + if ($i == 0) { + $v_result = "/".$v_result; + if ($v_skip > 0) { + // ----- It is an invalid path, so the path is not modified + // TBC + $v_result = $p_dir; + $v_skip = 0; + } + } + // ----- Last '/' i.e. indicates a directory + else if ($i == (sizeof($v_list)-1)) { + $v_result = $v_list[$i]; + } + // ----- Double '/' inside the path + else { + // ----- Ignore only the double '//' in path, + // but not the first and last '/' + } + } + else { + // ----- Look for item to skip + if ($v_skip > 0) { + $v_skip--; + } + else { + $v_result = $v_list[$i].($i!=(sizeof($v_list)-1)?"/".$v_result:""); + } + } + } + + // ----- Look for skip + if ($v_skip > 0) { + while ($v_skip > 0) { + $v_result = '../'.$v_result; + $v_skip--; + } + } + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : PclZipUtilPathInclusion() + // Description : + // This function indicates if the path $p_path is under the $p_dir tree. Or, + // said in an other way, if the file or sub-dir $p_path is inside the dir + // $p_dir. + // The function indicates also if the path is exactly the same as the dir. + // This function supports path with duplicated '/' like '//', but does not + // support '.' or '..' statements. + // Parameters : + // Return Values : + // 0 if $p_path is not inside directory $p_dir + // 1 if $p_path is inside directory $p_dir + // 2 if $p_path is exactly the same as $p_dir + // -------------------------------------------------------------------------------- + function PclZipUtilPathInclusion($p_dir, $p_path) + { + $v_result = 1; + + // ----- Look for path beginning by ./ + if ( ($p_dir == '.') + || ((strlen($p_dir) >=2) && (substr($p_dir, 0, 2) == './'))) { + $p_dir = PclZipUtilTranslateWinPath(getcwd(), FALSE).'/'.substr($p_dir, 1); + } + if ( ($p_path == '.') + || ((strlen($p_path) >=2) && (substr($p_path, 0, 2) == './'))) { + $p_path = PclZipUtilTranslateWinPath(getcwd(), FALSE).'/'.substr($p_path, 1); + } + + // ----- Explode dir and path by directory separator + $v_list_dir = explode("/", $p_dir); + $v_list_dir_size = sizeof($v_list_dir); + $v_list_path = explode("/", $p_path); + $v_list_path_size = sizeof($v_list_path); + + // ----- Study directories paths + $i = 0; + $j = 0; + while (($i < $v_list_dir_size) && ($j < $v_list_path_size) && ($v_result)) { + + // ----- Look for empty dir (path reduction) + if ($v_list_dir[$i] == '') { + $i++; + continue; + } + if ($v_list_path[$j] == '') { + $j++; + continue; + } + + // ----- Compare the items + if (($v_list_dir[$i] != $v_list_path[$j]) && ($v_list_dir[$i] != '') && ( $v_list_path[$j] != '')) { + $v_result = 0; + } + + // ----- Next items + $i++; + $j++; + } + + // ----- Look if everything seems to be the same + if ($v_result) { + // ----- Skip all the empty items + while (($j < $v_list_path_size) && ($v_list_path[$j] == '')) $j++; + while (($i < $v_list_dir_size) && ($v_list_dir[$i] == '')) $i++; + + if (($i >= $v_list_dir_size) && ($j >= $v_list_path_size)) { + // ----- There are exactly the same + $v_result = 2; + } + else if ($i < $v_list_dir_size) { + // ----- The path is shorter than the dir + $v_result = 0; + } + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : PclZipUtilCopyBlock() + // Description : + // Parameters : + // $p_mode : read/write compression mode + // 0 : src & dest normal + // 1 : src gzip, dest normal + // 2 : src normal, dest gzip + // 3 : src & dest gzip + // Return Values : + // -------------------------------------------------------------------------------- + function PclZipUtilCopyBlock($p_src, $p_dest, $p_size, $p_mode=0) + { + $v_result = 1; + + if ($p_mode==0) + { + while ($p_size != 0) + { + $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @fread($p_src, $v_read_size); + @fwrite($p_dest, $v_buffer, $v_read_size); + $p_size -= $v_read_size; + } + } + else if ($p_mode==1) + { + while ($p_size != 0) + { + $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @gzread($p_src, $v_read_size); + @fwrite($p_dest, $v_buffer, $v_read_size); + $p_size -= $v_read_size; + } + } + else if ($p_mode==2) + { + while ($p_size != 0) + { + $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @fread($p_src, $v_read_size); + @gzwrite($p_dest, $v_buffer, $v_read_size); + $p_size -= $v_read_size; + } + } + else if ($p_mode==3) + { + while ($p_size != 0) + { + $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @gzread($p_src, $v_read_size); + @gzwrite($p_dest, $v_buffer, $v_read_size); + $p_size -= $v_read_size; + } + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : PclZipUtilRename() + // Description : + // This function tries to do a simple rename() function. If it fails, it + // tries to copy the $p_src file in a new $p_dest file and then unlink the + // first one. + // Parameters : + // $p_src : Old filename + // $p_dest : New filename + // Return Values : + // 1 on success, 0 on failure. + // -------------------------------------------------------------------------------- + function PclZipUtilRename($p_src, $p_dest) + { + $v_result = 1; + + // ----- Try to rename the files + if (!@rename($p_src, $p_dest)) { + + // ----- Try to copy & unlink the src + if (!@copy($p_src, $p_dest)) { + $v_result = 0; + } + else if (!@unlink($p_src)) { + $v_result = 0; + } + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : PclZipUtilOptionText() + // Description : + // Translate option value in text. Mainly for debug purpose. + // Parameters : + // $p_option : the option value. + // Return Values : + // The option text value. + // -------------------------------------------------------------------------------- + function PclZipUtilOptionText($p_option) + { + + $v_list = get_defined_constants(); + for (reset($v_list); $v_key = key($v_list); next($v_list)) { + $v_prefix = substr($v_key, 0, 10); + if (( ($v_prefix == 'PCLZIP_OPT') + || ($v_prefix == 'PCLZIP_CB_') + || ($v_prefix == 'PCLZIP_ATT')) + && ($v_list[$v_key] == $p_option)) { + return $v_key; + } + } + + $v_result = 'Unknown'; + + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : PclZipUtilTranslateWinPath() + // Description : + // Translate windows path by replacing '\' by '/' and optionally removing + // drive letter. + // Parameters : + // $p_path : path to translate. + // $p_remove_disk_letter : true | false + // Return Values : + // The path translated. + // -------------------------------------------------------------------------------- + function PclZipUtilTranslateWinPath($p_path, $p_remove_disk_letter=true) + { + if (stristr(php_uname(), 'windows')) { + // ----- Look for potential disk letter + if (($p_remove_disk_letter) && (($v_position = strpos($p_path, ':')) != false)) { + $p_path = substr($p_path, $v_position+1); + } + // ----- Change potential windows directory separator + if ((strpos($p_path, '\\') > 0) || (substr($p_path, 0,1) == '\\')) { + $p_path = strtr($p_path, '\\', '/'); + } + } + return $p_path; + } + // -------------------------------------------------------------------------------- + \ No newline at end of file diff --git a/Classes/PHPExcel/Worksheet/HeaderFooter.php b/Classes/PHPExcel/Worksheet/HeaderFooter.php index f4ba2a42..394baf7c 100644 --- a/Classes/PHPExcel/Worksheet/HeaderFooter.php +++ b/Classes/PHPExcel/Worksheet/HeaderFooter.php @@ -15,7 +15,7 @@ * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software + * License along with this library; if not,241 write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * @category PHPExcel @@ -237,7 +237,7 @@ class PHPExcel_Worksheet_HeaderFooter * @return string */ public function getEvenHeader() - + { return $this->_evenHeader; }