setContent() public method

Valid types are strings, numbers, null, and objects that implement a __toString() method.
public setContent ( mixed $content ) : Response
$content mixed Content that can be cast to string
return Response
 /**
  * @Route("/edit/{user}",name="registration_admin_edit")
  */
 public function editAction(Request $request, $user)
 {
     $response = new Response();
     $em = $this->getDoctrine()->getManager();
     $form = $this->createForm(EditType::class);
     $form->handleRequest($request);
     $user = $em->getRepository(RegUser::class)->findOneByUsername($user);
     if ($form->isValid()) {
         $data = $form->getData();
         if ($data['action'] === true) {
             $password = new Password();
             $password->setHash($user->getPasswordHash());
             $password->setId('default');
             $password->setEncoder(CryptEncoder::class);
             $userLdap = $this->get('cloud.ldap.util.usermanipulator')->createUserObject($user->getUsername(), $password);
             $userLdap->setAltEmail($user->getAltEmail());
             $userLdap->setGpgPublicKey($user->getGpgPublicKey());
             $this->get('cloud.ldap.util.usermanipulator')->create($userLdap);
             $em->remove($user);
         } elseif ($data['action'] === false) {
             $em->remove($user);
         } else {
             $response->setStatusCode(400);
             return $response;
         }
         $em->flush();
     } else {
         $response->setContent(json_encode(['successfully' => false, 'error' => $form->getErrors(true)->__toString()]));
         return $response;
     }
     $response->setContent(json_encode(['successfully' => true]));
     return $response;
 }
Example #2
0
 public function edit(Request $request, Response $response, array $args)
 {
     $template = new \App\Template('form.twig');
     $template->title = 'Create';
     // Date granularities.
     $sql = "SELECT id, title FROM date_granularities ORDER BY id ASC";
     $template->date_granularities = $this->db->query($sql)->fetchAll();
     // Item.
     $item = new Item();
     if (isset($args['id'])) {
         $template->title = 'Editing #' . $args['id'];
         $item = new Item($args['id']);
     }
     $template->item = $item;
     // User.
     $item->setUser($this->user);
     if (!$this->user->getId()) {
         $msg = 'You have to ' . ' <a href="' . $this->config->baseUrl() . '/login" class="alert-link">log in</a> ' . ' before you can add or edit items.';
         $template->alert('info', $msg);
         $response->setContent($template->render());
         return $response;
     }
     $template->groups = $this->user->getGroups();
     // Other template data.
     $template->fileContents = $item->getFileContents();
     $template->itemTags = $item->getTagsString();
     $template->itemReadGroupId = $item->getReadGroup()->id;
     $template->itemEditGroupId = $item->getEditGroup()->id;
     $response->setContent($template->render());
     return $response;
 }
Example #3
0
 public function saveImagenAction(Request $request)
 {
     $em = $this->getDoctrine()->getManager();
     $response = new Response();
     try {
         $image = $request->get("image");
         if (!$image) {
             $response->setContent(json_decode(array("error" => ">No hay imagen seleccionada.")));
             $response->setStatusCode(Response::HTTP_NOT_FOUND);
             return $response;
         }
         $user = $this->getUser();
         $user->setPicture($image);
         $em->persist($user);
         $em->flush();
         $this->get('session')->getFlashBag()->add('success', 'Se actualizo la imagen de perfil');
         $response->setContent(json_encode(array("success" => "Imagen actualizada.")));
         $response->setStatusCode(Response::HTTP_OK);
         return $response;
     } catch (\Exception $exc) {
         $response->setContent(json_encode(array("error" => "Error al intentar guardar la imagen, intente con una mas pequeña o acerque mas la imagen")));
         $response->setStatusCode(Response::HTTP_NOT_FOUND);
         return $response;
     }
 }
 /**
  * Injects the datatable scripts into the given HTTP Response.
  *
  * @param Response $response A Response instance
  */
 protected function _injectDatatableScript(Response $response, Request $request)
 {
     $content = $response->getContent();
     $pos_body = strripos($content, '</body>');
     if (!$pos_body) {
         return;
     }
     $session = $request->getSession();
     $dom = '<script id="alidatatable-scripts" type="text/javascript">';
     $pos_container = strripos($content, 'alidatatable-scripts');
     $sess_dta = $session->get('datatable');
     $dta_script = null;
     array_walk($sess_dta, function (&$part, &$key) {
         $part = trim(preg_replace('/\\s\\s+/', ' ', $part));
     });
     $dta_script = implode("\n", $sess_dta);
     $session->set('datatable', array());
     if (!$pos_container) {
         $dta_container = $dom;
         $content = substr_replace($content, $dta_container . '</script>', $pos_body, 0);
         $response->setContent($content);
     }
     $pos_dta = strripos($content, $dom);
     $content = substr_replace($content, $dta_script, $pos_dta + strlen($dom), 0);
     $response->setContent($content);
 }
 /**
  * @param Request $request
  *
  * @return Response
  */
 public static function getResponse(Request $request)
 {
     ignore_user_abort(true);
     //turn off gzip compression
     if (function_exists('apache_setenv')) {
         apache_setenv('no-gzip', 1);
     }
     ini_set('zlib.output_compression', 0);
     $response = new Response();
     //removing any content encoding like gzip etc.
     $response->headers->set('Content-Encoding', 'none');
     //check to ses if request is a POST
     if ($request->getMethod() == 'GET') {
         $response->headers->set('Connection', 'close');
         //return 1x1 pixel transparent gif
         $response->headers->set('Content-Type', 'image/gif');
         //avoid cache time on browser side
         $response->headers->set('Content-Length', '42');
         $response->headers->set('Cache-Control', 'private, no-cache, no-cache=Set-Cookie, proxy-revalidate');
         $response->headers->set('Expires', 'Wed, 11 Jan 2000 12:59:00 GMT');
         $response->headers->set('Last-Modified', 'Wed, 11 Jan 2006 12:59:00 GMT');
         $response->headers->set('Pragma', 'no-cache');
         $response->setContent(self::getImage());
     } else {
         $response->setContent(' ');
     }
     return $response;
 }
 /**
  * Get callback response from paywall/payment provider and proccess it.
  *
  * @Route("/paywall/subscriptions/get", name="paywall_subscribe", options={"expose"=true})
  */
 public function getSubscriptionAction(Request $request)
 {
     $subscriptionService = $this->container->get('paywall.subscription.service');
     $userService = $this->get('user');
     $translator = $this->get('translator');
     $user = $userService->getCurrentUser();
     $em = $this->get('em');
     $response = new Response();
     $response->headers->set('Content-Type', 'text/html');
     $response->setCharset('utf-8');
     $templatesService = $this->get('newscoop.templates.service');
     $chosenSubscription = $em->getRepository('Newscoop\\PaywallBundle\\Entity\\Subscriptions')->findOneByName($request->get('subscription_name'));
     if (!$chosenSubscription) {
         $response->setContent($templatesService->fetchTemplate("_paywall/error.tpl", array('msg' => $translator->trans('paywall.alert.notexists'))));
         return $response;
     }
     $userSubscriptionInactive = $subscriptionService->getOneByUserAndSubscription($user->getId(), $chosenSubscription->getId(), 'N');
     $userSubscription = $subscriptionService->getOneByUserAndSubscription($user->getId(), $chosenSubscription->getId());
     if ($userSubscription || $userSubscriptionInactive) {
         $response->setContent($templatesService->fetchTemplate("_paywall/error.tpl", array('msg' => $translator->trans('paywall.manage.error.exists.subscription'))));
         return $response;
     }
     $specificationArray = $chosenSubscription->getSpecification()->toArray();
     $specification = $specificationArray[0];
     $subscription = $subscriptionService->create();
     $subscriptionData = new SubscriptionData(array('userId' => $user, 'subscriptionId' => $chosenSubscription, 'publicationId' => $request->get('publication_id') ?: $specification->getPublication()->getId(), 'toPay' => $chosenSubscription->getPrice(), 'days' => $chosenSubscription->getRange(), 'currency' => $chosenSubscription->getCurrency(), 'type' => 'T', 'active' => false), $subscription);
     $subscription = $subscriptionService->update($subscription, $subscriptionData);
     $subscriptionService->save($subscription);
     $this->dispatchNotificationEvent(PaywallEvents::ORDER_SUBSCRIPTION, $subscription);
     $response->setContent($templatesService->fetchTemplate("_paywall/success.tpl", array('subscription' => $subscription)));
     return $response;
 }
 /**
  * Obtener los datos del costeo
  * @Get("/rest-service/costos/data/{codigo}", options={"expose"=true})
  * @Rest\View
  */
 public function getDatosCosteoAction($codigo)
 {
     $response = new Response();
     // crea una respuesta con una cabecera ETag y Last-Modified
     // para determinar si se debe calcular el indicador u obtener de la caché
     // para el modo de desarrollo (dev) nunca tomar de caché
     //$response->setETag($fichaTec->getId().'_datos');
     //$response->setLastModified(($this->get('kernel')->getEnvironment() == 'dev') ? new \DateTime('NOW') : $fichaTec->getUltimaLectura() );
     $response->setPublic();
     // verifica que la respuesta no se ha modificado para la peticiĂłn dada
     //if ($response->isNotModified($this->getRequest())) {
     // devuelve inmediatamente la respuesta 304 de la caché
     //  return $response;
     //} else {
     $resp = array();
     $em = $this->getDoctrine()->getManager();
     $data = $em->getRepository('CostosBundle:Formulario')->getDatosCosteo($codigo);
     if (count($data) == 0) {
         $response->setContent('{"estado" : "error", "msj": "' . $this->get('translator')->trans('_no_datos_') . '"}');
     } else {
         $response->setContent(json_encode($data));
     }
     return $response;
     //}
 }
Example #8
0
 protected function doKernelResponse(Request $request, Response $response)
 {
     if (!$response instanceof DataResponse) {
         return;
     }
     $routeName = $request->attributes->get('_route');
     $route = $this->routes->get($routeName);
     if (!$route) {
         return;
     }
     $acceptedFormat = $route->getOption(RouteOptions::ACCEPTED_FORMAT);
     if (!$acceptedFormat) {
         $response->setContent('');
         $response->setStatusCode(406);
     }
     if ($this->encoder->supportsEncoding($acceptedFormat) && $acceptedFormat === 'json') {
         $contentType = $request->getMimeType($acceptedFormat);
         $jsonResponse = new JsonResponse($response->getContent());
         $response->setContent($jsonResponse->getContent());
         $response->headers->set('Content-Type', $contentType);
     } elseif ($this->encoder->supportsEncoding($acceptedFormat)) {
         $contentType = $request->getMimeType($acceptedFormat);
         $content = $this->encoder->encode($response->getContent(), $acceptedFormat);
         $response->setContent($content);
         $response->headers->set('Content-Type', $contentType);
     }
 }
 public function createAction()
 {
     $response = new Response();
     $response->headers->set('Content-type', 'application/json');
     if ($this->get('session')->get('user') === null) {
         $response->setStatusCode(401);
         $response->setContent(json_encode(array('response' => Response::$statusTexts[401])));
         return $response;
     }
     $data = $this->getRequest()->request->all();
     if (empty($data)) {
         $data = json_decode($this->getRequest()->getContent(), true);
     }
     $this->handleUpload($data);
     $userRepo = $this->getDoctrine()->getRepository('Emicro\\Bundles\\CoreBundle\\Entity\\User');
     $canvasRepo = $this->getDoctrine()->getRepository('Emicro\\Bundles\\CoreBundle\\Entity\\Canvas');
     $user = $this->get('session')->get('user');
     $canvasRepo->setUser($userRepo->find($user->getId()));
     if (isset($data['id'])) {
         $canvas = $canvasRepo->update($data, $data['id']);
         $response->setStatusCode(200);
     } else {
         $canvas = $canvasRepo->insert($data);
         $response->setStatusCode(201);
     }
     $serializer = new JsonSerializer();
     $response->setContent($serializer->serialize($canvas));
     return $response;
 }
 public function testPlainRequest()
 {
     $testBody = 'test';
     $this->response->setContent($testBody);
     $this->listener->onResponse($this->event);
     $this->assertEquals($testBody, $this->response->getContent());
 }
 /**
  * @param Request $request
  * @param $storageKey
  *
  * @return Response
  */
 protected function createFileResponse(Request $request, $storageKey)
 {
     $response = new Response();
     $parts = explode('/', $storageKey);
     $file = $this->getFile($parts[0]);
     if (!$file) {
         return $response->setContent('File not found.')->setStatusCode(Response::HTTP_NOT_FOUND);
     }
     if ($request->get('dl') !== null) {
         $filename = $file->getFilename();
         if (count($parts) > 1) {
             $filename = $parts[count($parts) - 1];
         }
         $filenameFallback = filter_var($filename, FILTER_SANITIZE_URL);
         if ($filenameFallback != $filename) {
             $guesser = ExtensionGuesser::getInstance();
             $extension = filter_var($guesser->guess($file->getMimeType()) ?: $file->getExtension(), FILTER_SANITIZE_URL);
             $filenameFallback = $file->getStorageKey() . ($extension ? '.' . $extension : '');
         }
         $response->headers->set('Content-Disposition', $response->headers->makeDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $filename, $filenameFallback));
     } else {
         $response->setCache(array('etag' => $file->getStorageKey(), 'last_modified' => $file->getCreatedAt()));
         if ($response->isNotModified($request)) {
             return $response;
         }
     }
     $response->setContent($file->getContents());
     $response->headers->set('Content-type', $file->getMimeType());
     $response->headers->set('Content-length', $file->getSize());
     return $response;
 }
 /**
  * Returns response based on request content type
  * @param  Request $request       [description]
  * @param  [type]  $response_data [description]
  * @param  integer $response_code [description]
  * @return [type]                 [description]
  */
 protected function handleResponse(Request $request, $response_data, $response_code = 200)
 {
     $response = new Response();
     $contentType = $request->headers->get('Content-Type');
     $format = null === $contentType ? $request->getRequestFormat() : $request->getFormat($contentType);
     if ($format == 'json') {
         $serializer = $this->get('serializer');
         $serialization_context = SerializationContext::create()->enableMaxDepthChecks()->setGroups(array('Default', 'detail', 'from_user', 'from_oauth'));
         $response->setContent($serializer->serialize($response_data, 'json', $serialization_context));
         $response->headers->set('Content-Type', 'application/json');
     } else {
         if (is_array($response_data)) {
             if (isset($response_data['message'])) {
                 $response->setContent($response_data['message']);
             } else {
                 $response->setContent(json_encode($response_data));
             }
         }
     }
     if ($response_code == 0) {
         $response->setStatusCode(500);
     } else {
         $response->setStatusCode($response_code);
     }
     return $response;
 }
 /**
  * Returns Response in JSON Format, given value has to be some encodeable Stuff (most likely an array ;) )
  * @param $value
  * @return \Symfony\Component\HttpFoundation\Response
  */
 public function handleResponse($value)
 {
     $this->throwNotFound($value);
     $this->response->setStatusCode(200);
     $this->response->setContent(json_encode($value));
     $this->response->headers->set('Content-Type', 'application/json');
     return $this->response;
 }
 /**
  * Product prices lookup.
  *
  * @Route("/prices")
  * @Method({"GET"})
  * @Template()
  *
  * @param Request $request
  * @return Response
  */
 public function pricesAction(Request $request)
 {
     $pricesData = $this->getProductPrices();
     $pricesDataJson = json_encode($pricesData);
     // Formulate JSON response
     $this->response->headers->set('Content-Type', 'application/json');
     $this->response->setContent($pricesDataJson);
     return $this->response;
 }
Example #15
0
 public function show($params)
 {
     $slug = $params['slug'];
     try {
         $data['content'] = $this->pageReader->readBySlug($slug);
     } catch (PageNotFoundException $e) {
         $this->response->setStatusCode(404);
         return $this->response->setContent('404 - Page not found');
     }
     $html = $this->twig->render('page.twig', $data);
     return $this->response->setContent($html);
 }
Example #16
0
 /**
  * @return \Symfony\Component\HttpFoundation\Response
  */
 public function getResponse()
 {
     $response = new Response();
     try {
         $response->headers->set('Content-Type', 'application/json');
         $response->setContent($this->run());
         $response->setStatusCode(200);
     } catch (Exception $e) {
         $response->setContent($e->getMessage());
         $response->setStatusCode($e->getCode());
     }
     return $response;
 }
Example #17
0
 protected function sendResponse($payload = NULL)
 {
     $this->res->setExpiration(FALSE);
     if (is_null($payload)) {
         $this->res->setStatusCode(204);
     } else {
         $this->res->setCharset('utf8');
         $this->res->headers->set('Content-Type', 'application/json');
         $content = json_encode($payload, JSON_PRETTY_PRINT);
         $this->res->setContent($content);
     }
     $this->res->send();
 }
 public function onKernelRequest(GetResponseEvent $event)
 {
     if ($this->isUnderMaintenance()) {
         $response = new Response();
         $response->setStatusCode(503);
         if (false !== strpos($this->maintenancePage, '.html.twig')) {
             $response->setContent($this->twig->render($this->maintenancePage));
         } else {
             $response->setContent(file_get_contents($this->maintenancePage));
         }
         $event->setResponse($response);
         $event->stopPropagation();
     }
 }
 /**
  * @Route("/", name="hello_homepage")
  * @Method({"GET"})
  */
 public function indexAction(Request $request)
 {
     $name = $request->query->get('name', null);
     $response = new Response();
     if (null !== $name) {
         $response->setContent(sprintf('<h1>Bonjour %s</h1>', $name));
         $response->setStatusCode(200);
     } else {
         $response->setContent('<h1>Page non trouvée</h1>');
         $response->setStatusCode(404);
     }
     $response->headers->set('Content-Type', 'text/html');
     return $response;
 }
 /**
  * @Route("/edit",name="profile_edit")
  *
  * @param $request Request
  * @return Response
  */
 public function editAction(Request $request)
 {
     $response = new Response();
     $form = $this->createForm(new ProfileType(), $this->getUser());
     // workaround to premit message from symfony 'This form should not contain extra fields.'
     $form->add('save', SubmitType::class, array('label' => 'save', 'attr' => ['class' => 'btn-primary']));
     $form->handleRequest($request);
     if ($form->isValid()) {
         $this->get('cloud.ldap.util.usermanipulator')->update($this->getUser());
         $response->setContent(json_encode(['successfully' => true]));
     } else {
         $response->setContent(json_encode(['successfully' => false]));
     }
     return $response;
 }
Example #21
0
 public function createHttpResponse()
 {
     $httpResponse = new HttpResponse();
     $httpResponse->setContent(json_encode($this));
     $httpResponse->headers->set('Content-Type', 'application/json');
     return $httpResponse;
 }
 /**
  * @View()
  */
 public function putCategoryAction($id, Request $request)
 {
     $this->denyAccessUnlessGranted('ROLE_ADMIN', null, 'Unable to access this page!');
     $em = $this->getDoctrine()->getManager();
     $response = new Response();
     $data = $request->request->all();
     if ($id === "null") {
         $category = new Category();
     } else {
         $category = $em->getRepository('AppBundle\\Entity\\Asset\\Category')->find($id);
     }
     $form = $this->createForm(CategoryType::class, $category, ['allow_extra_fields' => true]);
     try {
         $form->submit($data);
         if ($form->isValid()) {
             $category = $form->getData();
             $em->persist($category);
             $em->flush();
             $response->setStatusCode($request->getMethod() === 'POST' ? 201 : 204);
             $response->headers->set('Location', $this->generateUrl('app_admin_api_categories_get_category', array('id' => $category->getId()), true));
         } else {
             return $form;
         }
     } catch (Exception $e) {
         $response->setStatusCode(400);
         $response->setContent(json_encode(['message' => 'errors', 'errors' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine(), 'trace' => $e->getTraceAsString()]));
     }
     return $response;
 }
 /**
  * Injects the livereload script.
  *
  * @param Response $response A Response instance
  */
 protected function injectScript(Response $response)
 {
     if (function_exists('mb_stripos')) {
         $posrFunction = 'mb_strripos';
         $substrFunction = 'mb_substr';
     } else {
         $posrFunction = 'strripos';
         $substrFunction = 'substr';
     }
     $content = $response->getContent();
     $pos = $posrFunction($content, '</body>');
     if (false !== $pos) {
         $script = "livereload.js";
         if ($this->checkServerPresence) {
             // GET is required, as livereload apparently does not support HEAD requests ...
             $request = $this->httpClient->get($script);
             try {
                 $checkResponse = $this->httpClient->send($request);
                 if ($checkResponse->getStatusCode() !== 200) {
                     return;
                 }
             } catch (CurlException $e) {
                 // If error is connection failed, we assume the server is not running
                 if ($e->getCurlHandle()->getErrorNo() === 7) {
                     return;
                 }
                 throw $e;
             }
         }
         $content = $substrFunction($content, 0, $pos) . "\n" . '<script src="' . $this->httpClient->getBaseUrl() . $script . '"></script>' . "\n" . $substrFunction($content, $pos);
         $response->setContent($content);
     }
 }
 /**
  * @param Request $request
  *
  * @return Response
  */
 public function loadAction(Request $request)
 {
     $startDate = new \DateTime($request->get('start'));
     $endDate = new \DateTime($request->get('end'));
     $response = new Response();
     $response->headers->set('Content-Type', 'application/json');
     try {
         $content = $this->get('anca_rebeca_full_calendar.service.calendar')->getData($startDate, $endDate);
         $response->setContent($content);
         $response->setStatusCode(Response::HTTP_OK);
     } catch (\Exception $exception) {
         $response->setContent([]);
         $response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR);
     }
     return $response;
 }
 public function simpleSearchAction($format)
 {
     $request = $this->container->get('request');
     $serializer = $this->container->get('jms_serializer');
     $searchedTerm = $request->get('term');
     $useSynonyms = $request->get('useSynonyms');
     // Grabbing the repartition filters service, the department filter and the UE filter
     $repFilters = $this->get('eveg_app.repFilters');
     $depFrFilter = $repFilters->getDepFrFilterSession();
     $ueFilter = $repFilters->getUeFilterSession();
     if (!$searchedTerm) {
         throw new \Exception('Empty variable \'term\'.');
     }
     if (!$useSynonyms) {
         $useSynonyms = true;
     }
     $searchedTerm = $searchedTerm . ' ';
     $searchedTerm = str_replace(' ', '%', $searchedTerm);
     $result = $this->getDoctrine()->getManager()->getRepository('evegAppBundle:SyntaxonCore')->findForSearchEngine($searchedTerm, $useSynonyms, $depFrFilter, $ueFilter);
     $serializedResult = $serializer->serialize($result, $format, SerializationContext::create()->setGroups(array('searchEngine')));
     $response = new Response();
     $response->setContent($serializedResult);
     if ($format == 'json') {
         $response->headers->set('Content-Type', 'application/json');
     } elseif ($format == 'xml') {
         $response->headers->set('Content-Type', 'application/xml');
     }
     return $response;
 }
Example #26
0
 public function processAdaptation(\Symfony\Component\HttpFoundation\Response $response, $trkAjaxUrl)
 {
     $content = $response->getContent();
     $content = preg_replace('#(</body>)#', '<script type="text/javascript" src="' . $this->container->get('templating.helper.assets')->getUrl('bundles/skcmstracking/js/trk.js') . '"></script>' . '<script type="text/javascript">var trkAjaxUrl="' . $trkAjaxUrl . '";</script>' . '$1', $content);
     $response->setContent($content);
     return $response;
 }
 /**
  * Generates a test feed and simulates last-modified and etags.
  *
  * @param $use_last_modified
  *   Set TRUE to send a last modified header.
  * @param $use_etag
  *   Set TRUE to send an etag.
  * @param Request $request
  *   Information about the current HTTP request.
  *
  * @return \Symfony\Component\HttpFoundation\Response
  *   A feed that forces cache validation.
  */
 public function testFeed($use_last_modified, $use_etag, Request $request)
 {
     $response = new Response();
     $last_modified = strtotime('Sun, 19 Nov 1978 05:00:00 GMT');
     $etag = Crypt::hashBase64($last_modified);
     $if_modified_since = strtotime($request->server->get('HTTP_IF_MODIFIED_SINCE'));
     $if_none_match = stripslashes($request->server->get('HTTP_IF_NONE_MATCH'));
     // Send appropriate response. We respond with a 304 not modified on either
     // etag or on last modified.
     if ($use_last_modified) {
         $response->headers->set('Last-Modified', gmdate(DateTimePlus::RFC7231, $last_modified));
     }
     if ($use_etag) {
         $response->headers->set('ETag', $etag);
     }
     // Return 304 not modified if either last modified or etag match.
     if ($last_modified == $if_modified_since || $etag == $if_none_match) {
         $response->setStatusCode(304);
         return $response;
     }
     // The following headers force validation of cache.
     $response->headers->set('Expires', 'Sun, 19 Nov 1978 05:00:00 GMT');
     $response->headers->set('Cache-Control', 'must-revalidate');
     $response->headers->set('Content-Type', 'application/rss+xml; charset=utf-8');
     // Read actual feed from file.
     $file_name = drupal_get_path('module', 'aggregator_test') . '/aggregator_test_rss091.xml';
     $handle = fopen($file_name, 'r');
     $feed = fread($handle, filesize($file_name));
     fclose($handle);
     $response->setContent($feed);
     return $response;
 }
Example #28
0
 /**
  * {@inheritDoc}
  */
 public function processAction(Request $request)
 {
     $format = $this->container->get('settingsService')->get('zenmagick.mvc.rpc.format', 'JSON');
     $rpcRequest = Beans::getBean('ZMRpcRequest' . $format);
     $rpcRequest->setRequest($request);
     $method = $sacsMethod = $rpcRequest->getMethod();
     $rpcResponse = null;
     $sacsManager = $this->container->get('sacsManager');
     // check access on controller level
     if (!$sacsManager->authorize($request, $request->getRequestId(), $this->getUser(), false)) {
         $rpcResponse = $this->invalidCredentials($rpcRequest);
     }
     // (re-)check on method level if mapping exists
     $methodRequestId = $request->getRequestId() . '#' . $sacsMethod;
     if ($sacsManager->hasMappingForRequestId($methodRequestId)) {
         if (!$sacsManager->authorize($request, $methodRequestId, $this->getUser(), false)) {
             $rpcResponse = $this->invalidCredentials($rpcRequest);
         }
     }
     if (!$rpcResponse) {
         if (method_exists($this, $method) || in_array($method, $this->getAttachedMethods())) {
             $this->get('logger')->debug('calling method: ' . $method);
             $rpcResponse = $this->{$method}($rpcRequest);
         } else {
             $rpcResponse = $rpcRequest->createResponse();
             $rpcResponse->setStatus(false);
             $this->container->get('logger')->err("Invalid request - method '" . $request->getParameter('method') . "' not found!");
         }
     }
     $response = new Response();
     $response->headers->set('Content-Type', $rpcResponse->getContentType());
     $response->setContent($rpcResponse);
     return $response;
 }
 public function list_xmlAction()
 {
     $db = $this->container->get('arii_core.db');
     $data = $db->Connector('data');
     $qry = "SELECT frs.id,fs.name as spooler,\n                    frs.name,frs.hostname,frs.ip,frs.tcp_port,frs.version \n                FROM FOCUS_REMOTE_SCHEDULERS frs\n                LEFT JOIN FOCUS_SPOOLERS fs\n                ON frs.spooler_id=fs.id\n                ORDER BY fs.name";
     $res = $data->sql->query($qry);
     $xml = '<?xml version="1.0" encoding="UTF-8"?>';
     $xml .= '<rows><head><afterInit><call command="clearAll"/></afterInit></head>';
     $key_files = array();
     $Info = array();
     while ($line = $data->sql->get_next($res)) {
         $id = $line['spooler'] . '/' . $line['name'];
         foreach (array('id', 'ip', 'hostname', 'tcp_port', 'version') as $k) {
             $Info[$id][$k] = $line[$k];
         }
         $key_files[$id] = $id;
     }
     $tools = $this->container->get('arii_core.tools');
     $tree = $tools->explodeTree($key_files, "/");
     $xml .= $this->Connect2XML($tree, '', $Info);
     $xml .= '</rows>';
     $response = new Response();
     $response->headers->set('Content-Type', 'text/xml');
     $response->setContent($xml);
     return $response;
 }
 /**
  * Checks if a node's type requires a redirect.
  *
  * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
  *   The event to process.
  */
 public function purlCheckNodeContext(GetResponseEvent $event, $eventName, EventDispatcherInterface $dispatcher_interface)
 {
     $route_options = $this->routeMatch->getRouteObject()->getOptions();
     $isAdminRoute = array_key_exists('_admin_route', $route_options) && $route_options['_admin_route'];
     if (!$isAdminRoute && ($matched = $this->matchedModifiers->getMatched() && ($entity = $this->routeMatch->getParameter('node')))) {
         $node_type = $this->entityStorage->load($entity->bundle());
         $purl_settings = $node_type->getThirdPartySettings('purl');
         if (!isset($purl_settings['keep_context']) || !$purl_settings['keep_context']) {
             $url = \Drupal\Core\Url::fromRoute($this->routeMatch->getRouteName(), $this->routeMatch->getRawParameters()->all(), ['host' => Settings::get('purl_base_domain'), 'absolute' => TRUE]);
             try {
                 $redirect_response = new TrustedRedirectResponse($url->toString());
                 $redirect_response->getCacheableMetadata()->setCacheMaxAge(0);
                 $modifiers = $event->getRequest()->attributes->get('purl.matched_modifiers', []);
                 $new_event = new ExitedContextEvent($event->getRequest(), $redirect_response, $this->routeMatch, $modifiers);
                 $dispatcher_interface->dispatch(PurlEvents::EXITED_CONTEXT, $new_event);
                 $event->setResponse($new_event->getResponse());
                 return;
             } catch (RedirectLoopException $e) {
                 \Drupal::logger('redirect')->warning($e->getMessage());
                 $response = new Response();
                 $response->setStatusCode(503);
                 $response->setContent('Service unavailable');
                 $event->setResponse($response);
                 return;
             }
         }
     }
 }