Header.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023
  1. <?php
  2. /**
  3. * The KO7_HTTP_Header class provides an Object-Orientated interface
  4. * to HTTP headers. This can parse header arrays returned from the
  5. * PHP functions `apache_request_headers()` or the `http_parse_headers()`
  6. * function available within the PECL HTTP library.
  7. *
  8. * @package KO7
  9. * @category HTTP
  10. *
  11. * @since 3.1.0
  12. * @copyright (c) 2007-2016 Kohana Team
  13. * @copyright (c) since 2016 Koseven Team
  14. * @license https://koseven.dev/LICENSE
  15. */
  16. class KO7_HTTP_Header extends ArrayObject {
  17. // Default Accept-* quality value if none supplied
  18. const DEFAULT_QUALITY = 1;
  19. /**
  20. * Parses an Accept(-*) header and detects the quality
  21. *
  22. * @param array $parts accept header parts
  23. * @return array
  24. * @since 3.2.0
  25. */
  26. public static function accept_quality(array $parts)
  27. {
  28. $parsed = [];
  29. // Resource light iteration
  30. $parts_keys = array_keys($parts);
  31. foreach ($parts_keys as $key)
  32. {
  33. $value = trim(str_replace(["\r", "\n"], '', $parts[$key]));
  34. $pattern = '~\b(\;\s*+)?q\s*+=\s*+([.0-9]+)~';
  35. // If there is no quality directive, return default
  36. if ( ! preg_match($pattern, $value, $quality))
  37. {
  38. $parsed[$value] = (float) HTTP_Header::DEFAULT_QUALITY;
  39. }
  40. else
  41. {
  42. $quality = $quality[2];
  43. if ($quality[0] === '.')
  44. {
  45. $quality = '0'.$quality;
  46. }
  47. // Remove the quality value from the string and apply quality
  48. $parsed[trim(preg_replace($pattern, '', $value, 1), '; ')] = (float) $quality;
  49. }
  50. }
  51. return $parsed;
  52. }
  53. /**
  54. * Parses the accept header to provide the correct quality values
  55. * for each supplied accept type.
  56. *
  57. * @link http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1
  58. * @param string $accepts accept content header string to parse
  59. * @return array
  60. * @since 3.2.0
  61. */
  62. public static function parse_accept_header($accepts = NULL)
  63. {
  64. $accepts = explode(',', (string) $accepts);
  65. // If there is no accept, lets accept everything
  66. if ($accepts === NULL)
  67. return ['*' => ['*' => (float) HTTP_Header::DEFAULT_QUALITY]];
  68. // Parse the accept header qualities
  69. $accepts = HTTP_Header::accept_quality($accepts);
  70. $parsed_accept = [];
  71. // This method of iteration uses less resource
  72. $keys = array_keys($accepts);
  73. foreach ($keys as $key)
  74. {
  75. // Extract the parts
  76. $parts = explode('/', $key, 2);
  77. // Invalid content type- bail
  78. if ( ! isset($parts[1]))
  79. continue;
  80. // Set the parsed output
  81. $parsed_accept[$parts[0]][$parts[1]] = $accepts[$key];
  82. }
  83. return $parsed_accept;
  84. }
  85. /**
  86. * Parses the `Accept-Charset:` HTTP header and returns an array containing
  87. * the charset and associated quality.
  88. *
  89. * @link http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.2
  90. * @param string $charset charset string to parse
  91. * @return array
  92. * @since 3.2.0
  93. */
  94. public static function parse_charset_header($charset = NULL)
  95. {
  96. if ($charset === NULL)
  97. {
  98. return ['*' => (float) HTTP_Header::DEFAULT_QUALITY];
  99. }
  100. return HTTP_Header::accept_quality(explode(',', (string) $charset));
  101. }
  102. /**
  103. * Parses the `Accept-Encoding:` HTTP header and returns an array containing
  104. * the charsets and associated quality.
  105. *
  106. * @link http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3
  107. * @param string $encoding charset string to parse
  108. * @return array
  109. * @since 3.2.0
  110. */
  111. public static function parse_encoding_header($encoding = NULL)
  112. {
  113. // Accept everything
  114. if ($encoding === NULL)
  115. {
  116. return ['*' => (float) HTTP_Header::DEFAULT_QUALITY];
  117. }
  118. elseif ($encoding === '')
  119. {
  120. return ['identity' => (float) HTTP_Header::DEFAULT_QUALITY];
  121. }
  122. else
  123. {
  124. return HTTP_Header::accept_quality(explode(',', (string) $encoding));
  125. }
  126. }
  127. /**
  128. * Parses the `Accept-Language:` HTTP header and returns an array containing
  129. * the languages and associated quality.
  130. *
  131. * @link http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
  132. * @param string $language charset string to parse
  133. * @return array
  134. * @since 3.2.0
  135. */
  136. public static function parse_language_header($language = NULL)
  137. {
  138. if ($language === NULL)
  139. {
  140. return ['*' => ['*' => (float) HTTP_Header::DEFAULT_QUALITY]];
  141. }
  142. $language = HTTP_Header::accept_quality(explode(',', (string) $language));
  143. $parsed_language = [];
  144. $keys = array_keys($language);
  145. foreach ($keys as $key)
  146. {
  147. // Extract the parts
  148. $parts = explode('-', $key, 2);
  149. // Invalid content type- bail
  150. if ( ! isset($parts[1]))
  151. {
  152. $parsed_language[$parts[0]]['*'] = $language[$key];
  153. }
  154. else
  155. {
  156. // Set the parsed output
  157. $parsed_language[$parts[0]][$parts[1]] = $language[$key];
  158. }
  159. }
  160. return $parsed_language;
  161. }
  162. /**
  163. * Generates a Cache-Control HTTP header based on the supplied array.
  164. *
  165. * // Set the cache control headers you want to use
  166. * $cache_control = array(
  167. * 'max-age' => 3600,
  168. * 'must-revalidate',
  169. * 'public'
  170. * );
  171. *
  172. * // Create the cache control header, creates :
  173. * // cache-control: max-age=3600, must-revalidate, public
  174. * $response->headers('Cache-Control', HTTP_Header::create_cache_control($cache_control);
  175. *
  176. * @link http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13
  177. * @param array $cache_control Cache-Control to render to string
  178. * @return string
  179. */
  180. public static function create_cache_control(array $cache_control)
  181. {
  182. $parts = [];
  183. foreach ($cache_control as $key => $value)
  184. {
  185. $parts[] = (is_int($key)) ? $value : ($key.'='.$value);
  186. }
  187. return implode(', ', $parts);
  188. }
  189. /**
  190. * Parses the Cache-Control header and returning an array representation of the Cache-Control
  191. * header.
  192. *
  193. * // Create the cache control header
  194. * $response->headers('cache-control', 'max-age=3600, must-revalidate, public');
  195. *
  196. * // Parse the cache control header
  197. * if ($cache_control = HTTP_Header::parse_cache_control($response->headers('cache-control')))
  198. * {
  199. * // Cache-Control header was found
  200. * $maxage = $cache_control['max-age'];
  201. * }
  202. *
  203. * @param array $cache_control Array of headers
  204. * @return mixed
  205. */
  206. public static function parse_cache_control($cache_control)
  207. {
  208. $directives = explode(',', strtolower($cache_control));
  209. if ($directives === FALSE)
  210. return FALSE;
  211. $output = [];
  212. foreach ($directives as $directive)
  213. {
  214. if (strpos($directive, '=') !== FALSE)
  215. {
  216. list($key, $value) = explode('=', trim($directive), 2);
  217. $output[$key] = ctype_digit($value) ? (int) $value : $value;
  218. }
  219. else
  220. {
  221. $output[] = trim($directive);
  222. }
  223. }
  224. return $output;
  225. }
  226. /**
  227. * @var array Accept: (content) types
  228. */
  229. protected $_accept_content;
  230. /**
  231. * @var array Accept-Charset: parsed header
  232. */
  233. protected $_accept_charset;
  234. /**
  235. * @var array Accept-Encoding: parsed header
  236. */
  237. protected $_accept_encoding;
  238. /**
  239. * @var array Accept-Language: parsed header
  240. */
  241. protected $_accept_language;
  242. /**
  243. * @var array Accept-Language: language list of parsed header
  244. */
  245. protected $_accept_language_list;
  246. /**
  247. * Constructor method for [KO7_HTTP_Header]. Uses the standard constructor
  248. * of the parent `ArrayObject` class.
  249. *
  250. * $header_object = new HTTP_Header(array('x-powered-by' => 'KO7 3.1.x', 'expires' => '...'));
  251. *
  252. * @param mixed $input Input array
  253. * @param int $flags Flags
  254. * @param string $iterator_class The iterator class to use
  255. */
  256. public function __construct(array $input = [], $flags = 0, $iterator_class = 'ArrayIterator')
  257. {
  258. /**
  259. * @link http://www.w3.org/Protocols/rfc2616/rfc2616.html
  260. *
  261. * HTTP header declarations should be treated as case-insensitive
  262. */
  263. $input = array_change_key_case( (array) $input, CASE_LOWER);
  264. parent::__construct($input, $flags, $iterator_class);
  265. }
  266. /**
  267. * Returns the header object as a string, including
  268. * the terminating new line
  269. *
  270. * // Return the header as a string
  271. * echo (string) $request->headers();
  272. *
  273. * @return string
  274. */
  275. public function __toString()
  276. {
  277. $header = '';
  278. foreach ($this as $key => $value)
  279. {
  280. // Put the keys back the Case-Convention expected
  281. $key = Text::ucfirst($key);
  282. if (is_array($value))
  283. {
  284. $header .= $key.': '.(implode(', ', $value))."\r\n";
  285. }
  286. else
  287. {
  288. $header .= $key.': '.$value."\r\n";
  289. }
  290. }
  291. return $header."\r\n";
  292. }
  293. /**
  294. * Overloads `ArrayObject::offsetSet()` to enable handling of header
  295. * with multiple instances of the same directive. If the `$replace` flag
  296. * is `FALSE`, the header will be appended rather than replacing the
  297. * original setting.
  298. *
  299. * @param mixed $index index to set `$newval` to
  300. * @param mixed $newval new value to set
  301. * @param boolean $replace replace existing value
  302. * @return void
  303. * @since 3.2.0
  304. */
  305. public function offsetSet($index, $newval, $replace = TRUE)
  306. {
  307. // Ensure the index is lowercase
  308. $index = strtolower($index);
  309. if ($replace OR ! $this->offsetExists($index))
  310. {
  311. return parent::offsetSet($index, $newval);
  312. }
  313. $current_value = $this->offsetGet($index);
  314. if (is_array($current_value))
  315. {
  316. $current_value[] = $newval;
  317. }
  318. else
  319. {
  320. $current_value = [$current_value, $newval];
  321. }
  322. return parent::offsetSet($index, $current_value);
  323. }
  324. /**
  325. * Overloads the `ArrayObject::offsetExists()` method to ensure keys
  326. * are lowercase.
  327. *
  328. * @param string $index
  329. * @return boolean
  330. * @since 3.2.0
  331. */
  332. public function offsetExists($index)
  333. {
  334. return parent::offsetExists(strtolower($index));
  335. }
  336. /**
  337. * Overloads the `ArrayObject::offsetUnset()` method to ensure keys
  338. * are lowercase.
  339. *
  340. * @param string $index
  341. * @return void
  342. * @since 3.2.0
  343. */
  344. public function offsetUnset($index)
  345. {
  346. return parent::offsetUnset(strtolower($index));
  347. }
  348. /**
  349. * Overload the `ArrayObject::offsetGet()` method to ensure that all
  350. * keys passed to it are formatted correctly for this object.
  351. *
  352. * @param string $index index to retrieve
  353. * @return mixed
  354. * @since 3.2.0
  355. */
  356. public function offsetGet($index)
  357. {
  358. return parent::offsetGet(strtolower($index));
  359. }
  360. /**
  361. * Overloads the `ArrayObject::exchangeArray()` method to ensure that
  362. * all keys are changed to lowercase.
  363. *
  364. * @param mixed $input
  365. * @return array
  366. * @since 3.2.0
  367. */
  368. public function exchangeArray($input)
  369. {
  370. /**
  371. * @link http://www.w3.org/Protocols/rfc2616/rfc2616.html
  372. *
  373. * HTTP header declarations should be treated as case-insensitive
  374. */
  375. $input = array_change_key_case( (array) $input, CASE_LOWER);
  376. return parent::exchangeArray($input);
  377. }
  378. /**
  379. * Parses a HTTP Message header line and applies it to this HTTP_Header
  380. *
  381. * $header = $response->headers();
  382. * $header->parse_header_string(NULL, 'content-type: application/json');
  383. *
  384. * @param resource $resource the resource (required by Curl API)
  385. * @param string $header_line the line from the header to parse
  386. * @return int
  387. * @since 3.2.0
  388. */
  389. public function parse_header_string($resource, $header_line)
  390. {
  391. if (preg_match_all('/(\w[^\s:]*):[ ]*([^\r\n]*(?:\r\n[ \t][^\r\n]*)*)/', $header_line, $matches))
  392. {
  393. foreach ($matches[0] as $key => $value)
  394. {
  395. $this->offsetSet($matches[1][$key], $matches[2][$key], FALSE);
  396. }
  397. }
  398. return strlen($header_line);
  399. }
  400. /**
  401. * Returns the accept quality of a submitted mime type based on the
  402. * request `Accept:` header. If the `$explicit` argument is `TRUE`,
  403. * only precise matches will be returned, excluding all wildcard (`*`)
  404. * directives.
  405. *
  406. * // Accept: application/xml; application/json; q=.5; text/html; q=.2, text/*
  407. * // Accept quality for application/json
  408. *
  409. * // $quality = 0.5
  410. * $quality = $request->headers()->accepts_at_quality('application/json');
  411. *
  412. * // $quality_explicit = FALSE
  413. * $quality_explicit = $request->headers()->accepts_at_quality('text/plain', TRUE);
  414. *
  415. * @param string $type
  416. * @param boolean $explicit explicit check, excludes `*`
  417. * @return mixed
  418. * @since 3.2.0
  419. */
  420. public function accepts_at_quality($type, $explicit = FALSE)
  421. {
  422. // Parse Accept header if required
  423. if ($this->_accept_content === NULL)
  424. {
  425. if ($this->offsetExists('Accept'))
  426. {
  427. $accept = $this->offsetGet('Accept');
  428. }
  429. else
  430. {
  431. $accept = '*/*';
  432. }
  433. $this->_accept_content = HTTP_Header::parse_accept_header($accept);
  434. }
  435. // If not a real mime, try and find it in config
  436. if (strpos($type, '/') === FALSE)
  437. {
  438. $mime = KO7::$config->load('mimes.'.$type);
  439. if ($mime === NULL)
  440. return FALSE;
  441. $quality = FALSE;
  442. foreach ($mime as $_type)
  443. {
  444. $quality_check = $this->accepts_at_quality($_type, $explicit);
  445. $quality = ($quality_check > $quality) ? $quality_check : $quality;
  446. }
  447. return $quality;
  448. }
  449. $parts = explode('/', $type, 2);
  450. if (isset($this->_accept_content[$parts[0]][$parts[1]]))
  451. {
  452. return $this->_accept_content[$parts[0]][$parts[1]];
  453. }
  454. elseif ($explicit === TRUE)
  455. {
  456. return FALSE;
  457. }
  458. else
  459. {
  460. if (isset($this->_accept_content[$parts[0]]['*']))
  461. {
  462. return $this->_accept_content[$parts[0]]['*'];
  463. }
  464. elseif (isset($this->_accept_content['*']['*']))
  465. {
  466. return $this->_accept_content['*']['*'];
  467. }
  468. else
  469. {
  470. return FALSE;
  471. }
  472. }
  473. }
  474. /**
  475. * Returns the preferred response content type based on the accept header
  476. * quality settings. If items have the same quality value, the first item
  477. * found in the array supplied as `$types` will be returned.
  478. *
  479. * // Get the preferred acceptable content type
  480. * // Accept: text/html, application/json; q=.8, text/*
  481. * $result = $header->preferred_accept(array(
  482. * 'text/html'
  483. * 'text/rtf',
  484. * 'application/json'
  485. * )); // $result = 'application/json'
  486. *
  487. * $result = $header->preferred_accept(array(
  488. * 'text/rtf',
  489. * 'application/xml'
  490. * ), TRUE); // $result = FALSE (none matched explicitly)
  491. *
  492. *
  493. * @param array $types the content types to examine
  494. * @param boolean $explicit only allow explicit references, no wildcards
  495. * @return string name of the preferred content type
  496. * @since 3.2.0
  497. */
  498. public function preferred_accept(array $types, $explicit = FALSE)
  499. {
  500. $preferred = FALSE;
  501. $ceiling = 0;
  502. foreach ($types as $type)
  503. {
  504. $quality = $this->accepts_at_quality($type, $explicit);
  505. if ($quality > $ceiling)
  506. {
  507. $preferred = $type;
  508. $ceiling = $quality;
  509. }
  510. }
  511. return $preferred;
  512. }
  513. /**
  514. * Returns the quality of the supplied `$charset` argument. This method
  515. * will automatically parse the `Accept-Charset` header if present and
  516. * return the associated resolved quality value.
  517. *
  518. * // Accept-Charset: utf-8, utf-16; q=.8, iso-8859-1; q=.5
  519. * $quality = $header->accepts_charset_at_quality('utf-8');
  520. * // $quality = (float) 1
  521. *
  522. * @param string $charset charset to examine
  523. * @return float the quality of the charset
  524. * @since 3.2.0
  525. */
  526. public function accepts_charset_at_quality($charset)
  527. {
  528. if ($this->_accept_charset === NULL)
  529. {
  530. if ($this->offsetExists('Accept-Charset'))
  531. {
  532. $charset_header = strtolower($this->offsetGet('Accept-Charset'));
  533. $this->_accept_charset = HTTP_Header::parse_charset_header($charset_header);
  534. }
  535. else
  536. {
  537. $this->_accept_charset = HTTP_Header::parse_charset_header(NULL);
  538. }
  539. }
  540. $charset = strtolower($charset);
  541. if (isset($this->_accept_charset[$charset]))
  542. {
  543. return $this->_accept_charset[$charset];
  544. }
  545. elseif (isset($this->_accept_charset['*']))
  546. {
  547. return $this->_accept_charset['*'];
  548. }
  549. elseif ($charset === 'iso-8859-1')
  550. {
  551. return (float) 1;
  552. }
  553. return (float) 0;
  554. }
  555. /**
  556. * Returns the preferred charset from the supplied array `$charsets` based
  557. * on the `Accept-Charset` header directive.
  558. *
  559. * // Accept-Charset: utf-8, utf-16; q=.8, iso-8859-1; q=.5
  560. * $charset = $header->preferred_charset(array(
  561. * 'utf-10', 'ascii', 'utf-16', 'utf-8'
  562. * )); // $charset = 'utf-8'
  563. *
  564. * @param array $charsets charsets to test
  565. * @return mixed preferred charset or `FALSE`
  566. * @since 3.2.0
  567. */
  568. public function preferred_charset(array $charsets)
  569. {
  570. $preferred = FALSE;
  571. $ceiling = 0;
  572. foreach ($charsets as $charset)
  573. {
  574. $quality = $this->accepts_charset_at_quality($charset);
  575. if ($quality > $ceiling)
  576. {
  577. $preferred = $charset;
  578. $ceiling = $quality;
  579. }
  580. }
  581. return $preferred;
  582. }
  583. /**
  584. * Returns the quality of the `$encoding` type passed to it. Encoding
  585. * is usually compression such as `gzip`, but could be some other
  586. * message encoding algorithm. This method allows explicit checks to be
  587. * done ignoring wildcards.
  588. *
  589. * // Accept-Encoding: compress, gzip, *; q=.5
  590. * $encoding = $header->accepts_encoding_at_quality('gzip');
  591. * // $encoding = (float) 1.0s
  592. *
  593. * @param string $encoding encoding type to interrogate
  594. * @param boolean $explicit explicit check, ignoring wildcards and `identity`
  595. * @return float
  596. * @since 3.2.0
  597. */
  598. public function accepts_encoding_at_quality($encoding, $explicit = FALSE)
  599. {
  600. if ($this->_accept_encoding === NULL)
  601. {
  602. if ($this->offsetExists('Accept-Encoding'))
  603. {
  604. $encoding_header = $this->offsetGet('Accept-Encoding');
  605. }
  606. else
  607. {
  608. $encoding_header = NULL;
  609. }
  610. $this->_accept_encoding = HTTP_Header::parse_encoding_header($encoding_header);
  611. }
  612. // Normalize the encoding
  613. $encoding = strtolower($encoding);
  614. if (isset($this->_accept_encoding[$encoding]))
  615. {
  616. return $this->_accept_encoding[$encoding];
  617. }
  618. if ($explicit === FALSE)
  619. {
  620. if (isset($this->_accept_encoding['*']))
  621. {
  622. return $this->_accept_encoding['*'];
  623. }
  624. elseif ($encoding === 'identity')
  625. {
  626. return (float) HTTP_Header::DEFAULT_QUALITY;
  627. }
  628. }
  629. return (float) 0;
  630. }
  631. /**
  632. * Returns the preferred message encoding type based on quality, and can
  633. * optionally ignore wildcard references. If two or more encodings have the
  634. * same quality, the first listed in `$encodings` will be returned.
  635. *
  636. * // Accept-Encoding: compress, gzip, *; q.5
  637. * $encoding = $header->preferred_encoding(array(
  638. * 'gzip', 'bzip', 'blowfish'
  639. * ));
  640. * // $encoding = 'gzip';
  641. *
  642. * @param array $encodings encodings to test against
  643. * @param boolean $explicit explicit check, if `TRUE` wildcards are excluded
  644. * @return mixed
  645. * @since 3.2.0
  646. */
  647. public function preferred_encoding(array $encodings, $explicit = FALSE)
  648. {
  649. $ceiling = 0;
  650. $preferred = FALSE;
  651. foreach ($encodings as $encoding)
  652. {
  653. $quality = $this->accepts_encoding_at_quality($encoding, $explicit);
  654. if ($quality > $ceiling)
  655. {
  656. $ceiling = $quality;
  657. $preferred = $encoding;
  658. }
  659. }
  660. return $preferred;
  661. }
  662. /**
  663. * Returns the quality of `$language` supplied, optionally ignoring
  664. * wildcards if `$explicit` is set to a non-`FALSE` value. If the quality
  665. * is not found, `0.0` is returned.
  666. *
  667. * // Accept-Language: en-us, en-gb; q=.7, en; q=.5
  668. * $lang = $header->accepts_language_at_quality('en-gb');
  669. * // $lang = (float) 0.7
  670. *
  671. * $lang2 = $header->accepts_language_at_quality('en-au');
  672. * // $lang2 = (float) 0.5
  673. *
  674. * $lang3 = $header->accepts_language_at_quality('en-au', TRUE);
  675. * // $lang3 = (float) 0.0
  676. *
  677. * @param string $language language to interrogate
  678. * @param boolean $explicit explicit interrogation, `TRUE` ignores wildcards
  679. * @return float
  680. * @since 3.2.0
  681. */
  682. public function accepts_language_at_quality($language, $explicit = FALSE)
  683. {
  684. if ($this->_accept_language === NULL)
  685. {
  686. if ($this->offsetExists('Accept-Language'))
  687. {
  688. $language_header = strtolower($this->offsetGet('Accept-Language'));
  689. }
  690. else
  691. {
  692. $language_header = NULL;
  693. }
  694. $this->_accept_language = HTTP_Header::parse_language_header($language_header);
  695. }
  696. // Normalize the language
  697. $language_parts = explode('-', strtolower($language), 2);
  698. if (isset($this->_accept_language[$language_parts[0]]))
  699. {
  700. if (isset($language_parts[1]))
  701. {
  702. if (isset($this->_accept_language[$language_parts[0]][$language_parts[1]]))
  703. {
  704. return $this->_accept_language[$language_parts[0]][$language_parts[1]];
  705. }
  706. elseif ($explicit === FALSE AND isset($this->_accept_language[$language_parts[0]]['*']))
  707. {
  708. return $this->_accept_language[$language_parts[0]]['*'];
  709. }
  710. }
  711. elseif (isset($this->_accept_language[$language_parts[0]]['*']))
  712. {
  713. return $this->_accept_language[$language_parts[0]]['*'];
  714. }
  715. }
  716. if ($explicit === FALSE AND isset($this->_accept_language['*']))
  717. {
  718. return $this->_accept_language['*'];
  719. }
  720. return (float) 0;
  721. }
  722. /**
  723. * Parses the `Accept-Language:` HTTP header and returns an array containing
  724. * the language names.
  725. *
  726. * @param string $language charset string to parse
  727. * @return array
  728. * @since 3.3.8
  729. */
  730. protected static function _parse_language_header_as_list($language = NULL)
  731. {
  732. $languages = [];
  733. $language = explode(',', strtolower($language));
  734. foreach ($language as $lang)
  735. {
  736. $matches = [];
  737. if (preg_match('/([\w-]+)\s*(;.*q.*)?/', $lang, $matches))
  738. {
  739. $languages[] = $matches[1];
  740. }
  741. }
  742. return $languages;
  743. }
  744. /**
  745. * Returns the reordered list of supplied `$languages` using the order
  746. * from the `Accept-Language:` HTTP header.
  747. *
  748. * @param array $languages languages to order
  749. * @param boolean $explicit
  750. * @return array
  751. * @since 3.3.8
  752. */
  753. protected function _order_languages_as_received(array $languages, $explicit = FALSE)
  754. {
  755. if ($this->_accept_language_list === NULL)
  756. {
  757. if ($this->offsetExists('Accept-Language'))
  758. {
  759. $language_header = strtolower($this->offsetGet('Accept-Language'));
  760. }
  761. else
  762. {
  763. $language_header = NULL;
  764. }
  765. $this->_accept_language_list = HTTP_Header::_parse_language_header_as_list($language_header);
  766. }
  767. $new_order = [];
  768. foreach ($this->_accept_language_list as $accept_language)
  769. {
  770. foreach ($languages as $key => $language)
  771. {
  772. if (($explicit AND $accept_language == $language) OR
  773. ( ! $explicit AND substr($accept_language, 0, 2) == substr($language, 0, 2)))
  774. {
  775. $new_order[] = $language;
  776. unset($languages[$key]);
  777. }
  778. }
  779. }
  780. foreach ($languages as $language)
  781. {
  782. $new_order[] = $language;
  783. }
  784. return $new_order;
  785. }
  786. /**
  787. * Returns the preferred language from the supplied array `$languages` based
  788. * on the `Accept-Language` header directive.
  789. *
  790. * // Accept-Language: en-us, en-gb; q=.7, en; q=.5
  791. * $lang = $header->preferred_language(array(
  792. * 'en-gb', 'en-au', 'fr', 'es'
  793. * )); // $lang = 'en-gb'
  794. *
  795. * @param array $languages
  796. * @param boolean $explicit
  797. * @return mixed
  798. * @since 3.2.0
  799. */
  800. public function preferred_language(array $languages, $explicit = FALSE)
  801. {
  802. $ceiling = 0;
  803. $preferred = FALSE;
  804. $languages = $this->_order_languages_as_received($languages, $explicit);
  805. foreach ($languages as $language)
  806. {
  807. $quality = $this->accepts_language_at_quality($language, $explicit);
  808. if ($quality > $ceiling)
  809. {
  810. $ceiling = $quality;
  811. $preferred = $language;
  812. }
  813. }
  814. return $preferred;
  815. }
  816. /**
  817. * Sends headers to the php processor, or supplied `$callback` argument.
  818. * This method formats the headers correctly for output, re-instating their
  819. * capitalization for transmission.
  820. *
  821. * [!!] if you supply a custom header handler via `$callback`, it is
  822. * recommended that `$response` is returned
  823. *
  824. * @param HTTP_Response $response header to send
  825. * @param boolean $replace replace existing value
  826. * @param callback $callback optional callback to replace PHP header function
  827. * @return mixed
  828. * @since 3.2.0
  829. */
  830. public function send_headers(HTTP_Response $response = NULL, $replace = FALSE, $callback = NULL)
  831. {
  832. $protocol = $response->protocol();
  833. $status = $response->status();
  834. // Create the response header
  835. $processed_headers = [$protocol.' '.$status.' '.Response::$messages[$status]];
  836. // Get the headers array
  837. $headers = $response->headers()->getArrayCopy();
  838. foreach ($headers as $header => $value)
  839. {
  840. if (is_array($value))
  841. {
  842. $value = implode(', ', $value);
  843. }
  844. $processed_headers[] = Text::ucfirst($header).': '.$value;
  845. }
  846. if ( ! isset($headers['content-type']))
  847. {
  848. $processed_headers[] = 'Content-Type: '.KO7::$content_type.'; charset='.KO7::$charset;
  849. }
  850. if (KO7::$expose AND ! isset($headers['x-powered-by']))
  851. {
  852. $processed_headers[] = 'X-Powered-By: '.KO7::version();
  853. }
  854. // Get the cookies and apply
  855. if ($cookies = $response->cookie())
  856. {
  857. $processed_headers['Set-Cookie'] = $cookies;
  858. }
  859. if (is_callable($callback))
  860. {
  861. // Use the callback method to set header
  862. return call_user_func($callback, $response, $processed_headers, $replace);
  863. }
  864. else
  865. {
  866. $this->_send_headers_to_php($processed_headers, $replace);
  867. return $response;
  868. }
  869. }
  870. /**
  871. * Sends the supplied headers to the PHP output buffer. If cookies
  872. * are included in the message they will be handled appropriately.
  873. *
  874. * @param array $headers headers to send to php
  875. * @param boolean $replace replace existing headers
  876. * @return self
  877. * @since 3.2.0
  878. */
  879. protected function _send_headers_to_php(array $headers, $replace)
  880. {
  881. // If the headers have been sent, get out
  882. if (headers_sent())
  883. return $this;
  884. foreach ($headers as $key => $line)
  885. {
  886. if ($key == 'Set-Cookie' AND is_array($line))
  887. {
  888. // Send cookies
  889. foreach ($line as $name => $value)
  890. {
  891. Cookie::set($name, $value['value'], $value['expiration']);
  892. }
  893. continue;
  894. }
  895. header($line, $replace);
  896. }
  897. return $this;
  898. }
  899. }