]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - extlib/HTTP/Request2/MultipartBody.php
53e0c1b9eabfdda4a26ffeb1e9032317e5657593
[quix0rs-gnu-social.git] / extlib / HTTP / Request2 / MultipartBody.php
1 <?php\r
2 /**\r
3  * Helper class for building multipart/form-data request body\r
4  *\r
5  * PHP version 5\r
6  *\r
7  * LICENSE:\r
8  *\r
9  * Copyright (c) 2008-2012, Alexey Borzov <avb@php.net>\r
10  * All rights reserved.\r
11  *\r
12  * Redistribution and use in source and binary forms, with or without\r
13  * modification, are permitted provided that the following conditions\r
14  * are met:\r
15  *\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
23  *\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
35  *\r
36  * @category HTTP\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
42  */\r
43 \r
44 /**\r
45  * Class for building multipart/form-data request body\r
46  *\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
49  *\r
50  * @category HTTP\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
57  */\r
58 class HTTP_Request2_MultipartBody\r
59 {\r
60     /**\r
61      * MIME boundary\r
62      * @var  string\r
63      */\r
64     private $_boundary;\r
65 \r
66     /**\r
67      * Form parameters added via {@link HTTP_Request2::addPostParameter()}\r
68      * @var  array\r
69      */\r
70     private $_params = array();\r
71 \r
72     /**\r
73      * File uploads added via {@link HTTP_Request2::addUpload()}\r
74      * @var  array\r
75      */\r
76     private $_uploads = array();\r
77 \r
78     /**\r
79      * Header for parts with parameters\r
80      * @var  string\r
81      */\r
82     private $_headerParam = "--%s\r\nContent-Disposition: form-data; name=\"%s\"\r\n\r\n";\r
83 \r
84     /**\r
85      * Header for parts with uploads\r
86      * @var  string\r
87      */\r
88     private $_headerUpload = "--%s\r\nContent-Disposition: form-data; name=\"%s\"; filename=\"%s\"\r\nContent-Type: %s\r\n\r\n";\r
89 \r
90     /**\r
91      * Current position in parameter and upload arrays\r
92      *\r
93      * First number is index of "current" part, second number is position within\r
94      * "current" part\r
95      *\r
96      * @var  array\r
97      */\r
98     private $_pos = array(0, 0);\r
99 \r
100 \r
101     /**\r
102      * Constructor. Sets the arrays with POST data.\r
103      *\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
109      */\r
110     public function __construct(array $params, array $uploads, $useBrackets = true)\r
111     {\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
116             } else {\r
117                 for ($i = 0; $i < count($f['fp']); $i++) {\r
118                     $upload = array(\r
119                         'name' => ($useBrackets? $fieldName . '[' . $i . ']': $fieldName)\r
120                     );\r
121                     foreach (array('fp', 'filename', 'size', 'type') as $key) {\r
122                         $upload[$key] = $f[$key][$i];\r
123                     }\r
124                     $this->_uploads[] = $upload;\r
125                 }\r
126             }\r
127         }\r
128     }\r
129 \r
130     /**\r
131      * Returns the length of the body to use in Content-Length header\r
132      *\r
133      * @return   integer\r
134      */\r
135     public function getLength()\r
136     {\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
143         }\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
147         }\r
148         return $length;\r
149     }\r
150 \r
151     /**\r
152      * Returns the boundary to use in Content-Type header\r
153      *\r
154      * @return   string\r
155      */\r
156     public function getBoundary()\r
157     {\r
158         if (empty($this->_boundary)) {\r
159             $this->_boundary = '--' . md5('PEAR-HTTP_Request2-' . microtime());\r
160         }\r
161         return $this->_boundary;\r
162     }\r
163 \r
164     /**\r
165      * Returns next chunk of request body\r
166      *\r
167      * @param integer $length Number of bytes to read\r
168      *\r
169      * @return   string  Up to $length bytes of data, empty string if at end\r
170      */\r
171     public function read($length)\r
172     {\r
173         $ret         = '';\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
180                 $param = sprintf(\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
185 \r
186             } elseif ($this->_pos[0] < $paramCount + $uploadCount) {\r
187                 $pos    = $this->_pos[0] - $paramCount;\r
188                 $header = sprintf(\r
189                     $this->_headerUpload, $boundary, $this->_uploads[$pos]['name'],\r
190                     $this->_uploads[$pos]['filename'], $this->_uploads[$pos]['type']\r
191                 );\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
195                 }\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
200                 }\r
201                 if ($length > 0) {\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
206                 }\r
207 \r
208             } else {\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
212             }\r
213             if ($length > 0) {\r
214                 $this->_pos     = array($this->_pos[0] + 1, 0);\r
215             } else {\r
216                 $this->_pos[1] += $oldLength;\r
217             }\r
218         }\r
219         return $ret;\r
220     }\r
221 \r
222     /**\r
223      * Sets the current position to the start of the body\r
224      *\r
225      * This allows reusing the same body in another request\r
226      */\r
227     public function rewind()\r
228     {\r
229         $this->_pos = array(0, 0);\r
230         foreach ($this->_uploads as $u) {\r
231             rewind($u['fp']);\r
232         }\r
233     }\r
234 \r
235     /**\r
236      * Returns the body as string\r
237      *\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
240      *\r
241      * @return   string\r
242      */\r
243     public function __toString()\r
244     {\r
245         $this->rewind();\r
246         return $this->read($this->getLength());\r
247     }\r
248 \r
249 \r
250     /**\r
251      * Helper function to change the (probably multidimensional) associative array\r
252      * into the simple one.\r
253      *\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
257      *\r
258      * @return   array   array with the following items: array('item name', 'item value');\r
259      */\r
260     private static function _flattenArray($name, $values, $useBrackets)\r
261     {\r
262         if (!is_array($values)) {\r
263             return array(array($name, $values));\r
264         } else {\r
265             $ret = array();\r
266             foreach ($values as $k => $v) {\r
267                 if (empty($name)) {\r
268                     $newName = $k;\r
269                 } elseif ($useBrackets) {\r
270                     $newName = $name . '[' . $k . ']';\r
271                 } else {\r
272                     $newName = $name;\r
273                 }\r
274                 $ret = array_merge($ret, self::_flattenArray($newName, $v, $useBrackets));\r
275             }\r
276             return $ret;\r
277         }\r
278     }\r
279 }\r
280 ?>\r