1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
<?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace Zend\Http\Header;
use stdClass;
/**
* Abstract Accept Header
*
* Naming conventions:
*
* Accept: audio/mp3; q=0.2; version=0.5, audio/basic+mp3
* |------------------------------------------------------| header line
* |------| field name
* |-----------------------------------------------| field value
* |-------------------------------| field value part
* |------| type
* |--| subtype
* |--| format
* |----| subtype
* |---| format
* |-------------------| parameter set
* |-----------| parameter
* |-----| parameter key
* |--| parameter value
* |---| priority
*
*
* @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1
* @author Dolf Schimmel - Freeaqingme
*/
abstract class AbstractAccept implements HeaderInterface
{
/**
* @var stdClass[]
*/
protected $fieldValueParts = [];
protected $regexAddType;
/**
* Determines if since last mutation the stack was sorted
*
* @var bool
*/
protected $sorted = false;
/**
* Parse a full header line or just the field value part.
*
* @param string $headerLine
*/
public function parseHeaderLine($headerLine)
{
if (strpos($headerLine, ':') !== false) {
list($name, $value) = GenericHeader::splitHeaderLine($headerLine);
if (strtolower($name) !== strtolower($this->getFieldName())) {
$value = $headerLine; // This is just for preserve the BC.
}
} else {
$value = $headerLine;
}
HeaderValue::assertValid($value);
foreach ($this->getFieldValuePartsFromHeaderLine($value) as $value) {
$this->addFieldValuePartToQueue($value);
}
}
/**
* Factory method: parse Accept header string
*
* @param string $headerLine
* @return static
*/
public static function fromString($headerLine)
{
$obj = new static();
$obj->parseHeaderLine($headerLine);
return $obj;
}
/**
* Parse the Field Value Parts represented by a header line
*
* @param string $headerLine
* @throws Exception\InvalidArgumentException If header is invalid
* @return array
*/
public function getFieldValuePartsFromHeaderLine($headerLine)
{
// process multiple accept values, they may be between quotes
if (! preg_match_all('/(?:[^,"]|"(?:[^\\\"]|\\\.)*")+/', $headerLine, $values)
|| ! isset($values[0])
) {
throw new Exception\InvalidArgumentException(
'Invalid header line for ' . $this->getFieldName() . ' header string'
);
}
$out = [];
foreach ($values[0] as $value) {
$value = trim($value);
$out[] = $this->parseFieldValuePart($value);
}
return $out;
}
/**
* Parse the accept params belonging to a media range
*
* @param string $fieldValuePart
* @return stdClass
*/
protected function parseFieldValuePart($fieldValuePart)
{
$raw = $subtypeWhole = $type = $fieldValuePart;
if ($pos = strpos($fieldValuePart, ';')) {
$type = substr($fieldValuePart, 0, $pos);
}
$params = $this->getParametersFromFieldValuePart($fieldValuePart);
if ($pos = strpos($fieldValuePart, ';')) {
$fieldValuePart = trim(substr($fieldValuePart, 0, $pos));
}
$format = '*';
$subtype = '*';
return (object) [
'typeString' => trim($fieldValuePart),
'type' => $type,
'subtype' => $subtype,
'subtypeRaw' => $subtypeWhole,
'format' => $format,
'priority' => isset($params['q']) ? $params['q'] : 1,
'params' => $params,
'raw' => trim($raw),
];
}
/**
* Parse the keys contained in the header line
*
* @param string $fieldValuePart
* @return array
*/
protected function getParametersFromFieldValuePart($fieldValuePart)
{
$params = [];
if ((($pos = strpos($fieldValuePart, ';')) !== false)) {
preg_match_all('/(?:[^;"]|"(?:[^\\\"]|\\\.)*")+/', $fieldValuePart, $paramsStrings);
if (isset($paramsStrings[0])) {
array_shift($paramsStrings[0]);
$paramsStrings = $paramsStrings[0];
}
foreach ($paramsStrings as $param) {
$explode = explode('=', $param, 2);
if (count($explode) === 2) {
$value = trim($explode[1]);
} else {
$value = null;
}
if (isset($value[0]) && $value[0] == '"' && substr($value, -1) == '"') {
$value = substr(substr($value, 1), 0, -1);
}
$params[trim($explode[0])] = stripslashes($value);
}
}
return $params;
}
/**
* Get field value
*
* @param array|null $values
* @return string
*/
public function getFieldValue($values = null)
{
if ($values === null) {
return $this->getFieldValue($this->fieldValueParts);
}
$strings = [];
foreach ($values as $value) {
$params = $value->params;
array_walk($params, [$this, 'assembleAcceptParam']);
$strings[] = implode(';', [$value->typeString] + $params);
}
return implode(', ', $strings);
}
/**
* Assemble and escape the field value parameters based on RFC 2616 section 2.1
*
* @todo someone should review this thoroughly
* @param string $value
* @param string $key
* @return string
*/
protected function assembleAcceptParam(&$value, $key)
{
$separators = ['(', ')', '<', '>', '@', ',', ';', ':', '/', '[', ']', '?', '=', '{', '}', ' ', "\t"];
$escaped = preg_replace_callback(
'/[[:cntrl:]"\\\\]/', // escape cntrl, ", \
function ($v) {
return '\\' . $v[0];
},
$value
);
if ($escaped == $value && ! array_intersect(str_split($value), $separators)) {
$value = $key . ($value ? '=' . $value : '');
} else {
$value = $key . ($value ? '="' . $escaped . '"' : '');
}
return $value;
}
/**
* Add a type, with the given priority
*
* @param string $type
* @param int|float $priority
* @param array (optional) $params
* @throws Exception\InvalidArgumentException
* @return $this
*/
protected function addType($type, $priority = 1, array $params = [])
{
if (! preg_match($this->regexAddType, $type)) {
throw new Exception\InvalidArgumentException(sprintf(
'%s expects a valid type; received "%s"',
__METHOD__,
(string) $type
));
}
if (! is_int($priority) && ! is_float($priority) && ! is_numeric($priority)
|| $priority > 1 || $priority < 0
) {
throw new Exception\InvalidArgumentException(sprintf(
'%s expects a numeric priority; received %s',
__METHOD__,
(string) $priority
));
}
if ($priority != 1) {
$params = ['q' => sprintf('%01.1f', $priority)] + $params;
}
$assembledString = $this->getFieldValue(
[(object) ['typeString' => $type, 'params' => $params]]
);
$value = $this->parseFieldValuePart($assembledString);
$this->addFieldValuePartToQueue($value);
return $this;
}
/**
* Does the header have the requested type?
*
* @param array|string $matchAgainst
* @return bool
*/
protected function hasType($matchAgainst)
{
return (bool) $this->match($matchAgainst);
}
/**
* Match a media string against this header
*
* @param array|string $matchAgainst
* @return Accept\FieldValuePArt\AcceptFieldValuePart|bool The matched value or false
*/
public function match($matchAgainst)
{
if (is_string($matchAgainst)) {
$matchAgainst = $this->getFieldValuePartsFromHeaderLine($matchAgainst);
}
foreach ($this->getPrioritized() as $left) {
foreach ($matchAgainst as $right) {
if ($right->type == '*' || $left->type == '*') {
if ($this->matchAcceptParams($left, $right)) {
$left->setMatchedAgainst($right);
return $left;
}
}
if ($left->type == $right->type) {
if (($left->subtype == $right->subtype || ($right->subtype == '*' || $left->subtype == '*'))
&& ($left->format == $right->format || $right->format == '*' || $left->format == '*')
) {
if ($this->matchAcceptParams($left, $right)) {
$left->setMatchedAgainst($right);
return $left;
}
}
}
}
}
return false;
}
/**
* Return a match where all parameters in argument #1 match those in argument #2
*
* @param array $match1
* @param array $match2
* @return bool|array
*/
protected function matchAcceptParams($match1, $match2)
{
foreach ($match2->params as $key => $value) {
if (isset($match1->params[$key])) {
if (strpos($value, '-')) {
preg_match(
'/^(?|([^"-]*)|"([^"]*)")-(?|([^"-]*)|"([^"]*)")\z/',
$value,
$pieces
);
if (count($pieces) == 3
&& (version_compare($pieces[1], $match1->params[$key], '<=')
xor version_compare($pieces[2], $match1->params[$key], '>='))
) {
return false;
}
} elseif (strpos($value, '|')) {
$options = explode('|', $value);
$good = false;
foreach ($options as $option) {
if ($option == $match1->params[$key]) {
$good = true;
break;
}
}
if (! $good) {
return false;
}
} elseif ($match1->params[$key] != $value) {
return false;
}
}
}
return $match1;
}
/**
* Add a key/value combination to the internal queue
*
* @param stdClass $value
* @return number
*/
protected function addFieldValuePartToQueue($value)
{
$this->fieldValueParts[] = $value;
$this->sorted = false;
}
/**
* Sort the internal Field Value Parts
*
* @See rfc2616 sect 14.1
* Media ranges can be overridden by more specific media ranges or
* specific media types. If more than one media range applies to a given
* type, the most specific reference has precedence. For example,
*
* Accept: text/*, text/html, text/html;level=1, * /*
*
* have the following precedence:
*
* 1) text/html;level=1
* 2) text/html
* 3) text/*
* 4) * /*
*
* @return number
*/
protected function sortFieldValueParts()
{
$sort = function ($a, $b) {
// If A has higher precedence than B, return -1.
if ($a->priority > $b->priority) {
return -1;
} elseif ($a->priority < $b->priority) {
return 1;
}
// Asterisks
$values = ['type', 'subtype', 'format'];
foreach ($values as $value) {
if ($a->$value == '*' && $b->$value != '*') {
return 1;
} elseif ($b->$value == '*' && $a->$value != '*') {
return -1;
}
}
if ($a->type == 'application' && $b->type != 'application') {
return -1;
} elseif ($b->type == 'application' && $a->type != 'application') {
return 1;
}
// @todo count number of dots in case of type==application in subtype
// So far they're still the same. Longest string length may be more specific
if (strlen($a->raw) == strlen($b->raw)) {
return 0;
}
return (strlen($a->raw) > strlen($b->raw)) ? -1 : 1;
};
usort($this->fieldValueParts, $sort);
$this->sorted = true;
}
/**
* @return array with all the keys, values and parameters this header represents:
*/
public function getPrioritized()
{
if (! $this->sorted) {
$this->sortFieldValueParts();
}
return $this->fieldValueParts;
}
}