3 * Helper class for building multipart/form-data request body
\r
9 * Copyright (c) 2008, 2009, 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 CVS: $Id: MultipartBody.php 287306 2009-08-14 15:22:52Z 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 * @version Release: 0.4.1
\r
54 * @link http://tools.ietf.org/html/rfc1867
\r
56 class HTTP_Request2_MultipartBody
\r
65 * Form parameters added via {@link HTTP_Request2::addPostParameter()}
\r
68 private $_params = array();
\r
71 * File uploads added via {@link HTTP_Request2::addUpload()}
\r
74 private $_uploads = array();
\r
77 * Header for parts with parameters
\r
80 private $_headerParam = "--%s\r\nContent-Disposition: form-data; name=\"%s\"\r\n\r\n";
\r
83 * Header for parts with uploads
\r
86 private $_headerUpload = "--%s\r\nContent-Disposition: form-data; name=\"%s\"; filename=\"%s\"\r\nContent-Type: %s\r\n\r\n";
\r
89 * Current position in parameter and upload arrays
\r
91 * First number is index of "current" part, second number is position within
\r
96 private $_pos = array(0, 0);
\r
100 * Constructor. Sets the arrays with POST data.
\r
102 * @param array values of form fields set via {@link HTTP_Request2::addPostParameter()}
\r
103 * @param array file uploads set via {@link HTTP_Request2::addUpload()}
\r
104 * @param bool whether to append brackets to array variable names
\r
106 public function __construct(array $params, array $uploads, $useBrackets = true)
\r
108 $this->_params = self::_flattenArray('', $params, $useBrackets);
\r
109 foreach ($uploads as $fieldName => $f) {
\r
110 if (!is_array($f['fp'])) {
\r
111 $this->_uploads[] = $f + array('name' => $fieldName);
\r
113 for ($i = 0; $i < count($f['fp']); $i++) {
\r
115 'name' => ($useBrackets? $fieldName . '[' . $i . ']': $fieldName)
\r
117 foreach (array('fp', 'filename', 'size', 'type') as $key) {
\r
118 $upload[$key] = $f[$key][$i];
\r
120 $this->_uploads[] = $upload;
\r
127 * Returns the length of the body to use in Content-Length header
\r
131 public function getLength()
\r
133 $boundaryLength = strlen($this->getBoundary());
\r
134 $headerParamLength = strlen($this->_headerParam) - 4 + $boundaryLength;
\r
135 $headerUploadLength = strlen($this->_headerUpload) - 8 + $boundaryLength;
\r
136 $length = $boundaryLength + 6;
\r
137 foreach ($this->_params as $p) {
\r
138 $length += $headerParamLength + strlen($p[0]) + strlen($p[1]) + 2;
\r
140 foreach ($this->_uploads as $u) {
\r
141 $length += $headerUploadLength + strlen($u['name']) + strlen($u['type']) +
\r
142 strlen($u['filename']) + $u['size'] + 2;
\r
148 * Returns the boundary to use in Content-Type header
\r
152 public function getBoundary()
\r
154 if (empty($this->_boundary)) {
\r
155 $this->_boundary = '--' . md5('PEAR-HTTP_Request2-' . microtime());
\r
157 return $this->_boundary;
\r
161 * Returns next chunk of request body
\r
163 * @param integer Amount of bytes to read
\r
164 * @return string Up to $length bytes of data, empty string if at end
\r
166 public function read($length)
\r
169 $boundary = $this->getBoundary();
\r
170 $paramCount = count($this->_params);
\r
171 $uploadCount = count($this->_uploads);
\r
172 while ($length > 0 && $this->_pos[0] <= $paramCount + $uploadCount) {
\r
173 $oldLength = $length;
\r
174 if ($this->_pos[0] < $paramCount) {
\r
175 $param = sprintf($this->_headerParam, $boundary,
\r
176 $this->_params[$this->_pos[0]][0]) .
\r
177 $this->_params[$this->_pos[0]][1] . "\r\n";
\r
178 $ret .= substr($param, $this->_pos[1], $length);
\r
179 $length -= min(strlen($param) - $this->_pos[1], $length);
\r
181 } elseif ($this->_pos[0] < $paramCount + $uploadCount) {
\r
182 $pos = $this->_pos[0] - $paramCount;
\r
183 $header = sprintf($this->_headerUpload, $boundary,
\r
184 $this->_uploads[$pos]['name'],
\r
185 $this->_uploads[$pos]['filename'],
\r
186 $this->_uploads[$pos]['type']);
\r
187 if ($this->_pos[1] < strlen($header)) {
\r
188 $ret .= substr($header, $this->_pos[1], $length);
\r
189 $length -= min(strlen($header) - $this->_pos[1], $length);
\r
191 $filePos = max(0, $this->_pos[1] - strlen($header));
\r
192 if ($length > 0 && $filePos < $this->_uploads[$pos]['size']) {
\r
193 $ret .= fread($this->_uploads[$pos]['fp'], $length);
\r
194 $length -= min($length, $this->_uploads[$pos]['size'] - $filePos);
\r
197 $start = $this->_pos[1] + ($oldLength - $length) -
\r
198 strlen($header) - $this->_uploads[$pos]['size'];
\r
199 $ret .= substr("\r\n", $start, $length);
\r
200 $length -= min(2 - $start, $length);
\r
204 $closing = '--' . $boundary . "--\r\n";
\r
205 $ret .= substr($closing, $this->_pos[1], $length);
\r
206 $length -= min(strlen($closing) - $this->_pos[1], $length);
\r
209 $this->_pos = array($this->_pos[0] + 1, 0);
\r
211 $this->_pos[1] += $oldLength;
\r
218 * Sets the current position to the start of the body
\r
220 * This allows reusing the same body in another request
\r
222 public function rewind()
\r
224 $this->_pos = array(0, 0);
\r
225 foreach ($this->_uploads as $u) {
\r
231 * Returns the body as string
\r
233 * Note that it reads all file uploads into memory so it is a good idea not
\r
234 * to use this method with large file uploads and rely on read() instead.
\r
238 public function __toString()
\r
241 return $this->read($this->getLength());
\r
246 * Helper function to change the (probably multidimensional) associative array
\r
247 * into the simple one.
\r
249 * @param string name for item
\r
250 * @param mixed item's values
\r
251 * @param bool whether to append [] to array variables' names
\r
252 * @return array array with the following items: array('item name', 'item value');
\r
254 private static function _flattenArray($name, $values, $useBrackets)
\r
256 if (!is_array($values)) {
\r
257 return array(array($name, $values));
\r
260 foreach ($values as $k => $v) {
\r
261 if (empty($name)) {
\r
263 } elseif ($useBrackets) {
\r
264 $newName = $name . '[' . $k . ']';
\r
268 $ret = array_merge($ret, self::_flattenArray($newName, $v, $useBrackets));
\r