Пример #1
0
 /**
  * @expectedException \LogicException
  */
 function testGetPathOutsideBaseUrl()
 {
     $request = new Request();
     $request->setBaseUrl('/foo/');
     $request->setUrl('/bar/');
     $request->getPath();
 }
Пример #2
0
 /**
  * Dispatch the given request by finding and invoking the handler matching the request data.
  *
  * @param Request $request 
  * @param Response $response 
  * @return Response
  */
 public function dispatch(Request $request, Response $response)
 {
     $matches = $this->match($request->getPath(), $request->getMethod());
     if ($matches === null) {
         throw new \Exception('No routes match the path ' . $request->getPath() . '');
     }
     if (!is_callable($matches['handler'])) {
         throw new \Exception('The given handler is not a valid callback.');
     }
     $result = call_user_func_array($matches['handler'], array_merge(array($this->application), $matches['params']));
     if (is_string($result)) {
         $response->setContent($result);
     } elseif (is_numeric($result)) {
         $response->setStatus($result);
     }
     return $response;
 }
Пример #3
0
 public function matches(Request $request)
 {
     if (in_array($request->getMethod(), $this->methods)) {
         if (preg_match($this->pattern, $request->getPath(), $matches)) {
             return $matches;
         }
     }
     return false;
 }
 /**
  * @param Request $request
  * @todo alter expression to handle page params
  * @todo this is duplicated from PageRequestTarget, needs refactoring
  * @return type 
  */
 private function getPageClassForPath(Request $request)
 {
     $mapEntry = PageMap::getPageMap();
     foreach ($mapEntry as $path => $pageClass) {
         if (preg_match("/^" . $this->prepare($request->getRootPath()) . "\\/" . $path . "{1}([?|&]{1}\\S+={1}\\S+)*\$/", $request->getPath())) {
             return $pageClass::getIdentifier();
         }
     }
     return false;
 }
Пример #5
0
 /**
  * Returns true if the url of both specified requests match.
  *
  * @param  Request $first  First request to match.
  * @param  Request $second Second request to match.
  *
  * @return boolean True if the url of both specified requests match.
  */
 public static function matchUrl(Request $first, Request $second)
 {
     if (null !== $first->getPath()) {
         $path = str_replace('#', '\\#', $first->getPath());
         if (!preg_match('#' . $path . '#', rawurldecode($second->getPath()))) {
             return false;
         }
     }
     return true;
 }
Пример #6
0
 public function delete($path, $handler, $require_oauth = false)
 {
     $request = new Request();
     if ($this->routing_key) {
         $request->path = $request->params[$this->routing_key];
     }
     if ($request->getMethod() != 'DELETE') {
         return;
     }
     if ($request->getPath() != $path) {
         return;
     }
     $this->dispatch($handler, $require_oauth, $request);
 }
Пример #7
0
 /**
  * @param Request $request
  * @return Response
  * @throws Exception
  */
 public function run(Request $request)
 {
     $path = $request->getPath();
     $path = $path ? $path : $this->defaultRoute;
     $pathArray = explode('/', trim($path, '/'));
     Application::getInstance()->logger->i('ROUTER', 'Requested path "' . $path . '".');
     foreach ($this->routes as $name => $route) {
         $this->validate($name, $route);
         $patternArray = explode('/', trim($route['pattern'], '/'));
         if ($this->match($pathArray, $patternArray, $params)) {
             Application::getInstance()->logger->i('ROUTER', 'Found routes "' . $name . '" for path "' . $path . '".');
             return $this->dispatch($name, $route, $params);
         }
     }
     Application::getInstance()->logger->w('ROUTER', 'Not found routes for path "' . $path . '".');
     return new Response(404, "Not found path {$path}.");
 }
Пример #8
0
 public static function assetController()
 {
     $p = Request::getPath();
     if (Request::getContext() == 'css') {
         $file = 'css/' . $p[count($p) - 1] . '.css.twig';
         if (file_exists(Asset . $file)) {
             return self::$twig->render($file);
         }
     } else {
         if (Request::getContext() == 'js') {
             $file = Asset . 'js/' . $p[count($p) - 1] . '.js';
             if (file_exists($file)) {
                 return file_get_contents($file);
             }
         }
     }
     return '';
 }
Пример #9
0
 public static function run()
 {
     $dotenv = new \Dotenv\Dotenv(TXTROOT);
     $dotenv->load();
     if (isset($_SERVER['HTTP_USER_AGENT']) && stripos($_SERVER['HTTP_USER_AGENT'], 'Slackbot-LinkExpanding') !== false) {
         Response::sendResponse(Response::HTTP_403, ['error' => "No slackbots allowed"]);
         exit;
     }
     if (!getenv('REDIS_URL')) {
         Response::sendResponse(Response::HTTP_500, ['error' => "REDIS_URL environment variable required"]);
         exit;
     }
     if (!Request::isGet() && !Request::isPost()) {
         Response::sendResponse(Response::HTTP_405, ['error' => "Please use a GET or POST"]);
         exit;
     }
     if (getenv('AUTH') && (!isset($_POST['auth']) || !static::compareStrings(getenv('AUTH'), $_POST['auth']))) {
         Response::sendResponse(Response::HTTP_401, ['error' => "'auth' parameter is missing or invalid"]);
         exit;
     }
     //    header('Access-Control-Allow-Origin: ' . $_SERVER['ORIGIN']);
     //    header('Access-Control-Allow-Credentials: true');
     //    Access-Control-Allow-Methods: GET, POST
     // x-frame-options
     $redis = Redis::getRedis(getenv('REDIS_URL'));
     $hash = ltrim(Request::getPath(), '/');
     if ($hash) {
         if ($hash == 'robots.txt') {
             Response::setStatus(Response::HTTP_200);
             Response::setContentType(Response::TEXT);
             Response::setContent("User-agent: *\nDisallow: /");
             Response::send();
             exit;
         }
         if (Request::isPost()) {
             Response::sendResponse(Response::HTTP_405, ['error' => "Cannot post to a hash"]);
             exit;
         }
         if (strlen($hash) > Redis::MAX_KEY_LENGTH || !preg_match('/^[A-Za-z0-9]+$/', $hash)) {
             Response::sendResponse(Response::HTTP_404, ['error' => "Invalid hash"]);
             exit;
         }
         $data = $redis->hGetAll(Redis::PREFIX . $hash);
         if (!$data) {
             Response::sendResponse(Response::HTTP_404, ['error' => "Hash not found"]);
             exit;
         }
         $datum = Datum::createFromArray($data);
         if ($datum->once) {
             $redis->del(Redis::PREFIX . $hash);
         }
         // set proper cache header, esp for read-once
         // actually, PROBABLY NOT A GOOD IDEA, esp for things that are meant to expire. we should do the opposite - dont cache
         // Response::setCacheForeverHeaders();
         Response::sendResponse('datum', ['datum' => $datum]);
         exit;
     }
     if (Request::isGet()) {
         Response::sendResponse('home', ['domain' => 'http' . (Request::isSSL() ? 's' : '') . '://' . Request::getHost()]);
         exit;
     } else {
         $data = isset($_POST['data']) ? $_POST['data'] : file_get_contents("php://input");
         if (!$data) {
             Response::sendResponse(Response::HTTP_400, ['error' => 'No data submitted']);
             exit;
         }
         $datum = new Datum(trim($data), Datum::T_TEXT, Request::isFlagOn('once'));
         $key = substr(static::randId(), 0, Redis::MAX_KEY_LENGTH);
         $ttl = isset($_POST['ttl']) ? max(1, min((int) $_POST['ttl'], Redis::MAX_TTL)) : Redis::MAX_TTL;
         $redis->hMSet(Redis::PREFIX . $key, $datum->toArray());
         $redis->expire(Redis::PREFIX . $key, $ttl);
         $url = 'http' . (Request::isSSL() ? 's' : '') . '://' . Request::getHost() . '/' . $key;
         Response::sendResponse(Response::HTTP_201, ['url' => $url, 'ttl' => $ttl, '_textKey' => 'url']);
         exit;
     }
 }
Пример #10
0
 /**
  * Set Request instance
  * 
  * @param Request $request
  * @return void
  */
 public function setRequest(Request $request)
 {
     $this->_request = $request;
     if ($this->_url == null) {
         $url = $request->getPath() . '/?p=%page%';
         $this->setUrl($url);
     }
     $page = $request->getQuery('p');
     if (is_numeric($page)) {
         $this->setCurrentPage($page);
     }
 }
Пример #11
0
 public function getMap(Request $request)
 {
     $path = $request->getPath();
     $method = $request->method;
     return isset($this->_map[$path][$method]) ? $this->_map[$path][$method] : false;
 }
Пример #12
0
 /**
  * Returns true if the url of both specified requests match.
  *
  * @param  Request $first  First request to match.
  * @param  Request $second Second request to match.
  *
  * @return boolean True if the url of both specified requests match.
  */
 public static function matchUrl(Request $first, Request $second)
 {
     return $first->getPath() === $second->getPath();
 }
Пример #13
0
 /**
  * @covers Nethgui\Controller\Request::getPath
  * @todo   Implement testGetPath().
  */
 public function testGetPath()
 {
     $this->assertEquals(array('a', 'b', 'c', 'd'), $this->object->getPath());
 }
Пример #14
0
 /**
  * @covers Xoops\Core\Request::getPath
  */
 public function testGetPath()
 {
     $varname = 'RequestTest';
     $_REQUEST[$varname] = '/var/tmp';
     $this->assertEquals($_REQUEST[$varname], Request::getPath($varname), Request::getPath($varname));
     $_REQUEST[$varname] = ' modules/test/index.php?id=12 ';
     $this->assertEquals('modules/test/index.php?id=12', Request::getPath($varname), Request::getPath($varname));
     $_REQUEST[$varname] = '/var/tmp muck';
     $this->assertEquals('/var/tmp', Request::getPath($varname), Request::getPath($varname));
 }
Пример #15
0
 /**
  *
  */
 protected static function parsePath()
 {
     $direction = array();
     if ($url = parse_url(Request::server('REQUEST_URI'))) {
         if (isset($url['path'])) {
             $relpath = dirname(Request::server('SCRIPT_NAME'));
             $path = trim(str_replace($relpath != '/' ? $relpath : '', '', Request::server('REQUEST_URI')), '/');
             if (!empty($path)) {
                 Request::setPath(explode('/', $path));
             }
         }
         //make sure that module name is capitalized
         $module = ucfirst(Request::getPath(0));
         if (file_exists(\APPLICATION_BASE . '/' . $module)) {
             $direction[0] = $module;
             $direction[1] = Request::getPath(1);
         }
     }
     return $direction;
 }
Пример #16
0
<?php

define('__ROOT__', dirname(__FILE__));
require_once __ROOT__ . "/webready/controller.php";
require_once __ROOT__ . "/webready/request.php";
require_once __ROOT__ . "/webready/view.php";
$css = array("/style/style.css");
$js = array();
$request = new Request();
var_dump($request->getPath());
echo "<br />";
var_dump($request->getMethod());
echo "<br />";
echo json_encode($request->getContent());
Пример #17
0
 /**
  * Converts Request to Curl console command
  *
  * @param Request $request
  * @return string
  */
 public static function convertRequestToCurlCommand(Request $request)
 {
     $message = 'curl -X' . strtoupper($request->getMethod()) . ' ';
     $message .= '\'http://' . $request->getConnection()->getHost() . ':' . $request->getConnection()->getPort() . '/';
     $message .= $request->getPath();
     $query = $request->getQuery();
     if (!empty($query)) {
         $message .= '?' . http_build_query($query);
     }
     $message .= '\'';
     $data = $request->getData();
     if (!empty($data)) {
         $message .= ' -d \'' . json_encode($data) . '\'';
     }
     return $message;
 }
Пример #18
0
 /**
  * Dispatch the router
  *
  * @param Request  $req  Representation the HTTP request to process
  * @param Response $resp Response object to populate with the controller's output
  * @return void
  */
 public function dispatch(Request $req, Response $resp)
 {
     if ($this->options['dirmatch'] == 'ignore') {
         $path = '/' . trim($req->getPath(), '/');
     } elseif ($this->options['dirmatch'] == 'redirect' and substr($req->getPath(), -1, 1) === '/' and $req->getPath() !== '/') {
         $resp->setStatus(301);
         $resp->setHeader('Location', rtrim($req->getPath(), '/'));
         return;
     } else {
         $path = $req->getPath();
     }
     $method = strtolower($req->getMethod());
     $patterns = $this->patterns;
     $controller = null;
     $allowedmethods = array();
     foreach ($this->routes as $pattern => $dest) {
         $pattern = preg_replace_callback('/\\:(\\w+)/', function ($m) use($patterns) {
             return isset($patterns[$m[1]]) ? '(?<' . $m[1] . '>' . $patterns[$m[1]] . ')' : $m[0];
         }, $pattern);
         $pattern = '~^' . str_replace('~', '\\~', $pattern) . '$~' . ($this->options['matchcase'] ? '' : 'i');
         if (preg_match($pattern, $path, $m)) {
             // Handle naive redirects
             if (preg_match('/^(\\/|https?\\:\\/\\/)/i', $dest)) {
                 $dest = preg_replace_callback('/\\{\\{(\\w+)\\}\\}/', function ($m_dest) use($m) {
                     return isset($m[$m_dest[0]]) ? $m[$m_dest[0]] : $m[0];
                 }, $dest);
                 $resp->setStatus(301);
                 $resp->setHeader('Location', $dest);
                 return;
             }
             // Find applicable controller class
             if (!($controllerclass = $this->controllerClass($dest))) {
                 continue;
             }
             // If controller does not support the request method, record the methods it does support (so if no controller is found that can handle the request, an unsupported method error can be returned), then proceed to next route
             $availablemethods = array_intersect($controllerclass::getSupportedMethods(), $this->options['validmethods']);
             if (!in_array($method, $availablemethods)) {
                 $allowedmethods = array_merge($allowedmethods, $availablemethods);
                 continue;
             }
             // Extract and index the URL slugs
             foreach ($m as $key => $value) {
                 if (is_int($key)) {
                     unset($m[$key]);
                 }
             }
             $urlargs = $m;
             // Dispatch the controller.  If controller throws RouteRejectedException (either in contructor or verb method) treat the route as unmatched and attempt to find an alternative
             try {
                 $controller = new $controllerclass($this->di, $req, $resp, $urlargs);
                 if (!method_exists($controller, $method)) {
                     $method = 'all';
                 }
                 $controller->dispatch($method);
             } catch (RouteRejectedException $e) {
                 // TODO: Also consider resetting the $resp object to a blank state
                 $controller = null;
                 continue;
             }
             break;
         }
     }
     // If no controller was found to handle the request, assign a default one
     if (!$controller) {
         if ($allowedmethods) {
             $controllerclass = $this->getDefaultRouteControllerClass('unsupportedmethod');
             $urlargs = array('allowedmethods' => $allowedmethods);
         } else {
             $controllerclass = $this->getDefaultRouteControllerClass('noroute');
             $urlargs = array();
         }
         $controller = new $controllerclass($this->di, $req, $resp, $urlargs);
         if (!method_exists($controller, $method)) {
             $method = 'all';
         }
         $controller->{$method}();
     }
 }