function testgetHttpVersion() { $h = new HTTP_Header(); $this->assertTrue($h->getHttpVersion() == 1.0 || $h->getHttpVersion() == 1.1, ' http version is 1.0 or 1.1'); $h->setHttpVersion(1); $this->assertEquals(1, $h->getHttpVersion()); $h->setHttpVersion(1.1); $this->assertEquals(1.1, $h->getHttpVersion()); $h->setHttpVersion(2); $this->assertEquals(1.1, $h->getHttpVersion()); unset($h); }
/** * Check Cache * * Checks the browser cache to see the response needs to be returned * * @param string $etag Resource ETag [Optional] * @param Request $request The request to test against [Optional] * * @return Response * * @throws Request_Exception */ public function check_cache($etag = NULL, Request $request = NULL) { if (!$etag) { $etag = $this->generate_etag(); } if (!$request) { throw new Request_Exception('A Request object must be supplied with an etag for evaluation'); } // Set the ETag header $this->_header['etag'] = $etag; // Add the Cache-Control header if it is not already set // This allows etags to be used with max-age, etc if ($this->_header->offsetExists('cache-control')) { if (is_array($this->_header['cache-control'])) { // @todo $this->_header['cache-control'][] = new HTTP_Header_Value('must-revalidate'); } else { $this->_header['cache-control'] = $this->_header['cache-control'] . ', must-revalidate'; } } else { $this->_header['cache-control'] = 'must-revalidate'; } if ($request->headers('if-none-match') and (string) $request->headers('if-none-match') === $etag) { // No need to send data again $this->_status = 304; $this->send_headers(); // Stop execution exit; } return $this; }
/** * Override of the set_cache method, works in exactly the same way except * the check for the max-age header in the response has been removed so that * Codebase API responses will always be cached, this breaks HTTP Cache * rules but is the cleanest way of enabling caching for all responses * within Kohana. * * @param Response $response * @return boolean */ public function set_cache(Response $response) { $headers = $response->headers()->getArrayCopy(); if ($cache_control = Arr::get($headers, 'cache-control')) { // Parse the cache control $cache_control = HTTP_Header::parse_cache_control($cache_control); // If the no-cache or no-store directive is set, return if (array_intersect($cache_control, array('no-cache', 'no-store'))) { return FALSE; } // Check for private cache and get out of here if invalid if (!$this->_allow_private_cache and in_array('private', $cache_control)) { if (!isset($cache_control['s-maxage'])) { return FALSE; } // If there is a s-maxage directive we can use that $cache_control['max-age'] = $cache_control['s-maxage']; } } /** * if the max-age cache control header is set to 0 in the response, set * it to 1 hour so the reponse will be cacheable */ $cache_control_header = $response->headers('Cache-Control'); $response->headers('Cache-Control', str_replace('max-age=0', 'max-age=3600', $cache_control_header)); if ($expires = Arr::get($headers, 'expires') and !isset($cache_control['max-age'])) { // Can't cache things that have expired already if (strtotime($expires) <= time()) { return FALSE; } } return TRUE; }
/** * Constructor * * Set the amount of time to cache. * * @access public * @return object HTTP_Header_Cache * @param int $expires * @param string $unit */ function HTTP_Header_Cache($expires = 0, $unit = 'seconds') { parent::HTTP_Header(); $this->setHeader('Pragma', 'cache'); $this->setHeader('Cache-Control', 'public'); $this->setHeader('Last-Modified', $this->getCacheStart()); if ($expires && !$this->isOlderThan($expires, $unit)) { $this->exitIfCached(); } }
/** * Constructor * * Set the amount of time to cache. * * @access public * @return object HTTP_Header_Cache * @param int $expires * @param string $unit */ function HTTP_Header_Cache($expires = 0, $unit = 'seconds') { parent::HTTP_Header(); $this->setHeader('Pragma', 'cache'); $this->setHeader('Last-Modified', $this->getCacheStart()); $this->setHeader('Cache-Control', 'private, must-revalidate, max-age=0'); if ($expires) { if (!$this->isOlderThan($expires, $unit)) { $this->exitCached(); } $this->setHeader('Last-Modified', time()); } }
function &factory($name) { $name = empty($name) ? APPLICATION_DEFAULT_PAGE : $name; include_once $file = PAGE_FACTORY_SEARCH_DIR . $name . '.php'; if (!class_exists($classname = 'Page_' . basename($file, '.php'))) { if ($name == APPLICATION_404_PAGE) { return PEAR::raiseError(null, PAGE_FACTORY_ERROR_NOT_FOUND, null, null, null, 'PageFactory_Error', true); } else { HTTP_Header::redirect(SAURL::url(APPLICATION_404_PAGE)); exit; } } $obj =& new $classname(); return $obj; }
function SApplication() { $this->_updateMeStatic(); if (ENABLE_PROFILING) { include_once 'Benchmark/Timer.php'; $this->_timer =& new Benchmark_Timer(); $this->_timer->start(); } parent::PEAR(); $u = SAURL::restore(); if (PEAR::isError($u)) { if ($u->getCode() == URL_MANIPULATION) { HTTP_Header::redirect(SAUrl::Url(APPLICATION_401_PAGE)); exit; } } }
/** * Устанавливает язык интерфейса в зависимости от настроек в браузере пользователя * * @param $default - site language * @param bool $strict - always use the language specified in the config file? * * @return mixed */ public static function get_accepted_language($default, $strict = true) { if ($strict) { return $default; } // Учитываем язык в настройках браузера if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { $langs = HTTP_Header::parse_language_header($_SERVER['HTTP_ACCEPT_LANGUAGE']); if (is_array($langs)) { $langs = array_keys($langs); return array_shift($langs); } else { return $default; } } else { return $default; } }
/** * Tests the parse_header_values() method. * * @dataProvider provider_parse_header_values * * @param array header array to parse * @param array expected result * @return void */ public function test_parse_header_values($header_array, $expected) { $header = HTTP_Header::parse_header_values($header_array); // Test the correct type is returned $this->assertTrue(is_array($header)); foreach ($header as $key => $value) { if ($value instanceof HTTP_Header_Value) { $this->assertSame($value->value(), $expected[$key]->value()); $this->assertSame($value->key(), $expected[$key]->key()); $this->assertSame($value->properties(), $expected[$key]->properties()); } elseif (is_array($value)) { foreach ($value as $k => $v) { $this->assertSame($v->value(), $expected[$key][$k]->value()); $this->assertSame($v->key(), $expected[$key][$k]->key()); $this->assertSame($v->properties(), $expected[$key][$k]->properties()); } } else { $this->fail('Unexpected value in HTTP_Header::parse_header_values() return value.'); } } }
/** * Calculates the total Time To Live based on the specification * RFC 2616 cache lifetime rules. * * @param Response $response Response to evaluate * @return mixed TTL value or false if the response should not be cached */ public function cache_lifetime(Response $response) { // Get out of here if this cannot be cached if (!$this->set_cache($response)) { return FALSE; } // Calculate apparent age if ($date = $response->headers('date')) { $apparent_age = max(0, $this->_response_time - strtotime($date)); } else { $apparent_age = max(0, $this->_response_time); } // Calculate corrected received age if ($age = $response->headers('age')) { $corrected_received_age = max($apparent_age, intval($age)); } else { $corrected_received_age = $apparent_age; } // Corrected initial age $corrected_initial_age = $corrected_received_age + $this->request_execution_time(); // Resident time $resident_time = time() - $this->_response_time; // Current age $current_age = $corrected_initial_age + $resident_time; // Prepare the cache freshness lifetime $ttl = NULL; // Cache control overrides if ($cache_control = $response->headers('cache-control')) { // Parse the cache control header $cache_control = HTTP_Header::parse_cache_control($cache_control); if (isset($cache_control['max-age'])) { $ttl = $cache_control['max-age']; } if (isset($cache_control['s-maxage']) and isset($cache_control['private']) and $this->_allow_private_cache) { $ttl = $cache_control['s-maxage']; } if (isset($cache_control['max-stale']) and !isset($cache_control['must-revalidate'])) { $ttl = $current_age + $cache_control['max-stale']; } } // If we have a TTL at this point, return if ($ttl !== NULL) { return $ttl; } if ($expires = $response->headers('expires')) { return strtotime($expires) - $current_age; } return FALSE; }
/** * Returns the quality of `$language` supplied, optionally ignoring * wildcards if `$explicit` is set to a non-`FALSE` value. If the quality * is not found, `0.0` is returned. * * // Accept-Language: en-us, en-gb; q=.7, en; q=.5 * $lang = $header->accepts_language_at_quality('en-gb'); * // $lang = (float) 0.7 * * $lang2 = $header->accepts_language_at_quality('en-au'); * // $lang2 = (float) 0.5 * * $lang3 = $header->accepts_language_at_quality('en-au', TRUE); * // $lang3 = (float) 0.0 * * @param string $language language to interrogate * @param boolean $explicit explicit interrogation, `TRUE` ignores wildcards * @return float * @since 3.2.0 */ public function accepts_language_at_quality($language, $explicit = FALSE) { if ($this->_accept_language === NULL) { if ($this->offsetExists('Accept-Language')) { $language_header = strtolower($this->offsetGet('Accept-Language')); } else { $language_header = NULL; } $this->_accept_language = HTTP_Header::parse_language_header($language_header); } // Normalize the language $language_parts = explode('-', strtolower($language), 2); if (isset($this->_accept_language[$language_parts[0]])) { if (isset($language_parts[1])) { if (isset($this->_accept_language[$language_parts[0]][$language_parts[1]])) { return $this->_accept_language[$language_parts[0]][$language_parts[1]]; } elseif ($explicit === FALSE and isset($this->_accept_language[$language_parts[0]]['*'])) { return $this->_accept_language[$language_parts[0]]['*']; } } elseif (isset($this->_accept_language[$language_parts[0]]['*'])) { return $this->_accept_language[$language_parts[0]]['*']; } } if ($explicit === FALSE and isset($this->_accept_language['*'])) { return $this->_accept_language['*']; } return (double) 0; }
/** * Tests that `preferred_language` correctly identifies the right * language based on the Accept-Language header and `$explicit` setting * * @dataProvider provider_preferred_language * * @param array state in * @param array languages to interrogate * @param boolean explicit check * @param string expected output * @return void */ public function test_preferred_language(array $state, array $languages, $explicit, $expected) { $header = new HTTP_Header($state); $this->assertSame($expected, $header->preferred_language($languages, $explicit)); }
<?php require_once 'HTTP/Header.php'; $h =& new HTTP_Header(); $s = 200; foreach ($_GET as $header => $value) { if (!strcasecmp('redirect', $header)) { HTTP_Header::redirect($value); } if (strcasecmp('status', $header)) { $h->setHeader($header, $value); } else { $s = $value; } } $h->sendHeaders(); $h->sendStatusCode($s);
/** * Gets or sets HTTP headers to the request or response. All headers * are included immediately after the HTTP protocol definition during * transmission. This method provides a simple array or key/value * interface to the headers. * * @param mixed $key Key or array of key/value pairs to set * @param string $value Value to set to the supplied key * * @return Request|HTTP_Header|mixed */ public function headers($key = NULL, $value = NULL) { if ($key instanceof HTTP_Header) { // Act a setter, replace all headers $this->_header = $key; return $this; } if (is_array($key)) { // Act as a setter, replace all headers $this->_header->exchangeArray($key); return $this; } if ($this->_header->count() === 0 and $this->is_initial()) { // Lazy load the request headers $this->_header = HTTP::request_headers(); } if ($key === NULL) { // Act as a getter, return all headers return $this->_header; } elseif ($value === NULL) { // Act as a getter, single header return $this->_header->offsetExists($key) ? $this->_header->offsetGet($key) : NULL; } // Act as a setter for a single header $this->_header[$key] = $value; return $this; }
/** * Sort the headers by quality property if the header matches the * [Kohana_HTTP_Header::$default_sort_filter] definition. * * #### Default sort values * * - Accept * - Accept-Chars * - Accept-Encoding * - Accept-Lang * * @param array $filter Header fields to parse * @return self */ public function sort_values_by_quality(array $filter = array()) { // If a filter argument is supplied if ($filter) { // Apply filter and store previous $previous_filter = HTTP_Header::$default_sort_filter; HTTP_Header::$default_sort_filter = $filter; } // Get a copy of this ArrayObject $values = $this->getArrayCopy(); foreach ($values as $key => $value) { if (!is_array($value) or !in_array($key, HTTP_Header::$default_sort_filter)) { unset($values[$key]); continue; } // Sort them by comparison uasort($value, array($this, '_sort_by_comparison')); $values[$key] = $value; } // Return filter to previous state if required if ($filter) { HTTP_Header::$default_sort_filter = $previous_filter; } foreach ($values as $key => $value) { $this[$key] = $value; } // Return this return $this; }
/** * Parses the `Accept-Language:` HTTP header and returns an array containing * the languages and associated quality. * * @link http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4 * * @param string $language charset string to parse * * @return array * @since 3.2.0 */ public static function parse_language_header($language = null) { if ($language === null) { return ['*' => ['*' => (double) HTTP_Header::DEFAULT_QUALITY]]; } $language = HTTP_Header::accept_quality(explode(',', (string) $language)); $parsed_language = []; $keys = array_keys($language); foreach ($keys as $key) { // Extract the parts $parts = explode('-', $key, 2); // Invalid content type- bail if (!isset($parts[1])) { $parsed_language[$parts[0]]['*'] = $language[$key]; } else { // Set the parsed output $parsed_language[$parts[0]][$parts[1]] = $language[$key]; } } return $parsed_language; }
function render($options = array(), $added_assigns = array()) { if (is_string($options)) { $options = array('action' => $options); } if (isset($options['status'])) { require_once 'HTTP/Header.php'; $http = new HTTP_Header(); $http->sendStatusCode($options['status']); unset($http); } if (isset($options['nothing']) && $options['nothing']) { return ''; } if (isset($options['text'])) { $out = $options['text']; if ($options['layout']) { $this->renderLayout($options['layout'], $out); } return $out; } $return = isset($options['return']) ? (bool) $options['return'] : false; // non-default action might be passed $action = isset($options['action']) ? $options['action'] : $this->action; $filename = null; // look for specific file if (isset($options['file'])) { $filename = $options['file']; } if (!isset($filename) || !is_file($filename)) { // get the default filename $filename = $this->_getViewFileName(Inflector::underscore($action)); // var_dump($filename); } if (!$filename && !isset($options['layout'])) { // TODO: raise an error here - no file exists for the action/file specified return; } $out = ''; if ($filename) { $this->assign($this->_view_assigns); if (!$this->isCached($options)) { $this->assign('_EXTERNAL_CACHE_', defined('EXTERNAL_CACHE') && constant('EXTERNAL_CACHE') ? EXTERNAL_CACHE : false); $this->assign($added_assigns); } $out = $this->fetch($filename, $this->view_cache_name); } // check for a layout and render if one was passed if (isset($options['layout']) && (!$this->controller || (!isset($this->controller->params['bare']) || !$this->controller->params['bare']))) { $out = $this->renderLayout($options['layout'], $out, null, $return); } // return $out or print it if ($return) { return $out; } print $out; }