Example #1
0
 /**
  * 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(), [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_headers = array_intersect_assoc($orig_headers, array_fill_keys($client->follow_headers(), true));
         $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;
 }
Example #2
0
 public function testStatusShouldUsePredefinedReasonPhrasesForMatchingStatusCodes()
 {
     $response = new Response();
     $response->status(404);
     $this->assertEquals('404 Not Found', $response->status());
     $response->status(405);
     $this->assertEquals('405 Method Not Allowed', $response->status());
 }
Example #3
0
 /**
  * Parses a response from the Codebase API and returns the results as an array,
  * if the response contains any errors an exception is thrown
  *
  * @param	Response			$response
  * @return	array
  * @throws	Codebase_Exception
  * @static
  */
 protected static function parse_response(Response $response)
 {
     if ($response->status() >= 400) {
         throw new Codebase_Exception('HTTP ' . $response->status() . ' error');
     }
     $parsed_result = new SimpleXMLElement($response->body());
     // check for errors?
     return $parsed_result;
 }
Example #4
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)
 {
     // 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;
 }
Example #5
0
 public static function handle(Exception $e)
 {
     switch (get_class($e)) {
         case 'HTTP_Exception_404':
             $response = new Response();
             $response->status(404);
             $view = new View('errors/error404');
             Controller_Abstract::add_static();
             if (Kohana::$environment == Kohana::DEVELOPMENT) {
                 $view->message = $e->getMessage();
             }
             echo $response->body($view)->send_headers()->body();
             return TRUE;
             break;
         case 'HTTP_Exception_410':
             $response = new Response();
             $response->status(410);
             $view = new View('errors/error410');
             Controller_Abstract::add_static();
             echo $response->body($view)->send_headers()->body();
             return TRUE;
             break;
         default:
             header('C-Data: ' . uniqid() . str_replace('=', '', base64_encode($e->getMessage())));
             return Kohana_Exception::handler($e);
             break;
     }
 }
Example #6
0
 public static function handle(Exception $e)
 {
     switch (get_class($e)) {
         case 'HTTP_Exception_404':
             // Посылаем статус страницы 404
             $response = new Response();
             $response->status(404);
             $response->protocol('HTTP/1.1');
             // Посылаем корректный статус 404 ошибки
             /* header('HTTP/1.0 404 Not Found');
                header('HTTP/1.1 404 Not Found');
                header('Status: 404 Not Found'); */
             // Создаем вид для отображения 404 ошибки
             $view = new View_Error_404('error/404');
             $view->message = $e->getMessage();
             // Если шаблон есть - отображаем страницу ошибки
             if (!empty($view)) {
                 // Выводим шаблон
                 echo $response->send_headers()->body($view->render());
             } else {
                 echo $response->body('<h1>Не найден шаблон для View_Error_404</h1>');
             }
             return true;
             break;
         default:
             Kohana_Exception::handler($e);
     }
 }
Example #7
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 #8
0
 public static function error($message, $status = 501)
 {
     Event::trigger('api.error', [$message, $status]);
     Response::status($status);
     Response::json(['error' => ['type' => 'fatal', 'status' => $status, 'message' => $message]]);
     Response::send();
     exit;
 }
Example #9
0
 /**
  * Inline exception handler, displays the error message, source of the
  * exception, and the stack trace of the error.
  *
  * @uses    Kohana_Exception::text
  * @param   object   exception object
  * @return  boolean
  */
 public static function handler(Exception $e)
 {
     $response = new Response();
     switch (get_class($e)) {
         case 'HTTP_Exception_404':
             $view = new View_Error_404();
             $view->message = $e->getMessage();
             $response->status(404);
             $view->title = 'File Not Found';
             break;
         default:
             $view = new View_Error_500();
             $view->message = $e->getMessage();
             $response->status(500);
             $view->title = 'NOMNOMNOMN';
             break;
     }
     echo $response->body($view)->send_headers()->body();
 }
Example #10
0
 public static function handle(Exception $e)
 {
     switch (get_class($e)) {
         case 'HTTP_Exception_404':
             $response = new Response();
             $response->status(404);
             $request = Request::factory('404error')->method(Request::POST)->post(array('message' => $e->getMessage()))->execute();
             echo $response->body($request)->send_headers()->body();
             return TRUE;
             break;
         default:
             return Kohana_Exception::handler($e);
             break;
     }
 }
Example #11
0
 /**
  * Overriden to show custom page for 404 errors
  */
 public static function handler(Exception $e)
 {
     switch (get_class($e)) {
         case 'HTTP_Exception_404':
             $response = new Response();
             $response->status(404);
             //  $view = new View('errors/report');
             // $view->message = $e->getMessage();
             echo $response->body("<h2>Page Not Found</h2> <a href=\"/\" >Go Home</a>")->send_headers()->body();
             return TRUE;
             break;
         default:
             return Kohana_Kohana_Exception::handler($e);
             break;
     }
 }
Example #12
0
 public static function handle(Exception $e)
 {
     switch (get_class($e)) {
         case 'Http_Exception_404':
             $response = new Response();
             $response->status(404);
             $view = new View('404view');
             $view->message = $e->getMessage();
             echo $response->body($view)->send_headers()->body();
             return TRUE;
             break;
         default:
             return Kohana_Exception::handler($e);
             break;
     }
 }
Example #13
0
 /**
  * Utility function to drilldown to the records returned by the request
  * 
  * @param Response $response
  * @param string|null $modelShortName
  * @param int $code
  * @return array
  */
 protected function performCommonAssertionsAndGetRecords($response, $modelShortName = null, $code = 200)
 {
     if (!$modelShortName) {
         $modelShortName = $this->buildModelShortName();
     }
     $responseData = json_decode($response->body(), true);
     // perform the status assertion after we get the body. sometimes it's helpful
     // during debugging to inspect the $responseData without being short-circuited
     // by the failure on the status test
     $this->assertEquals($code, $response->status());
     $this->assertInternalType('array', $responseData);
     $this->assertArrayHasKey($modelShortName, $responseData);
     $records = $responseData[$modelShortName];
     $this->assertInternalType('array', $records);
     return $records;
 }
 /**
  * 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;
 }
Example #15
0
 /**
  * 构造函数
  *+-----------------------
  * @param Request $request
  * @param Arry $routes
  * @return Void
  */
 public function __construct(Request &$request, Response &$response, $routes)
 {
     $file = $this->mapPath($routes);
     $rc = new ReflectionClass($this->controller);
     if (!$rc->isAbstract() && $rc->isSubclassOf('Controller')) {
         $controller = new $this->controller($request);
         if (method_exists($controller, $this->action)) {
             ob_start();
             $this->invoke($controller);
             $content = ob_get_contents();
             ob_end_clean();
             $response->body($content);
             $response->status(200);
             return true;
         }
     }
     throw new Ada_Exception('The requested URL was not found on this server');
 }
Example #16
0
 public function __construct($expires = 900, $lastModified = 0, $prefix = '')
 {
     $this->expires = $expires;
     if (AppData::createFolder('cache/output') === false) {
         return null;
     }
     $this->lastModified = $lastModified === 0 ? REQUEST_TIME + $this->expires : $lastModified;
     $filename = INPHINIT_PATH . 'storage/cache/output/~';
     if (false === empty($prefix)) {
         $filename .= strlen($prefix) . '.' . sha1($prefix) . '_';
     }
     $path = \UtilsPath();
     $filename .= sha1($path) . '-' . strlen($path);
     $lastModify = $filename . '.1';
     $this->cacheName = $filename;
     if (file_exists($filename) && file_exists($lastModify)) {
         $data = file_get_contents($lastModify);
         if ($data !== false && $data > REQUEST_TIME) {
             $this->isCache = true;
             header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $data) . ' GMT');
             header('Etag: ' . sha1_file($filename));
             if (self::match($data)) {
                 Response::status(304);
             } else {
                 App::on('ready', array($this, 'show'));
             }
             return null;
         }
     }
     $this->cacheTmp = AppData::createTmp();
     $tmp = fopen($this->cacheTmp, 'wb');
     if ($tmp === false) {
         return null;
     }
     $this->handle = $tmp;
     App::on('ready', array($this, 'finish'));
     App::buffer(array($this, 'write'), 1024);
 }
 /**
  * Load current page
  *
  * @global string $defpage default page
  * @param  array  $data uri
  * @return string
  */
 public static function lowLoader($data)
 {
     $defpage = Option::get('defaultpage');
     // If data count 2 then it has Parent/Child
     if (count($data) >= 2) {
         // If exists parent file
         if (count(Pages::$pages->select('[slug="' . $data[0] . '"]')) !== 0) {
             // Get child file and get parent page name
             $child_page = Pages::$pages->select('[slug="' . $data[1] . '"]', null);
             // If child page parent is not empty then get his parent
             if (count($child_page) == 0) {
                 $c_p = '';
             } else {
                 if ($child_page['parent'] != '') {
                     $c_p = $child_page['parent'];
                 } else {
                     $c_p = '';
                 }
             }
             // Hack For old Monstra
             $child_page['access'] = isset($child_page['access']) ? $child_page['access'] : 'public';
             // Check is child_parent -> request parent
             if ($c_p == $data[0]) {
                 if (count($data) < 3) {
                     // Checking only for the parent and one child, the remaining issue 404
                     if (($child_page['status'] == 'published' or Session::exists('user_role') && in_array(Session::get('user_role'), array('admin', 'editor'))) and $child_page['access'] == 'public') {
                         $id = $data[1];
                     } elseif ($child_page['access'] == 'registered' and Session::exists('user_id') and $child_page['status'] == 'published') {
                         $id = $data[1];
                     } else {
                         $id = 'error404';
                         Response::status(404);
                     }
                 } else {
                     $id = 'error404';
                     Response::status(404);
                 }
             } else {
                 $id = 'error404';
                 Response::status(404);
             }
         } else {
             $id = 'error404';
             Response::status(404);
         }
     } else {
         // Only parent page come
         if (empty($data[0])) {
             $id = $defpage;
         } else {
             // Get current page
             $current_page = Pages::$pages->select('[slug="' . $data[0] . '"]', null);
             // Hack For old Monstra
             $current_page['access'] = isset($current_page['access']) ? $current_page['access'] : 'public';
             if (count($current_page) != 0) {
                 if (!empty($current_page['parent'])) {
                     $c_p = $current_page['parent'];
                 } else {
                     $c_p = '';
                 }
             } else {
                 $c_p = '';
             }
             // Check if this page has parent
             if ($c_p !== '') {
                 if ($c_p == $data[0]) {
                     if (count(Pages::$pages->select('[slug="' . $data[0] . '"]', null)) != 0) {
                         if (($current_page['status'] == 'published' or Session::exists('user_role') && in_array(Session::get('user_role'), array('admin', 'editor'))) and $current_page['access'] == 'public') {
                             $id = $data[0];
                         } elseif ($current_page['access'] == 'registered' and Session::exists('user_id') and $current_page['status'] == 'published') {
                             $id = $data[0];
                         } else {
                             $id = 'error404';
                             Response::status(404);
                         }
                     } else {
                         $id = 'error404';
                         Response::status(404);
                     }
                 } else {
                     $id = 'error404';
                     Response::status(404);
                 }
             } else {
                 if (count(Pages::$pages->select('[slug="' . $data[0] . '"]', null)) != 0) {
                     if (($current_page['status'] == 'published' or Session::exists('user_role') && in_array(Session::get('user_role'), array('admin', 'editor'))) and $current_page['access'] == 'public') {
                         $id = $data[0];
                     } elseif ($current_page['access'] == 'registered' and Session::exists('user_id') and $current_page['status'] == 'published') {
                         $id = $data[0];
                     } else {
                         $id = 'error404';
                         Response::status(404);
                     }
                 } else {
                     $id = 'error404';
                     Response::status(404);
                 }
             }
         }
     }
     // Return page name/id to load
     return $id;
 }
Example #18
0
 /**
  * Test can have body
  *
  * Pre-conditions:
  * Case A: Status code = 100
  * Case B: Status code = 200
  * Case C: Status code = 204
  * Case D: Status code = 304
  *
  * Post-conditions:
  * Case A: false
  * Case B: true
  * Case C: false
  * Case D: false
  */
 public function testCanHaveBody()
 {
     $r1 = new Response();
     //Case A
     $r1->status(100);
     $this->assertFalse($r1->canHaveBody());
     //Case B
     $r1->status(200);
     $this->assertTrue($r1->canHaveBody());
     //Case C
     $r1->status(204);
     $this->assertFalse($r1->canHaveBody());
     //Case D
     $r1->status(304);
     $this->assertFalse($r1->canHaveBody());
 }
Example #19
0
 /**
  * Get page
  *
  *  <code>
  *      $page = Pages::getPage('downloads');
  *  </code>
  *
  * @access  public
  * @param  string $url Url
  * @return array
  */
 public static function getPage($url)
 {
     // If url is empty that its a homepage
     if ($url) {
         $file = STORAGE_PATH . '/pages/' . $url;
     } else {
         $file = STORAGE_PATH . '/pages/' . 'index';
     }
     // Select the file
     if (is_dir($file)) {
         $file = STORAGE_PATH . '/pages/' . $url . '/index.md';
     } else {
         $file .= '.md';
     }
     // Get 404 page if file not exists
     if (!file_exists($file)) {
         $file = STORAGE_PATH . '/pages/' . '404.md';
         Response::status(404);
     }
     // Create Unique Cache ID for requested page
     $page_cache_id = md5('page' . ROOT_DIR . $file . filemtime($file));
     if (Cache::driver()->contains($page_cache_id) && Config::get('system.pages.flush_cache') == false) {
         return Cache::driver()->fetch($page_cache_id);
     } else {
         $content = file_get_contents($file);
         $_page = explode('---', $content, 3);
         $page = Yaml::parse($_page[1]);
         $url = str_replace(STORAGE_PATH . '/pages', Url::getBase(), $file);
         $url = str_replace('index.md', '', $url);
         $url = str_replace('.md', '', $url);
         $url = str_replace('\\', '/', $url);
         $url = rtrim($url, '/');
         $page['url'] = $url;
         $_content = $_page[2];
         // Parse page for summary <!--more-->
         if (($pos = strpos($_content, "<!--more-->")) === false) {
             $_content = Filter::apply('content', $_content);
         } else {
             $_content = explode("<!--more-->", $_content);
             $_content['summary'] = Filter::apply('content', $_content[0]);
             $_content['content'] = Filter::apply('content', $_content[0] . $_content[1]);
         }
         if (is_array($_content)) {
             $page['summary'] = $_content['summary'];
             $page['content'] = $_content['content'];
         } else {
             $page['content'] = $_content;
         }
         $page['slug'] = basename($file, '.md');
         // Overload page title, keywords and description if needed
         empty($page['title']) and $page['title'] = Config::get('site.title');
         empty($page['keywords']) and $page['keywords'] = Config::get('site.keywords');
         empty($page['description']) and $page['description'] = Config::get('site.description');
         Cache::driver()->save($page_cache_id, $page);
         return $page;
     }
 }
Example #20
0
 /**
  * Start the route dispatcher and resolve the URL request.
  * @param  string $URL The URL to match onto.
  * @param  string $method The HTTP method.
  * @param  bool $return_route If setted to true it will *NOT* execute the route but it will return her.
  * @return boolean true if a route callback was executed.
  */
 public static function dispatch($URL = null, $method = null, $return_route = false)
 {
     if (!$URL) {
         $URL = Request::URI();
     }
     if (!$method) {
         $method = Request::method();
     }
     $__deferred_send = new Deferred(function () {
         if (Options::get('core.response.autosend', true)) {
             Response::send();
         }
     });
     if (empty(static::$optimized_tree)) {
         foreach ((array) static::$routes as $group => $routes) {
             foreach ($routes as $route) {
                 if (is_a($route, 'Route') && $route->match($URL, $method)) {
                     if ($return_route) {
                         return $route;
                     } else {
                         $route->run($route->extractArgs($URL), $method);
                         return true;
                     }
                 }
             }
         }
     } else {
         $routes =& static::$optimized_tree;
         foreach (explode('/', trim($URL, '/')) as $segment) {
             if (is_array($routes) && isset($routes[$segment])) {
                 $routes =& $routes[$segment];
             } else {
                 if (is_array($routes) && isset($routes[''])) {
                     $routes =& $routes[''];
                 } else {
                     break;
                 }
             }
         }
         if (is_array($routes) && isset($routes[0]) && !is_array($routes[0])) {
             foreach ((array) $routes as $route) {
                 if (is_a($route, __CLASS__) && $route->match($URL, $method)) {
                     if ($return_route) {
                         return $route;
                     } else {
                         $route->run($route->extractArgs($URL), $method);
                         return true;
                     }
                 }
             }
         }
     }
     Response::status(404, '404 Resource not found.');
     foreach (array_filter(array_merge(static::trigger(404) ?: [], Event::trigger(404) ?: [])) as $res) {
         Response::add($res);
     }
     return false;
 }
 /**
  * Handle routing item
  *
  * @param  lang.Oject instance
  * @param  lang.reflect.Method method
  * @param  var[] args
  * @param  webservices.rest.srv.RestContext context
  * @return webservices.rest.srv.Response
  */
 public function handle($instance, $method, $args)
 {
     foreach ($args as $i => $arg) {
         $args[$i] = $this->unmarshal(typeof($arg), $arg);
     }
     // HACK: Ungeneric XML-related
     $properties = array();
     if ($method->hasAnnotation('xmlfactory', 'element')) {
         $properties['name'] = $method->getAnnotation('xmlfactory', 'element');
     } else {
         if (($class = $method->getDeclaringClass()) && $class->hasAnnotation('xmlfactory', 'element')) {
             $properties['name'] = $class->getAnnotation('xmlfactory', 'element');
         }
     }
     // Invoke the method
     try {
         $result = $method->invoke($instance, $args);
         $this->cat && $this->cat->debug('<-', $result);
     } catch (TargetInvocationException $e) {
         $this->cat && $this->cat->warn('<-', $e);
         return $this->mapException($e->getCause());
     }
     // For "VOID" methods, set status to "no content". If a response is returned,
     // use its status, headers and payload. For any other methods, set status to "OK".
     if (Type::$VOID->equals($method->getReturnType())) {
         return Response::status(HttpConstants::STATUS_NO_CONTENT);
     } else {
         if ($result instanceof webservices·rest·srv·Output) {
             $result->payload = $this->marshal($result->payload, $properties);
             return $result;
         } else {
             return Response::status(HttpConstants::STATUS_OK)->withPayload($this->marshal(new Payload($result), $properties));
         }
     }
 }
Example #22
0
 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;
 }
 public function with_two_cookies()
 {
     $user = new Cookie('user', 'Test');
     $lang = new Cookie('language', 'de');
     $this->assertEquals(array($user, $lang), Response::status(200)->withCookie($user)->withCookie($lang)->cookies);
 }
 public function handle_exception_with_mapper()
 {
     $t = new Throwable('Test');
     $this->fixture->addExceptionMapping('lang.Throwable', newinstance('webservices.rest.srv.ExceptionMapper', array(), '{
     public function asResponse($t, RestContext $ctx) {
       return Response::error(500)->withPayload(array("message" => $t->getMessage()));
     }
   }'));
     $this->assertEquals(Response::status(500)->withPayload(new Payload(array('message' => 'Test'), array('name' => 'exception'))), $this->fixture->handle($this, $this->getClass()->getMethod('raiseAnError'), array($t)));
 }
Example #25
0
 /**
  * Get page
  *
  *  <code>
  *      $page = Morfy::getPage('downloads');
  *  </code>
  *
  * @access  public
  * @param  string $url Url
  * @return array
  */
 public static function getPage($url)
 {
     // Get the file path
     if ($url) {
         $file = PAGES_PATH . '/' . $url;
     } else {
         $file = PAGES_PATH . '/' . 'index';
     }
     // Load the file
     if (is_dir($file)) {
         $file = PAGES_PATH . '/' . $url . '/index.md';
     } else {
         $file .= '.md';
     }
     if (file_exists($file)) {
         $content = file_get_contents($file);
     } else {
         $content = file_get_contents(PAGES_PATH . '/' . '404.md');
         Response::status(404);
     }
     $_page = explode('---', $content, 3);
     $page = Spyc::YAMLLoad($_page[1]);
     $url = str_replace(PAGES_PATH, static::$site['url'], $file);
     $url = str_replace('index.md', '', $url);
     $url = str_replace('.md', '', $url);
     $url = str_replace('\\', '/', $url);
     $url = rtrim($url, '/');
     $page['url'] = $url;
     $_content = static::parseContent($_page[2]);
     if (is_array($_content)) {
         $page['summary'] = $_content['summary'];
         $page['content'] = $_content['content'];
     } else {
         $page['content'] = $_content;
     }
     $page['slug'] = basename($file, '.md');
     // Overload page title, keywords and description if needed
     empty($page['title']) and $page['title'] = static::$site['title'];
     empty($page['keywords']) and $page['keywords'] = static::$site['keywords'];
     empty($page['description']) and $page['description'] = static::$site['description'];
     return $page;
 }
Example #26
0
 /**
  * Handle user exceptions
  *
  * This is the global Exception handler that will catch an uncaught Exception
  * and display a nice-looking error page with details about the Exception.
  *
  * @param   Exception $e
  * @return  void
  */
 public static function handleExceptions(Exception $e)
 {
     //Log error here with error_log() if in DEVELOPMENT mode and logging turned on
     ob_clean();
     $r = new Response();
     $r->status(500);
     $r->body(self::generateErrorMarkup($e->getMessage(), $e->getFile(), $e->getLine(), $e->getTraceAsString()));
     $r->send();
     exit;
 }
Example #27
0
<?php

/**
 * Morfy Feed Plugin
 *
 * (c) Romanenko Sergey / Awilum <*****@*****.**>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
if (Url::getUriSegment(0) == 'rss') {
    Morfy::factory()->addAction('before_render', function () {
        $fenom = Fenom::factory(PLUGINS_PATH . '/feed/templates/', CACHE_PATH . '/fenom/', Morfy::$fenom);
        $fenom->setOptions(array("strip" => false));
        Response::status(200);
        Request::setHeaders('Content-Type: text/xml; charset=utf-8');
        $fenom->display('rss.tpl', array('page' => Morfy::factory()->getPage(Morfy::$plugins['feed']['page']), 'pages' => Morfy::factory()->getPages(Morfy::$plugins['feed']['page'], 'date', 'DESC', array('404'))));
        Request::shutdown();
    });
}
Example #28
0
 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()));
     }
 }
Example #29
0
 /**
  * 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
         $follow_request = Request::factory($response->headers('Location'))->method($follow_method)->headers(Arr::extract($request->headers(), $client->follow_headers()));
         if ($follow_method !== Request::GET) {
             $follow_request->body($request->body());
         }
         return $follow_request;
     }
     return NULL;
 }
Example #30
0
<?php

Route::filter('bo_auth', function ($request) {
    /** @var Request $request */
    if ($request->cookie('bo_auth')) {
        $auth = explode(';', $request->cookie('bo_auth'));
        if (count($auth) == 4) {
            list($pub_key, $uid, $expires, $sec_hash) = $auth;
            $known_keys = array('test' => 'om nom nom');
            if ($expires > time() && isset($known_keys[$pub_key])) {
                // generate hash
                $private_key = $known_keys[$pub_key];
                $set = array($pub_key, $private_key, $expires, $uid);
                sort($set);
                $calculated_hash = md5(implode(';', $set));
                if ($sec_hash == $calculated_hash) {
                    return null;
                }
            }
        }
    }
    return Response::status(401);
    // auth required
});