3 * Helper class for building multipart/form-data request body
\r
9 * Copyright (c) 2008-2012, Alexey Borzov <avb@php.net>
\r
10 * All rights reserved.
\r
12 * Redistribution and use in source and binary forms, with or without
\r
13 * modification, are permitted provided that the following conditions
\r
16 * * Redistributions of source code must retain the above copyright
\r
17 * notice, this list of conditions and the following disclaimer.
\r
18 * * Redistributions in binary form must reproduce the above copyright
\r
19 * notice, this list of conditions and the following disclaimer in the
\r
20 * documentation and/or other materials provided with the distribution.
\r
21 * * The names of the authors may not be used to endorse or promote products
\r
22 * derived from this software without specific prior written permission.
\r
24 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
\r
25 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
\r
26 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
\r
27 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
\r
28 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
\r
29 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
\r
30 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
\r
31 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
\r
32 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
\r
33 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
\r
34 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
\r
37 * @package HTTP_Request2
\r
38 * @author Alexey Borzov <avb@php.net>
\r
39 * @license http://opensource.org/licenses/bsd-license.php New BSD License
\r
40 * @version SVN: $Id: MultipartBody.php 324415 2012-03-21 10:50:50Z avb $
\r
41 * @link http://pear.php.net/package/HTTP_Request2
\r
45 * Class for building multipart/form-data request body
\r
47 * The class helps to reduce memory consumption by streaming large file uploads
\r
48 * from disk, it also allows monitoring of upload progress (see request #7630)
\r
51 * @package HTTP_Request2
\r
52 * @author Alexey Borzov <avb@php.net>
\r
53 * @license http://opensource.org/licenses/bsd-license.php New BSD License
\r
54 * @version Release: 2.1.1
\r
55 * @link http://pear.php.net/package/HTTP_Request2
\r
56 * @link http://tools.ietf.org/html/rfc1867
\r
58 class HTTP_Request2_MultipartBody
\r
67 * Form parameters added via {@link HTTP_Request2::addPostParameter()}
\r
70 private $_params = array();
\r
73 * File uploads added via {@link HTTP_Request2::addUpload()}
\r
76 private $_uploads = array();
\r
79 * Header for parts with parameters
\r
82 private $_headerParam = "--%s\r\nContent-Disposition: form-data; name=\"%s\"\r\n\r\n";
\r
85 * Header for parts with uploads
\r
88 private $_headerUpload = "--%s\r\nContent-Disposition: form-data; name=\"%s\"; filename=\"%s\"\r\nContent-Type: %s\r\n\r\n";
\r
91 * Current position in parameter and upload arrays
\r
93 * First number is index of "current" part, second number is position within
\r
98 private $_pos = array(0, 0);
\r
102 * Constructor. Sets the arrays with POST data.
\r
104 * @param array $params values of form fields set via
\r
105 * {@link HTTP_Request2::addPostParameter()}
\r
106 * @param array $uploads file uploads set via
\r
107 * {@link HTTP_Request2::addUpload()}
\r
108 * @param bool $useBrackets whether to append brackets to array variable names
\r
110 public function __construct(array $params, array $uploads, $useBrackets = true)
\r
112 $this->_params = self::_flattenArray('', $params, $useBrackets);
\r
113 foreach ($uploads as $fieldName => $f) {
\r
114 if (!is_array($f['fp'])) {
\r
115 $this->_uploads[] = $f + array('name' => $fieldName);
\r
117 for ($i = 0; $i < count($f['fp']); $i++) {
\r
119 'name' => ($useBrackets? $fieldName . '[' . $i . ']': $fieldName)
\r
121 foreach (array('fp', 'filename', 'size', 'type') as $key) {
\r
122 $upload[$key] = $f[$key][$i];
\r
124 $this->_uploads[] = $upload;
\r
131 * Returns the length of the body to use in Content-Length header
\r
135 public function getLength()
\r
137 $boundaryLength = strlen($this->getBoundary());
\r
138 $headerParamLength = strlen($this->_headerParam) - 4 + $boundaryLength;
\r
139 $headerUploadLength = strlen($this->_headerUpload) - 8 + $boundaryLength;
\r
140 $length = $boundaryLength + 6;
\r
141 foreach ($this->_params as $p) {
\r
142 $length += $headerParamLength + strlen($p[0]) + strlen($p[1]) + 2;
\r
144 foreach ($this->_uploads as $u) {
\r
145 $length += $headerUploadLength + strlen($u['name']) + strlen($u['type']) +
\r
146 strlen($u['filename']) + $u['size'] + 2;
\r
152 * Returns the boundary to use in Content-Type header
\r
156 public function getBoundary()
\r
158 if (empty($this->_boundary)) {
\r
159 $this->_boundary = '--' . md5('PEAR-HTTP_Request2-' . microtime());
\r
161 return $this->_boundary;
\r
165 * Returns next chunk of request body
\r
167 * @param integer $length Number of bytes to read
\r
169 * @return string Up to $length bytes of data, empty string if at end
\r
171 public function read($length)
\r
174 $boundary = $this->getBoundary();
\r
175 $paramCount = count($this->_params);
\r
176 $uploadCount = count($this->_uploads);
\r
177 while ($length > 0 && $this->_pos[0] <= $paramCount + $uploadCount) {
\r
178 $oldLength = $length;
\r
179 if ($this->_pos[0] < $paramCount) {
\r
181 $this->_headerParam, $boundary, $this->_params[$this->_pos[0]][0]
\r
182 ) . $this->_params[$this->_pos[0]][1] . "\r\n";
\r
183 $ret .= substr($param, $this->_pos[1], $length);
\r
184 $length -= min(strlen($param) - $this->_pos[1], $length);
\r
186 } elseif ($this->_pos[0] < $paramCount + $uploadCount) {
\r
187 $pos = $this->_pos[0] - $paramCount;
\r
189 $this->_headerUpload, $boundary, $this->_uploads[$pos]['name'],
\r
190 $this->_uploads[$pos]['filename'], $this->_uploads[$pos]['type']
\r
192 if ($this->_pos[1] < strlen($header)) {
\r
193 $ret .= substr($header, $this->_pos[1], $length);
\r
194 $length -= min(strlen($header) - $this->_pos[1], $length);
\r
196 $filePos = max(0, $this->_pos[1] - strlen($header));
\r
197 if ($length > 0 && $filePos < $this->_uploads[$pos]['size']) {
\r
198 $ret .= fread($this->_uploads[$pos]['fp'], $length);
\r
199 $length -= min($length, $this->_uploads[$pos]['size'] - $filePos);
\r
202 $start = $this->_pos[1] + ($oldLength - $length) -
\r
203 strlen($header) - $this->_uploads[$pos]['size'];
\r
204 $ret .= substr("\r\n", $start, $length);
\r
205 $length -= min(2 - $start, $length);
\r
209 $closing = '--' . $boundary . "--\r\n";
\r
210 $ret .= substr($closing, $this->_pos[1], $length);
\r
211 $length -= min(strlen($closing) - $this->_pos[1], $length);
\r
214 $this->_pos = array($this->_pos[0] + 1, 0);
\r
216 $this->_pos[1] += $oldLength;
\r
223 * Sets the current position to the start of the body
\r
225 * This allows reusing the same body in another request
\r
227 public function rewind()
\r
229 $this->_pos = array(0, 0);
\r
230 foreach ($this->_uploads as $u) {
\r
236 * Returns the body as string
\r
238 * Note that it reads all file uploads into memory so it is a good idea not
\r
239 * to use this method with large file uploads and rely on read() instead.
\r
243 public function __toString()
\r
246 return $this->read($this->getLength());
\r
251 * Helper function to change the (probably multidimensional) associative array
\r
252 * into the simple one.
\r
254 * @param string $name name for item
\r
255 * @param mixed $values item's values
\r
256 * @param bool $useBrackets whether to append [] to array variables' names
\r
258 * @return array array with the following items: array('item name', 'item value');
\r
260 private static function _flattenArray($name, $values, $useBrackets)
\r
262 if (!is_array($values)) {
\r
263 return array(array($name, $values));
\r
266 foreach ($values as $k => $v) {
\r
267 if (empty($name)) {
\r
269 } elseif ($useBrackets) {
\r
270 $newName = $name . '[' . $k . ']';
\r
274 $ret = array_merge($ret, self::_flattenArray($newName, $v, $useBrackets));
\r