/**
  * Validator.
  *
  * @access  public
  * @param   string   $input  Input value
  * @param   array    $field  Comparison field
  * @return  boolean
  */
 public function validate($input, $field)
 {
     if ($this->request->post($field)) {
         return $input < $this->request->post($field);
     }
     return true;
 }
Beispiel #2
0
 /**
  * {@inheritdoc}
  */
 public function register()
 {
     $this->container->registerSingleton([Request::class, 'request'], function ($container) {
         $config = $container->get('config');
         $request = new Request(['languages' => $config->get('application.languages')], $container->get('signer'));
         $request->setTrustedProxies($config->get('application.trusted_proxies'));
         return $request;
     });
 }
 /**
  * {@inheritdoc}
  */
 public function send(Request $request, Response $response)
 {
     $this->isCGI = $request->isCGI();
     if (!$this->isCGI) {
         $response->header('content-encoding', 'chunked');
         $response->header('transfer-encoding', 'chunked');
     }
     $response->sendHeaders();
     $this->flow();
 }
 /**
  * {@inheritdoc}
  */
 public function create($items, $itemsPerPage = null, array $options = []) : PaginationInterface
 {
     $itemsPerPage = $itemsPerPage ?? $this->options['items_per_page'];
     $options = $options + $this->options;
     $currentPage = max((int) $this->request->get($options['page_key'], 1), 1);
     $pagination = new Pagination($items, $itemsPerPage, $currentPage, $options);
     $pagination->setRequest($this->request);
     $pagination->setURLBuilder($this->urlBuilder);
     $pagination->setViewFactory($this->viewFactory);
     return $pagination;
 }
 /**
  * Returns a basic authentication response if login is required and NULL if not.
  *
  * @access  public
  * @return  \mako\http\Response|null
  */
 public function basicAuth()
 {
     if ($this->isLoggedIn() || $this->login($this->request->username(), $this->request->password()) === true) {
         return;
     }
     return $this->basicHTTPAuthenticationResponse();
 }
 /**
  * Send output to browser.
  *
  * @access  public
  */
 public function send()
 {
     if ($this->body instanceof ResponseContainerInterface) {
         // This is a response container so we'll just pass it the
         // request and response instances and let it handle the rest itself
         $this->body->send($this->request, $this);
     } else {
         $sendBody = true;
         // Make sure that output buffering is enabled
         if (ob_get_level() === 0) {
             ob_start();
         }
         // Cast body to string so that everything is rendered
         // before running through response filters
         $this->body = (string) $this->body;
         // Run body through the response filters
         foreach ($this->outputFilters as $outputFilter) {
             $this->body = $outputFilter($this->body);
         }
         // Check ETag if response cache is enabled
         if ($this->responseCache === true) {
             $hash = '"' . hash('sha256', $this->body) . '"';
             $this->header('ETag', $hash);
             if (str_replace('-gzip', '', $this->request->header('if-none-match')) === $hash) {
                 $this->status(304);
                 $sendBody = false;
             }
         }
         if ($sendBody && !in_array($this->statusCode, [100, 101, 102, 204, 304])) {
             // Start compressed output buffering if output compression is enabled
             if ($this->outputCompression) {
                 ob_start('ob_gzhandler');
             }
             echo $this->body;
             // If output compression is enabled then we'll have to flush the compressed buffer
             // so that we can get the compressed content length when setting the content-length header
             if ($this->outputCompression) {
                 ob_end_flush();
             }
             // Add the content-length header
             if (!array_key_exists('transfer-encoding', $this->headers)) {
                 $this->header('content-length', ob_get_length());
             }
         }
         // Send the headers and flush the output buffer
         $this->sendHeaders();
         ob_end_flush();
     }
 }
Beispiel #7
0
 /**
  * Builds and returns the pagination array.
  *
  * @access  public
  * @return  array
  */
 public function pagination()
 {
     if (empty($this->pagination)) {
         if (empty($this->request)) {
             throw new RuntimeException(vsprintf("%s(): A [ Request ] instance is required to generate the pagination array.", [__METHOD__]));
         }
         if (empty($this->urlBuilder)) {
             throw new RuntimeException(vsprintf("%s(): A [ URLBuilder ] instance is required to generate the pagination array.", [__METHOD__]));
         }
         $pagination = ['items' => $this->items, 'items_per_page' => $this->itemsPerPage, 'number_of_pages' => $this->pages];
         $params = $this->request->get();
         if ($this->currentPage > 1) {
             $pagination['first'] = $this->urlBuilder->current(array_merge($params, [$this->options['page_key'] => 1]));
             $pagination['previous'] = $this->urlBuilder->current(array_merge($params, [$this->options['page_key'] => $this->currentPage - 1]));
         }
         if ($this->currentPage < $this->pages) {
             $pagination['last'] = $this->urlBuilder->current(array_merge($params, [$this->options['page_key'] => $this->pages]));
             $pagination['next'] = $this->urlBuilder->current(array_merge($params, [$this->options['page_key'] => $this->currentPage + 1]));
         }
         if ($this->options['max_page_links'] !== 0) {
             if ($this->pages > $this->options['max_page_links']) {
                 $start = max($this->currentPage - ceil($this->options['max_page_links'] / 2), 0);
                 $end = $start + $this->options['max_page_links'];
                 if ($end > $this->pages) {
                     $end = $this->pages;
                 }
                 if ($start > $end - $this->options['max_page_links']) {
                     $start = $end - $this->options['max_page_links'];
                 }
             } else {
                 $start = 0;
                 $end = $this->pages;
             }
             $pagination['pages'] = [];
             for ($i = $start + 1; $i <= $end; $i++) {
                 $pagination['pages'][] = ['url' => $this->urlBuilder->current(array_merge($params, [$this->options['page_key'] => $i])), 'number' => $i, 'is_current' => $i == $this->currentPage];
             }
         }
         $this->pagination = $pagination;
     }
     return $this->pagination;
 }
Beispiel #8
0
 /**
  * Starts the session.
  *
  * @access  public
  */
 public function start()
 {
     if ($this->started) {
         throw new LogicException(vsprintf("%s(): The session has already been started.", [__METHOD__]));
     }
     // Set the started flag to true
     $this->started = true;
     // Get the session id from the cookie or generate a new one if it doesn't exist.
     $this->sessionId = $this->request->signedCookie($this->cookieName, false);
     if ($this->sessionId === false) {
         $this->sessionId = $this->generateId();
     }
     // Create a new / update the existing session cookie
     $this->setCookie();
     // Load the session data
     $this->loadData();
     // Create a session token if we don't have one
     if (empty($this->sessionData['mako.token'])) {
         $this->sessionData['mako.token'] = $this->generateId();
     }
     $this->token = $this->sessionData['mako.token'];
 }
Beispiel #9
0
 /**
  * Checks if a user is logged in.
  *
  * @access  protected
  * @return  \padlock\models\User|null
  */
 protected function check()
 {
     if (empty($this->user)) {
         // Check if there'a user that can be logged in
         $token = $this->session->get($this->authKey, false);
         if ($token === false) {
             $token = $this->request->signedCookie($this->authKey, false);
             if ($token !== false) {
                 $this->session->put($this->authKey, $token);
             }
         }
         if ($token !== false) {
             $model = $this->userModel;
             $this->user = $model::where('token', '=', $token)->first();
             if ($this->user === false || $this->user->isBanned() || !$this->user->isActivated()) {
                 $this->logout();
             }
         }
         // Set checked status to TRUE
         $this->isChecked = true;
     }
     return $this->user;
 }
 /**
  * Returns the current URL of the request.
  *
  * @access  public
  * @param   array    $queryParams  Associative array used to build URL-encoded query string
  * @param   string   $separator    Argument separator
  * @param   mixed    $language     Request language
  * @return  string
  */
 public function current(array $queryParams = [], $separator = '&amp;', $language = true)
 {
     $queryParams = $queryParams ?: $this->request->get();
     return $this->to($this->request->path(), $queryParams, $separator, $language);
 }
 /**
  * Validator.
  *
  * @access  public
  * @param   string   $input  Input value
  * @param   array    $min    Minor field
  * @param   array    $max    Max field
  * @return  boolean
  */
 public function validate($input, $min, $max)
 {
     return $input >= $this->request->post($min) && $input <= $this->request->post($max);
 }
 /**
  * Should we return the error as JSON?
  *
  * @access  protected
  * @return  boolean
  */
 protected function returnAsJson()
 {
     $acceptableContentTypes = $this->request->acceptableContentTypes();
     return $this->request->isAjax() || isset($acceptableContentTypes[0]) && in_array($acceptableContentTypes[0], ['application/json', 'text/json']);
 }
 /**
  *
  */
 public function testGetRoute()
 {
     $request = new Request();
     $this->assertNull($request->getRoute());
     $route = m::mock('mako\\http\\routing\\Route');
     $request->setRoute($route);
     $this->assertSame($route, $request->getRoute());
 }
Beispiel #14
0
 /**
  * Matches and returns the appropriate route along with its parameters.
  *
  * @access  public
  * @param   \mako\http\Request  $request  Request
  * @return  array
  */
 public function route(Request $request)
 {
     $matched = false;
     $parameters = [];
     $requestMethod = $request->method();
     $requestPath = $request->path();
     foreach ($this->routes->getRoutes() as $route) {
         if ($this->matches($route, $requestPath, $parameters)) {
             if (!$route->allows($requestMethod)) {
                 $matched = true;
                 continue;
             }
             // Redirect to URL with trailing slash if the route should have one
             if ($route->hasTrailingSlash() && !empty($requestPath) && substr($requestPath, -1) !== '/') {
                 return [$this->redirectRoute($requestPath), []];
             }
             // If this is an "OPTIONS" request then well collect all the allowed request methods
             // from all routes matching the requested path. We'll then add an "allows" header
             // to the matched route
             if ($requestMethod === 'OPTIONS') {
                 return [$this->optionsRoute($requestPath), []];
             }
             // Assign the route to the request
             $request->setRoute($route);
             // Return the matched route and parameters
             return [$route, $parameters];
         }
     }
     if ($matched) {
         // We found a matching route but it does not allow the request method so we'll throw a 405 exception
         throw new MethodNotAllowedException($this->getAllowedMethodsForMatchingRoutes($requestPath));
     } else {
         // No routes matched so we'll throw a 404 exception
         throw new NotFoundException($requestMethod . ': ' . $requestPath);
     }
 }
Beispiel #15
0
 /**
  * {@inheritdoc}
  */
 public function send(Request $request, Response $response)
 {
     // Add headers that should always be included
     $response->type($this->options['content_type']);
     $response->header('accept-ranges', $request->isSafe() ? 'bytes' : 'none');
     $response->header('content-disposition', $this->options['disposition'] . '; filename="' . $this->options['file_name'] . '"');
     // Get the requested byte range
     $range = $request->header('range');
     if ($range !== null) {
         $range = $this->calculateRange($range);
     }
     if ($range === false) {
         // Not an acceptable range so we'll just send an empty response
         // along with a "requested range not satisfiable" status
         $response->status(416);
         $response->sendHeaders();
     } else {
         if ($range === null) {
             // No range was provided by the client so we'll just fake one for the sendFile method
             // and set the content-length header value to the full file size
             $range = ['start' => 0, 'end' => $this->fileSize - 1];
             $response->header('content-length', $this->fileSize);
         } else {
             // Valid range so we'll need to tell the client which range we're sending
             // and set the content-length header value to the length of the byte range
             $response->status(206);
             $response->header('content-range', sprintf('bytes %s-%s/%s', $range['start'], $range['end'], $this->fileSize));
             $response->header('content-length', $range['end'] - $range['start'] + 1);
         }
         // Send headers and the requested byte range
         $response->sendHeaders();
         $this->sendFile($range['start'], $range['end']);
         // Execute callback if there is one
         if (!empty($this->options['callback'])) {
             $this->options['callback']($this->filePath);
         }
     }
 }