Completed
Push — master ( 349239...be8479 )
by Nazar
11:19
created

Data_and_files::init_data_and_files()   D

Complexity

Conditions 9
Paths 26

Size

Total Lines 30
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 20
CRAP Score 9

Importance

Changes 0
Metric Value
cc 9
eloc 20
nc 26
nop 4
dl 0
loc 30
ccs 20
cts 20
cp 1
crap 9
rs 4.909
c 0
b 0
f 0
1
<?php
2
/**
3
 * @package   CleverStyle Framework
4
 * @author    Nazar Mokrynskyi <[email protected]>
5
 * @copyright Copyright (c) 2016, Nazar Mokrynskyi
6
 * @license   MIT License, see license.txt
7
 */
8
namespace cs\Request;
9
use
10
	UnexpectedValueException,
11
	cs\ExitException,
12
	nazarpc\Stream_slicer;
13
14
trait Data_and_files {
15
	/**
16
	 * Data array, similar to `$_POST`
17
	 *
18
	 * @var array
19
	 */
20
	public $data;
21
	/**
22
	 * Normalized files array
23
	 *
24
	 * Each file item can be either single file or array of files (in contrast with native PHP arrays where each field like `name` become an array) with keys
25
	 * `name`, `type`, `size`, `tmp_name`, `stream` and `error`
26
	 *
27
	 * `name`, `type`, `size` and `error` keys are similar to native PHP fields in `$_FILES`; `tmp_name` might not be temporary file, but file descriptor
28
	 * wrapper like `request-file:///file` instead and `stream` is resource like obtained with `fopen('/tmp/xyz', 'rb')`
29
	 *
30
	 * @var array[]
31
	 */
32
	public $files;
33
	/**
34
	 * Data stream resource, similar to `fopen('php://input', 'rb')`
35
	 *
36
	 * Make sure you're controlling position in stream where you read something, if code in some other place might seek on this stream
37
	 *
38
	 * Stream is read-only
39
	 *
40
	 * @var null|resource
41
	 */
42
	public $data_stream;
43
	/**
44
	 * `$this->init_server()` assumed to be called already
45
	 *
46
	 * @param array                $data        Typically `$_POST`
47
	 * @param array[]              $files       Typically `$_FILES`; might be like native PHP array `$_FILES` or normalized; each file item MUST contain keys
48
	 *                                          `name`, `type`, `size`, `error` and at least one of `tmp_name` or `stream`
49
	 * @param null|resource|string $data_stream String, like `php://input` or resource, like `fopen('php://input', 'rb')` with request body, will be parsed for
50
	 *                                          data and files if necessary
51
	 * @param bool                 $copy_stream Sometimes data stream can only being read once (like most of times with `php://input`), so it is necessary to
52
	 *                                          copy it and store its contents for longer period of time
53
	 *
54
	 * @throws ExitException
55
	 */
56 30
	function init_data_and_files ($data = [], $files = [], $data_stream = null, $copy_stream = true) {
57 30
		if (is_resource($this->data_stream)) {
58 4
			fclose($this->data_stream);
59
		}
60 30
		$this->data        = $data;
61 30
		$this->files       = $this->normalize_files($files);
62 30
		$this->data_stream = null;
63 30
		if (in_array($this->method, ['GET', 'HEAD', 'OPTIONS'])) {
64 20
			return;
65
		}
66 10
		$data_stream = is_string($data_stream) ? fopen($data_stream, 'rb') : $data_stream;
67 10
		if (is_resource($data_stream)) {
68 8
			rewind($data_stream);
69 8
			if ($copy_stream) {
70 8
				$this->data_stream = fopen('php://temp', 'w+b');
71 8
				stream_copy_to_stream($data_stream, $this->data_stream);
72 8
				fclose($data_stream);
73
			} else {
74 4
				$this->data_stream = $data_stream;
75
			}
76
		}
77
		/**
78
		 * If we don't appear to have any data or files detected - probably, we need to parse request ourselves
79
		 */
80 10
		if (!$this->data && !$this->files && is_resource($this->data_stream)) {
81 4
			$this->parse_data_stream();
82
		}
83
		// Hack: for compatibility we'll override $_POST since it might be filled during parsing
84 10
		$_POST = $this->data;
85 10
	}
86
	/**
87
	 * Get data item by name
88
	 *
89
	 * @param string[]|string[][] $name
90
	 *
91
	 * @return mixed|mixed[]|null Data items (or associative array of data items) if exists or `null` otherwise (in case if `$name` is an array even one
92
	 *                             missing key will cause the whole thing to fail)
93
	 */
94 32
	function data (...$name) {
95 32
		if (count($name) === 1) {
96 28
			$name = $name[0];
97
		}
98
		/**
99
		 * @var string|string[] $name
100
		 */
101 32
		if (is_array($name)) {
102 6
			$result = [];
103 6
			foreach ($name as &$n) {
104 6
				if (!array_key_exists($n, $this->data)) {
105 2
					return null;
106
				}
107 6
				$result[$n] = $this->data[$n];
108
			}
109 6
			return $result;
110
		}
111
		/** @noinspection OffsetOperationsInspection */
112 28
		return @$this->data[$name];
113
	}
114
	/**
115
	 * Get file item by name
116
	 *
117
	 * @param string $name
118
	 *
119
	 * @return array|null File item if exists or `null` otherwise
120
	 */
121 2
	function files ($name) {
122 2
		return @$this->files[$name];
123
	}
124
	/**
125
	 * @param array[] $files
126
	 * @param string  $file_path
127
	 *
128
	 * @return array[]
129
	 */
130 30
	protected function normalize_files ($files, $file_path = '') {
131 30
		if (!isset($files['name'])) {
132 30
			foreach ($files as $field => &$file) {
133 2
				$file = $this->normalize_files($file, "$file_path/$field");
134
			}
135 30
			return $files;
136
		}
137 2
		if (is_array($files['name'])) {
138 2
			$result = [];
139 2
			foreach (array_keys($files['name']) as $index) {
140 2
				$result[] = $this->normalize_file(
141
					[
142 2
						'name'     => $files['name'][$index],
143 2
						'type'     => $files['type'][$index],
144 2
						'size'     => $files['size'][$index],
145 2
						'tmp_name' => @$files['tmp_name'][$index],
146 2
						'stream'   => @$files['stream'][$index],
147 2
						'error'    => $files['error'][$index]
148
					],
149 2
					"$file_path/$index"
150
				);
151
			}
152 2
			return $result;
153
		} else {
154 2
			return $this->normalize_file($files, $file_path);
155
		}
156
	}
157
	/**
158
	 * @param array  $file
159
	 * @param string $file_path
160
	 *
161
	 * @return array
162
	 */
163 2
	protected function normalize_file ($file, $file_path) {
164
		$file += [
165 2
			'tmp_name' => null,
166
			'stream'   => null
167
		];
168 2
		if (isset($file['tmp_name']) && $file['stream'] === null) {
169 2
			$file['stream'] = fopen($file['tmp_name'], 'rb');
170
		}
171 2
		if (isset($file['stream']) && !$file['tmp_name']) {
172 2
			$file['tmp_name'] = "request-file://$file_path";
173
		}
174 2
		if ($file['tmp_name'] === null && $file['stream'] === null) {
175 2
			$file['error'] = UPLOAD_ERR_NO_FILE;
176
		}
177 2
		return $file;
178
	}
179
	/**
180
	 * Parsing request body for following Content-Type: `application/json`, `application/x-www-form-urlencoded` and `multipart/form-data`
181
	 *
182
	 * @throws ExitException
183
	 */
184 4
	protected function parse_data_stream () {
185 4
		$content_type = $this->header('content-type');
186 4
		rewind($this->data_stream);
187
		/**
188
		 * application/json
189
		 */
190 4
		if (preg_match('#^application/([^+\s]+\+)?json#', $content_type)) {
191 2
			$this->data = _json_decode(stream_get_contents($this->data_stream)) ?: [];
192 2
			return;
193
		}
194
		/**
195
		 * application/x-www-form-urlencoded
196
		 */
197 2
		if (strpos($content_type, 'application/x-www-form-urlencoded') === 0) {
198 2
			@parse_str(stream_get_contents($this->data_stream), $this->data);
199 2
			return;
200
		}
201
		/**
202
		 * multipart/form-data
203
		 */
204
		if (preg_match('#multipart/form-data;.*boundary="?([^;"]{1,70})(?:"|;|$)#Ui', $content_type, $matches)) {
205
			try {
206
				$parts = $this->parse_multipart_into_parts($this->data_stream, trim($matches[1])) ?: [];
207
				list($this->data, $files) = $this->parse_multipart_analyze_parts($this->data_stream, $parts);
208
				$this->files = $this->normalize_files($files);
209
			} catch (UnexpectedValueException $e) {
210
				// Do nothing, if parsing failed then we'll just leave `::$data` and `::$files` empty
211
			}
212
		}
213
	}
214
	/**
215
	 * Parse content stream
216
	 *
217
	 * @param resource $stream
218
	 * @param string   $boundary
219
	 *
220
	 * @return array[]|false
221
	 *
222
	 * @throws UnexpectedValueException
223
	 * @throws ExitException
224
	 */
225
	protected function parse_multipart_into_parts ($stream, $boundary) {
226
		$parts    = [];
227
		$crlf     = "\r\n";
228
		$position = 0;
229
		$body     = '';
230
		list($offset, $body) = $this->parse_multipart_find($stream, $body, "--$boundary$crlf");
231
		/**
232
		 * strlen doesn't take into account trailing CRLF since we'll need it in loop below
233
		 */
234
		$position += $offset + strlen("--$boundary");
235
		$body = substr($body, strlen("--$boundary"));
236
		/**
237
		 * Each part always starts with CRLF
238
		 */
239
		while (strpos($body, $crlf) === 0) {
240
			$position += 2;
241
			$body = substr($body, 2);
242
			$part = [
243
				'headers' => [
244
					'offset' => $position,
245
					'size'   => 0
246
				],
247
				'body'    => [
248
					'offset' => 0,
249
					'size'   => 0
250
				]
251
			];
252
			if (strpos($body, $crlf) === 0) {
253
				/**
254
				 * No headers
255
				 */
256
				$position += 2;
257
				$body = substr($body, 2);
258
			} else {
259
				/**
260
				 * Find headers end in order to determine size
261
				 */
262
				list($offset, $body) = $this->parse_multipart_find($stream, $body, $crlf.$crlf);
263
				$part['headers']['size'] = $offset;
264
				$position += $offset + 4;
265
				$body = substr($body, 4);
266
			}
267
			$part['body']['offset'] = $position;
268
			/**
269
			 * Find body end in order to determine its size
270
			 */
271
			list($offset, $body) = $this->parse_multipart_find($stream, $body, "$crlf--$boundary");
272
			$part['body']['size'] = $offset;
273
			$position += $offset + strlen("$crlf--$boundary");
274
			$body = substr($body, strlen("$crlf--$boundary"));
275
			if ($part['headers']['size']) {
276
				$parts[] = $part;
277
			}
278
		}
279
		/**
280
		 * Last boundary after all parts ends with '--' and we don't care what rubbish happens after it
281
		 */
282
		$post_max_size = $this->post_max_size();
283
		if (0 !== strpos($body, '--')) {
284
			return false;
285
		}
286
		/**
287
		 * Check whether body size is bigger than allowed limit
288
		 */
289
		if ($position + strlen($body) > $post_max_size) {
290
			throw new ExitException(413);
291
		}
292
		return $parts;
293
	}
294
	/**
295
	 * @param resource $stream
296
	 * @param array[]  $parts
297
	 *
298
	 * @return array[]
299
	 */
300
	protected function parse_multipart_analyze_parts ($stream, $parts) {
301
		$data  = [];
302
		$files = [];
303
		foreach ($parts as $part) {
304
			$headers = $this->parse_multipart_headers(
305
				stream_get_contents($stream, $part['headers']['size'], $part['headers']['offset'])
306
			);
307
			if (
308
				!isset($headers['content-disposition'][0], $headers['content-disposition']['name']) ||
309
				$headers['content-disposition'][0] != 'form-data'
310
			) {
311
				continue;
312
			}
313
			$name = $headers['content-disposition']['name'];
314
			if (isset($headers['content-disposition']['filename'])) {
315
				$file = [
316
					'name'   => $headers['content-disposition']['filename'],
317
					'type'   => @$headers['content-type'] ?: 'application/octet-stream',
318
					'size'   => $part['body']['size'],
319
					'stream' => Stream_slicer::slice($stream, $part['body']['offset'], $part['body']['size']),
320
					'error'  => UPLOAD_ERR_OK
321
				];
322
				if ($headers['content-disposition']['filename'] === '') {
323
					$file['type']   = '';
324
					$file['stream'] = null;
325
					$file['error']  = UPLOAD_ERR_NO_FILE;
326
				} elseif ($file['size'] > $this->upload_max_file_size()) {
327
					$file['stream'] = null;
328
					$file['error']  = UPLOAD_ERR_INI_SIZE;
329
				}
330
				$this->parse_multipart_set_target($files, $name, $file);
331
			} else {
332
				if ($part['body']['size'] == 0) {
333
					$this->parse_multipart_set_target($data, $name, '');
334
				} else {
335
					$this->parse_multipart_set_target(
336
						$data,
337
						$name,
338
						stream_get_contents($stream, $part['body']['size'], $part['body']['offset'])
339
					);
340
				}
341
			}
342
		}
343
		return [$data, $files];
344
	}
345
	/**
346
	 * @return int
347
	 */
348
	protected function post_max_size () {
349
		$size = ini_get('post_max_size') ?: ini_get('hhvm.server.max_post_size');
350
		return $this->convert_size_to_bytes($size);
351
	}
352
	/**
353
	 * @return int
354
	 */
355
	protected function upload_max_file_size () {
356
		$size = ini_get('upload_max_filesize') ?: ini_get('hhvm.server.upload.upload_max_file_size');
357
		return $this->convert_size_to_bytes($size);
358
	}
359
	/**
360
	 * @param int|string $size
361
	 *
362
	 * @return int
363
	 */
364
	protected function convert_size_to_bytes ($size) {
365
		switch (strtolower(substr($size, -1))) {
366
			case 'g';
367
				$size = (int)$size * 1024;
368
			case 'm';
369
				$size = (int)$size * 1024;
370
			case 'k';
371
				$size = (int)$size * 1024;
372
		}
373
		return (int)$size ?: PHP_INT_MAX;
374
	}
375
	/**
376
	 * @param resource $stream
377
	 * @param string   $next_data
378
	 * @param string   $target
379
	 *
380
	 * @return array
381
	 *
382
	 * @throws UnexpectedValueException
383
	 */
384
	protected function parse_multipart_find ($stream, $next_data, $target) {
385
		$offset    = 0;
386
		$prev_data = '';
387
		while (($found = strpos($prev_data.$next_data, $target)) === false) {
388
			if (feof($stream)) {
389
				throw new UnexpectedValueException;
390
			}
391
			if ($prev_data) {
392
				$offset += strlen($prev_data);
393
			}
394
			$prev_data = $next_data;
395
			$next_data = fread($stream, 1024);
396
		}
397
		$offset += $found;
398
		/**
399
		 * Read some more bytes so that we'll always have some remainder in place, since empty remainder might cause problems with `strpos()` call later
400
		 */
401
		$remainder = substr($prev_data.$next_data, $found).(fread($stream, 1024) ?: '');
402
		return [$offset, $remainder];
403
	}
404
	/**
405
	 * @param string $content
406
	 *
407
	 * @return array
408
	 */
409
	protected function parse_multipart_headers ($content) {
410
		$headers = [];
411
		foreach (explode("\r\n", $content) as $header) {
412
			list($name, $value) = explode(':', $header, 2);
413
			if (!preg_match_all('/(.+)(?:="*?(.*)"?)?(?:;\s|$)/U', $value, $matches)) {
414
				continue;
415
			}
416
			$name           = strtolower($name);
417
			$headers[$name] = [];
418
			foreach (array_keys($matches[1]) as $index) {
419
				if (isset($headers[$name][0]) || strlen($matches[2][$index])) {
420
					$headers[$name][trim($matches[1][$index])] = urldecode(trim($matches[2][$index]));
421
				} else {
422
					$headers[$name][] = trim($matches[1][$index]);
423
				}
424
			}
425
			if (count($headers[$name]) == 1) {
426
				$headers[$name] = $headers[$name][0];
427
			}
428
		}
429
		return $headers;
430
	}
431
	/**
432
	 * @param array        $source
433
	 * @param string       $name
434
	 * @param array|string $value
435
	 */
436
	protected function parse_multipart_set_target (&$source, $name, $value) {
437
		preg_match_all('/(?:^|\[)([^\[\]]*)\]?/', $name, $matches);
438
		if ($matches[1][0] === '') {
439
			return;
440
		}
441
		foreach ($matches[1] as $component) {
442
			if (!strlen($component)) {
443
				$source = &$source[];
444
			} else {
445
				if (!isset($source[$component])) {
446
					$source[$component] = [];
447
				}
448
				$source = &$source[$component];
449
			}
450
		}
451
		$source = $value;
452
	}
453
}
454