/** * 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; }
/** * check database connection based on provided setting */ public function checkConnection() { $success = false; $message = ''; $config = $this->getPostConfiguration(); try { $this->makeConnection($config); /** * Just trying to show tables with current connection */ switch ($config['driver']) { case 'mysql': $tables = Capsule::select('show tables'); break; case 'sqlite': $tables = Capsule::select("SELECT * FROM sqlite_master WHERE type='table'"); break; case 'sqlsrv': $tables = Capsule::select("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'"); break; case 'pgsql': $tables = Capsule::select("SELECT * FROM pg_catalog.pg_tables"); break; } $success = true; $message = 'Successfully connected!'; } catch (Exception $e) { $success = false; $message = $e->getMessage(); } Response::headers()->set('Content-Type', 'application/json'); Response::setBody(json_encode(array('success' => $success, 'message' => $message, 'config' => $config))); }
public static function check_cache(Request $request, Response $response, $etag = NULL) { if ($etag == NULL) { $etag = $response->generate_etag(); } $response->headers("etag", $etag); if ($response->headers("cache-control")) { $response->headers("cache-control", $response->headers("cache-control") . ", must-revalidate"); } else { $response->headers("cache-control", "must-revalidate"); } if ($request->headers("if-none-match") and (string) $request->headers("if-none-match") === $etag) { throw HTTP_Exception::factory(304)->headers("etag", $etag); } return $response; }
/** * Sends the HTTP message [Request] to a remote server and processes * the response. * * @param Request $request request to send * @param Response $request response to send * @return Response */ public function _send_message(Request $request, Response $response) { // Response headers $response_headers = array(); $options = array(); // Set the request method $options = $this->_set_curl_request_method($request, $options); // Set the request body. This is perfectly legal in CURL even // if using a request other than POST. PUT does support this method // and DOES NOT require writing data to disk before putting it, if // reading the PHP docs you may have got that impression. SdF // This will also add a Content-Type: application/x-www-form-urlencoded header unless you override it if ($body = $request->body()) { $options[CURLOPT_POSTFIELDS] = $request->body(); } // Process headers if ($headers = $request->headers()) { $http_headers = array(); foreach ($headers as $key => $value) { $http_headers[] = $key . ': ' . $value; } $options[CURLOPT_HTTPHEADER] = $http_headers; } // Process cookies if ($cookies = $request->cookie()) { $options[CURLOPT_COOKIE] = http_build_query($cookies, NULL, '; '); } // Get any exisiting response headers $response_header = $response->headers(); // Implement the standard parsing parameters $options[CURLOPT_HEADERFUNCTION] = array($response_header, 'parse_header_string'); $this->_options[CURLOPT_RETURNTRANSFER] = TRUE; $this->_options[CURLOPT_HEADER] = FALSE; // Apply any additional options set to $options += $this->_options; $uri = $request->uri(); if ($query = $request->query()) { $uri .= '?' . http_build_query($query, NULL, '&'); } // Open a new remote connection $curl = curl_init($uri); // Set connection options if (!curl_setopt_array($curl, $options)) { throw new Request_Exception('Failed to set CURL options, check CURL documentation: :url', array(':url' => 'http://php.net/curl_setopt_array')); } // Get the response body $body = curl_exec($curl); // Get the response information $code = curl_getinfo($curl, CURLINFO_HTTP_CODE); if ($body === FALSE) { $error = curl_error($curl); } // Close the connection curl_close($curl); if (isset($error)) { throw new Request_Exception('Error fetching remote :url [ status :code ] :error', array(':url' => $request->url(), ':code' => $code, ':error' => $error)); } $response->status($code)->body($body); return $response; }
/** * Test the content type is sent when set * * @test */ public function test_content_type_when_set() { $this->markTestSkipped('send_headers() can only be executed once, test will never pass in current API'); $content_type = 'application/json'; $response = new Response(); $response->headers('content-type', $content_type); $headers = $response->send_headers()->headers(); $this->assertSame($content_type, (string) $headers['content-type']); }
/** * Checks the browser cache to see the response needs to be returned, * execution will halt and a 304 Not Modified will be sent if the * browser cache is up to date. * * @param Request $request Request * @param Response $response Response * @param string $etag Resource ETag * @throws HTTP_Exception_304 * @return Response */ public static function check_cache(Request $request, Response $response, $etag = NULL) { // Generate an etag if necessary if ($etag == NULL) { $etag = $response->generate_etag(); } // Set the ETag header $response->headers('etag', $etag); // Add the Cache-Control header if it is not already set // This allows etags to be used with max-age, etc if ($response->headers('cache-control')) { $response->headers('cache-control', $response->headers('cache-control') . ', must-revalidate'); } else { $response->headers('cache-control', 'must-revalidate'); } // Check if we have a matching etag if ($request->headers('if-none-match') and (string) $request->headers('if-none-match') === $etag) { // No need to send data again throw HTTP_Exception::factory(304)->headers('etag', $etag); } return $response; }
function Auth() { if (!Sentry::check()) { if (Request::isAjax()) { Response::headers()->set('Content-Type', 'application/json'); Response::setBody(json_encode(array('success' => false, 'message' => 'Session expired or unauthorized access.', 'code' => 401))); App::stop(); } else { $redirect = Request::getResourceUri(); Response::redirect(App::urlFor('login') . '?redirect=' . base64_encode($redirect)); } } }
/** * check database connection based on provided setting */ public function checkConnection() { $success = false; $message = ''; $config = $this->getPostConfiguration(); try { $this->makeConnection($config); $tables = Capsule::select('show tables'); $success = true; $message = 'Successfully connected!'; } catch (Exception $e) { $success = false; $message = $e->getMessage(); } Response::headers()->set('Content-Type', 'application/json'); Response::setBody(json_encode(array('success' => $success, 'message' => $message, 'config' => $config))); }
/** * Sends the HTTP message [Request] to a remote server and processes * the response. * * @param Request $request request to send * @param Response $request response to send * @return Response * @uses [PHP cURL](http://php.net/manual/en/book.curl.php) */ public function _send_message(Request $request, Response $response) { // Calculate stream mode $mode = $request->method() === HTTP_Request::GET ? 'r' : 'r+'; // Process cookies if ($cookies = $request->cookie()) { $request->headers('cookie', http_build_query($cookies, NULL, '; ')); } // Get the message body $body = $request->body(); if (is_resource($body)) { $body = stream_get_contents($body); } // Set the content length $request->headers('content-length', (string) strlen($body)); list($protocol) = explode('/', $request->protocol()); // Create the context $options = array(strtolower($protocol) => array('method' => $request->method(), 'header' => (string) $request->headers(), 'content' => $body)); // Create the context stream $context = stream_context_create($options); stream_context_set_option($context, $this->_options); $uri = $request->uri(); if ($query = $request->query()) { $uri .= '?' . http_build_query($query, NULL, '&'); } $stream = fopen($uri, $mode, FALSE, $context); $meta_data = stream_get_meta_data($stream); // Get the HTTP response code $http_response = array_shift($meta_data['wrapper_data']); if (preg_match_all('/(\\w+\\/\\d\\.\\d) (\\d{3})/', $http_response, $matches) !== FALSE) { $protocol = $matches[1][0]; $status = (int) $matches[2][0]; } else { $protocol = NULL; $status = NULL; } // Get any exisiting response headers $response_header = $response->headers(); // Process headers array_map(array($response_header, 'parse_header_string'), array(), $meta_data['wrapper_data']); $response->status($status)->protocol($protocol)->body(stream_get_contents($stream)); // Close the stream after use fclose($stream); return $response; }
/** * Vérification de la connection sur base des informations fournies */ public function checkConnection() { $success = false; $message = ''; $config = $this->getPostConfiguration(); try { $this->makeConnection($config); /** * Essaie de montrer les tables ! */ switch ($config['driver']) { case 'mysql': $tables = Capsule::select('show tables'); break; } $success = true; $message = 'Connexion établie avec succés !'; } catch (Exception $e) { $success = false; $message = $e->getMessage(); } Response::headers()->set('Content-Type', 'application/json'); Response::setBody(json_encode(array('success' => $success, 'message' => $message, 'config' => $config))); }
<?php /** * Sample group routing with user check in middleware */ Route::group('/admin', function () { if (!Sentry::check()) { if (Request::isAjax()) { Response::headers()->set('Content-Type', 'application/json'); Response::setBody(json_encode(array('success' => false, 'message' => 'Session expired or unauthorized access.', 'code' => 401))); App::stop(); } else { $redirect = Request::getResourceUri(); Response::redirect(App::urlFor('login') . '?redirect=' . base64_encode($redirect)); } } }, function () use($app) { /** sample namespaced controller */ Route::get('/', 'Admin\\AdminController:index')->name('admin'); foreach (Module::getModules() as $module) { $module->registerAdminRoute(); } }); Route::get('/login', 'Admin\\AdminController:login')->name('login'); Route::get('/logout', 'Admin\\AdminController:logout')->name('logout'); Route::post('/login', 'Admin\\AdminController:doLogin'); /** Route to documentation */ Route::get('/doc(/:page+)', 'DocController:index'); foreach (Module::getModules() as $module) { $module->registerPublicRoute(); }
/** * Test the content type is sent when set * * @test */ public function test_content_type_when_set() { $content_type = 'application/json'; $response = new Response(); $response->headers('content-type', $content_type); $headers = $response->send_headers()->headers(); $this->assertSame($content_type, (string) $headers['content-type']); }
public function testAddHeaderShouldAddHeaderToHeadersList() { $response = new Response(); $response->header('some header'); $this->assertContains('some header', $response->headers()); }
/** * Test headers * * Pre-conditions: * Case A: Set Content-Type to 'application/json' * Case B: Get non-existent header * * Post-conditions: * Case A: Header is set correctly * Case B: Returned value is NULL */ public function testResponseHeaders() { //Case A $r1 = new Response(); $r1->header('Content-Type', 'application/json'); $this->assertEquals($r1->header('Content-Type'), 'application/json'); $this->assertEquals($r1->headers(), array('Content-Type' => 'application/json')); //Case B $this->assertNull($r1->header('foo')); }
/** * Controls whether the response can be cached. Uses HTTP * protocol to determine whether the response can be cached. * * @link http://www.w3.org/Protocols/rfc2616/rfc2616.html RFC 2616 * @param Response $response The 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']; } // Check that max-age has been set and if it is valid for caching if (isset($cache_control['max-age']) and $cache_control['max-age'] < 1) { return FALSE; } } 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; }
/** * Tests that send headers processes the headers sent to PHP correctly * * @dataProvider provider_send_headers * * @param array state in * @param array expected out * @return void */ public function test_send_headers(array $state, array $expected, $expose) { Kohana::$expose = $expose; $response = new Response(); $response->headers($state); $this->assertSame($expected, $response->send_headers(FALSE, array($this, 'send_headers_handler'))); }
public static function on_header_location(Request $request, Response $response, Request_Client $client) { if ($client->follow() and in_array($response->status(), array(201, 301, 302, 303, 307))) { switch ($response->status()) { default: case 301: case 307: $follow_method = $request->method(); break; case 201: case 303: $follow_method = Request::GET; break; case 302: if ($client->strict_redirect()) { $follow_method = $request->method(); } else { $follow_method = Request::GET; } break; } $orig_headers = $request->headers()->getArrayCopy(); $follow_header_keys = array_intersect(array_keys($orig_headers), $client->follow_headers()); $follow_headers = \Arr::extract($orig_headers, $follow_header_keys); $follow_request = Request::factory($response->headers("Location"))->method($follow_method)->headers($follow_headers); if ($follow_method !== Request::GET) { $follow_request->body($request->body()); } return $follow_request; } return NULL; }
private function mergeResponse(KohanaResponse $kohanaResponse, NucleusResponse $nucleusResponse) { $kohanaResponse->body($nucleusResponse->getContent()); $kohanaResponse->headers($nucleusResponse->headers->all()); $kohanaResponse->status($nucleusResponse->getStatusCode()); foreach ($nucleusResponse->headers->getCookies() as $cookie) { /* @var $cookie \Symfony\Component\HttpFoundation\Cookie */ $kohanaResponse->cookie($cookie->getName(), array('value' => $cookie->getValue(), 'expiration' => $cookie->getExpiresTime())); } }
/** * The default handler for following redirects, triggered by the presence of * a Location header in the response. * * The client's follow property must be set TRUE and the HTTP response status * one of 201, 301, 302, 303 or 307 for the redirect to be followed. * * @param Request $request * @param Response $response * @param Request_Client $client */ public static function on_header_location(Request $request, Response $response, Request_Client $client) { // Do we need to follow a Location header ? if ($client->follow() and in_array($response->status(), array(201, 301, 302, 303, 307))) { // Figure out which method to use for the follow request switch ($response->status()) { default: case 301: case 307: $follow_method = $request->method(); break; case 201: case 303: $follow_method = Request::GET; break; case 302: // Cater for sites with broken HTTP redirect implementations if ($client->strict_redirect()) { $follow_method = $request->method(); } else { $follow_method = Request::GET; } break; } // Prepare the additional request, copying any follow_headers that were present on the original request $orig_headers = $request->headers()->getArrayCopy(); $follow_header_keys = array_intersect(array_keys($orig_headers), $client->follow_headers()); $follow_headers = \Arr::extract($orig_headers, $follow_header_keys); $follow_request = Request::factory($response->headers('Location'))->method($follow_method)->headers($follow_headers); if ($follow_method !== Request::GET) { $follow_request->body($request->body()); } return $follow_request; } return NULL; }
public function testParse_Response_1Header_ProperHeaders() { $http_response = $this->mock_http_resp('one-header-block'); $response = new Response($http_response, true); $headers = $response->headers(); $this->assertEquals('Apache/2.0.63 (CentOS)', $headers['server']); $this->assertEquals('bytes', $headers['accept-ranges']); $this->assertEquals('text/html; charset=UTF-8', $headers['content-type']); $this->assertEquals('close', $headers['connection']); $this->assertEquals('Mon, 31 Jan 2011 05:12:26 GMT', $headers['date']); $this->assertEquals('5', $headers['age']); $this->assertEquals('3067', $headers['content-length']); }