]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - extlib/HTTP/Request2/MultipartBody.php
a7bd948bafe4e90bc7295b8f83e7ac64dff6a857
[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-2011, 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 308322 2011-02-14 13:58:03Z 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  * @version    Release: 2.0.0RC1\r
54  * @link       http://tools.ietf.org/html/rfc1867\r
55  */\r
56 class HTTP_Request2_MultipartBody\r
57 {\r
58    /**\r
59     * MIME boundary\r
60     * @var  string\r
61     */\r
62     private $_boundary;\r
63 \r
64    /**\r
65     * Form parameters added via {@link HTTP_Request2::addPostParameter()}\r
66     * @var  array\r
67     */\r
68     private $_params = array();\r
69 \r
70    /**\r
71     * File uploads added via {@link HTTP_Request2::addUpload()}\r
72     * @var  array\r
73     */\r
74     private $_uploads = array();\r
75 \r
76    /**\r
77     * Header for parts with parameters\r
78     * @var  string\r
79     */\r
80     private $_headerParam = "--%s\r\nContent-Disposition: form-data; name=\"%s\"\r\n\r\n";\r
81 \r
82    /**\r
83     * Header for parts with uploads\r
84     * @var  string\r
85     */\r
86     private $_headerUpload = "--%s\r\nContent-Disposition: form-data; name=\"%s\"; filename=\"%s\"\r\nContent-Type: %s\r\n\r\n";\r
87 \r
88    /**\r
89     * Current position in parameter and upload arrays\r
90     *\r
91     * First number is index of "current" part, second number is position within\r
92     * "current" part\r
93     *\r
94     * @var  array\r
95     */\r
96     private $_pos = array(0, 0);\r
97 \r
98 \r
99    /**\r
100     * Constructor. Sets the arrays with POST data.\r
101     *\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
105     */\r
106     public function __construct(array $params, array $uploads, $useBrackets = true)\r
107     {\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
112             } else {\r
113                 for ($i = 0; $i < count($f['fp']); $i++) {\r
114                     $upload = array(\r
115                         'name' => ($useBrackets? $fieldName . '[' . $i . ']': $fieldName)\r
116                     );\r
117                     foreach (array('fp', 'filename', 'size', 'type') as $key) {\r
118                         $upload[$key] = $f[$key][$i];\r
119                     }\r
120                     $this->_uploads[] = $upload;\r
121                 }\r
122             }\r
123         }\r
124     }\r
125 \r
126    /**\r
127     * Returns the length of the body to use in Content-Length header\r
128     *\r
129     * @return   integer\r
130     */\r
131     public function getLength()\r
132     {\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
139         }\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
143         }\r
144         return $length;\r
145     }\r
146 \r
147    /**\r
148     * Returns the boundary to use in Content-Type header\r
149     *\r
150     * @return   string\r
151     */\r
152     public function getBoundary()\r
153     {\r
154         if (empty($this->_boundary)) {\r
155             $this->_boundary = '--' . md5('PEAR-HTTP_Request2-' . microtime());\r
156         }\r
157         return $this->_boundary;\r
158     }\r
159 \r
160    /**\r
161     * Returns next chunk of request body\r
162     *\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
165     */\r
166     public function read($length)\r
167     {\r
168         $ret         = '';\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
180 \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
190                 }\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
195                 }\r
196                 if ($length > 0) {\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
201                 }\r
202 \r
203             } else {\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
207             }\r
208             if ($length > 0) {\r
209                 $this->_pos     = array($this->_pos[0] + 1, 0);\r
210             } else {\r
211                 $this->_pos[1] += $oldLength;\r
212             }\r
213         }\r
214         return $ret;\r
215     }\r
216 \r
217    /**\r
218     * Sets the current position to the start of the body\r
219     *\r
220     * This allows reusing the same body in another request\r
221     */\r
222     public function rewind()\r
223     {\r
224         $this->_pos = array(0, 0);\r
225         foreach ($this->_uploads as $u) {\r
226             rewind($u['fp']);\r
227         }\r
228     }\r
229 \r
230    /**\r
231     * Returns the body as string\r
232     *\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
235     *\r
236     * @return   string\r
237     */\r
238     public function __toString()\r
239     {\r
240         $this->rewind();\r
241         return $this->read($this->getLength());\r
242     }\r
243 \r
244 \r
245    /**\r
246     * Helper function to change the (probably multidimensional) associative array\r
247     * into the simple one.\r
248     *\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
253     */\r
254     private static function _flattenArray($name, $values, $useBrackets)\r
255     {\r
256         if (!is_array($values)) {\r
257             return array(array($name, $values));\r
258         } else {\r
259             $ret = array();\r
260             foreach ($values as $k => $v) {\r
261                 if (empty($name)) {\r
262                     $newName = $k;\r
263                 } elseif ($useBrackets) {\r
264                     $newName = $name . '[' . $k . ']';\r
265                 } else {\r
266                     $newName = $name;\r
267                 }\r
268                 $ret = array_merge($ret, self::_flattenArray($newName, $v, $useBrackets));\r
269             }\r
270             return $ret;\r
271         }\r
272     }\r
273 }\r
274 ?>\r