prepare() public method

This method tweaks the Response to ensure that it is compliant with RFC 2616. Most of the changes are based on the Request that is "associated" with this Response.
public prepare ( Request $request ) : Response
$request Request A Request instance
return Response The current response
 public function onEventResponse(Application $app, Response $response)
 {
     if (null === $response->getCharset()) {
         $response->setCharset($app->getParameter('charset'));
     }
     $response->prepare($app->getRequest());
 }
Beispiel #2
0
 /**
  * Handle a request for a file
  *
  * @param Request $request HTTP request
  * @return Response
  */
 public function getResponse(Request $request)
 {
     $response = new Response();
     $response->prepare($request);
     $path = implode('/', $request->getUrlSegments());
     if (!preg_match('~serve-file/e(\\d+)/l(\\d+)/d([ia])/c([01])/([a-zA-Z0-9\\-_]+)/(.*)$~', $path, $m)) {
         return $response->setStatusCode(400)->setContent('Malformatted request URL');
     }
     list(, $expires, $last_updated, $disposition, $use_cookie, $mac, $path_from_dataroot) = $m;
     if ($expires && $expires < time()) {
         return $response->setStatusCode(403)->setContent('URL has expired');
     }
     $hmac_data = array('expires' => (int) $expires, 'last_updated' => (int) $last_updated, 'disposition' => $disposition, 'path' => $path_from_dataroot, 'use_cookie' => (int) $use_cookie);
     if ((bool) $use_cookie) {
         $hmac_data['cookie'] = $this->getCookieValue($request);
     }
     ksort($hmac_data);
     $hmac = $this->crypto->getHmac($hmac_data);
     if (!$hmac->matchesToken($mac)) {
         return $response->setStatusCode(403)->setContent('HMAC mistmatch');
     }
     $dataroot = $this->config->getDataPath();
     $filenameonfilestore = "{$dataroot}{$path_from_dataroot}";
     if (!is_readable($filenameonfilestore)) {
         return $response->setStatusCode(404)->setContent('File not found');
     }
     $actual_last_updated = filemtime($filenameonfilestore);
     if ($actual_last_updated != $last_updated) {
         return $response->setStatusCode(403)->setContent('URL has expired');
     }
     $if_none_match = $request->headers->get('if_none_match');
     if (!empty($if_none_match)) {
         // strip mod_deflate suffixes
         $request->headers->set('if_none_match', str_replace('-gzip', '', $if_none_match));
     }
     $etag = '"' . $actual_last_updated . '"';
     $response->setPublic()->setEtag($etag);
     if ($response->isNotModified($request)) {
         return $response;
     }
     $public = $use_cookie ? false : true;
     $content_disposition = $disposition == 'i' ? 'inline' : 'attachment';
     $headers = ['Content-Type' => (new MimeTypeDetector())->getType($filenameonfilestore)];
     $response = new BinaryFileResponse($filenameonfilestore, 200, $headers, $public, $content_disposition);
     $sendfile_type = $this->config->getVolatile('X-Sendfile-Type');
     if ($sendfile_type) {
         $request->headers->set('X-Sendfile-Type', $sendfile_type);
         $mapping = (string) $this->config->getVolatile('X-Accel-Mapping');
         $request->headers->set('X-Accel-Mapping', $mapping);
         $response->trustXSendfileTypeHeader();
     }
     $response->prepare($request);
     if (empty($expires)) {
         $expires = strtotime('+1 year');
     }
     $expires_dt = (new DateTime())->setTimestamp($expires);
     $response->setExpires($expires_dt);
     $response->setEtag($etag);
     return $response;
 }
Beispiel #3
0
 /**
  * Make response object with RFC 2616 compliant HTTP header
  *
  * @return \BEAR\Sunday\Web\ResponseInterface
  */
 public function prepare()
 {
     $this->response = new Response($this->view, $this->resource->code, (array) $this->resource->headers);
     // compliant with RFC 2616.
     $this->response->prepare();
     return $this;
 }
Beispiel #4
0
 function handle(Request $request, $type = HttpFoundation::MASTER_REQUEST, $catch = true)
 {
     $pathinfo = $request->getPathInfo();
     if (preg_match('{^/_pipe/(.+)$}', $pathinfo, $matches)) {
         $path = $matches[1];
         if (!$path or !($asset = $this->env->find($path, array('bundled' => true)))) {
             $this->log->error("pipe: Asset '{$path}' not found");
             return new Response('Not Found', 404);
         }
         $lastModified = new \DateTime();
         $lastModified->setTimestamp($asset->getLastModified());
         $response = new Response();
         $response->setPublic();
         $response->setLastModified($lastModified);
         if ($response->isNotModified($request)) {
             $this->log->info("pipe: 302 {$path}");
             return $response;
         }
         $start = microtime(true);
         $response->setContent($asset->getBody());
         $this->log->info(sprintf('pipe: Rendered "%s" in %d seconds', $path, microtime(true) - $start));
         $response->headers->set('Content-Type', $asset->getContentType());
         $response->prepare($request);
         return $response;
     }
     return $this->app->handle($request, $type, $catch);
 }
Beispiel #5
0
 /**
  * @Route("/items/save", name="items_save")
  * @method POST
  * @param Request $request
  * @return Response
  */
 public function itemsSaveAction(Request $request)
 {
     $result = '';
     $contentType = 'text/plain';
     $request = Request::createFromGlobals();
     $method = $request->getMethod();
     if ($method == 'POST') {
         $params = $request->getContent();
         if ($request->headers->get('content_type') == 'application/json') {
             $params = json_decode($params, true);
         }
         try {
             $result = $this->get($this->resource)->persist($params);
         } catch (\Exception $e) {
             echo $e->getMessage();
             exit;
             $result = $e->getMessage();
             $contentType = 'text/plain';
             $this->response_code = $e->getCode();
         }
     } else {
         $result = 'Method or action not implemented for the resource ' . $this->resource;
         $this->response_code = Response::HTTP_BAD_REQUEST;
     }
     $response = new Response('Content', $this->response_code, ['content-type' => $contentType]);
     $response->setContent($result);
     $response->setStatusCode($this->response_code);
     $response->prepare($request);
     //$response->send();
     return $response;
 }
Beispiel #6
0
 function handle(HttpFoundation\Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
 {
     $path = ltrim($request->getPathInfo(), '/');
     $asset = $this->environment->find($path, array("bundled" => true));
     $debug = $request->query->get("debug", false);
     $cache = !$request->query->get("nocache", false);
     if (!$asset or $path == '') {
         return $this->renderNotFound($request);
     }
     if ($debug) {
         $this->environment->bundleProcessors->clear();
     }
     $lastModified = new \DateTime();
     $lastModified->setTimestamp($asset->getLastModified());
     $response = new HttpFoundation\Response();
     $response->setPublic();
     $response->setLastModified($lastModified);
     if ($cache and $response->isNotModified($request)) {
         return $response;
     }
     $response->setContent($asset->getBody());
     $response->headers->set('Content-Type', $asset->getContentType());
     $response->prepare($request);
     return $response;
 }
 /**
  * Handle a request for a file
  *
  * @param Request $request HTTP request
  * @return Response
  */
 public function getResponse($request)
 {
     $response = new Response();
     $response->prepare($request);
     $path = implode('/', $request->getUrlSegments());
     if (!preg_match('~download-file/g(\\d+)$~', $path, $m)) {
         return $response->setStatusCode(400)->setContent('Malformatted request URL');
     }
     $this->application->start();
     $guid = (int) $m[1];
     $file = get_entity($guid);
     if (!$file instanceof ElggFile) {
         return $response->setStatusCode(404)->setContent("File with guid {$guid} does not exist");
     }
     $filenameonfilestore = $file->getFilenameOnFilestore();
     if (!is_readable($filenameonfilestore)) {
         return $response->setStatusCode(404)->setContent('File not found');
     }
     $last_updated = filemtime($filenameonfilestore);
     $etag = '"' . $last_updated . '"';
     $response->setPublic()->setEtag($etag);
     if ($response->isNotModified($request)) {
         return $response;
     }
     $response = new BinaryFileResponse($filenameonfilestore, 200, array(), false, 'attachment');
     $response->prepare($request);
     $expires = strtotime('+1 year');
     $expires_dt = (new DateTime())->setTimestamp($expires);
     $response->setExpires($expires_dt);
     $response->setEtag($etag);
     return $response;
 }
Beispiel #8
0
 public function indexAction(Request $request, $key)
 {
     $userManager = $this->container->get('ilioscore.user.manager');
     $user = $userManager->findUserBy(array('icsFeedKey' => $key));
     if (!$user) {
         throw new NotFoundHttpException();
     }
     $calendar = new ICS\Calendar('Ilios Calendar for ' . $user->getFirstAndLastName());
     $calendar->setPublishedTTL('P1H');
     $from = new \DateTime('-6 months');
     $to = new \DateTime('+6 months');
     $events = $userManager->findEventsForUser($user->getId(), $from, $to);
     foreach ($events as $event) {
         $vEvent = new ICS\Event();
         $vEvent->setDtStart($event->startDate)->setDtEnd($event->endDate)->setSummary($event->name)->setDescription($this->getDescriptionForEvent($event))->setCategories([$event->eventClass])->setLocation($event->location);
         $calendar->addComponent($vEvent);
     }
     $response = new Response();
     $response->setContent($calendar->render());
     $response->setCharset('utf-8');
     $response->headers->set('Content-Type', 'text/calendar');
     $response->headers->set('Content-Disposition', 'attachment; filename="' . $key . '.ics"');
     $response->prepare($request);
     $response->send();
 }
Beispiel #9
0
 /**
  * Create a response if none is found, and prepare it.
  */
 public function run()
 {
     try {
         (yield null);
     } catch (\Exception $exception) {
         if (!$this->master() || $this->app['debug']) {
             throw $exception;
         } elseif ($exception instanceof HttpException) {
             $this->response($exception->getMessage() ?: Response::$statusTexts[$exception->getStatusCode()], $exception->getStatusCode(), $exception->getHeaders());
         } else {
             $this->response($exception->getMessage(), 500);
         }
     } finally {
         if (!$this->response()) {
             $result = $this->last();
             if (is_array($result)) {
                 $response = new JsonResponse($result);
             } elseif (is_int($result) && array_key_exists($result, Response::$statusTexts)) {
                 $response = new Response(null, $result);
             } else {
                 $response = new Response($result);
             }
             $response->prepare($this->request());
             $this->response($response);
         }
     }
 }
 public function meOptionsAction(Request $request)
 {
     $response = new Response('Go Ahead!', Response::HTTP_OK);
     $response->setCharset('UTF-8');
     $response->prepare($request);
     $response->send();
     return;
 }
Beispiel #11
0
 public function prepare(Request $request)
 {
     if ('xml' === $request->getRequestFormat()) {
         $this->requestFormat = 'xml';
         $this->headers->set('Content-Type', 'application/hal+xml');
     }
     return parent::prepare($request);
 }
 /**
  * Export a Json file containing NodeType datas and fields.
  *
  * @param Symfony\Component\HttpFoundation\Request $request
  * @param int                                      $nodeTypeId
  *
  * @return Symfony\Component\HttpFoundation\Response
  */
 public function exportJsonFileAction(Request $request, $nodeTypeId)
 {
     $this->validateAccessForRole('ROLE_ACCESS_NODETYPES');
     $nodeType = $this->getService('em')->find('RZ\\Roadiz\\Core\\Entities\\NodeType', (int) $nodeTypeId);
     $response = new Response(NodeTypeJsonSerializer::serialize($nodeType), Response::HTTP_OK, []);
     $response->headers->set('Content-Disposition', $response->headers->makeDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $nodeType->getName() . '.rzt'));
     // Rezo-Zero Type
     $response->prepare($request);
     return $response;
 }
 /**
  * Write the response (header and response body).
  *
  * @param OutgoingResponse &$outGoingResponse Headers and streams to output.
  * @param Request &$request The original Symfony Request
  */
 public function getResponse()
 {
     $outGoingResponse = $this->response;
     $request = $this->request;
     $headers = $outGoingResponse->getHeaders();
     $status_code = isset($headers[ODataConstants::HTTPRESPONSE_HEADER_STATUS]) ? $headers[ODataConstants::HTTPRESPONSE_HEADER_STATUS] : 200;
     unset($headers[ODataConstants::HTTPRESPONSE_HEADER_STATUS]);
     $response = new Response(trim($outGoingResponse->getStream()), $status_code, array_filter($headers));
     $response->prepare($request->getRequest());
     return $response;
 }
 /**
  * Export a Group in a Json file (.rzt).
  *
  * @param Symfony\Component\HttpFoundation\Request $request
  * @param int                                      $groupId
  *
  * @return Symfony\Component\HttpFoundation\Response
  */
 public function exportAction(Request $request, $groupId)
 {
     $this->validateAccessForRole('ROLE_ACCESS_GROUPS');
     $existingGroup = $this->getService('em')->find('RZ\\Roadiz\\Core\\Entities\\Group', (int) $groupId);
     $group = GroupCollectionJsonSerializer::serialize([$existingGroup]);
     $response = new Response($group, Response::HTTP_OK, []);
     $response->headers->set('Content-Disposition', $response->headers->makeDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, 'group-' . $existingGroup->getName() . '-' . date("YmdHis") . '.rzt'));
     // Rezo-Zero Type
     $response->prepare($request);
     return $response;
 }
 /**
  * @param InternalResponse $iResponse
  * @return Response
  */
 public function adaptResponse(InternalResponse $iResponse)
 {
     $response = new Response($iResponse->getContent(), $iResponse->getStatusCode(), $iResponse->getHeaders());
     if ($this->request) {
         $response->prepare($this->request);
     }
     if ($response->getStatusCode() !== 200) {
         $response->setContent(Response::$statusTexts[$response->getStatusCode()]);
         return $response;
     }
     return $response;
 }
Beispiel #16
0
 /**
  * {@inheritdoc}
  */
 public function prepare(Request $request)
 {
     $session_id = $request->get('session_id');
     $code = db_query("SELECT solution FROM {captcha_sessions} WHERE csid = :csid", [':csid' => $session_id])->fetchField();
     if ($code !== FALSE) {
         $this->image = @$this->generateImage($code);
         if (!$this->image) {
             $this->logger->log(WATCHDOG_ERROR, 'Generation of image CAPTCHA failed. Check your image CAPTCHA configuration and especially the used font.', []);
         }
     }
     return parent::prepare($request);
 }
Beispiel #17
0
 /**
  * Send the response to the browser
  *
  * @param  Response $response Optional overwrite response
  * @return Void
  */
 public function send(Response $response = null)
 {
     if ($response) {
         $this->response = $response;
     }
     $this->response->prepare($this->request);
     $this->response->send();
     // If a cacheWrite callback exists execute
     // it now to write the image to the cache
     if (is_callable($this->cacheWrite)) {
         call_user_func_array($this->cacheWrite, array($this->cache, $this->getCachePath()));
     }
 }
 /**
  * Export all Node in a Json file (.rzn).
  *
  * @param Symfony\Component\HttpFoundation\Request $request
  *
  * @return Symfony\Component\HttpFoundation\Response
  */
 public function exportAllAction(Request $request)
 {
     $this->validateAccessForRole('ROLE_ACCESS_NODES');
     $existingNodes = $this->getService('em')->getRepository('RZ\\Roadiz\\Core\\Entities\\Node')->findBy(["parent" => null]);
     foreach ($existingNodes as $existingNode) {
         $this->getService('em')->refresh($existingNode);
     }
     $node = NodeJsonSerializer::serialize($existingNodes);
     $response = new Response($node, Response::HTTP_OK, []);
     $response->headers->set('Content-Disposition', $response->headers->makeDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, 'node-all-' . date("YmdHis") . '.rzn'));
     $response->prepare($request);
     return $response;
 }
Beispiel #19
0
 /**
  * display the page
  *
  */
 public function display()
 {
     // generate all the data
     $this->generatePage();
     $this->generateMenu();
     $this->generateBreadcrumb();
     // process the template
     $output = $this->generateOutput();
     // send the page
     $response = new Response($output, Response::HTTP_OK, array('content-type' => 'text/html'));
     $response->prepare($this->docmark->request);
     $response->send();
 }
 public function getResponse(RepresentationInterface $representation, $statusCode, array $headers = array(), array $context = array())
 {
     $request = $this->requestStack->getCurrentRequest();
     $this->prepareSerializer($request, 'Accept');
     $format = $this->formatParser->getSupportedFormat($request, 'Accept', $this->serializer);
     $request->setRequestFormat($format);
     //make the actual serialization
     $serializedData = $this->serializer->serialize($representation, $format, $context);
     $this->restoreDefaultTransformers();
     //build and return the response
     $response = new Response($serializedData, $statusCode, $headers);
     $response->prepare($request);
     return $response;
 }
 /**
  * @return Response
  */
 public function getResponse()
 {
     if (null !== $this->response) {
         $this->response->setPublic();
         $this->response->setPrivate();
         $this->response->setMaxAge($this->configuration->getTtl());
         $this->response->setSharedMaxAge($this->configuration->getTtl());
         $this->response->setCharset('UTF-8');
         $this->response->prepare($this->request);
         return $this->response;
     } else {
         throw new \RuntimeException("Request had not been handled. Use handle() method before getResponse()", 1);
     }
 }
 /**
  * Export a Tag in a Json file (.rzn).
  *
  * @param Symfony\Component\HttpFoundation\Request $request
  * @param int                                      $tagId
  *
  * @return Symfony\Component\HttpFoundation\Response
  */
 public function exportAllAction(Request $request, $tagId)
 {
     $this->validateAccessForRole('ROLE_ACCESS_TAGS');
     $existingTags = $this->getService('em')->getRepository('RZ\\Roadiz\\Core\\Entities\\Tag')->findBy(["parent" => null]);
     foreach ($existingTags as $existingTag) {
         $this->getService('em')->refresh($existingTag);
     }
     $tag = TagJsonSerializer::serialize($existingTags);
     $response = new Response($tag, Response::HTTP_OK, []);
     $response->headers->set('Content-Disposition', $response->headers->makeDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, 'tag-all-' . date("YmdHis") . '.rzg'));
     // Rezo-Zero Type
     $response->prepare($request);
     return $response;
 }
Beispiel #23
0
 /**
  * Handle a request for a file
  *
  * @param Request $request HTTP request
  * @return Response
  */
 public function getResponse($request)
 {
     $response = new Response();
     $response->prepare($request);
     $path = implode('/', $request->getUrlSegments());
     if (!preg_match('~serve-file/e(\\d+)/l(\\d+)/d([ia])/c([01])/([a-zA-Z0-9\\-_]+)/(.*)$~', $path, $m)) {
         return $response->setStatusCode(400)->setContent('Malformatted request URL');
     }
     list(, $expires, $last_updated, $disposition, $use_cookie, $mac, $path_from_dataroot) = $m;
     if ($expires && $expires < time()) {
         return $response->setStatusCode(403)->setContent('URL has expired');
     }
     $etag = '"' . $last_updated . '"';
     $response->setPublic()->setEtag($etag);
     if ($response->isNotModified($request)) {
         return $response;
     }
     // @todo: change to minimal boot without plugins
     $this->application->bootCore();
     $hmac_data = array('expires' => (int) $expires, 'last_updated' => (int) $last_updated, 'disposition' => $disposition, 'path' => $path_from_dataroot, 'use_cookie' => (int) $use_cookie);
     if ((bool) $use_cookie) {
         $hmac_data['cookie'] = _elgg_services()->session->getId();
     }
     ksort($hmac_data);
     $hmac = elgg_build_hmac($hmac_data);
     if (!$hmac->matchesToken($mac)) {
         return $response->setStatusCode(403)->setContent('HMAC mistmatch');
     }
     $dataroot = _elgg_services()->config->getDataPath();
     $filenameonfilestore = "{$dataroot}{$path_from_dataroot}";
     if (!is_readable($filenameonfilestore)) {
         return $response->setStatusCode(404)->setContent('File not found');
     }
     $actual_last_updated = filemtime($filenameonfilestore);
     if ($actual_last_updated != $last_updated) {
         return $response->setStatusCode(403)->setContent('URL has expired');
     }
     $public = $use_cookie ? false : true;
     $content_disposition = $disposition == 'i' ? 'inline' : 'attachment';
     $response = new BinaryFileResponse($filenameonfilestore, 200, array(), $public, $content_disposition);
     $response->prepare($request);
     if (empty($expires)) {
         $expires = strtotime('+1 year');
     }
     $expires_dt = (new DateTime())->setTimestamp($expires);
     $response->setExpires($expires_dt);
     $response->setEtag($etag);
     return $response;
 }
Beispiel #24
0
 public function handle()
 {
     try {
         $this->matchRoute();
         $response = $this->loadResource();
     } catch (ResourceNotFoundException $e) {
         $response = new Response();
         $response->setStatusCode(404);
     } catch (MethodNotAllowedException $e) {
         $response = new Response();
         $response->setStatusCode(405);
     }
     $response->prepare($this->request);
     $response->send();
 }
Beispiel #25
0
 /**
  * @ApiDoc(
  *     description="Доавить заказ в базу",
  *     statusCodes={
  *         200="Нормальный ответ"
  *     }
  * )
  *
  * @param int $id
  *
  * @Route("/addOrder/{id}", name="add_order", defaults={"_format": "json"})
  * @Method({"GET"})
  *
  * @Rest\View()
  * @return mixed
  */
 public function addOrderAction($id)
 {
     $user = $this->getUser();
     $em = $this->getDoctrine()->getManager();
     /** @var Product $product */
     $product = $em->getRepository('ShopProductBundle:Product')->findOneById($id);
     $order = $em->getRepository("ShopOrderBundle:Order")->findOneBy(['users' => $user->getId(), 'shops' => $product->getShops()->getId(), 'isPay' => false]);
     if ($order) {
         /** @var OrderItem $orderItem */
         $orderItem = $em->getRepository("ShopOrderBundle:OrderItem")->findOneBy(['order' => $order->getId(), 'product' => $id]);
         if ($orderItem) {
             $orderItem->setNumber($orderItem->getNumber() + 1);
             $em->flush();
             return "successful";
         }
     } else {
         $order = new Order();
         $order->setUsers($user);
         $order->setShops($product->getShops());
     }
     $orderItem = new OrderItem();
     $orderItem->setNumber(1);
     $orderItem->setProduct($product);
     $orderItem->setOrder($order);
     $order->addOrderItem($orderItem);
     $em->persist($order);
     $em->flush();
     if (!$this->getUser()) {
         $orders = [];
         $id = $orderItem->getId();
         $response = new Response();
         if ($response->headers->has("orders")) {
             $orders = json_decode($response->headers->getCookies());
             if (!isset($orders[$id])) {
                 $orders[$id] = 0;
             } else {
                 $orders[$id] = $orders[$id] + 1;
             }
         } else {
             $orders[$id] = 0;
         }
         $response->headers->setCookie(new Cookie('orders', json_encode($orders), time() + 3600));
         $response->prepare($this->get("request"));
         $response->send();
         return $response->send();
     }
     return "successful";
 }
Beispiel #26
0
 /**
  * display the page
  *
  */
 public function display()
 {
     if ($this->systemError) {
         $this->template = $this->systemErrorTemplate;
     } else {
         // generate all the data
         $this->generateMenu();
     }
     $this->templates->addData(array('pageTitle' => 'Page not found'));
     // process the template
     $output = $this->generateOutput();
     // send the page
     $response = new Response($output, Response::HTTP_NOT_FOUND, array('content-type' => 'text/html'));
     $response->prepare($this->docmark->request);
     $response->send();
 }
 /**
  * Export all settings in a Json file (.rzt).
  *
  * @param Symfony\Component\HttpFoundation\Request $request
  *
  * @return Symfony\Component\HttpFoundation\Response
  */
 public function exportAllAction(Request $request)
 {
     $this->validateAccessForRole('ROLE_ACCESS_SETTINGS');
     $groups = $this->getService('em')->getRepository('RZ\\Roadiz\\Core\\Entities\\SettingGroup')->findAll();
     $lonelySettings = $this->getService('em')->getRepository('RZ\\Roadiz\\Core\\Entities\\Setting')->findBy(['settingGroup' => null]);
     $tmpGroup = new SettingGroup();
     $tmpGroup->setName('__default__');
     $tmpGroup->addSettings($lonelySettings);
     $groups[] = $tmpGroup;
     $data = SettingCollectionJsonSerializer::serialize($groups);
     $response = new Response($data, Response::HTTP_OK, []);
     $response->headers->set('Content-Disposition', $response->headers->makeDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, 'setting-all-' . date("YmdHis") . '.rzt'));
     // Rezo-Zero Type
     $response->prepare($request);
     return $response;
 }
 /**
  * Sending back a response to mongrel2 webserver.
  *
  * @param Request $request
  * @param Response $response
  */
 private function sendResponseToMongrel(Request $request, Response $response)
 {
     $response->prepare($request);
     // Map back our Symfony Response to a MongrelResponse.
     $mongrelResponse = new MongrelResponse($request->attributes->get('mongrel2_uuid'), [$request->attributes->get('mongrel2_listener')]);
     $mongrelResponse->setContent($response->getContent());
     $headers = $response->headers->all();
     foreach ($response->headers->getCookies() as $cookie) {
         $headers['Set-Cookie'][] = $cookie;
     }
     $mongrelResponse->setHeaders($headers);
     $mongrelResponse->setHttpVersion($response->getProtocolVersion());
     $mongrelResponse->setStatusCode($response->getStatusCode());
     $mongrelResponse->setReasonPhrase(Response::$statusTexts[$response->getStatusCode()]);
     $this->handler->sendResponse($mongrelResponse);
 }
Beispiel #29
0
 /**
  * Send value as json string
  *
  * @param array $data
  * @return boolean
  */
 protected function setJsonContent($data)
 {
     $this->response->prepare($this->request);
     // Send Json response header
     if (!headers_sent()) {
         $this->response->headers->set('Content-Type', 'application/json');
         $this->response->headers->set('Cache-Control', 'no-cache, no-store, must-revalidate');
         $this->response->headers->set('Pragma', 'no-cache');
         $this->response->headers->set('Expires', '0');
         $encoding = $this->request->server->get('HTTP_ACCEPT_ENCODING');
         if (isset($encoding) && strpos($encoding, 'gzip') !== false) {
             ob_start('ob_gzhandler');
             $this->response->headers->set('Content-Encoding', 'gzip');
         }
     }
     $this->response->setContent($this->encoder->encode($data));
     return true;
 }
 public function connect(Application $app)
 {
     global $beforeTokenCheker;
     $controllers = $app['controllers_factory'];
     $self = $this;
     // ToDo: Add token check
     $controllers->get('/filedownloader', function (Request $request) use($app, $self) {
         $fileID = $request->get('file');
         $filePath = __DIR__ . '/../../../' . FileController::$fileDirName . "/" . basename($fileID);
         $app['logger']->addDebug($filePath);
         if (file_exists($filePath)) {
             $response = new Response();
             $lastModified = new \DateTime();
             $file = new \SplFileInfo($filePath);
             $lastModified = new \DateTime();
             $lastModified->setTimestamp($file->getMTime());
             $response->setLastModified($lastModified);
             if ($response->isNotModified($request)) {
                 $response->prepare($request)->send();
                 return $response;
             }
             $response = $app->sendFile($filePath);
             $currentDate = new \DateTime(null, new \DateTimeZone('UTC'));
             $response->setDate($currentDate)->prepare($request)->send();
             return $response;
         } else {
             return $self->returnErrorResponse("file doesn't exists.");
         }
     });
     //})->before($app['beforeTokenChecker']);
     // ToDo: Add token check
     $controllers->post('/fileuploader', function (Request $request) use($app, $self) {
         $file = $request->files->get(FileController::$paramName);
         $fineName = \Spika\Utils::randString(20, 20) . time();
         if (!is_writable(__DIR__ . '/../../../' . FileController::$fileDirName)) {
             return $self->returnErrorResponse(FileController::$fileDirName . " dir is not writable.");
         }
         $file->move(__DIR__ . '/../../../' . FileController::$fileDirName, $fineName);
         return $fineName;
     })->before($app['beforeApiGeneral']);
     //})->before($app['beforeTokenChecker']);
     return $controllers;
 }