[TASK] Update PEAR packages
[Packages/TYPO3.CMS.git] / typo3 / contrib / pear / HTTP / Request2 / MultipartBody.php
1 <?php
2 /**
3 * Helper class for building multipart/form-data request body
4 *
5 * PHP version 5
6 *
7 * LICENSE:
8 *
9 * Copyright (c) 2008-2012, Alexey Borzov <avb@php.net>
10 * All rights reserved.
11 *
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
14 * are met:
15 *
16 * * Redistributions of source code must retain the above copyright
17 * notice, this list of conditions and the following disclaimer.
18 * * Redistributions in binary form must reproduce the above copyright
19 * notice, this list of conditions and the following disclaimer in the
20 * documentation and/or other materials provided with the distribution.
21 * * The names of the authors may not be used to endorse or promote products
22 * derived from this software without specific prior written permission.
23 *
24 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
25 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
26 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
27 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
28 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
30 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
31 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
32 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
33 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
34 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35 *
36 * @category HTTP
37 * @package HTTP_Request2
38 * @author Alexey Borzov <avb@php.net>
39 * @license http://opensource.org/licenses/bsd-license.php New BSD License
40 * @version SVN: $Id: MultipartBody.php 324415 2012-03-21 10:50:50Z avb $
41 * @link http://pear.php.net/package/HTTP_Request2
42 */
43
44 /**
45 * Class for building multipart/form-data request body
46 *
47 * The class helps to reduce memory consumption by streaming large file uploads
48 * from disk, it also allows monitoring of upload progress (see request #7630)
49 *
50 * @category HTTP
51 * @package HTTP_Request2
52 * @author Alexey Borzov <avb@php.net>
53 * @license http://opensource.org/licenses/bsd-license.php New BSD License
54 * @version Release: 2.1.1
55 * @link http://pear.php.net/package/HTTP_Request2
56 * @link http://tools.ietf.org/html/rfc1867
57 */
58 class HTTP_Request2_MultipartBody
59 {
60 /**
61 * MIME boundary
62 * @var string
63 */
64 private $_boundary;
65
66 /**
67 * Form parameters added via {@link HTTP_Request2::addPostParameter()}
68 * @var array
69 */
70 private $_params = array();
71
72 /**
73 * File uploads added via {@link HTTP_Request2::addUpload()}
74 * @var array
75 */
76 private $_uploads = array();
77
78 /**
79 * Header for parts with parameters
80 * @var string
81 */
82 private $_headerParam = "--%s\r\nContent-Disposition: form-data; name=\"%s\"\r\n\r\n";
83
84 /**
85 * Header for parts with uploads
86 * @var string
87 */
88 private $_headerUpload = "--%s\r\nContent-Disposition: form-data; name=\"%s\"; filename=\"%s\"\r\nContent-Type: %s\r\n\r\n";
89
90 /**
91 * Current position in parameter and upload arrays
92 *
93 * First number is index of "current" part, second number is position within
94 * "current" part
95 *
96 * @var array
97 */
98 private $_pos = array(0, 0);
99
100
101 /**
102 * Constructor. Sets the arrays with POST data.
103 *
104 * @param array $params values of form fields set via
105 * {@link HTTP_Request2::addPostParameter()}
106 * @param array $uploads file uploads set via
107 * {@link HTTP_Request2::addUpload()}
108 * @param bool $useBrackets whether to append brackets to array variable names
109 */
110 public function __construct(array $params, array $uploads, $useBrackets = true)
111 {
112 $this->_params = self::_flattenArray('', $params, $useBrackets);
113 foreach ($uploads as $fieldName => $f) {
114 if (!is_array($f['fp'])) {
115 $this->_uploads[] = $f + array('name' => $fieldName);
116 } else {
117 for ($i = 0; $i < count($f['fp']); $i++) {
118 $upload = array(
119 'name' => ($useBrackets? $fieldName . '[' . $i . ']': $fieldName)
120 );
121 foreach (array('fp', 'filename', 'size', 'type') as $key) {
122 $upload[$key] = $f[$key][$i];
123 }
124 $this->_uploads[] = $upload;
125 }
126 }
127 }
128 }
129
130 /**
131 * Returns the length of the body to use in Content-Length header
132 *
133 * @return integer
134 */
135 public function getLength()
136 {
137 $boundaryLength = strlen($this->getBoundary());
138 $headerParamLength = strlen($this->_headerParam) - 4 + $boundaryLength;
139 $headerUploadLength = strlen($this->_headerUpload) - 8 + $boundaryLength;
140 $length = $boundaryLength + 6;
141 foreach ($this->_params as $p) {
142 $length += $headerParamLength + strlen($p[0]) + strlen($p[1]) + 2;
143 }
144 foreach ($this->_uploads as $u) {
145 $length += $headerUploadLength + strlen($u['name']) + strlen($u['type']) +
146 strlen($u['filename']) + $u['size'] + 2;
147 }
148 return $length;
149 }
150
151 /**
152 * Returns the boundary to use in Content-Type header
153 *
154 * @return string
155 */
156 public function getBoundary()
157 {
158 if (empty($this->_boundary)) {
159 $this->_boundary = '--' . md5('PEAR-HTTP_Request2-' . microtime());
160 }
161 return $this->_boundary;
162 }
163
164 /**
165 * Returns next chunk of request body
166 *
167 * @param integer $length Number of bytes to read
168 *
169 * @return string Up to $length bytes of data, empty string if at end
170 */
171 public function read($length)
172 {
173 $ret = '';
174 $boundary = $this->getBoundary();
175 $paramCount = count($this->_params);
176 $uploadCount = count($this->_uploads);
177 while ($length > 0 && $this->_pos[0] <= $paramCount + $uploadCount) {
178 $oldLength = $length;
179 if ($this->_pos[0] < $paramCount) {
180 $param = sprintf(
181 $this->_headerParam, $boundary, $this->_params[$this->_pos[0]][0]
182 ) . $this->_params[$this->_pos[0]][1] . "\r\n";
183 $ret .= substr($param, $this->_pos[1], $length);
184 $length -= min(strlen($param) - $this->_pos[1], $length);
185
186 } elseif ($this->_pos[0] < $paramCount + $uploadCount) {
187 $pos = $this->_pos[0] - $paramCount;
188 $header = sprintf(
189 $this->_headerUpload, $boundary, $this->_uploads[$pos]['name'],
190 $this->_uploads[$pos]['filename'], $this->_uploads[$pos]['type']
191 );
192 if ($this->_pos[1] < strlen($header)) {
193 $ret .= substr($header, $this->_pos[1], $length);
194 $length -= min(strlen($header) - $this->_pos[1], $length);
195 }
196 $filePos = max(0, $this->_pos[1] - strlen($header));
197 if ($length > 0 && $filePos < $this->_uploads[$pos]['size']) {
198 $ret .= fread($this->_uploads[$pos]['fp'], $length);
199 $length -= min($length, $this->_uploads[$pos]['size'] - $filePos);
200 }
201 if ($length > 0) {
202 $start = $this->_pos[1] + ($oldLength - $length) -
203 strlen($header) - $this->_uploads[$pos]['size'];
204 $ret .= substr("\r\n", $start, $length);
205 $length -= min(2 - $start, $length);
206 }
207
208 } else {
209 $closing = '--' . $boundary . "--\r\n";
210 $ret .= substr($closing, $this->_pos[1], $length);
211 $length -= min(strlen($closing) - $this->_pos[1], $length);
212 }
213 if ($length > 0) {
214 $this->_pos = array($this->_pos[0] + 1, 0);
215 } else {
216 $this->_pos[1] += $oldLength;
217 }
218 }
219 return $ret;
220 }
221
222 /**
223 * Sets the current position to the start of the body
224 *
225 * This allows reusing the same body in another request
226 */
227 public function rewind()
228 {
229 $this->_pos = array(0, 0);
230 foreach ($this->_uploads as $u) {
231 rewind($u['fp']);
232 }
233 }
234
235 /**
236 * Returns the body as string
237 *
238 * Note that it reads all file uploads into memory so it is a good idea not
239 * to use this method with large file uploads and rely on read() instead.
240 *
241 * @return string
242 */
243 public function __toString()
244 {
245 $this->rewind();
246 return $this->read($this->getLength());
247 }
248
249
250 /**
251 * Helper function to change the (probably multidimensional) associative array
252 * into the simple one.
253 *
254 * @param string $name name for item
255 * @param mixed $values item's values
256 * @param bool $useBrackets whether to append [] to array variables' names
257 *
258 * @return array array with the following items: array('item name', 'item value');
259 */
260 private static function _flattenArray($name, $values, $useBrackets)
261 {
262 if (!is_array($values)) {
263 return array(array($name, $values));
264 } else {
265 $ret = array();
266 foreach ($values as $k => $v) {
267 if (empty($name)) {
268 $newName = $k;
269 } elseif ($useBrackets) {
270 $newName = $name . '[' . $k . ']';
271 } else {
272 $newName = $name;
273 }
274 $ret = array_merge($ret, self::_flattenArray($newName, $v, $useBrackets));
275 }
276 return $ret;
277 }
278 }
279 }
280 ?>