/**
  * Convert data to JSON and set as response, with caching header.
  *
  * @param $data mixed
  *
  * @return Response
  */
 public function buildResponse($data)
 {
     // Construct response based on provided data.
     $builtResponse = $this->response->withHeader('Content-Type', 'application/json')->write(json_encode($data, JSON_PRETTY_PRINT));
     // Return the response with an ETag added, for caching.
     return $this->c->cache->withEtag($builtResponse, sha1($builtResponse->getBody()));
 }
Exemplo n.º 2
4
 public function __invoke(Request $req, Response $res)
 {
     $school = $req->getAttribute('school');
     $appForm = $this->appFormService->findSchoolApplicationForm($school->id);
     if (null === $appForm) {
         return $res->withStatus(404);
     }
     $html = $this->view->fetch('application_form/pdf.twig', ['school' => $school, 'appForm' => $appForm, 'logo' => base64_encode(file_get_contents(__DIR__ . '/../../public/img/application_form/minedu_logo.jpg')), 'style' => file_get_contents(__DIR__ . '/../../public/css/application_form/pdf.css')]);
     $pdf = new \Dompdf\Dompdf(['default_paper_size' => 'A4', 'default_font' => 'DejaVu Sans', 'isHtml5ParserEnabled' => true, 'is_remote_enabled' => false]);
     $pdf->loadHtml($html);
     $pdf->render();
     $filename = 'edulabs_app_form_' . $appForm['id'] . '.pdf';
     $str = $pdf->output();
     $length = mb_strlen($str, '8bit');
     return $res->withHeader('Cache-Control', 'private')->withHeader('Content-type', 'application/pdf')->withHeader('Content-Length', $length)->withHeader('Content-Disposition', 'attachment;  filename=' . $filename)->withHeader('Accept-Ranges', $length)->write($str);
 }
 /**
  * __invoke is called by slim when a route matches
  * @param $request Request
  * @param $response Response
  * @param $args array
  * *
  * @return $response \Slim\Http\Response
  */
 public function __invoke(Request $request, Response $response, array $args)
 {
     $this->response = $response;
     //check for api key
     $queryParams = $request->getQueryParams();
     if (isset($queryParams['api_key'])) {
         $userData = UserModel::getUserWithApiKey($queryParams['api_key']);
         if ($userData !== false) {
             $this->currentUser = new User($userData);
         }
     }
     $this->response = $this->response->withHeader('Content-type', 'application/json');
 }
Exemplo n.º 4
0
 public function __invoke(Request $req, Response $res, callable $next)
 {
     // $path = $req->getUri()->getPath();
     // $path = "/".trim($path, "/");
     $user = self::getUser();
     if (empty($user)) {
         return $res->withHeader("Location", $_SERVER['HTTP_REFERER']);
     }
     if (!in_array($user["level"], $this->allow)) {
         return $res->withHeader("Location", $_SERVER['HTTP_REFERER']);
     }
     return $next($req, $res);
 }
 public function product_mediaRemove(Request $req, Response $res, $attr = [])
 {
     $container = $this->slim->getContainer();
     $db = $container->medoo;
     $media = $db->get("product_media", "*", ["id" => $attr["id"]]);
     if (!$media) {
         return $res->withHeader("Location", $req->getUri()->getBasePath() . "/product/" . $attr["product_id"] . "/media");
     }
     if ($media["type"] == "image") {
         @unlink("../product_media/" . $media["image_path"]);
     }
     $db->delete("product_media", ["id" => $attr["id"]]);
     return $res->withHeader("Location", $req->getUri()->getBasePath() . "/product/" . $attr["product_id"] . "/media");
 }
Exemplo n.º 6
0
 public function learningcenterRemove(Request $req, Response $res, $attr = [])
 {
     $container = $this->slim->getContainer();
     $db = $container->medoo;
     $db->delete("learningcenter", ["id" => $attr["id"]]);
     return $res->withHeader("Location", $req->getUri()->getBasePath() . "/learningcenter");
 }
 public function productRemove(Request $req, Response $res, $attr = [])
 {
     $container = $this->slim->getContainer();
     $db = $container->medoo;
     $db->delete("product", ["id" => $attr["id"]]);
     $db->delete("person_cripple", ["cripple_id" => $attr["id"]]);
     return $res->withHeader("Location", $req->getUri()->getBasePath() . "/product");
 }
Exemplo n.º 8
0
 public function disavantaged_typeRemove(Request $req, Response $res, $attr = [])
 {
     $container = $this->slim->getContainer();
     $db = $container->medoo;
     $db->delete("disavantaged_type", ["id" => $attr["id"]]);
     $db->delete("person_disavantaged", ["disavantaged_id" => $attr["id"]]);
     return $res->withHeader("Location", $req->getUri()->getBasePath() . "/disavantaged_type");
 }
Exemplo n.º 9
0
 public function anyLogout(Request $req, Response $res)
 {
     $container = $this->slim->getContainer();
     /** @var Aura\Session\Session */
     $session = $container->session;
     $loginSegment = $session->getSegment("login");
     $loginSegment->clear();
     $session->commit();
     return $res->withHeader("Location", $req->getUri()->getBasePath() . "/login");
 }
Exemplo n.º 10
0
 /**
  * @param Response $response
  * @return Response
  */
 public function logout(Response $response)
 {
     if ($this->isAuthenticated()) {
         $this->_cookies->set("session_token", ["value" => "", "expires" => time() - 3600]);
         $this->getUser()->storeRememberToken(null);
         $this->_user = null;
         $this->_authenticated = false;
         return $response->withHeader('Set-Cookie', $this->_cookies->toHeaders());
     }
     return $response;
 }
Exemplo n.º 11
0
 public function __invoke(Request $req, Response $res, callable $next)
 {
     $path = $req->getUri()->getPath();
     $path = "/" . trim($path, "/");
     $allowNotAuth = ["/", "/login"];
     if (!in_array($path, $allowNotAuth)) {
         /** @var Aura\Session\Session */
         $session = $this->container["session"];
         $loginSegment = $session->getSegment("login");
         if (empty($loginSegment->get("user"))) {
             return $res->withHeader("Location", $req->getUri()->getBasePath() . "/login");
         }
     }
     return $next($req, $res);
 }
Exemplo n.º 12
0
/**
 * @param string              $repo
 * @param string              $file
 * @param int                 $width
 * @param bool                $archived
 * @param \Slim\Http\Response $response
 * @return mixed
 */
function thumb($repo, $file, $width, $archived, $response, $format)
{
    $md5 = md5($file);
    $file = $md5[0] . '/' . $md5[0] . $md5[1] . '/' . $file;
    $path = $repo . ($archived ? 'archive/' : '') . $file;
    if (is_readable($path)) {
        $path = realpath($path);
        $pathParts = pathinfo($path);
        if (strpos($pathParts['dirname'], $repo) === 0) {
            $cacheDir = $repo . 'thumb/' . ($archived ? 'archive/' : '') . $file;
            if (!is_dir($cacheDir)) {
                if (!mkdir($cacheDir, 0777, true)) {
                    return $response->withStatus(403);
                }
            }
            if ($format != 'jpg') {
                $cacheFile = $cacheDir . '/' . $width . 'px-' . $pathParts['basename'];
            } else {
                $cacheFile = $cacheDir . '/' . $width . 'px-' . $pathParts['filename'] . '.jpg';
            }
            if (!is_readable($cacheFile)) {
                $image = new ImageResize($path);
                if ($width > $image->getSourceWidth()) {
                    return $response->withRedirect('/images/' . $file);
                } else {
                    $image->resizeToWidth($width);
                    if ($format != 'jpg') {
                        $image->save($cacheFile);
                    } else {
                        $image->save($cacheFile, IMAGETYPE_JPEG);
                    }
                }
            }
            $finfo = finfo_open(FILEINFO_MIME_TYPE);
            $type = finfo_file($finfo, $cacheFile);
            $stream = new \GuzzleHttp\Psr7\LazyOpenStream($cacheFile, 'r');
            return $response->withHeader('Content-type', $type)->withBody($stream);
        }
    }
    return $response->withStatus(404);
}
Exemplo n.º 13
0
 public function testETagWithCacheMiss()
 {
     $etag = 'abc';
     $ifNoneMatch = 'xyz';
     $cache = new Cache('public', 86400);
     $req = $this->requestFactory()->withHeader('If-None-Match', $ifNoneMatch);
     $res = new Response();
     $next = function (Request $req, Response $res) use($etag) {
         return $res->withHeader('ETag', $etag);
     };
     $res = $cache($req, $res, $next);
     $this->assertEquals(200, $res->getStatusCode());
 }
Exemplo n.º 14
0
 /**
  * Redirect to video file.
  *
  * @param Request  $request  PSR-7 request
  * @param Response $response PSR-7 response
  *
  * @return Response HTTP response
  */
 public function redirect(Request $request, Response $response)
 {
     $params = $request->getQueryParams();
     if (isset($params['url'])) {
         try {
             $url = $this->download->getURL($params['url'], $params['format']);
             return $response->withRedirect($url);
         } catch (\Exception $e) {
             $response->getBody()->write($e->getMessage());
             return $response->withHeader('Content-Type', 'text/plain');
         }
     }
 }
Exemplo n.º 15
0
 /**
  * @param Request $request
  * @param Response $response
  * @param array $args
  * @return Response
  */
 public function stream(Request $request, Response $response, array $args)
 {
     $record = $this->getModel()->find($args['id']);
     return $response->withHeader('Last-Modified', $record->feed->lastModified)->withHeader('Content-Type', "application/xhtml+xml")->write($this->toXml($record, $args['format'])->saveXML());
 }
Exemplo n.º 16
0
 public function downloadMedia(Request $request, Response $response, $arguments)
 {
     $filename = $arguments['filename'];
     try {
         $file = $this->filesystem->read($filename);
         $mime = $this->filesystem->getWithMetadata($filename, ['mimetype'])['mimetype'];
         return $response->withHeader('Content-Disposition', "attachment; filename={$filename}")->withHeader('Content-Type', $mime)->write($file);
     } catch (FileNotFoundException $e) {
         return $response->withStatus(404);
     }
 }
Exemplo n.º 17
0
     if ($this->redis['client']->exists($hash) === 1 && $this->redis['client']->exists($hash . "-hash") === 1 && ($redis_expiration == false || time() < $redis_expiration)) {
         if ($request->getHeader('Hash')) {
             $response->getBody()->write($this->redis['client']->get($hash . "-hash"));
         } else {
             $response->getBody()->write($this->redis['client']->get($hash));
         }
         return $response->withAddedHeader('X-Redis-Cache', 'true')->withAddedHeader('X-Redis-Expiration', $redis_expiration ? date('r', $redis_expiration) : -1)->withAddedHeader('X-Redis-Time', microtime(true) - $qt)->withAddedHeader('X-Cache-Hash', $hash);
     } else {
         $response = $next($request, $response);
         $this->redis['client']->set($hash, $response->getBody());
         $_hash = json_encode(json_decode($response->getBody())->Hash);
         $this->redis['client']->set($hash . "-hash", $_hash);
         if ($request->getHeader('Hash')) {
             // Cors to everybody. It's only a hash.
             $newresponse = new Response();
             return $newresponse->withHeader('Content-type', 'application/json')->withHeader('Access-Control-Allow-Credentials', 'true')->withHeader('Access-Control-Allow-Origin', '*')->withHeader('X-Cache-Hash', $hash)->write($_hash);
         } else {
             return $response->withAddedHeader('X-Cache-Hash', $hash);
         }
     }
 }
 // Clear Cache on Post or Backend Calls
 if ($request->isPost() || $_calltype != "apicall") {
     $prefix = $this->redis['client']->getOptions()->__get('prefix')->getPrefix();
     $keys = $this->redis['client']->keys("*");
     $removed = 0;
     foreach ($keys as $key) {
         if (substr($key, 0, strlen($prefix)) == $prefix) {
             $key = substr($key, strlen($prefix));
             $this->redis['client']->del($key);
             $this->redis['client']->del($key . "-hash");