3 * @copyright Copyright (C) 2010-2021, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Util;
25 * Derived from the work of Reid Johnson <https://codereview.stackexchange.com/users/4020/reid-johnson>
26 * @see https://codereview.stackexchange.com/questions/69882/parsing-multipart-form-data-in-php-for-put-requests
30 public static function process()
32 $content_parts = explode(';', static::getContentType());
37 $content_type = array_shift($content_parts);
39 foreach ($content_parts as $part) {
40 if (strpos($part, 'boundary') !== false) {
41 $part = explode('=', $part, 2);
42 if (!empty($part[1])) {
43 $boundary = '--' . $part[1];
45 } elseif (strpos($part, 'charset') !== false) {
46 $part = explode('=', $part, 2);
47 if (!empty($part[1])) {
51 if ($boundary !== '' && $encoding !== '') {
56 if ($content_type == 'multipart/form-data') {
57 return self::fetchFromMultipart($boundary);
60 // can be handled by built in PHP functionality
61 $content = static::getPhpInputContent();
63 $variables = json_decode($content, true);
65 if (empty($variables)) {
66 parse_str($content, $variables);
69 return ['variables' => $variables, 'files' => []];
72 private static function fetchFromMultipart(string $boundary)
74 $result = ['variables' => [], 'files' => []];
76 $stream = static::getPhpInputStream();
78 $sanity = fgets($stream, strlen($boundary) + 5);
80 // malformed file, boundary should be first item
81 if (rtrim($sanity) !== $boundary) {
87 while (($chunk = fgets($stream)) !== false) {
88 if ($chunk === $boundary) {
92 if (!empty(trim($chunk))) {
93 $raw_headers .= $chunk;
97 $result = self::parseRawHeader($stream, $raw_headers, $boundary, $result);
107 private static function parseRawHeader($stream, string $raw_headers, string $boundary, array $result)
109 $variables = $result['variables'];
110 $files = $result['files'];
114 foreach (explode("\r\n", $raw_headers) as $header) {
115 if (strpos($header, ':') === false) {
118 list($name, $value) = explode(':', $header, 2);
120 $headers[strtolower($name)] = ltrim($value, ' ');
123 if (!isset($headers['content-disposition'])) {
124 return ['variables' => $variables, 'files' => $files];
127 if (!preg_match('/^(.+); *name="([^"]+)"(; *filename="([^"]+)")?/', $headers['content-disposition'], $matches)) {
128 return ['variables' => $variables, 'files' => $files];
132 $filename = $matches[4] ?? '';
134 if (!empty($filename)) {
135 $files[$name] = static::fetchFileData($stream, $boundary, $headers, $filename);
136 return ['variables' => $variables, 'files' => $files];
138 $variables = self::fetchVariables($stream, $boundary, $headers, $name, $variables);
141 return ['variables' => $variables, 'files' => $files];
144 protected static function fetchFileData($stream, string $boundary, array $headers, string $filename)
146 $error = UPLOAD_ERR_OK;
148 if (isset($headers['content-type'])) {
149 $tmp = explode(';', $headers['content-type']);
151 $contentType = $tmp[0];
153 $contentType = 'unknown';
156 $tmpnam = tempnam(ini_get('upload_tmp_dir'), 'php');
157 $fileHandle = fopen($tmpnam, 'wb');
159 if ($fileHandle === false) {
160 $error = UPLOAD_ERR_CANT_WRITE;
163 while (($chunk = fgets($stream, 8096)) !== false && strpos($chunk, $boundary) !== 0) {
164 if ($lastLine !== null) {
165 if (!fwrite($fileHandle, $lastLine)) {
166 $error = UPLOAD_ERR_CANT_WRITE;
173 if ($lastLine !== null && $error !== UPLOAD_ERR_CANT_WRITE) {
174 if (!fwrite($fileHandle, rtrim($lastLine, "\r\n"))) {
175 $error = UPLOAD_ERR_CANT_WRITE;
182 'type' => $contentType,
183 'tmp_name' => $tmpnam,
185 'size' => filesize($tmpnam)
189 private static function fetchVariables($stream, string $boundary, array $headers, string $name, array $variables)
194 while (($chunk = fgets($stream)) !== false && strpos($chunk, $boundary) !== 0) {
195 if ($lastLine !== null) {
196 $fullValue .= $lastLine;
202 if ($lastLine !== null) {
203 $fullValue .= rtrim($lastLine, "\r\n");
206 if (isset($headers['content-type'])) {
209 foreach (explode(';', $headers['content-type']) as $part) {
210 if (strpos($part, 'charset') !== false) {
211 $part = explode($part, '=', 2);
212 if (isset($part[1])) {
213 $encoding = $part[1];
219 if ($encoding !== '' && strtoupper($encoding) !== 'UTF-8' && strtoupper($encoding) !== 'UTF8') {
220 $tmp = mb_convert_encoding($fullValue, 'UTF-8', $encoding);
221 if ($tmp !== false) {
227 $fullValue = $name . '=' . $fullValue;
230 parse_str($fullValue, $tmp);
232 return self::expandVariables(explode('[', $name), $variables, $tmp);
235 private static function expandVariables(array $names, $variables, array $values)
237 if (!is_array($variables)) {
241 $name = rtrim(array_shift($names), ']');
243 $name = $name . '=p';
246 parse_str($name, $tmp);
248 $tmp = array_keys($tmp);
253 $variables[] = reset($values);
254 } elseif (isset($variables[$name]) && isset($values[$name])) {
255 $variables[$name] = self::expandVariables($names, $variables[$name], $values[$name]);
256 } elseif (isset($values[$name])) {
257 $variables[$name] = $values[$name];
264 * Returns the current PHP input stream
265 * Mainly used for test doubling
267 * @return false|resource
269 protected static function getPhpInputStream()
271 return fopen('php://input', 'rb');
275 * Returns the content of the current PHP input
276 * Mainly used for test doubling
278 * @return false|string
280 protected static function getPhpInputContent()
282 return file_get_contents('php://input');
286 * Returns the content type string of the current call
287 * Mainly used for test doubling
289 * @return false|string
291 protected static function getContentType()
293 return $_SERVER['CONTENT_TYPE'] ?? 'application/x-www-form-urlencoded';