Example #1
0
 /**
  * @todo Implement testGet().
  */
 public function testGet()
 {
     $response = $this->presta->uri('http://example.com')->get();
     $entity_body = $response->entity_body;
     $this->assertTrue(!empty($entity_body), "No Entity Body returned");
     $this->assertTrue($response->status_code == '200', "Response code expected 200, found [" . $response->header('status_code') . "]");
 }
Example #2
0
 /**
  * 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)
 {
     $http_method_mapping = array(HTTP_Request::GET => HTTPRequest::METH_GET, HTTP_Request::HEAD => HTTPRequest::METH_HEAD, HTTP_Request::POST => HTTPRequest::METH_POST, HTTP_Request::PUT => HTTPRequest::METH_PUT, HTTP_Request::DELETE => HTTPRequest::METH_DELETE, HTTP_Request::OPTIONS => HTTPRequest::METH_OPTIONS, HTTP_Request::TRACE => HTTPRequest::METH_TRACE, HTTP_Request::CONNECT => HTTPRequest::METH_CONNECT);
     // Create an http request object
     $http_request = new HTTPRequest($request->uri(), $http_method_mapping[$request->method()]);
     if ($this->_options) {
         // Set custom options
         $http_request->setOptions($this->_options);
     }
     // Set headers
     $http_request->setHeaders($request->headers()->getArrayCopy());
     // Set cookies
     $http_request->setCookies($request->cookie());
     // Set query data (?foo=bar&bar=foo)
     $http_request->setQueryData($request->query());
     // Set the body
     if ($request->method() == HTTP_Request::PUT) {
         $http_request->addPutData($request->body());
     } else {
         $http_request->setBody($request->body());
     }
     try {
         $http_request->send();
     } catch (HTTPRequestException $e) {
         throw new Request_Exception($e->getMessage());
     } catch (HTTPMalformedHeaderException $e) {
         throw new Request_Exception($e->getMessage());
     } catch (HTTPEncodingException $e) {
         throw new Request_Exception($e->getMessage());
     }
     // Build the response
     $response->status($http_request->getResponseCode())->headers($http_request->getResponseHeader())->cookie($http_request->getResponseCookies())->body($http_request->getResponseBody());
     return $response;
 }
Example #3
0
 public function __construct()
 {
     parent::__construct();
     if (Request::uri() !== 'ajax/project/issue_upload_attachment') {
         $this->filter('before', 'auth');
     }
 }
Example #4
0
 public static function render($template, $data = array())
 {
     // get default theme
     $theme = Config::get('metadata.theme');
     // load global theming functions but not for the admin template
     if (strpos(static::$path, 'system/admin/theme') === false) {
         $includes = array('articles', 'comments', 'config', 'helpers', 'menus', 'metadata', 'pages', 'posts', 'search', 'users');
         foreach ($includes as $file) {
             require PATH . 'system/functions/' . $file . '.php';
         }
     }
     // load theme functions
     if (file_exists(static::$path . 'functions.php')) {
         require static::$path . 'functions.php';
     }
     // render files
     foreach (array('includes/header', $template, 'includes/footer') as $file) {
         $filepath = static::$path . $file . '.php';
         //  Nasty hack, but hey, we've got custom pages now.
         if ($file === 'page' and file_exists(static::$path . Request::uri() . '.php') !== false) {
             $filepath = static::$path . Request::uri() . '.php';
         }
         if (file_exists($filepath) === false) {
             throw new ErrorException('Theme file <strong>themes/' . $theme . '/' . $file . '.php</strong> not found.');
         }
         static::parse($filepath, $data);
     }
 }
 public function execute(Request $request)
 {
     if ($this->callback_depth() > $this->max_callback_depth()) {
         throw new Request_Client_Recursion_Exception("Could not execute request to :uri - too many recursions after :depth requests", array(":uri" => $request->uri(), ":depth" => $this->callback_depth() - 1));
     }
     $orig_response = $response = Response::factory(array("_protocol" => $request->protocol()));
     if (($cache = $this->cache()) instanceof HTTP_Cache) {
         return $cache->execute($this, $request, $response);
     }
     $response = $this->execute_request($request, $response);
     foreach ($this->header_callbacks() as $header => $callback) {
         if ($response->headers($header)) {
             $cb_result = call_user_func($callback, $request, $response, $this);
             if ($cb_result instanceof Request) {
                 $this->assign_client_properties($cb_result->client());
                 $cb_result->client()->callback_depth($this->callback_depth() + 1);
                 $response = $cb_result->execute();
             } elseif ($cb_result instanceof Response) {
                 $response = $cb_result;
             }
             if ($response !== $orig_response) {
                 break;
             }
         }
     }
     return $response;
 }
Example #6
0
 private static function parse()
 {
     // get uri
     $uri = Request::uri();
     // lets log our initial uri
     Log::info('Requested URI: ' . $uri);
     // route definitions
     $routes = array();
     // posts host page
     if ($page = IoC::resolve('posts_page')) {
         $routes[$page->slug . '/(:any)'] = 'article/$1';
     }
     // fallback to 'admin'
     $admin_folder = Config::get('application.admin_folder', 'admin');
     // static routes
     $routes = array_merge($routes, array($admin_folder . '/(:any)/(:any)/(:any)' => 'admin/$1/$2/$3', $admin_folder . '/(:any)/(:any)' => 'admin/$1/$2', $admin_folder . '/(:any)' => 'admin/$1', $admin_folder => 'admin', 'search/(:any)' => 'search/$1', 'search' => 'search', 'rss' => 'rss', '(:any)' => 'page/$1'));
     // define wild-cards
     $search = array(':any', ':num');
     $replace = array('[0-9a-zA-Z~%\\.:_\\-]+', '[0-9]+');
     // parse routes
     foreach ($routes as $route => $translated) {
         // replace wildcards
         $route = str_replace($search, $replace, $route);
         // look for matches
         if (preg_match('#^' . $route . '#', $uri, $matches)) {
             // replace matched values
             foreach ($matches as $k => $match) {
                 $translated = str_replace('$' . $k, $match, $translated);
             }
             // return on first match
             return $translated;
         }
     }
     return $uri;
 }
 /**
  * Basic cache key generator that hashes the entire request and returns
  * it. This is fine for static content, or dynamic content where user
  * specific information is encoded into the request.
  * 
  *      // Generate cache key
  *      $cache_key = HTTP_Cache::basic_cache_key_generator($request);
  *
  * @param   Request $request
  * @return  string
  */
 public static function basic_cache_key_generator(Request $request)
 {
     $uri = $request->uri();
     $query = $request->query();
     $headers = $request->headers()->getArrayCopy();
     $body = $request->body();
     return sha1($uri . '?' . http_build_query($query, NULL, '&') . '~' . implode('~', $headers) . '~' . $body);
 }
Example #8
0
 function __construct()
 {
     echo 'Install::App started!<br>';
     echo Request::uri();
     echo '?page=', Request::get('page', 1, false);
     $layout = Responce::layout('start');
     $layout->title('Test page!');
 }
Example #9
0
 public function __construct(Request $request)
 {
     // Delete the authorization
     cookie::delete('authorized');
     // Redirect to the login page
     $request->redirect(url::site($request->uri(array('controller' => NULL))));
     // Do not call anything here, redirect has already halted execution.
 }
Example #10
0
 /**
  * Sends the HTTP message [Request] to a remote server and processes
  * the response.
  *
  * @param   Request   request to send
  * @return  Response
  */
 public function _send_message(Request $request)
 {
     // Response headers
     $response_headers = array();
     // Set the request method
     $options[CURLOPT_CUSTOMREQUEST] = $request->method();
     // 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
     $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, '; ');
     }
     // Create response
     $response = $request->create_response();
     $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;
 }
Example #11
0
 public static function call($name = '')
 {
     $page = basename(Request::uri());
     if (empty($name)) {
         $name = 'main';
     }
     if ($func = isset(static::$stack[$page][$name]) ? static::$stack[$page][$name] : false) {
         return is_callable($func) ? $func() : '';
     }
     return '';
 }
Example #12
0
 /**
  * Calculate the signature of a request.
  * Should be called just before the request is sent.
  *
  * @param Request $request
  * @param $private_key
  * @return string Calculated HMAC
  */
 public static function calculate_hmac(Request $request, $private_key)
 {
     // Consolidate data that's not in the main route (params)
     $query = array_change_key_case($request->query());
     $post = array_change_key_case($request->post());
     // Sort alphabetically
     ksort($query);
     ksort($post);
     $data_to_sign = ['method' => $request->method(), 'uri' => $request->uri(), 'post' => $post, 'query' => $query];
     // Calculate the signature
     return hash_hmac('sha256', json_encode($data_to_sign), $private_key);
 }
 /**
  * Tests if the route matches a given URI. A successful match will return
  * all of the routed parameters as an array. A failed match will return
  * boolean FALSE.
  *
  *     // Params: controller = users, action = edit, id = 10
  *     $params = $route->matches('users/edit/10');
  *
  * This method should almost always be used within an if/else block:
  *
  *     if ($params = $route->matches($uri))
  *     {
  *         // Parse the parameters
  *     }
  *
  * @param   string  $uri    URI to match
  * @return  array   on success
  * @return  FALSE   on failure
  */
 public function matches(Request $request)
 {
     // Get the URI from the Request
     $uri = trim($request->uri(), '/');
     if (!preg_match($this->_route_regex, $uri, $matches)) {
         return FALSE;
     }
     $params = array();
     foreach ($matches as $key => $value) {
         if (is_int($key)) {
             // Skip all unnamed keys
             continue;
         }
         // Set the value for all matched keys
         $params[$key] = $value;
         //<---
         // added by Yuna
         if (is_array($this->_retain) and in_array($key, $this->_retain) && $value != '') {
             // Value should be retained; add it to the _uri_defaults
             $this->_uri_defaults[$key] = $value;
         }
         //-->
     }
     foreach ($this->_defaults as $key => $value) {
         if (!isset($params[$key]) or $params[$key] === '') {
             // Set default values for any key that was not matched
             $params[$key] = $value;
         }
     }
     if (!empty($params['controller'])) {
         // PSR-0: Replace underscores with spaces, run ucwords, then replace underscore
         $params['controller'] = str_replace(' ', '_', ucwords(str_replace('_', ' ', $params['controller'])));
     }
     if (!empty($params['directory'])) {
         // PSR-0: Replace underscores with spaces, run ucwords, then replace underscore
         $params['directory'] = str_replace(' ', '_', ucwords(str_replace('_', ' ', $params['directory'])));
     }
     if ($this->_filters) {
         foreach ($this->_filters as $callback) {
             // Execute the filter giving it the route, params, and request
             $return = call_user_func($callback, $this, $params, $request);
             if ($return === FALSE) {
                 // Filter has aborted the match
                 return FALSE;
             } elseif (is_array($return)) {
                 // Filter has modified the parameters
                 $params = $return;
             }
         }
     }
     return $params;
 }
Example #14
0
 /**
  * Open a HTML form.
  *
  * @param  string  $action
  * @param  string  $method
  * @param  array   $attributes
  * @param  bool    $https
  * @return string
  */
 public static function open($action = null, $method = 'POST', $attributes = array(), $https = false)
 {
     $attributes['action'] = HTML::entities(URL::to(is_null($action) ? Request::uri() : $action, $https));
     // PUT and DELETE methods are spoofed using a hidden field containing the request method.
     // Since, HTML does not support PUT and DELETE on forms, we will use POST.
     $attributes['method'] = ($method == 'PUT' or $method == 'DELETE') ? 'POST' : $method;
     if (!array_key_exists('accept-charset', $attributes)) {
         $attributes['accept-charset'] = Config::get('application.encoding');
     }
     $html = '<form' . HTML::attributes($attributes) . '>';
     if ($method == 'PUT' or $method == 'DELETE') {
         $html .= PHP_EOL . static::input('hidden', 'REQUEST_METHOD', $method);
     }
     return $html . PHP_EOL;
 }
Example #15
0
 public static function extend($page)
 {
     if (is_array($page)) {
         $pages = array();
         foreach ($page as $itm) {
             $pages[] = static::extend($itm);
         }
         return $pages;
     }
     if (is_object($page)) {
         $uri = Request::uri();
         $page->url = Url::make($page->slug);
         $page->active = strlen($uri) ? strpos($uri, $page->slug) !== false : $page->slug === 'posts';
         return $page;
     }
     return false;
 }
Example #16
0
 /**
  * Sends the HTTP message [Request] to a remote server and processes
  * the response.
  *
  * @param   Request   request to send
  * @return  Response
  * @uses    [PHP cURL](http://php.net/manual/en/book.curl.php)
  */
 public function _send_message(Request $request)
 {
     // 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;
     }
     // Create a response
     $response = $request->create_response();
     $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;
 }
 public function execute_request(Request $request, Response $response)
 {
     $prefix = "Controller_";
     $directory = $request->directory();
     $controller = $request->controller();
     if ($directory) {
         $prefix .= str_replace(array("\\", "/"), "_", trim($directory, "/")) . "_";
     }
     if (JsonApiApplication::$profiling) {
         $benchmark = "'" . $request->uri() . "'";
         if ($request !== Request::$initial and Request::$current) {
             $benchmark .= " « '" . Request::$current->uri() . "'";
         }
         $benchmark = Profiler::start("Requests", $benchmark);
     }
     $previous = Request::$current;
     Request::$current = $request;
     $initial_request = $request === Request::$initial;
     try {
         if (!class_exists($prefix . $controller)) {
             throw HTTP_Exception::factory(404, "The requested URL :uri was not found on this server.", array(":uri" => $request->uri()))->request($request);
         }
         $class = new ReflectionClass($prefix . $controller);
         if ($class->isAbstract()) {
             throw new JsonApiApplication_Exception("Cannot create instances of abstract :controller", array(":controller" => $prefix . $controller));
         }
         $controller = $class->newInstance($request, $response);
         $response = $class->getMethod("execute")->invoke($controller);
         if (!$response instanceof Response) {
             throw new JsonApiApplication_Exception("Controller failed to return a Response");
         }
     } catch (HTTP_Exception $e) {
         if ($e->request() === NULL) {
             $e->request($request);
         }
         $response = $e->get_response();
     } catch (Exception $e) {
         $response = JsonApiApplication_Exception::_handler($e);
     }
     Request::$current = $previous;
     if (isset($benchmark)) {
         Profiler::stop($benchmark);
     }
     return $response;
 }
Example #18
0
 public static function extend($page)
 {
     if (is_array($page)) {
         $pages = array();
         foreach ($page as $itm) {
             $pages[] = static::extend($itm);
         }
         return $pages;
     }
     if (is_object($page)) {
         $uri = Request::uri();
         $page->url = Url::make($page->slug);
         $page->active = false;
         if ($current = IoC::resolve('page')) {
             if ($current->id == $page->id) {
                 $page->active = true;
             }
         }
         return $page;
     }
     return false;
 }
Example #19
0
 /**
  * Processes the request, executing the controller action that handles this
  * request, determined by the [Route].
  *
  * 1. Before the controller action is called, the [Controller::before] method
  * will be called.
  * 2. Next the controller action will be called.
  * 3. After the controller action is called, the [Controller::after] method
  * will be called.
  *
  * By default, the output from the controller is captured and returned, and
  * no headers are sent.
  *
  *     $request->execute();
  *
  * @param   Request $request
  * @return  Response
  * @throws  Kohana_Exception
  * @uses    [Kohana::$profiling]
  * @uses    [Profiler]
  * @deprecated passing $params to controller methods deprecated since version 3.1
  *             will be removed in 3.2
  */
 public function execute_request(Request $request)
 {
     // Create the class prefix
     $prefix = 'controller_';
     // Directory
     $directory = $request->directory();
     // Controller
     $controller = $request->controller();
     if ($directory) {
         // Add the directory name to the class prefix
         $prefix .= str_replace(array('\\', '/'), '_', trim($directory, '/')) . '_';
     }
     if (Kohana::$profiling) {
         // Set the benchmark name
         $benchmark = '"' . $request->uri() . '"';
         if ($request !== Request::$initial and Request::$current) {
             // Add the parent request uri
             $benchmark .= ' « "' . Request::$current->uri() . '"';
         }
         // Start benchmarking
         $benchmark = Profiler::start('Requests', $benchmark);
     }
     // Store the currently active request
     $previous = Request::$current;
     // Change the current request to this request
     Request::$current = $request;
     // Is this the initial request
     $initial_request = $request === Request::$initial;
     try {
         if (!class_exists($prefix . $controller)) {
             throw new HTTP_Exception_404('The requested URL :uri was not found on this server.', array(':uri' => $request->uri()));
         }
         // Load the controller using reflection
         $class = new ReflectionClass($prefix . $controller);
         if ($class->isAbstract()) {
             throw new Kohana_Exception('Cannot create instances of abstract :controller', array(':controller' => $prefix . $controller));
         }
         // Create a new instance of the controller
         $controller = $class->newInstance($request, $request->response() ? $request->response() : $request->create_response());
         $class->getMethod('before')->invoke($controller);
         // Determine the action to use
         $action = $request->action();
         $params = $request->param();
         // If the action doesn't exist, it's a 404
         if (!$class->hasMethod('action_' . $action)) {
             throw new HTTP_Exception_404('The requested URL :uri was not found on this server.', array(':uri' => $request->uri()));
         }
         $method = $class->getMethod('action_' . $action);
         $method->invoke($controller);
         // Execute the "after action" method
         $class->getMethod('after')->invoke($controller);
     } catch (Exception $e) {
         // Restore the previous request
         if ($previous instanceof Request) {
             Request::$current = $previous;
         }
         if (isset($benchmark)) {
             // Delete the benchmark, it is invalid
             Profiler::delete($benchmark);
         }
         // Re-throw the exception
         throw $e;
     }
     // Restore the previous request
     Request::$current = $previous;
     if (isset($benchmark)) {
         // Stop the benchmark
         Profiler::stop($benchmark);
     }
     // Return the response
     return $request->response();
 }
Example #20
0
File: URI.php Project: rezon/sugi
 public static function current()
 {
     return Request::uri();
 }
Example #21
0
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	<title>Tiny Issue</title>
	<script>
	   var siteurl = '<?php 
echo URL::to();
?>
';
		var current_url = '/<?php 
echo Request::uri();
?>
';
		var baseurl = '<?php 
echo URL::base();
?>
';
	</script>

	<meta name="viewport" content="width=device-width,initial-scale=1">
	<?php 
echo Asset::styles();
?>
	<?php 
echo Asset::scripts();
?>
</head>
<body>
Example #22
0
 /**
  * Execute the request using PHP stream. (not recommended)
  *
  * @param   Request   $request  Request to execute
  * @return  Response
  */
 protected function _native_execute(Request $request)
 {
     // Reset the headers
     Request_Client_External::$_processed_headers = array();
     // 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, '; '));
     }
     // Create the context
     $options = array($request->protocol() => array('method' => $request->method(), 'header' => (string) $request->headers(), 'content' => $request->body(), 'user-agent' => 'Kohana Framework ' . Kohana::VERSION . ' (' . Kohana::CODENAME . ')'));
     // Create the context stream
     $context = stream_context_create($options);
     stream_context_set_option($context, $this->_options);
     $stream = fopen($request->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;
     }
     // Process headers
     array_map(array('Request_Client_External', '_parse_headers'), array(), $meta_data['wrapper_data']);
     // Create a response
     $response = $request->create_response();
     $response->status($status)->protocol($protocol)->headers(Request_Client_External::$_processed_headers)->body(stream_get_contents($stream));
     // Close the stream after use
     fclose($stream);
     return $response;
 }
Example #23
0
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	<title>Tiny Issue</title>
	<script>
	   var siteurl = '<?php 
echo URL::to();
?>
';
		var current_url = '<?php 
echo URL::to(Request::uri());
?>
';
		var baseurl = '<?php 
echo URL::base();
?>
';
	</script>

	<meta name="viewport" content="width=device-width,initial-scale=1">
	<?php 
echo Asset::styles();
?>
	<?php 
echo Asset::scripts();
?>
</head>
<body>
Example #24
0
        break;
    }
}
// --------------------------------------------------------------
// Route the request and get the response from the route.
// --------------------------------------------------------------
if (is_null($response)) {
    $route = Routing\Router::make(Request::method(), Request::uri(), new Routing\Loader(ACTIVE_MODULE_PATH))->route();
    $response = is_null($route) ? Response::error('404') : $route->call();
}
$response = Response::prepare($response);
// --------------------------------------------------------------
// Call the "after" filter for the application and module.
// --------------------------------------------------------------
foreach (array(ACTIVE_MODULE . '::after', 'after') as $filter) {
    Routing\Filter::call($filter, array($response, Request::method(), Request::uri()));
}
// --------------------------------------------------------------
// Stringify the response.
// --------------------------------------------------------------
$response->content = (string) $response->content;
// --------------------------------------------------------------
// Close the session.
// --------------------------------------------------------------
if (Config::get('session.driver') != '') {
    Session::close();
}
// --------------------------------------------------------------
// Send the response to the browser.
// --------------------------------------------------------------
$response->send();
Example #25
0
 static function page_by($root)
 {
     $page = trim(Request::uri(), '/');
     if (isset($root)) {
         foreach ((array) $root as $url) {
             $url = trim($url, '/');
             @(list($prefix, $tail) = explode("/{$url}/", "/{$page}/", 2));
             if ($prefix === '' and isset($tail)) {
                 return trim($tail, '/');
             }
         }
     } else {
         return $page;
     }
 }
Example #26
0
 public function execute_request(Request $request, Response $response)
 {
     // Create the class prefix
     $prefix = 'Controller_';
     // Directory
     $directory = $request->directory();
     // Controller
     $controller = $request->controller();
     if ($directory) {
         // Add the directory name to the class prefix
         $prefix .= str_replace(array('\\', '/'), '_', trim($directory, '/')) . '_';
     }
     if (Kohana::$profiling) {
         // Set the benchmark name
         $benchmark = '"' . $request->uri() . '"';
         if ($request !== Request::$initial and Request::$current) {
             // Add the parent request uri
             $benchmark .= ' « "' . Request::$current->uri() . '"';
         }
         // Start benchmarking
         $benchmark = Profiler::start('Requests', $benchmark);
     }
     // Store the currently active request
     $previous = Request::$current;
     // Change the current request to this request
     Request::$current = $request;
     // Is this the initial request
     $initial_request = $request === Request::$initial;
     try {
         if (!class_exists($prefix . $controller)) {
             $prefix = str_replace('_', '\\', $prefix);
             $controller = str_replace('_', '\\', $controller);
             if (!class_exists($prefix . $controller)) {
                 $z = new HTTP_Exception_404('The requested URL :uri was not found on this server.at :prefix :controller', array(':uri' => $request->uri(), ':prefix' => $prefix, ':controller' => $controller));
                 $z->request($request);
                 throw $z;
             }
         }
         // Load the controller using reflection
         $class = new ReflectionClass($prefix . $controller);
         if ($class->isAbstract()) {
             throw new Kohana_Exception('Cannot create instances of abstract :controller', array(':controller' => $prefix . $controller));
         }
         // Create a new instance of the controller
         $controller = $class->newInstance($request, $response);
         // Run the controller's execute() method
         $response = $class->getMethod('execute')->invoke($controller);
         if (!$response instanceof Response) {
             // Controller failed to return a Response.
             throw new Kohana_Exception('Controller failed to return a Response');
         }
     } catch (HTTP_Exception $e) {
         // Store the request context in the Exception
         if ($e->request() === NULL) {
             $e->request($request);
         }
         // Get the response via the Exception
         $response = $e->get_response();
     } catch (Exception $e) {
         // Generate an appropriate Response object
         $response = Kohana_Exception::_handler($e);
     }
     // Restore the previous request
     Request::$current = $previous;
     if (isset($benchmark)) {
         // Stop the benchmark
         Profiler::stop($benchmark);
     }
     // Return the response
     return $response;
 }
Example #27
0
 /**
  * Tests that the uri supplied to Request is only trimed
  * for internal requests.
  * 
  * @dataProvider provider_uri_only_trimed_on_internal
  *
  * @return void
  */
 public function test_uri_only_trimed_on_internal(Request $request, $expected)
 {
     $this->assertSame($request->uri(), $expected);
 }
Example #28
0
 /**
  * Processes the request, executing the controller action that handles this
  * request, determined by the [Route].
  *
  * 1. Before the controller action is called, the [Controller::before] method
  * will be called.
  * 2. Next the controller action will be called.
  * 3. After the controller action is called, the [Controller::after] method
  * will be called.
  *
  * By default, the output from the controller is captured and returned, and
  * no headers are sent.
  *
  *     $request->execute();
  *
  * @param   Request   $request   A request object
  * @param   Response  $response  A response object
  * @return  Response
  * @throws  Kohana_Exception
  * @uses    [Kohana::$profiling]
  * @uses    [Profiler]
  */
 public function execute_request(Request $request, Response $response)
 {
     if (Kohana::$profiling) {
         // Set the benchmark name
         $benchmark = '"' . $request->uri() . '"';
         if ($request !== Request::$initial and Request::$current) {
             // Add the parent request uri
             $benchmark .= ' « "' . Request::$current->uri() . '"';
         }
         // Start benchmarking
         $benchmark = Profiler::start('Requests', $benchmark);
     }
     // Store the current active request and replace current with new request
     $previous = Request::$current;
     Request::$current = $request;
     // Resolve the POST fields
     if ($post = $request->post()) {
         $request->body(http_build_query($post, NULL, '&'))->headers('content-type', 'application/x-www-form-urlencoded; charset=' . Kohana::$charset);
     }
     $request->headers('content-length', (string) $request->content_length());
     // If Kohana expose, set the user-agent
     if (Kohana::$expose) {
         $request->headers('user-agent', Kohana::version());
     }
     try {
         $response = $this->_send_message($request, $response);
     } catch (Exception $e) {
         // Restore the previous request
         Request::$current = $previous;
         if (isset($benchmark)) {
             // Delete the benchmark, it is invalid
             Profiler::delete($benchmark);
         }
         // Re-throw the exception
         throw $e;
     }
     // Restore the previous request
     Request::$current = $previous;
     if (isset($benchmark)) {
         // Stop the benchmark
         Profiler::stop($benchmark);
     }
     // Return the response
     return $response;
 }
Example #29
0
 /**
  * Processes the request, executing the controller action that handles this
  * request, determined by the [Route].
  *
  * 1. Before the controller action is called, the [Controller::before] method
  * will be called.
  * 2. Next the controller action will be called.
  * 3. After the controller action is called, the [Controller::after] method
  * will be called.
  *
  * By default, the output from the controller is captured and returned, and
  * no headers are sent.
  *
  *     $request->execute();
  *
  * @param   Request   $request
  * @param   Response  $response
  * @return  Response
  * @throws  Kohana_Exception
  * @uses    [Kohana::$profiling]
  * @uses    [Profiler]
  */
 public function execute(Request $request)
 {
     // Prevent too much recursion of header callback requests
     if ($this->callback_depth() > $this->max_callback_depth()) {
         throw new Request_Client_Recursion_Exception("Could not execute request to :uri - too many recursions after :depth requests", array(':uri' => $request->uri(), ':depth' => $this->callback_depth() - 1));
     }
     // Execute the request and pass the currently used protocol
     $orig_response = $response = Response::factory(array('_protocol' => $request->protocol()));
     if (($cache = $this->cache()) instanceof HTTP_Cache) {
         return $cache->execute($this, $request, $response);
     }
     $response = $this->execute_request($request, $response);
     // Execute response callbacks
     foreach ($this->header_callbacks() as $header => $callback) {
         if ($response->headers($header)) {
             $cb_result = call_user_func($callback, $request, $response, $this);
             if ($cb_result instanceof Request) {
                 // If the callback returns a request, automatically assign client params
                 $this->assign_client_properties($cb_result->client());
                 $cb_result->client()->callback_depth($this->callback_depth() + 1);
                 // Execute the request
                 $response = $cb_result->execute();
             } elseif ($cb_result instanceof Response) {
                 // Assign the returned response
                 $response = $cb_result;
             }
             // If the callback has created a new response, do not process any further
             if ($response !== $orig_response) {
                 break;
             }
         }
     }
     return $response;
 }
Example #30
0
 /**
  * Set the active link based on the current request
  *
  * @since 3.0
  * @param Request $request
  * @return bool|\Menu_Item
  */
 public function guess_active_item(Request $request)
 {
     return $this->set_current($request->uri());
 }