Пример #1
0
 /**
  * Get default status code
  * @param int|null $code
  * @return null
  */
 protected function getCode($code = NULL)
 {
     if ($code === NULL) {
         $code = $code = isset($this->defaultCodes[$this->request->getMethod()]) ? $this->defaultCodes[$this->request->getMethod()] : 200;
     }
     return (int) $code;
 }
Пример #2
0
 /**
  * Get prederred method 
  * @param  IRequest $request 
  * @return string            
  */
 protected function getPreferredMethod(IRequest $request)
 {
     $method = $request->getMethod();
     $isPost = $method === IRequest::POST;
     $header = $request->getHeader(self::OVERRIDE_HEADER);
     $param = $request->getQuery(self::OVERRIDE_PARAM);
     if ($header && $isPost) {
         return $header;
     }
     if ($param && $isPost) {
         return $param;
     }
     return $request->getMethod();
 }
Пример #3
0
 /**
  * Renders panel.
  * @return string
  */
 public function getPanel()
 {
     ob_start();
     $request = $this->request;
     $routers = $this->routers;
     $source = $this->source;
     $hasModule = (bool) array_filter($routers, function ($rq) {
         return $rq['module'];
     });
     $url = $this->httpRequest->getUrl();
     $method = $this->httpRequest->getMethod();
     require __DIR__ . '/templates/RoutingPanel.panel.phtml';
     return ob_get_clean();
 }
Пример #4
0
	/**
	 * Maps HTTP request to a Request object.
	 * @return Nette\Application\Request|NULL
	 */
	public function match(Nette\Http\IRequest $httpRequest)
	{
		if ($httpRequest->getUrl()->getPathInfo() !== '') {
			return NULL;
		}
		// combine with precedence: get, (post,) defaults
		$params = $httpRequest->getQuery();
		$params += $this->defaults;

		if (!isset($params[self::PRESENTER_KEY]) || !is_string($params[self::PRESENTER_KEY])) {
			return NULL;
		}

		$presenter = $this->module . $params[self::PRESENTER_KEY];
		unset($params[self::PRESENTER_KEY]);

		return new Application\Request(
			$presenter,
			$httpRequest->getMethod(),
			$params,
			$httpRequest->getPost(),
			$httpRequest->getFiles(),
			array(Application\Request::SECURED => $httpRequest->isSecured())
		);
	}
Пример #5
0
 /**
  * Maps HTTP request to a Request object.
  *
  * @param Nette\Http\IRequest $httpRequest
  * @return Request|NULL
  */
 public function match(Nette\Http\IRequest $httpRequest)
 {
     $relativeUrl = trim($httpRequest->getUrl()->relativeUrl, "/");
     $path = trim($httpRequest->getUrl()->path, "/");
     if ($relativeUrl == "") {
         $target = $this->defaultRoute;
         $this->currentTarget->setCurrentTarget($this->targetDao->findTarget($target->presenter, $target->action, $target->id));
     } elseif ($relativeUrl == "sitemap.xml") {
         $target = new Target("Seo:Meta", "sitemap");
     } elseif ($relativeUrl == "robots.txt") {
         $target = new Target("Seo:Meta", "robots");
     } elseif (substr($relativeUrl, 0, 6) == "google" && $this->settingsDao->getWebmasterToolsName() == $relativeUrl) {
         $target = new Target("Seo:Meta", "googleWebmasterTools");
     } else {
         $route = $this->routeDao->findRouteBySlug($relativeUrl, TRUE);
         if (!$route) {
             $route = $this->routeDao->findRouteBySlug($path, TRUE);
             if (!$route) {
                 return NULL;
             }
         }
         $this->currentTarget->setCurrentTarget($route->getTarget());
         $target = new Target($route->target->targetPresenter, $route->target->targetAction, $route->target->targetId);
     }
     $params = array();
     $params["action"] = $target->action;
     if ($target->id) {
         $params["id"] = $target->id;
     }
     $params += $httpRequest->getQuery();
     return new Request($target->presenter, $httpRequest->getMethod(), $params, $httpRequest->getPost(), $httpRequest->getFiles(), array(Request::SECURED => $httpRequest->isSecured()));
 }
Пример #6
0
 /**
  * CLI commands run from app/console.php
  *
  * Maps HTTP request to a Request object.
  * @return Nette\Application\Request|NULL
  */
 public function match(Nette\Http\IRequest $httpRequest)
 {
     $this->loadLocales();
     $urlPath = new Services\UrlPath($httpRequest);
     $urlPath->setPredefinedLocales($this->locales);
     /** @var Url $urlEntity */
     $urlEntity = $this->loadUrlEntity($urlPath->getPath(true));
     if ($urlEntity === null) {
         // no route found
         $this->onUrlNotFound($urlPath);
         return null;
     }
     if ($urlEntity->getActualUrlToRedirect() === null) {
         $presenter = $urlEntity->getPresenter();
         $internal_id = $urlEntity->getInternalId();
         $action = $urlEntity->getAction();
     } else {
         $presenter = $urlEntity->getActualUrlToRedirect()->getPresenter();
         $internal_id = $urlEntity->getActualUrlToRedirect()->getInternalId();
         $action = $urlEntity->getActualUrlToRedirect()->getAction();
     }
     $params = $httpRequest->getQuery();
     $params['action'] = $action;
     $params['locale'] = $urlPath->getLocale();
     $this->urlParametersConverter->in($urlEntity, $params);
     // todo
     if ($internal_id !== null) {
         $params['internal_id'] = $internal_id;
     }
     return new Nette\Application\Request($presenter, $httpRequest->getMethod(), $params, $httpRequest->getPost(), $httpRequest->getFiles());
 }
Пример #7
0
 /**
  * Get request method flag
  * @param Http\IRequest $httpRequest
  * @return string|null
  */
 public function getMethod(Http\IRequest $httpRequest)
 {
     $method = $httpRequest->getMethod();
     if (!isset($this->methodDictionary[$method])) {
         return NULL;
     }
     return $this->methodDictionary[$method];
 }
Пример #8
0
 /**
  * Match request
  * @param  IRequest $request 
  * @return Request            
  */
 public function match(Http\IRequest $request)
 {
     $path = $request->url->getPathInfo();
     if (!Strings::contains($path, $this->prefix)) {
         return NULL;
     }
     $path = Strings::substring($path, strlen($this->prefix) + 1);
     $pathParts = explode('/', $path);
     $pathArguments = array_slice($pathParts, 1);
     $action = $this->getActionName($request->getMethod(), $pathArguments);
     $params = $this->getPathParameters($pathArguments);
     $params[Route::MODULE_KEY] = $this->module;
     $params[Route::PRESENTER_KEY] = $pathParts[0];
     $params['action'] = $action;
     $presenter = ($this->module ? $this->module . ':' : '') . $params[Route::PRESENTER_KEY];
     $appRequest = new Application\Request($presenter, $request->getMethod(), $params, $request->getPost(), $request->getFiles());
     return $appRequest;
 }
Пример #9
0
 /**
  * @param Http\IRequest $httpRequest
  * @return string
  */
 private function detectHttpMethod(Http\IRequest $httpRequest)
 {
     $method = $httpRequest->getMethod();
     if ($this->headerOverride && $method === Http\IRequest::POST) {
         $overriden = $httpRequest->getHeader($this->headerOverride);
         $method = $overriden ? strtoupper($overriden) : $method;
     }
     return $method;
 }
Пример #10
0
 public function match(\Nette\Http\IRequest $httpRequest)
 {
     $httpMethod = $httpRequest->getMethod();
     $flags = $this->getFlags();
     if (($flags & self::RESTFUL) == self::RESTFUL) {
         $presenterRequest = parent::match($httpRequest);
         if ($presenterRequest != NULL) {
             switch ($httpMethod) {
                 case 'GET':
                     $action = 'default';
                     break;
                 case 'POST':
                     $action = 'create';
                     break;
                 case 'PUT':
                     $action = 'update';
                     break;
                 case 'PATCH':
                     $action = 'update';
                     break;
                 case 'DELETE':
                     $action = 'delete';
                     break;
                 default:
                     $action = 'default';
             }
             $params = $presenterRequest->getParameters();
             $params['action'] = $action;
             $presenterRequest->setParameters($params);
             return $presenterRequest;
         } else {
             return NULL;
         }
     }
     if (($flags & self::METHOD_POST) == self::METHOD_POST && $httpMethod != 'POST') {
         return NULL;
     }
     if (($flags & self::METHOD_GET) == self::METHOD_GET && $httpMethod != 'GET') {
         return NULL;
     }
     if (($flags & self::METHOD_PUT) == self::METHOD_PUT && $httpMethod != 'PUT') {
         return NULL;
     }
     if (($flags & self::METHOD_PATCH) == self::METHOD_PATCH && $httpMethod != 'PATCH') {
         return NULL;
     }
     if (($flags & self::METHOD_DELETE) == self::METHOD_DELETE && $httpMethod != 'DELETE') {
         return NULL;
     }
     return parent::match($httpRequest);
 }
Пример #11
0
 public function match(\Nette\Http\IRequest $httpRequest)
 {
     $httpMethod = $httpRequest->getMethod();
     if (($this->flags & self::RESTFUL) == self::RESTFUL) {
         $presenterRequest = parent::match($httpRequest);
         if ($presenterRequest != NULL) {
             $payload = null;
             $payloadParameters = array();
             switch ($httpMethod) {
                 case 'GET':
                     $action = 'default';
                     break;
                 case 'POST':
                     $action = 'create';
                     break;
                 case 'PUT':
                     $action = 'update';
                     $payload = file_get_contents("php://input");
                     parse_str($payload, $payloadParameters);
                     break;
                 case 'DELETE':
                     $action = 'delete';
                     break;
                 default:
                     $action = 'default';
             }
             $parameters = $presenterRequest->getParameters();
             $parameters['action'] = $action;
             $parameters['payload'] = $payload;
             $parameters = array_merge($parameters, $payloadParameters);
             $presenterRequest->setParameters($parameters);
             return $presenterRequest;
         } else {
             return NULL;
         }
     }
     if (($this->flags & self::METHOD_POST) == self::METHOD_POST && $httpMethod != 'POST') {
         return NULL;
     }
     if (($this->flags & self::METHOD_GET) == self::METHOD_GET && $httpMethod != 'GET') {
         return NULL;
     }
     if (($this->flags & self::METHOD_PUT) == self::METHOD_PUT && $httpMethod != 'PUT') {
         return NULL;
     }
     if (($this->flags & self::METHOD_DELETE) == self::METHOD_DELETE && $httpMethod != 'DELETE') {
         return NULL;
     }
     return parent::match($httpRequest);
 }
Пример #12
0
 public function match(IRequest $httpRequest)
 {
     $httpMethod = $httpRequest->getMethod();
     if (($this->flags & self::RESTFUL) == self::RESTFUL) {
         $presenterRequest = parent::match($httpRequest);
         if ($presenterRequest != NULL) {
             switch ($httpMethod) {
                 //see: http://en.wikipedia.org/wiki/Representational_state_transfer#RESTful_web_APIs
                 case 'GET':
                     $action = 'get';
                     break;
                 case 'POST':
                     $action = 'post';
                     break;
                     //CREATE
                 //CREATE
                 case 'PUT':
                     $action = 'put';
                     break;
                     //UPDATE
                 //UPDATE
                 case 'DELETE':
                     $action = 'delete';
                     break;
                 default:
                     $action = 'get';
             }
             $params = $presenterRequest->getParameters();
             $params['action'] = $action;
             $presenterRequest->setParameters($params);
             return $presenterRequest;
         } else {
             return NULL;
         }
     }
     if (($this->flags & self::METHOD_POST) == self::METHOD_POST && $httpMethod != 'POST') {
         return NULL;
     }
     if (($this->flags & self::METHOD_GET) == self::METHOD_GET && $httpMethod != 'GET') {
         return NULL;
     }
     if (($this->flags & self::METHOD_PUT) == self::METHOD_PUT && $httpMethod != 'PUT') {
         return NULL;
     }
     if (($this->flags & self::METHOD_DELETE) == self::METHOD_DELETE && $httpMethod != 'DELETE') {
         return NULL;
     }
     return parent::match($httpRequest);
 }
Пример #13
0
    /**
     * Maps HTTP request to a Request object.
     *
     * @param Nette\Http\IRequest $httpRequest
     * @return NULL|Request
     */
    public function match(Nette\Http\IRequest $httpRequest)
    {
        $slug = ltrim($httpRequest->getUrl()->getPath(), '/');
        $id = $this->dibi->query('
			SELECT [c.id]
			FROM [old_links] [l]

			INNER JOIN [contents] [c] ON [c.youtube_id] = [l.target]

			WHERE [mask] = %s', $slug, '
		')->fetchSingle();
        if (!$id) {
            return NULL;
        }
        return new Request('Video', $httpRequest->getMethod(), ['action' => 'default', 'videoId' => $id]);
    }
Пример #14
0
 /**
  * Maps HTTP request to a Request object.
  *
  * @return AppRequest|NULL
  */
 public function match(HttpRequest $httpRequest)
 {
     $url = $httpRequest->getUrl();
     $slug = rtrim(substr($url->getPath(), strrpos($url->getScriptPath(), '/') + 1), '/');
     foreach ($this->tableOut as $destination2 => $slug2) {
         if ($slug === rtrim($slug2, '/')) {
             $destination = $destination2;
             break;
         }
     }
     if (!isset($destination)) {
         return NULL;
     }
     $params = $httpRequest->getQuery();
     $pos = strrpos($destination, ':');
     $presenter = substr($destination, 0, $pos);
     $params['action'] = substr($destination, $pos + 1);
     return new AppRequest($presenter, $httpRequest->getMethod(), $params, $httpRequest->getPost(), $httpRequest->getFiles(), array(AppRequest::SECURED => $httpRequest->isSecured()));
 }
Пример #15
0
    /**
     * Maps HTTP request to a Request object.
     *
     * @param Http\IRequest $httpRequest
     * @return NULL|Request
     */
    public function match(Http\IRequest $httpRequest)
    {
        $path = ltrim($httpRequest->getUrl()->getPath(), '/');
        $match = Strings::match($path, '~^([^/]+)/(?P<slug>[^/]+)/lekce~');
        if (!$match) {
            return NULL;
        }
        $id = $this->dibi->query('
			SELECT [c.id]
			FROM [old_links] [l]

			INNER JOIN [contents] [c] ON [c.youtube_id] = [l.target]

			WHERE [mask] = %s', $match['slug'], '
		')->fetchSingle();
        if (!$id) {
            return NULL;
        }
        return new Request('Video', $httpRequest->getMethod(), ['action' => 'default', 'videoId' => $id]);
    }
Пример #16
0
 /**
  * @param IRequest $request
  *
  * @return string
  */
 protected function detectMethod(IRequest $request)
 {
     $requestMethod = $request->getMethod();
     if ($requestMethod !== 'POST') {
         return $request->getMethod();
     }
     $method = $request->getHeader(self::METHOD_OVERRIDE_HTTP_HEADER);
     if (isset($method)) {
         return Strings::upper($method);
     }
     $method = $request->getQuery(self::METHOD_OVERRIDE_QUERY_PARAM);
     if (isset($method)) {
         return Strings::upper($method);
     }
     return $requestMethod;
 }
Пример #17
0
 function match(Nette\Http\IRequest $httpRequest)
 {
     if ($httpRequest->getUrl()->getPathInfo() !== '') {
         return NULL;
     }
     $params = $httpRequest->getQuery();
     $params += $this->defaults;
     if (!isset($params[self::PRESENTER_KEY])) {
         throw new Nette\InvalidStateException('Missing presenter.');
     }
     $presenter = $this->module . $params[self::PRESENTER_KEY];
     unset($params[self::PRESENTER_KEY]);
     return new Application\Request($presenter, $httpRequest->getMethod(), $params, $httpRequest->getPost(), $httpRequest->getFiles(), array(Application\Request::SECURED => $httpRequest->isSecured()));
 }
Пример #18
0
 /**
  * @param Nette\Http\IRequest $httpRequest
  * @return Request|null
  */
 public function match(Nette\Http\IRequest $httpRequest)
 {
     $url = $httpRequest->getUrl();
     $path = substr($url->path, strlen($url->basePath));
     if (in_array($path, $this->options[self::IGNORE_URL])) {
         return NULL;
     }
     if ($action = $this->source->toAction($url)) {
         $params = array_merge($httpRequest->getQuery(), $action->getParameters());
         $presenter = $action->getPresenter();
         $params['action'] = $action->getAction();
         // presenter not set from ISource, load from parameters or default presenter
         if (!mb_strlen($presenter)) {
             if (isset($params['presenter']) && $params['presenter']) {
                 $presenter = $params['presenter'];
             } else {
                 return NULL;
             }
         }
         unset($params['presenter']);
         return new Request($presenter, $httpRequest->getMethod(), $params, $httpRequest->getPost(), $httpRequest->getFiles());
     }
     return NULL;
 }
Пример #19
0
 /**
  * Maps HTTP request to a Request object.
  *
  * @param \Nette\Http\IRequest $httpRequest
  * @throws \Nette\Application\BadRequestException
  * @return App\Request|NULL
  */
 public function match(Http\IRequest $httpRequest)
 {
     // 1) PARSE URL
     $url = $httpRequest->getUrl();
     $path = trim($url->path, $url->scriptPath);
     $params = array();
     $lang = array();
     if ($path !== '') {
         $parts = explode($url->scriptPath, $path, 4);
         //            echo print_r($parts);
         if (in_array($parts[0], $this->slugManager->getLocale())) {
             $params['locale'] = $parts[0];
             $lang = $parts[0];
             unset($parts[0]);
             $parts = array_values($parts);
             if (count($parts) == 2) {
                 $slugName = $parts[1];
                 $params['prefix'] = $parts[0];
             } else {
                 $slugName = $parts[0];
             }
         } else {
             if (count($parts) == 2) {
                 $slugName = $parts[1];
                 $params['prefix'] = $parts[0];
             } else {
                 $slugName = $parts[0];
             }
         }
         //get row by slug
         $row = $this->slugManager->getRowBySlug($slugName, $lang, $params['prefix']);
     } else {
         $parts = array('Homepage', 'default');
         $row = $this->slugManager->getDefault();
     }
     if (!$row) {
         //throw new Nette\Application\BadRequestException('Page does not exist');
         return null;
     }
     //id
     if (isset($parts[2])) {
         $id = $parts[2];
     }
     $params['page_id'] = $row->id;
     if (isset($id)) {
         $params['id'] = $id;
     }
     //$url->query into params
     if ($url->getQuery() !== '') {
         $query = explode('&', $url->getQuery());
         foreach ($query as $singlequery) {
             $result = explode('=', $singlequery);
             $params[$result[0]] = $result[1];
         }
     }
     // Presenter preset
     if ($row->pages_types_id == 0) {
         $presenterArr = implode(":", array_slice(explode(':', $row->presenter), 0, -1));
         $presenter = $presenterArr;
     } else {
         if (!empty($row->presenter)) {
             $presenter = $row->presenter;
         } else {
             $presenter = $row->pages_types->presenter;
         }
     }
     // Action
     if ($row->pages_templates_id != null) {
         $params['action'] = $row->pages_templates->template;
     } else {
         if ($row->pages_types_id == 0) {
             $params['action'] = substr($row->presenter, strrpos($row->presenter, ":") + 1);
         } else {
             $params['action'] = $row->pages_types->action;
         }
     }
     return new App\Request($presenter, $httpRequest->getMethod(), $params, $httpRequest->getPost(), $httpRequest->getFiles(), array(App\Request::SECURED => $httpRequest->isSecured()));
 }
Пример #20
0
 /**
  * @return Nette\Application\IResponse
  */
 protected function process(Nette\Application\Request $request)
 {
     // Query output content type -------------------------------------------
     // Accept header is comma separated fallback sequence
     // @todo sequence should be actually sorted by the degree of specificity
     // @todo make support for version options (ie. application/json;version=2)
     // 		see: RESTful Web Services Cookbook page 250
     $cTypes = preg_split('/,/', $this->httpRequest->getHeader('Accept'), 0, PREG_SPLIT_NO_EMPTY);
     foreach ($cTypes as $cType) {
         // We ignore all the options
         $cType = preg_replace('/;.*/', '', $cType);
         if (strcasecmp($cType, 'text/html') === 0 || strcmp($cType, '*/*') === 0) {
             $this->outputContentType = 'text/html';
             $this->httpResponse->setContentType('text/html', 'utf-8');
             break;
         } elseif (strcasecmp($cType, 'application/json') === 0) {
             $this->outputContentType = 'application/json';
             $this->httpResponse->setContentType('application/json', 'utf-8');
             break;
         }
     }
     if ($this->outputContentType === NULL) {
         $this->terminateWithError(self::ERROR_INVALID_REQUEST, "Accept header is missing or not satisfiable.", 406);
     }
     // Process Content-Language header -------------------------------------
     // Process Authorization header ----------------------------------------
     if (($authHeader = $this->httpRequest->getHeader('Authorization')) !== NULL) {
         if (preg_match('/^Bearer\\s([^\\s,;]+)/i', $authHeader, $matches)) {
             $tokenHash = $matches[1];
             // If connection is not secured return error and invalidate sent token
             // just in case
             if (!$request->hasFlag(Nette\Application\Request::SECURED) && $this->isInProductionMode()) {
                 $this->tokenManager->invalidateToken($tokenHash);
                 $this->terminateWithError(self::ERROR_INVALID_REQUEST, "Secured connection required", 400);
             }
             if (!$this->attemptLogger->getRemainingAttempts(self::ATTEMPT_IP_TOKEN, $this->httpRequest->getRemoteAddress())) {
                 $this->terminateWithError(OAuth2ResourceProvider::ERROR_MAXIMUM_ATTEMPTS_EXCEEDED, 'Maximum number of authorization attempts exceeded.', 403);
             }
             $token = $this->tokenManager->getToken($tokenHash);
             if (!$token) {
                 $this->attemptLogger->logFail(self::ATTEMPT_IP_TOKEN, $this->httpRequest->getRemoteAddress());
                 $this->httpResponse->addHeader('WWW-Authenticate', 'Bearer realm="' . $this->link() . '"');
                 $this->terminateWithError(OAuth2ResourceProvider::ERROR_INVALID_GRANT, 'Given authorization token is not valid.', 401);
             }
             $this->attemptLogger->logSuccess(self::ATTEMPT_IP_TOKEN, $this->httpRequest->getRemoteAddress());
             if (isset($token->parameters->userIdentity)) {
                 $this->user->login(User::AUTHN_METHOD_INVALID, User::AUTHN_SOURCE_ALL, $token->parameters->userIdentity);
             }
             if (isset($token->parameters->client)) {
                 $this->client = $token->parameters->client;
             }
         }
     }
     // Find request handler ------------------------------------------------
     // Gather resource path
     $parameters = $request->getParameters();
     $resourcePath = isset($parameters[self::PARAM_KEY_PATH]) ? trim($parameters[self::PARAM_KEY_PATH]) : NULL;
     if (!$resourcePath) {
         $this->terminateWithError(self::ERROR_INVALID_REQUEST, "No resource path given.", 400);
     }
     // Request router expects leading slash
     if ($resourcePath[0] != '/') {
         $resourcePath = "/{$resourcePath}";
     }
     // Request router: find resource handler
     try {
         /** @var vBuilder\RestApi\Request */
         $this->resourceRequest = $handlerRequest = $this->requestRouter->createRequest($this->httpRequest->getMethod(), $resourcePath);
     } catch (RequestException $e) {
         $this->terminateWithError(self::ERROR_INVALID_REQUEST, $e->getMessage(), $e->getCode() == RequestException::METHOD_NOT_ALLOWED ? 405 : 404);
     }
     // Request authorization -----------------------------------------------
     $handlerMethodAnnotations = $handlerRequest->getMethodReflection()->getAnnotations();
     if (!isset($handlerMethodAnnotations['NoAuthorization']) || !$handlerMethodAnnotations['NoAuthorization'][0]) {
         if (!$this->client) {
             $this->httpResponse->addHeader('WWW-Authenticate', 'Bearer realm="' . $this->link() . '"');
             $this->terminateWithError(self::ERROR_UNAUTHORIZED, 'Requested resource requires authorization. Please add Authorization header with correct security token.', 401);
         }
     }
     // Decode POST data ----------------------------------------------------
     if ($this->httpRequest->isPost()) {
         $cType = $this->httpRequest->getHeader('Content-Type');
         if (strcasecmp($cType, 'application/json') === 0) {
             try {
                 $this->postData = Nette\Utils\Json::decode(file_get_contents('php://input'), Nette\Utils\Json::FORCE_ARRAY);
             } catch (Nette\Utils\JsonException $e) {
                 $this->terminateWithError(self::ERROR_INVALID_REQUEST, "Malformed POST data (JSON expected).", 400);
             }
         } elseif (strcasecmp($cType, 'application/x-www-form-urlencoded') === 0) {
             $this->postData = $this->httpRequest->getPost();
         } elseif ($cType === NULL) {
             $this->terminateWithError(self::ERROR_INVALID_REQUEST, "Missing Content-Type header, which is mandatory for POST requests.", 400);
         } else {
             $this->terminateWithError(self::ERROR_INVALID_REQUEST, "Request content type of POST data is not supported.", 415);
         }
     }
     // Create resource instance and prepare all dependencies ---------------
     $class = $handlerRequest->getResourceClassName();
     $resource = new $class();
     $resource->presenter = $this;
     $this->systemContainer->callInjects($resource);
     // Prepare and order invoke parameters ---------------------------------
     $mReflection = $handlerRequest->getMethodReflection();
     $invokeParams = array();
     $requestParams = $handlerRequest->getParameters();
     $definedParams = $mReflection->getParameters();
     $index = 0;
     foreach ($definedParams as $pReflection) {
         $index++;
         // Parameter not given in URL?
         if (!isset($requestParams[$pReflection->getName()])) {
             // Default value where available
             if ($pReflection->isDefaultValueAvailable()) {
                 $invokeParams[$pReflection->getName()] = $pReflection->getDefaultValue();
                 continue;
             }
             $this->terminateWithError(self::ERROR_INVALID_REQUEST, "Missing #{$index} parameter for resource handler {$class}::" . $mReflection->getName() . '().', 400);
         }
         $invokeParams[$pReflection->getName()] = $requestParams[$pReflection->getName()];
     }
     // Perform startup
     $resource->startup();
     // Invoke handler method on resource instance
     $responsePayload = $mReflection->invokeArgs($resource, $invokeParams);
     // Automatically set HTTP 204 No Content if necessary
     if ($responsePayload === NULL && $this->httpResponse->getCode() == 200) {
         $this->httpResponse->setCode(204);
     }
     return $responsePayload === NULL ? $this->createResponse() : $this->createResponse($responsePayload);
 }
Пример #21
0
Nette\InvalidArgumentException("Argument must be array or string in format Presenter:action, '$defaults' given.");}$defaults=array(self::PRESENTER_KEY=>substr($defaults,0,$a),'action'=>$a===strlen($defaults)-1?Application\UI\Presenter::DEFAULT_ACTION:substr($defaults,$a+1));}if(isset($defaults[self::MODULE_KEY])){$this->module=$defaults[self::MODULE_KEY].':';unset($defaults[self::MODULE_KEY]);}$this->defaults=$defaults;$this->flags=$flags;}function
match(Nette\Http\IRequest$httpRequest){if($httpRequest->getUrl()->getPathInfo()!==''){return
NULL;}$params=$httpRequest->getQuery();$params+=$this->defaults;if(!isset($params[self::PRESENTER_KEY])){throw
new
Nette\InvalidStateException('Missing presenter.');}$presenter=$this->module.$params[self::PRESENTER_KEY];unset($params[self::PRESENTER_KEY]);return
new
Application\Request($presenter,$httpRequest->getMethod(),$params,$httpRequest->getPost(),$httpRequest->getFiles(),array(Application\Request::SECURED=>$httpRequest->isSecured()));}function
Пример #22
0
 /**
  * @inheritdoc
  */
 public function getMethod()
 {
     return $this->current->getMethod();
 }
 /**
  * Maps HTTP request to a Request object.
  * @return Nette\Application\Request|NULL
  */
 public function match(Nette\Http\IRequest $httpRequest)
 {
     // combine with precedence: mask (params in URL-path), fixity, query, (post,) defaults
     // 1) URL MASK
     $url = $httpRequest->getUrl();
     $re = $this->re;
     if ($this->type === self::HOST) {
         $host = $url->getHost();
         $path = '//' . $host . $url->getPath();
         $host = ip2long($host) ? array($host) : array_reverse(explode('.', $host));
         $re = strtr($re, array('/%basePath%/' => preg_quote($url->getBasePath(), '#'), '%tld%' => preg_quote($host[0], '#'), '%domain%' => preg_quote(isset($host[1]) ? "{$host['1']}.{$host['0']}" : $host[0], '#')));
     } elseif ($this->type === self::RELATIVE) {
         $basePath = $url->getBasePath();
         if (strncmp($url->getPath(), $basePath, strlen($basePath)) !== 0) {
             return NULL;
         }
         $path = (string) substr($url->getPath(), strlen($basePath));
     } else {
         $path = $url->getPath();
     }
     if ($path !== '') {
         $path = rtrim($path, '/') . '/';
     }
     if (!($matches = Strings::match($path, $re))) {
         // stop, not matched
         return NULL;
     }
     // deletes numeric keys, restore '-' chars
     $params = array();
     foreach ($matches as $k => $v) {
         if (is_string($k) && $v !== '') {
             $params[str_replace('___', '-', $k)] = $v;
             // trick
         }
     }
     // 2) CONSTANT FIXITY
     foreach ($this->metadata as $name => $meta) {
         if (isset($params[$name])) {
             //$params[$name] = $this->flags & self::CASE_SENSITIVE === 0 ? strtolower($params[$name]) : */$params[$name]; // strtolower damages UTF-8
         } elseif (isset($meta['fixity']) && $meta['fixity'] !== self::OPTIONAL) {
             $params[$name] = NULL;
             // cannot be overwriten in 3) and detected by isset() in 4)
         }
     }
     // 3) QUERY
     if ($this->xlat) {
         $params += self::renameKeys($httpRequest->getQuery(), array_flip($this->xlat));
     } else {
         $params += $httpRequest->getQuery();
     }
     // 4) APPLY FILTERS & FIXITY
     foreach ($this->metadata as $name => $meta) {
         if (isset($params[$name])) {
             if (!is_scalar($params[$name])) {
             } elseif (isset($meta[self::FILTER_TABLE][$params[$name]])) {
                 // applies filterTable only to scalar parameters
                 $params[$name] = $meta[self::FILTER_TABLE][$params[$name]];
             } elseif (isset($meta[self::FILTER_TABLE]) && !empty($meta[self::FILTER_STRICT])) {
                 return NULL;
                 // rejected by filterTable
             } elseif (isset($meta[self::FILTER_IN])) {
                 // applies filterIn only to scalar parameters
                 $params[$name] = call_user_func($meta[self::FILTER_IN], (string) $params[$name]);
                 if ($params[$name] === NULL && !isset($meta['fixity'])) {
                     return NULL;
                     // rejected by filter
                 }
             }
         } elseif (isset($meta['fixity'])) {
             $params[$name] = $meta[self::VALUE];
         }
     }
     if (isset($this->metadata[NULL][self::FILTER_IN])) {
         $params = call_user_func($this->metadata[NULL][self::FILTER_IN], $params);
         if ($params === NULL) {
             return NULL;
         }
     }
     // 5) BUILD Request
     if (!isset($params[self::PRESENTER_KEY])) {
         throw new Nette\InvalidStateException('Missing presenter in route definition.');
     } elseif (!is_string($params[self::PRESENTER_KEY])) {
         return NULL;
     }
     if (isset($this->metadata[self::MODULE_KEY])) {
         if (!isset($params[self::MODULE_KEY])) {
             throw new Nette\InvalidStateException('Missing module in route definition.');
         }
         $presenter = $params[self::MODULE_KEY] . ':' . $params[self::PRESENTER_KEY];
         unset($params[self::MODULE_KEY], $params[self::PRESENTER_KEY]);
     } else {
         $presenter = $params[self::PRESENTER_KEY];
         unset($params[self::PRESENTER_KEY]);
     }
     return new Application\Request($presenter, $httpRequest->getMethod(), $params, $httpRequest->getPost(), $httpRequest->getFiles(), array(Application\Request::SECURED => $httpRequest->isSecured()));
 }
Пример #24
0
 /**
  * @param  Nette\Http\IRequest $request
  * @return string
  */
 public function resolveMethod(Nette\Http\IRequest $request)
 {
     if (!empty($request->getHeader('X-HTTP-Method-Override'))) {
         return Strings::upper($request->getHeader('X-HTTP-Method-Override'));
     }
     if ($method = Strings::upper($request->getQuery('__apiRouteMethod'))) {
         if (isset($this->actions[$method])) {
             return $method;
         }
     }
     return Strings::upper($request->getMethod());
 }