PageRenderTime 42ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/common/libraries/plugin/pear/HTTP/Request2/MultipartBody.php

https://bitbucket.org/chamilo/chamilo-dev/
PHP | 294 lines | 153 code | 15 blank | 126 comment | 13 complexity | feff7dac69584080b350036e9cd9f958 MD5 | raw file
Possible License(s): GPL-2.0, BSD-3-Clause, LGPL-2.1, LGPL-3.0, GPL-3.0, MIT
  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, 2009, 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 290192 2009-11-03 21:29:32Z avb $
  41. * @link http://pear.php.net/package/HTTP_Request2
  42. */
  43. /**
  44. * Class for building multipart/form-data request body
  45. *
  46. * The class helps to reduce memory consumption by streaming large file uploads
  47. * from disk, it also allows monitoring of upload progress (see request #7630)
  48. *
  49. * @category HTTP
  50. * @package HTTP_Request2
  51. * @author Alexey Borzov <avb@php.net>
  52. * @version Release: 0.5.2
  53. * @link http://tools.ietf.org/html/rfc1867
  54. */
  55. class HTTP_Request2_MultipartBody
  56. {
  57. /**
  58. * MIME boundary
  59. * @var string
  60. */
  61. private $_boundary;
  62. /**
  63. * Form parameters added via {@link HTTP_Request2::addPostParameter()}
  64. * @var array
  65. */
  66. private $_params = array();
  67. /**
  68. * File uploads added via {@link HTTP_Request2::addUpload()}
  69. * @var array
  70. */
  71. private $_uploads = array();
  72. /**
  73. * Header for parts with parameters
  74. * @var string
  75. */
  76. private $_headerParam = "--%s\r\nContent-Disposition: form-data; name=\"%s\"\r\n\r\n";
  77. /**
  78. * Header for parts with uploads
  79. * @var string
  80. */
  81. private $_headerUpload = "--%s\r\nContent-Disposition: form-data; name=\"%s\"; filename=\"%s\"\r\nContent-Type: %s\r\n\r\n";
  82. /**
  83. * Current position in parameter and upload arrays
  84. *
  85. * First number is index of "current" part, second number is position within
  86. * "current" part
  87. *
  88. * @var array
  89. */
  90. private $_pos = array(0, 0);
  91. /**
  92. * Constructor. Sets the arrays with POST data.
  93. *
  94. * @param array values of form fields set via {@link HTTP_Request2::addPostParameter()}
  95. * @param array file uploads set via {@link HTTP_Request2::addUpload()}
  96. * @param bool whether to append brackets to array variable names
  97. */
  98. public function __construct(array $params, array $uploads, $useBrackets = true)
  99. {
  100. $this->_params = self :: _flattenArray('', $params, $useBrackets);
  101. foreach ($uploads as $fieldName => $f)
  102. {
  103. if (! is_array($f['fp']))
  104. {
  105. $this->_uploads[] = $f + array('name' => $fieldName);
  106. }
  107. else
  108. {
  109. for($i = 0; $i < count($f['fp']); $i ++)
  110. {
  111. $upload = array('name' => ($useBrackets ? $fieldName . '[' . $i . ']' : $fieldName));
  112. foreach (array('fp', 'filename', 'size', 'type') as $key)
  113. {
  114. $upload[$key] = $f[$key][$i];
  115. }
  116. $this->_uploads[] = $upload;
  117. }
  118. }
  119. }
  120. }
  121. /**
  122. * Returns the length of the body to use in Content-Length header
  123. *
  124. * @return integer
  125. */
  126. public function getLength()
  127. {
  128. $boundaryLength = strlen($this->getBoundary());
  129. $headerParamLength = strlen($this->_headerParam) - 4 + $boundaryLength;
  130. $headerUploadLength = strlen($this->_headerUpload) - 8 + $boundaryLength;
  131. $length = $boundaryLength + 6;
  132. foreach ($this->_params as $p)
  133. {
  134. $length += $headerParamLength + strlen($p[0]) + strlen($p[1]) + 2;
  135. }
  136. foreach ($this->_uploads as $u)
  137. {
  138. $length += $headerUploadLength + strlen($u['name']) + strlen($u['type']) + strlen($u['filename']) + $u['size'] + 2;
  139. }
  140. return $length;
  141. }
  142. /**
  143. * Returns the boundary to use in Content-Type header
  144. *
  145. * @return string
  146. */
  147. public function getBoundary()
  148. {
  149. if (empty($this->_boundary))
  150. {
  151. $this->_boundary = '--' . md5('PEAR-HTTP_Request2-' . microtime());
  152. }
  153. return $this->_boundary;
  154. }
  155. /**
  156. * Returns next chunk of request body
  157. *
  158. * @param integer Amount of bytes to read
  159. * @return string Up to $length bytes of data, empty string if at end
  160. */
  161. public function read($length)
  162. {
  163. $ret = '';
  164. $boundary = $this->getBoundary();
  165. $paramCount = count($this->_params);
  166. $uploadCount = count($this->_uploads);
  167. while ($length > 0 && $this->_pos[0] <= $paramCount + $uploadCount)
  168. {
  169. $oldLength = $length;
  170. if ($this->_pos[0] < $paramCount)
  171. {
  172. $param = sprintf($this->_headerParam, $boundary, $this->_params[$this->_pos[0]][0]) . $this->_params[$this->_pos[0]][1] . "\r\n";
  173. $ret .= substr($param, $this->_pos[1], $length);
  174. $length -= min(strlen($param) - $this->_pos[1], $length);
  175. }
  176. elseif ($this->_pos[0] < $paramCount + $uploadCount)
  177. {
  178. $pos = $this->_pos[0] - $paramCount;
  179. $header = sprintf($this->_headerUpload, $boundary, $this->_uploads[$pos]['name'], $this->_uploads[$pos]['filename'], $this->_uploads[$pos]['type']);
  180. if ($this->_pos[1] < strlen($header))
  181. {
  182. $ret .= substr($header, $this->_pos[1], $length);
  183. $length -= min(strlen($header) - $this->_pos[1], $length);
  184. }
  185. $filePos = max(0, $this->_pos[1] - strlen($header));
  186. if ($length > 0 && $filePos < $this->_uploads[$pos]['size'])
  187. {
  188. $ret .= fread($this->_uploads[$pos]['fp'], $length);
  189. $length -= min($length, $this->_uploads[$pos]['size'] - $filePos);
  190. }
  191. if ($length > 0)
  192. {
  193. $start = $this->_pos[1] + ($oldLength - $length) - strlen($header) - $this->_uploads[$pos]['size'];
  194. $ret .= substr("\r\n", $start, $length);
  195. $length -= min(2 - $start, $length);
  196. }
  197. }
  198. else
  199. {
  200. $closing = '--' . $boundary . "--\r\n";
  201. $ret .= substr($closing, $this->_pos[1], $length);
  202. $length -= min(strlen($closing) - $this->_pos[1], $length);
  203. }
  204. if ($length > 0)
  205. {
  206. $this->_pos = array($this->_pos[0] + 1, 0);
  207. }
  208. else
  209. {
  210. $this->_pos[1] += $oldLength;
  211. }
  212. }
  213. return $ret;
  214. }
  215. /**
  216. * Sets the current position to the start of the body
  217. *
  218. * This allows reusing the same body in another request
  219. */
  220. public function rewind()
  221. {
  222. $this->_pos = array(0, 0);
  223. foreach ($this->_uploads as $u)
  224. {
  225. rewind($u['fp']);
  226. }
  227. }
  228. /**
  229. * Returns the body as string
  230. *
  231. * Note that it reads all file uploads into memory so it is a good idea not
  232. * to use this method with large file uploads and rely on read() instead.
  233. *
  234. * @return string
  235. */
  236. public function __toString()
  237. {
  238. $this->rewind();
  239. return $this->read($this->getLength());
  240. }
  241. /**
  242. * Helper function to change the (probably multidimensional) associative array
  243. * into the simple one.
  244. *
  245. * @param string name for item
  246. * @param mixed item's values
  247. * @param bool whether to append [] to array variables' names
  248. * @return array array with the following items: array('item name', 'item value');
  249. */
  250. private static function _flattenArray($name, $values, $useBrackets)
  251. {
  252. if (! is_array($values))
  253. {
  254. return array(array($name, $values));
  255. }
  256. else
  257. {
  258. $ret = array();
  259. foreach ($values as $k => $v)
  260. {
  261. if (empty($name))
  262. {
  263. $newName = $k;
  264. }
  265. elseif ($useBrackets)
  266. {
  267. $newName = $name . '[' . $k . ']';
  268. }
  269. else
  270. {
  271. $newName = $name;
  272. }
  273. $ret = array_merge($ret, self :: _flattenArray($newName, $v, $useBrackets));
  274. }
  275. return $ret;
  276. }
  277. }
  278. }
  279. ?>