setCharset() public method

Sets the response charset.
public setCharset ( string $charset ) : Response
$charset string Character set
return Response
Esempio n. 1
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 onEventResponse(Application $app, Response $response)
 {
     if (null === $response->getCharset()) {
         $response->setCharset($app->getParameter('charset'));
     }
     $response->prepare($app->getRequest());
 }
Esempio n. 3
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();
 }
 /**
  * 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;
 }
 public function testGetCharset()
 {
     $response = new Response();
     $charsetOrigin = 'UTF-8';
     $response->setCharset($charsetOrigin);
     $charset = $response->getCharset();
     $this->assertEquals($charsetOrigin, $charset);
 }
 public function meOptionsAction(Request $request)
 {
     $response = new Response('Go Ahead!', Response::HTTP_OK);
     $response->setCharset('UTF-8');
     $response->prepare($request);
     $response->send();
     return;
 }
 /**
  * Get a public file
  *
  * @param string Path to file
  * @param string Content-type
  * @return Response
  */
 public function getFile($path, $contentType)
 {
     if (is_file($path)) {
         $response = new Response(file_get_contents($path));
         $response->headers->set('Content-Type', $contentType);
         $response->setCharset('UTF-8');
         return $response;
     }
     return new Response('', 404);
 }
 public function testFilterDoesNothingIfCharsetIsOverridden()
 {
     $listener = new ResponseListener('ISO-8859-15');
     $this->dispatcher->addListener(KernelEvents::RESPONSE, array($listener, 'onKernelResponse'), 1);
     $response = new Response('foo');
     $response->setCharset('ISO-8859-1');
     $event = new FilterResponseEvent($this->kernel, Request::create('/'), HttpKernelInterface::MASTER_REQUEST, $response);
     $this->dispatcher->dispatch(KernelEvents::RESPONSE, $event);
     $this->assertEquals('ISO-8859-1', $response->getCharset());
 }
 /**
  * @Route("/{path}", requirements={"path"=".*"})
  *
  * @return Response
  */
 public function notFoundAction(Request $request, $path)
 {
     $url = preg_replace('~\\.\\w+$~', '', $request->getUri()) . '.json';
     $content = $this->translator->trans('not-found', ['%url%' => $url], 'messages') . PHP_EOL . PHP_EOL . $this->translator->trans('help', [], 'messages');
     $response = new Response();
     $response->setStatusCode(404);
     $response->setCharset('UTF-8');
     $response->setContent($content);
     $response->headers->set('Content-Type', 'text/plain; charset=UTF-8');
     return $response;
 }
 /**
  * @param string $path Path to the file
  *
  * @return Response
  */
 public function getFile($path)
 {
     if (is_file($path)) {
         $file = new File($path);
         $fileContent = file_get_contents($path);
         $response = new Response($fileContent);
         $response->headers->set('Content-Type', $this->getContentType($file->getExtension()));
         $response->setCharset('UTF-8');
         return $response;
     }
     return new Response('File not found', 404);
 }
Esempio n. 11
0
 /**
  * Mark the given ticket as printed.
  *
  * @param Request $request
  * @param int     $id
  * @param string  $code
  *
  * @return Response
  */
 public function printAction(Request $request, $id, $code)
 {
     $ticket = $this->ticketRepo->getTicketByIdAndCode($id, $code)->getOrThrow(new NotFoundHttpException('Ticket not found.'));
     $updateCommand = new UpdateResourceCommand();
     $updateCommand->class = '\\BCRM\\BackendBundle\\Entity\\Event\\Ticket';
     $updateCommand->id = $id;
     $updateCommand->data = array('printed' => $request->getMethod() === 'PATCH');
     $this->commandBus->handle($updateCommand);
     $response = new Response(json_encode(array('status' => 'OK')));
     $response->setCharset('utf-8');
     $response->headers->set('Content-Type', 'application/json');
     return $response;
 }
 /**
  * Serialize the data in the requested format and create a response object.
  *
  * @param Request $request
  * @param mixed   $data
  *
  * @return Response
  */
 protected function createResponse(Request $request, $result)
 {
     $response = new Response();
     $response->setCharset('UTF-8');
     $response->headers->set('Access-Control-Allow-Origin', '*');
     $response->headers->set('Access-Control-Allow-Methods', '*');
     $dataFormat = $request->getRequestFormat('json');
     // labels = list of months
     // series = [version: [month-1, month-2, ...]]
     $data = ['labels' => [], 'series' => []];
     foreach ($result as $row) {
         $label = $row['year'] . '-' . $row['month'];
         $version = implode('.', array_slice(explode('.', $row['value']), 0, 2));
         if (!in_array($label, $data['labels'])) {
             $data['labels'][] = $label;
         }
         $column = array_search($label, $data['labels']);
         if (!isset($data['series'][$version])) {
             $data['series'][$version] = array_fill(0, count($data['labels']), 0);
         }
         if (!isset($data['series'][$version][$column])) {
             $data['series'][$version][$column] = 0;
         }
         $data['series'][$version][$column] += $row['summary'];
     }
     // Now normalize the table - we might have empty cells.
     foreach (array_keys($data['series']) as $version) {
         foreach (array_keys($data['labels']) as $column) {
             if (!isset($data['series'][$version][$column])) {
                 $data['series'][$version][$column] = 0;
             }
         }
     }
     ksort($data['series']);
     switch ($dataFormat) {
         case 'json':
             $serialized = $this->serializer->serialize($data, 'json');
             $response->headers->set('Content-Type', sprintf('application/json; charset=UTF-8'));
             $response->setContent($serialized);
             break;
         case 'yml':
             $serialized = $this->serializer->serialize($data, 'yml');
             $response->headers->set('Content-Type', sprintf('text/yaml; charset=UTF-8'));
             $response->setContent($serialized);
             break;
         default:
             throw new FileNotFoundException($request->getPathInfo());
     }
     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);
     }
 }
 /**
  * @Route("/get", name="aslak_doc_get")
  * @return \Symfony\Component\HttpFoundation\Response
  */
 public function getAction()
 {
     $extracted = $this->get('doc.extractor')->extract();
     $final = $this->get('doc.parser')->parse($extracted);
     $encoders = array(new JsonEncoder());
     $normalizer = new ObjectNormalizer();
     $serializer = new Serializer([$normalizer], $encoders);
     $json = $serializer->serialize($final, 'json');
     $response = new Response($json);
     $response->headers->set('Content-Type', 'application/json; charset=UTF-8');
     $response->setCharset('UTF-8');
     $response->setStatusCode(200);
     return $response;
 }
Esempio n. 15
0
 public function getResponse()
 {
     $response = new Response($this->content);
     $disposition = $response->headers->makeDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $this->getFilename());
     $response->headers->set('Content-Description', 'File Transfer');
     $response->headers->set('Content-Disposition', $disposition);
     $response->headers->set('Content-Type', 'application/vnd.ms-excel');
     $response->headers->set('Content-Transfer-Encoding', 'binary');
     $response->headers->set('Expires', '0');
     $response->headers->set('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
     $response->headers->set('Pragma', 'public');
     $response->headers->set('Content-Length', strlen($this->content));
     $response->setCharset('UTF-8');
     return $response;
 }
Esempio n. 16
0
 /**
  * Renders the exception panel stylesheet for the given token.
  *
  * @param string $token The profiler token
  *
  * @return Response A Response instance
  *
  * @throws NotFoundHttpException
  */
 public function cssAction($token)
 {
     if (null === $this->profiler) {
         throw new NotFoundHttpException('The profiler must be enabled.');
     }
     $this->profiler->disable();
     $exception = $this->profiler->loadProfile($token)->getCollector('exception')->getException();
     $template = $this->getTemplate();
     if (!$this->templateExists($template)) {
         $handler = new ExceptionHandler();
         $response = new Response($handler->getStylesheet($exception), 200, array('Content-Type' => 'text/css'));
     } else {
         $response = new Response($this->twig->render('@WebProfiler/Collector/exception.css.twig'), 200, array('Content-Type' => 'text/css'));
     }
     $response->setCharset('UTF-8');
     return $response;
 }
Esempio n. 17
0
 /**
  * Creates the JSON used to render the stats.
  *
  * @param Request $request
  *
  * @return Response
  */
 protected function statsJson(Request $request)
 {
     $response = new Response();
     $response->setTtl(60 * 5);
     $response->setPublic();
     if ($response->isNotModified($request)) {
         return $response;
     }
     $event = $this->eventRepo->getNextEvent()->getOrThrow(new AccesDeniedHttpException('No event.'));
     $tickets = $this->ticketRepo->getTicketsForEvent($event);
     $unregistrations = $this->unregistrationRepo->getUnregistrationsForEvent($event);
     $stats = array('checkins' => array('sa' => $this->getCheckinsPerDay($tickets, Ticket::DAY_SATURDAY), 'sa_hour' => $this->getCheckinsPerHour($tickets, Ticket::DAY_SATURDAY), 'su' => $this->getCheckinsPerDay($tickets, Ticket::DAY_SUNDAY), 'su_hour' => $this->getCheckinsPerHour($tickets, Ticket::DAY_SUNDAY), 'unique' => array('sa' => $this->getUniqueDayCheckins($tickets, Ticket::DAY_SATURDAY), 'su' => $this->getUniqueDayCheckins($tickets, Ticket::DAY_SUNDAY), 'both' => $this->getUniqueDayCheckins($tickets, Ticket::DAY_SUNDAY, true)), 'noshows' => array('sa' => $this->getNoShows($tickets, Ticket::DAY_SATURDAY), 'su' => $this->getNoShows($tickets, Ticket::DAY_SUNDAY))), 'unregistrations' => $this->getUnregistrationsPerDay($unregistrations));
     $data = array('stats' => $stats);
     $response->setContent(json_encode($data));
     $response->setCharset('utf-8');
     $response->headers->set('Content-Type', 'application/json');
     return $response;
 }
Esempio n. 18
0
 /**
  * Filters the Response.
  *
  * @param EventInterface $event    An EventInterface instance
  * @param Response       $response A Response instance
  */
 public function filter(EventInterface $event, Response $response)
 {
     if (HttpKernelInterface::MASTER_REQUEST !== $event->get('request_type')) {
         return $response;
     }
     if (null === $response->getCharset()) {
         $response->setCharset($this->charset);
     }
     if ($response->headers->has('Content-Type')) {
         return $response;
     }
     $request = $event->get('request');
     $format = $request->getRequestFormat();
     if (null !== $format && ($mimeType = $request->getMimeType($format))) {
         $response->headers->set('Content-Type', $mimeType);
     }
     return $response;
 }
Esempio n. 19
0
 public function indexAction(Request $request, $key)
 {
     $manager = $this->container->get('ilioscore.user.manager');
     $user = $manager->findOneBy(array('icsFeedKey' => $key));
     if (!$user) {
         throw new NotFoundHttpException();
     }
     $calendar = new ICS\Calendar('Ilios Calendar for ' . $user->getFirstAndLastName());
     $calendar->setPublishedTTL('P1H');
     $from = new \DateTime(self::LOOK_BACK);
     $to = new \DateTime(self::LOOK_FORWARD);
     $events = $manager->findEventsForUser($user->getId(), $from, $to);
     $publishedEvents = array_filter($events, function (UserEvent $event) {
         return $event->isPublished && !$event->isScheduled;
     });
     $publishedEvents = $manager->addInstructorsToEvents($publishedEvents);
     $scheduledEvents = array_filter($events, function (UserEvent $event) {
         return $event->isPublished && $event->isScheduled;
     });
     /* @var UserEvent $event */
     foreach ($publishedEvents 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);
     }
     foreach ($scheduledEvents as $event) {
         $vEvent = new ICS\Event();
         $vEvent->setDtStart($event->startDate)->setDtEnd($event->endDate)->setSummary('Scheduled');
         $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);
     return $response;
 }
Esempio n. 20
0
 /**
  * RSS Календаря
  * @Route("/calendar/rss/{year}/{month}", name = "event_calendar_rss", defaults = {"year" = null, "month" = null}, requirements = {"year" = "\d+", "month" = "\d+"})
  */
 public function showCalendarRssAction($year, $month)
 {
     $starts = new \DateTime();
     if ($year == null && $month == null) {
         $default = true;
     } else {
         $default = false;
     }
     if ($year != null) {
         if ($month != null) {
             $starts->setDate($year, $month, 1);
         } else {
             $starts->setDate($year, $starts->format('m'), 1);
         }
     }
     $ends = clone $starts;
     if ($default == true) {
         $starts->modify('- 5 year');
         $ends->modify('+ 5 year');
     } else {
         $ends->modify('+ 1 month');
     }
     $starts = mktime(0, 0, 0, $starts->format('m'), 1, $starts->format('Y'));
     $ends = mktime(0, 0, 0, $ends->format('m'), 1, $ends->format('Y'));
     $events = $this->getDoctrine()->getRepository('EvrikaMainBundle:Event')->findForPeriod($starts, $ends, 'all', 'all');
     foreach ($events as $k => $e) {
         $txt = $e->getBody();
         $txt = preg_replace('~style="[^"]*"~i', '', $txt);
         $txt = str_replace('&', '&', $txt);
         $txt = str_replace('<p>&nbsp;</p>', '', $txt);
         $txt = str_replace('&nbsp;', '', $txt);
         $txt = str_replace('nbsp;', '', $txt);
         $txt = str_replace('&amp;', '', $txt);
         $txt = str_replace("", '', $txt);
         $txt = str_replace("", '', $txt);
         $txt = str_replace("", '', $txt);
         $txt = str_replace("", '', $txt);
         $txt = str_replace("", '', $txt);
         $events[$k]->setBody($txt);
     }
     $response = new Response();
     $response->setCharset('UTF-8');
     $response->headers->set('Content-Type', 'application/rss+xml');
     $template = $this->renderView('EvrikaMainBundle:Index:calendar_rss.html.twig', array('events' => $events));
     $response->setContent($template);
     return $response;
 }
 /**
  * @param string $contenttypeslug
  *
  * @return Response
  */
 public function feed($contenttypeslug = null)
 {
     /** @var EntityManager $storage */
     $storage = $this->app['storage'];
     /** @var \Twig_Loader_Filesystem $twigFilesystem */
     $twigFilesystem = $this->app['twig.loader.filesystem'];
     /** @var \Bolt\Render $renderer */
     $renderer = $this->app['render'];
     // Defaults for later
     $defaultFeedRecords = 5;
     $defaultTemplate = 'amp.twig';
     $content = [];
     $contentTypes = [];
     // If we're on the front page, use sitewide configuration
     $contentTypeName = $contenttypeslug ?: 'sitewide';
     if (!isset($this->config[$contentTypeName]['enabled']) || $this->config[$contentTypeName]['enabled'] != 'true') {
         $this->app->abort(404, "Feed for '{$contentTypeName}' not found.");
     }
     // Better safe than sorry: abs to prevent negative values
     $amount = (int) abs(!empty($this->config[$contentTypeName]['feed_records']) ? $this->config[$contentTypeName]['feed_records'] : $defaultFeedRecords);
     // How much to display in the description. Value of 0 means full body!
     $contentLength = (int) abs(!empty($this->config[$contentTypeName]['content_length']) ? $this->config[$contentTypeName]['content_length'] : 0);
     // Get our content
     if ($contentTypeName == 'sitewide') {
         foreach ($this->config[$contentTypeName]['content_types'] as $types) {
             $contentTypes[] = $storage->getContentType($types);
         }
     } else {
         $contentTypes[] = $storage->getContentType($contentTypeName);
     }
     // Get content for each contentType we've selected as an assoc. array
     // by content type
     foreach ($contentTypes as $contentType) {
         $content[$contentType['slug']] = $storage->getContent($contentType['slug'], ['limit' => $amount, 'order' => 'datepublish desc']);
     }
     // Now narrow our content array to $amount based on date
     $tmp = [];
     foreach ($content as $slug => $recordid) {
         if (!empty($recordid)) {
             foreach ($recordid as $record) {
                 $key = strtotime($record->values['datepublish']) . $slug;
                 $tmp[$key] = $record;
             }
         }
     }
     // Sort the array and return a reduced one
     krsort($tmp);
     $content = array_slice($tmp, 0, $amount);
     if (!$content) {
         $this->app->abort(404, "Feed for '{$contentTypeName}' not found.");
     }
     // Then, select which template to use, based on our
     // 'cascading templates rules'
     if (!empty($this->config[$contentTypeName]['feed_template'])) {
         $template = $this->config[$contentTypeName]['feed_template'];
     } else {
         $template = $defaultTemplate;
     }
     $twigFilesystem->addPath(dirname(__DIR__) . '/templates/');
     $body = $renderer->render($template, ['records' => $content, 'content_length' => $contentLength, $contentTypeName => $content]);
     $response = new Response($body, Response::HTTP_OK);
     $response->setCharset('utf-8')->setPublic()->setSharedMaxAge(3600)->headers->set('Content-Type', 'application/rss+xml');
     return $response;
 }
Esempio n. 22
0
 /**
  * Really send the feed
  *
  * @param feed_interface $feed
  *
  * @return Response
  *
  * @throw exception\feed_exception
  */
 protected function send_feed_do(feed_interface $feed)
 {
     $feed_updated_time = 0;
     $item_vars = array();
     $board_url = $this->feed_helper->get_board_url();
     // Open Feed
     $feed->open();
     // Iterate through items
     while ($row = $feed->get_item()) {
         // BBCode options to correctly disable urls, smilies, bbcode...
         if ($feed->get('options') === null) {
             // Allow all combinations
             $options = 7;
             if ($feed->get('enable_bbcode') !== null && $feed->get('enable_smilies') !== null && $feed->get('enable_magic_url') !== null) {
                 $options = ($row[$feed->get('enable_bbcode')] ? OPTION_FLAG_BBCODE : 0) + ($row[$feed->get('enable_smilies')] ? OPTION_FLAG_SMILIES : 0) + ($row[$feed->get('enable_magic_url')] ? OPTION_FLAG_LINKS : 0);
             }
         } else {
             $options = $row[$feed->get('options')];
         }
         $title = isset($row[$feed->get('title')]) && $row[$feed->get('title')] !== '' ? $row[$feed->get('title')] : (isset($row[$feed->get('title2')]) ? $row[$feed->get('title2')] : '');
         $published = $feed->get('published') !== null ? (int) $row[$feed->get('published')] : 0;
         $updated = $feed->get('updated') !== null ? (int) $row[$feed->get('updated')] : 0;
         $display_attachments = $this->auth->acl_get('u_download') && $this->auth->acl_get('f_download', $row['forum_id']) && isset($row['post_attachment']) && $row['post_attachment'] ? true : false;
         $item_row = array('author' => $feed->get('creator') !== null ? $row[$feed->get('creator')] : '', 'published' => $published > 0 ? $this->feed_helper->format_date($published) : '', 'updated' => $updated > 0 ? $this->feed_helper->format_date($updated) : '', 'link' => '', 'title' => censor_text($title), 'category' => $this->config['feed_item_statistics'] && !empty($row['forum_id']) ? $board_url . '/viewforum.' . $this->php_ext . '?f=' . $row['forum_id'] : '', 'category_name' => $this->config['feed_item_statistics'] && isset($row['forum_name']) ? $row['forum_name'] : '', 'description' => censor_text($this->feed_helper->generate_content($row[$feed->get('text')], $row[$feed->get('bbcode_uid')], $row[$feed->get('bitfield')], $options, $row['forum_id'], $display_attachments ? $feed->get_attachments($row['post_id']) : array())), 'statistics' => '');
         // Adjust items, fill link, etc.
         $feed->adjust_item($item_row, $row);
         $item_vars[] = $item_row;
         $feed_updated_time = max($feed_updated_time, $published, $updated);
     }
     // If we do not have any items at all, sending the current time is better than sending no time.
     if (!$feed_updated_time) {
         $feed_updated_time = time();
     }
     $feed->close();
     $content = $this->template->render('feed.xml.twig', array('FEED_IMAGE' => '', 'SELF_LINK' => $this->controller_helper->route($this->request->attributes->get('_route'), $this->request->attributes->get('_route_params'), true, '', UrlGeneratorInterface::ABSOLUTE_URL), 'FEED_LINK' => $board_url . '/index.' . $this->php_ext, 'FEED_TITLE' => $this->config['sitename'], 'FEED_SUBTITLE' => $this->config['site_desc'], 'FEED_UPDATED' => $this->feed_helper->format_date($feed_updated_time), 'FEED_LANG' => $this->user->lang['USER_LANG'], 'FEED_AUTHOR' => $this->config['sitename'], 'FEED_ROWS' => $item_vars));
     $response = new Response($content);
     $response->headers->set('Content-Type', 'application/atom+xml');
     $response->setCharset('UTF-8');
     $response->setLastModified(new \DateTime('@' . $feed_updated_time));
     if (!empty($this->user->data['is_bot'])) {
         // Let reverse proxies know we detected a bot.
         $response->headers->set('X-PHPBB-IS-BOT', 'yes');
     }
     return $response;
 }
 public function feed($contenttypeslug = '')
 {
     // jQuery not required
     $this->app['extensions']->disableJquery();
     // Clear snippet list. There's no clear any more, so just set to null
     $this->app['extensions']->clearSnippetQueue();
     $this->app['debugbar'] = false;
     // Defaults for later
     $defaultFeedRecords = 5;
     $defaultTemplate = 'rss.twig';
     $content = array();
     $contenttypes = array();
     // If we're on the front page, use sitewide configuration
     if ($contenttypeslug == '') {
         $contenttypeslug = 'sitewide';
     }
     if (!isset($this->config[$contenttypeslug]['enabled']) || $this->config[$contenttypeslug]['enabled'] != 'true') {
         $this->app->abort(404, "Feed for '{$contenttypeslug}' not found.");
     }
     // Better safe than sorry: abs to prevent negative values
     $amount = (int) abs(!empty($this->config[$contenttypeslug]['feed_records']) ? $this->config[$contenttypeslug]['feed_records'] : $defaultFeedRecords);
     // How much to display in the description. Value of 0 means full body!
     $contentLength = (int) abs(!empty($this->config[$contenttypeslug]['content_length']) ? $this->config[$contenttypeslug]['content_length'] : 0);
     // Get our content
     if ($contenttypeslug == 'sitewide') {
         foreach ($this->config[$contenttypeslug]['content_types'] as $types) {
             $contenttypes[] = $this->app['storage']->getContentType($types);
         }
     } else {
         $contenttypes[] = $this->app['storage']->getContentType($contenttypeslug);
     }
     // Get content for each contenttype we've selected as an assoc. array
     // by content type
     foreach ($contenttypes as $contenttype) {
         $content[$contenttype['slug']] = $this->app['storage']->getContent($contenttype['slug'], array('limit' => $amount, 'order' => 'datepublish desc'));
     }
     // Now narrow our content array to $amount based on date
     $tmp = array();
     foreach ($content as $slug => $recordid) {
         if (!empty($recordid)) {
             foreach ($recordid as $record) {
                 $key = strtotime($record->values['datepublish']) . $slug;
                 $tmp[$key] = $record;
             }
         }
     }
     // Sort the array and return a reduced one
     krsort($tmp);
     $content = array_slice($tmp, 0, $amount);
     if (!$content) {
         $this->app->abort(404, "Feed for '{$contenttypeslug}' not found.");
     }
     // Then, select which template to use, based on our
     // 'cascading templates rules'
     if (!empty($this->config[$contenttypeslug]['feed_template'])) {
         $template = $this->config[$contenttypeslug]['feed_template'];
     } else {
         $template = $defaultTemplate;
     }
     $this->app['twig.loader.filesystem']->addPath(dirname(__DIR__) . '/assets/');
     $body = $this->app['render']->render($template, array('records' => $content, 'content_length' => $contentLength, $contenttype['slug'] => $content));
     $response = new Response($body, Response::HTTP_OK);
     $response->setCharset('utf-8')->setPublic()->setSharedMaxAge(3600)->headers->set('Content-Type', 'application/rss+xml');
     return $response;
 }
Esempio n. 24
0
 public function connect(SilexApplication $app)
 {
     $app['controller.lightbox'] = $this;
     $controllers = $app['controllers_factory'];
     $controllers->before(function (Request $request) use($app) {
         if (!$request->query->has('LOG')) {
             return;
         }
         if ($app['authentication']->isAuthenticated()) {
             $app['authentication']->closeAccount();
         }
         if (null === ($token = $app['repo.tokens']->findValidToken($request->query->get('LOG')))) {
             $app->addFlash('error', $app->trans('The URL you used is out of date, please login'));
             return $app->redirectPath('homepage');
         }
         $app['authentication']->openAccount($token->getUser());
         switch ($token->getType()) {
             case TokenManipulator::TYPE_FEED_ENTRY:
                 return $app->redirectPath('lightbox_feed_entry', ['entry_id' => $token->getData()]);
                 break;
             case TokenManipulator::TYPE_VALIDATE:
             case TokenManipulator::TYPE_VIEW:
                 return $app->redirectPath('lightbox_validation', ['basket' => $token->getData()]);
                 break;
         }
     });
     $app['firewall']->addMandatoryAuthentication($controllers);
     $controllers->before($app['middleware.basket.converter'])->before($app['middleware.basket.user-access']);
     $controllers->get('/', function (SilexApplication $app) {
         try {
             \Session_Logger::updateClientInfos($app, 6);
         } catch (SessionNotFound $e) {
             return $app->redirectPath('logout');
         }
         $repository = $app['repo.baskets'];
         $basket_collection = array_merge($repository->findActiveByUser($app['authentication']->getUser()), $repository->findActiveValidationByUser($app['authentication']->getUser()));
         $template = 'lightbox/index.html.twig';
         if (!$app['browser']->isNewGeneration() && !$app['browser']->isMobile()) {
             $template = 'lightbox/IE6/index.html.twig';
         }
         return new Response($app['twig']->render($template, ['baskets_collection' => $basket_collection, 'module_name' => 'Lightbox', 'module' => 'lightbox']));
     })->bind('lightbox');
     $controllers->get('/ajax/NOTE_FORM/{sselcont_id}/', function (SilexApplication $app, $sselcont_id) {
         if (!$app['browser']->isMobile()) {
             return new Response('');
         }
         $basketElement = $app['repo.basket-elements']->findUserElement($sselcont_id, $app['authentication']->getUser());
         $parameters = ['basket_element' => $basketElement, 'module_name' => ''];
         return $app['twig']->render('lightbox/note_form.html.twig', $parameters);
     })->bind('lightbox_ajax_note_form')->assert('sselcont_id', '\\d+');
     $controllers->get('/ajax/LOAD_BASKET_ELEMENT/{sselcont_id}/', function (SilexApplication $app, $sselcont_id) {
         $repository = $app['repo.basket-elements'];
         $BasketElement = $repository->findUserElement($sselcont_id, $app['authentication']->getUser());
         if ($app['browser']->isMobile()) {
             $output = $app['twig']->render('lightbox/basket_element.html.twig', ['basket_element' => $BasketElement, 'module_name' => $BasketElement->getRecord($app)->get_title()]);
             return new Response($output);
         } else {
             $template_options = 'lightbox/sc_options_box.html.twig';
             $template_agreement = 'lightbox/agreement_box.html.twig';
             $template_selector = 'lightbox/selector_box.html.twig';
             $template_note = 'lightbox/sc_note.html.twig';
             $template_preview = 'common/preview.html.twig';
             $template_caption = 'common/caption.html.twig';
             if (!$app['browser']->isNewGeneration()) {
                 $template_options = 'lightbox/IE6/sc_options_box.html.twig';
                 $template_agreement = 'lightbox/IE6/agreement_box.html.twig';
             }
             $Basket = $BasketElement->getBasket();
             $ret = [];
             $ret['number'] = $BasketElement->getRecord($app)->get_number();
             $ret['title'] = $BasketElement->getRecord($app)->get_title();
             $ret['preview'] = $app['twig']->render($template_preview, ['record' => $BasketElement->getRecord($app), 'not_wrapped' => true]);
             $ret['options_html'] = $app['twig']->render($template_options, ['basket_element' => $BasketElement]);
             $ret['agreement_html'] = $app['twig']->render($template_agreement, ['basket' => $Basket, 'basket_element' => $BasketElement]);
             $ret['selector_html'] = $app['twig']->render($template_selector, ['basket_element' => $BasketElement]);
             $ret['note_html'] = $app['twig']->render($template_note, ['basket_element' => $BasketElement]);
             $ret['caption'] = $app['twig']->render($template_caption, ['view' => 'preview', 'record' => $BasketElement->getRecord($app)]);
             return $app->json($ret);
         }
     })->bind('lightbox_ajax_load_basketelement')->assert('sselcont_id', '\\d+');
     $controllers->get('/ajax/LOAD_FEED_ITEM/{entry_id}/{item_id}/', function (SilexApplication $app, $entry_id, $item_id) {
         $entry = $app['repo.feed-entries']->find($entry_id);
         $item = $entry->getItem($item_id);
         if ($app['browser']->isMobile()) {
             $output = $app['twig']->render('lightbox/feed_element.html.twig', ['feed_element' => $item, 'module_name' => $item->getRecord($app)->get_title()]);
             return new Response($output);
         } else {
             $template_options = 'lightbox/feed_options_box.html.twig';
             $template_preview = 'common/preview.html.twig';
             $template_caption = 'common/caption.html.twig';
             if (!$app['browser']->isNewGeneration()) {
                 $template_options = 'lightbox/IE6/feed_options_box.html.twig';
             }
             $ret = [];
             $ret['number'] = $item->getRecord($app)->get_number();
             $ret['title'] = $item->getRecord($app)->get_title();
             $ret['preview'] = $app['twig']->render($template_preview, ['record' => $item->getRecord($app), 'not_wrapped' => true]);
             $ret['options_html'] = $app['twig']->render($template_options, ['feed_element' => $item]);
             $ret['caption'] = $app['twig']->render($template_caption, ['view' => 'preview', 'record' => $item->getRecord($app)]);
             $ret['agreement_html'] = $ret['selector_html'] = $ret['note_html'] = '';
             return $app->json($ret);
         }
     })->bind('lightbox_ajax_load_feeditem')->assert('entry_id', '\\d+')->assert('item_id', '\\d+');
     $controllers->get('/validate/{basket}/', function (SilexApplication $app, $basket) {
         try {
             \Session_Logger::updateClientInfos($app, 6);
         } catch (SessionNotFound $e) {
             return $app->redirectPath('logout');
         }
         $repository = $app['repo.baskets'];
         $basket_collection = $repository->findActiveValidationAndBasketByUser($app['authentication']->getUser());
         if ($basket->getIsRead() === false) {
             $basket = $app['EM']->merge($basket);
             $basket->setIsRead(true);
             $app['EM']->flush();
         }
         if ($basket->getValidation() && $basket->getValidation()->getParticipant($app['authentication']->getUser())->getIsAware() === false) {
             $basket = $app['EM']->merge($basket);
             $basket->getValidation()->getParticipant($app['authentication']->getUser())->setIsAware(true);
             $app['EM']->flush();
         }
         $template = 'lightbox/validate.html.twig';
         if (!$app['browser']->isNewGeneration() && !$app['browser']->isMobile()) {
             $template = 'lightbox/IE6/validate.html.twig';
         }
         $response = new Response($app['twig']->render($template, ['baskets_collection' => $basket_collection, 'basket' => $basket, 'local_title' => strip_tags($basket->getName()), 'module' => 'lightbox', 'module_name' => $app->trans('admin::monitor: module validation')]));
         $response->setCharset('UTF-8');
         return $response;
     })->bind('lightbox_validation')->assert('basket', '\\d+');
     $controllers->get('/compare/{basket}/', function (SilexApplication $app, Basket $basket) {
         try {
             \Session_Logger::updateClientInfos($app, 6);
         } catch (SessionNotFound $e) {
             return $app->redirectPath('logout');
         }
         $repository = $app['repo.baskets'];
         $basket_collection = $repository->findActiveValidationAndBasketByUser($app['authentication']->getUser());
         if ($basket->getIsRead() === false) {
             $basket = $app['EM']->merge($basket);
             $basket->setIsRead(true);
             $app['EM']->flush();
         }
         if ($basket->getValidation() && $basket->getValidation()->getParticipant($app['authentication']->getUser())->getIsAware() === false) {
             $basket = $app['EM']->merge($basket);
             $basket->getValidation()->getParticipant($app['authentication']->getUser())->setIsAware(true);
             $app['EM']->flush();
         }
         $template = 'lightbox/validate.html.twig';
         if (!$app['browser']->isNewGeneration() && !$app['browser']->isMobile()) {
             $template = 'lightbox/IE6/validate.html.twig';
         }
         $response = new Response($app['twig']->render($template, ['baskets_collection' => $basket_collection, 'basket' => $basket, 'local_title' => strip_tags($basket->getName()), 'module' => 'lightbox', 'module_name' => $app->trans('admin::monitor: module validation')]));
         $response->setCharset('UTF-8');
         return $response;
     })->bind('lightbox_compare')->assert('basket', '\\d+');
     $controllers->get('/feeds/entry/{entry_id}/', function (SilexApplication $app, $entry_id) {
         try {
             \Session_Logger::updateClientInfos($app, 6);
         } catch (SessionNotFound $e) {
             return $app->redirectPath('logout');
         }
         $feed_entry = $app['repo.feed-entries']->find($entry_id);
         $template = 'lightbox/feed.html.twig';
         if (!$app['browser']->isNewGeneration() && !$app['browser']->isMobile()) {
             $template = 'lightbox/IE6/feed.html.twig';
         }
         $content = $feed_entry->getItems();
         $first = $content->first();
         $output = $app['twig']->render($template, ['feed_entry' => $feed_entry, 'first_item' => $first, 'local_title' => $feed_entry->getTitle(), 'module' => 'lightbox', 'module_name' => $app->trans('admin::monitor: module validation')]);
         $response = new Response($output, 200);
         $response->setCharset('UTF-8');
         return $response;
     })->bind('lightbox_feed_entry')->assert('entry_id', '\\d+');
     $controllers->get('/ajax/LOAD_REPORT/{basket}/', function (SilexApplication $app, Basket $basket) {
         return new Response($app['twig']->render('lightbox/basket_content_report.html.twig', ['basket' => $basket]));
     })->bind('lightbox_ajax_report')->assert('basket', '\\d+');
     $controllers->post('/ajax/SET_NOTE/{sselcont_id}/', function (SilexApplication $app, $sselcont_id) {
         $output = ['error' => true, 'datas' => $app->trans('Erreur lors de l\'enregistrement des donnees')];
         $request = $app['request'];
         $note = $request->request->get('note');
         if (is_null($note)) {
             return new Response('You must provide a note value', 400);
         }
         $repository = $app['repo.basket-elements'];
         $basket_element = $repository->findUserElement($sselcont_id, $app['authentication']->getUser());
         $validationDatas = $basket_element->getUserValidationDatas($app['authentication']->getUser());
         $validationDatas->setNote($note);
         $app['EM']->merge($validationDatas);
         $app['EM']->flush();
         if ($app['browser']->isMobile()) {
             $datas = $app['twig']->render('lightbox/sc_note.html.twig', ['basket_element' => $basket_element]);
             $output = ['error' => false, 'datas' => $datas];
         } else {
             $template = 'lightbox/sc_note.html.twig';
             $datas = $app['twig']->render($template, ['basket_element' => $basket_element]);
             $output = ['error' => false, 'datas' => $datas];
         }
         return $app->json($output);
     })->bind('lightbox_ajax_set_note')->assert('sselcont_id', '\\d+');
     $controllers->post('/ajax/SET_ELEMENT_AGREEMENT/{sselcont_id}/', function (SilexApplication $app, $sselcont_id) {
         $request = $app['request'];
         $agreement = $request->request->get('agreement');
         if (is_null($agreement)) {
             return new Response('You must provide an agreement value', 400);
         }
         $agreement = $agreement > 0;
         $releasable = false;
         try {
             $ret = ['error' => true, 'releasable' => false, 'datas' => $app->trans('Erreur lors de la mise a jour des donnes')];
             $repository = $app['repo.basket-elements'];
             $basket_element = $repository->findUserElement($sselcont_id, $app['authentication']->getUser());
             /* @var $basket_element BasketElement */
             $validationDatas = $basket_element->getUserValidationDatas($app['authentication']->getUser());
             if (!$basket_element->getBasket()->getValidation()->getParticipant($app['authentication']->getUser())->getCanAgree()) {
                 throw new ControllerException('You can not agree on this');
             }
             $validationDatas->setAgreement($agreement);
             $participant = $basket_element->getBasket()->getValidation()->getParticipant($app['authentication']->getUser());
             $app['EM']->merge($basket_element);
             $app['EM']->flush();
             $releasable = false;
             if ($participant->isReleasable() === true) {
                 $releasable = $app->trans('Do you want to send your report ?');
             }
             $ret = ['error' => false, 'datas' => '', 'releasable' => $releasable];
         } catch (ControllerException $e) {
             $ret['datas'] = $e->getMessage();
         }
         return $app->json($ret);
     })->bind('lightbox_ajax_set_element_agreement')->assert('sselcont_id', '\\d+');
     $controllers->post('/ajax/SET_RELEASE/{basket}/', function (SilexApplication $app, Basket $basket) {
         $datas = ['error' => true, 'datas' => ''];
         try {
             if (!$basket->getValidation()) {
                 throw new ControllerException('There is no validation session attached to this basket');
             }
             if (!$basket->getValidation()->getParticipant($app['authentication']->getUser())->getCanAgree()) {
                 throw new ControllerException('You have not right to agree');
             }
             $agreed = false;
             /* @var $basket Basket */
             foreach ($basket->getElements() as $element) {
                 if (null !== $element->getUserValidationDatas($app['authentication']->getUser())->getAgreement()) {
                     $agreed = true;
                 }
             }
             if (!$agreed) {
                 throw new ControllerException($app->trans('You have to give your feedback at least on one document to send a report'));
             }
             /* @var $basket Basket */
             $participant = $basket->getValidation()->getParticipant($app['authentication']->getUser());
             $token = $app['manipulator.token']->createBasketValidationToken($basket);
             $url = $app->url('lightbox', ['LOG' => $token->getValue()]);
             $to = $basket->getValidation()->getInitiator($app)->getId();
             $app['dispatcher']->dispatch(PhraseaEvents::VALIDATION_DONE, new ValidationEvent($participant, $basket, $url));
             $participant->setIsConfirmed(true);
             $app['EM']->merge($participant);
             $app['EM']->flush();
             $datas = ['error' => false, 'datas' => $app->trans('Envoie avec succes')];
         } catch (ControllerException $e) {
             $datas = ['error' => true, 'datas' => $e->getMessage()];
         }
         return $app->json($datas);
     })->bind('lightbox_ajax_set_release')->assert('basket', '\\d+');
     return $controllers;
 }
Esempio n. 25
0
 /**
  * @param File $file
  * @return Response
  */
 public function uploadAction(File $file)
 {
     $this->denyAccessUnlessGranted('ROLE_USER', null, 'Unable to access this page!');
     $fichier = $file->getName();
     $response = new Response();
     $response->setStatusCode(200);
     $response->headers->set('Content-Type', "application/pdf");
     $response->headers->set('Content-Disposition', sprintf('attachment;filename="%s"', $fichier));
     $response->setContent(file_get_contents($file->getWebPath()));
     $response->setCharset('UTF-8');
     // prints the HTTP headers followed by the content
     $response->send();
     return $response;
 }
Esempio n. 26
0
 public function testDefaultContentType()
 {
     $headerMock = $this->getMock('Symfony\\Component\\HttpFoundation\\ResponseHeaderBag', array('set'));
     $headerMock->expects($this->at(0))->method('set')->with('Content-Type', 'text/html; charset=UTF-8');
     $headerMock->expects($this->at(1))->method('set')->with('Content-Type', 'text/html; charset=Foo');
     $response = new Response();
     $response->headers = $headerMock;
     // verify first set()
     $response->__toString();
     $response->headers->remove('Content-Type');
     $response->setCharset('Foo');
     // verify second set()
     $response->__toString();
 }
Esempio n. 27
0
 /**
  * Do a forward to specified uri using request dispatcher.
  *
  * This method is used by all internal method needing to do a forward.
  *
  * @param string $uri Context-relative URI to forward to
  * @param \Symfony\Component\HttpFoundation\Request $request Current page request
  * @param \Symfony\Component\HttpFoundation\Response $response Current page response
  */
 protected function doForward($uri, \Symfony\Component\HttpFoundation\Request $request, \Symfony\Component\HttpFoundation\Response $response)
 {
     // Create a new URI
     $uri = $request->getUriForPath($uri);
     // Consider using standard $_POST, $_FILES etc.
     $subRequest = Request::create($uri, $request->getMethod(), $request->getMethod() == 'POST' ? $request->request->all() : $request->query->all(), $request->cookies->all(), $request->files->all(), $request->server->all());
     // If it was a POST then ensure it also has any query parameters
     if ($request->getMethod() == 'POST') {
         $subRequest->query->add($request->query->all());
     }
     if ($request->getSession()) {
         $subRequest->setSession($request->getSession());
     }
     // Obtain a new subrequest without Silex attributes
     $allowedKeys = array_filter(array_keys($request->attributes->all()), function ($key) {
         // Filter out silex "_" attributes
         return substr($key, 0, 1) != '_';
     });
     $subRequest->attributes->add(array_intersect_key($request->attributes->all(), array_flip($allowedKeys)));
     // Call for a sub-request (Note: Non-conventionally passes parent query/attributes)
     $subResponse = $this->actionKernel->getApplication()->handle($subRequest, HttpKernelInterface::SUB_REQUEST, false);
     // Update our current response to bring in the response
     $response->setContent($subResponse->getContent());
     $response->setStatusCode($subResponse->getStatusCode());
     $response->setCharset($subResponse->getCharset());
     $response->setProtocolVersion($subResponse->getProtocolVersion());
     // Determine whether all headers are 'added' or should replace (?)
     $response->headers->add($subResponse->headers->all());
 }
Esempio n. 28
0
        if ($response->isNotModified($request)) {
            return $response;
        }
        $manifestData = json_decode(file_get_contents($file->getPathname()), true);
        // Sorting the versions in descending order
        $builder = new \Herrera\Version\Builder();
        uasort($manifestData, function ($a, $b) use($builder) {
            if ($a['version'] === $b['version']) {
                return 0;
            }
            return \Herrera\Version\Comparator::isLessThan($builder->importString($a['version'])->getVersion(), $builder->importString($b['version'])->getVersion());
        });
        // Adding the "highlighted" bool value to every version.
        // Only the latest stable release is highlighted in every major version.
        $prevMajorVersion = null;
        foreach ($manifestData as $key => $data) {
            $manifestData[$key]['highlighted'] = false;
            $version = $builder->importString($data['version'])->getVersion();
            if ($version->getMajor() !== $prevMajorVersion && $version->isStable()) {
                $manifestData[$key]['highlighted'] = true;
                $prevMajorVersion = $version->getMajor();
            }
        }
    }
    // Rendering the template, setting up the response
    $response->headers->set('Content-Type', 'text/html');
    $response->setCharset('UTF-8');
    $response->setContent($app['twig']->render('download.twig', ['manifest_data' => $manifestData]));
    return $response;
});
return $controller;
Esempio n. 29
0
 /**
  * @Route("/contrat/export-pca", name="pca_export")
  */
 public function exportPcaAction(Request $request)
 {
     ini_set('memory_limit', '-1');
     // $response = new StreamedResponse();
     $formRequest = $request->request->get('form');
     $dateDebutString = $formRequest['dateDebut'] . " 23:59:59";
     $dateDebut = \DateTime::createFromFormat('d/m/Y H:i:s', $dateDebutString);
     $dm = $this->get('doctrine_mongodb')->getManager();
     $cm = $this->get('contrat.manager');
     $pca_for_csv = $cm->getPcaForCsv($dateDebut);
     $filename = sprintf("export_pca_du_%s.csv", $dateDebut->format("Y-m-d"));
     $handle = fopen('php://memory', 'r+');
     foreach ($pca_for_csv as $paiement) {
         fputcsv($handle, $paiement, ';');
     }
     rewind($handle);
     $content = stream_get_contents($handle);
     fclose($handle);
     $response = new Response(utf8_decode($content), 200, array('Content-Type' => 'text/csv', 'Content-Disposition' => 'attachment; filename=' . $filename));
     $response->setCharset('UTF-8');
     return $response;
 }
 /**
  * Serialize the data in the requested format and create a response object.
  *
  * @param Request $request
  * @param mixed   $data
  *
  * @return Response
  */
 protected function createResponse(Request $request, $timeParts, $valueParts, $result)
 {
     $response = new Response();
     $response->setCharset('UTF-8');
     $response->headers->set('Access-Control-Allow-Origin', '*');
     $response->headers->set('Access-Control-Allow-Methods', '*');
     $format = $request->getRequestFormat('json');
     $formatParts = explode('.', $format);
     $hierarchy = false;
     while (count($formatParts) > 1) {
         $hierarchy = array_shift($formatParts);
     }
     $dataFormat = array_shift($formatParts);
     switch ($hierarchy) {
         case 'flat':
             $valuePart = array_pop($valueParts);
             $lastPart = array_pop($valueParts);
             $data = [];
             foreach ($result as $row) {
                 $key = [];
                 foreach ($timeParts as $part) {
                     $key[] = $row[$part];
                 }
                 $key = implode('-', $key);
                 if (!isset($data[$key])) {
                     $data[$key] = [];
                 }
                 $ref =& $data[$key];
                 foreach ($valueParts as $part) {
                     $part = $row[$part];
                     if (!isset($ref[$part])) {
                         $ref[$part] = [];
                     }
                     $ref =& $ref[$part];
                 }
                 $ref[$row[$lastPart]] = $row[$valuePart];
             }
             break;
         default:
             $valuePart = array_pop($valueParts);
             $lastPart = array_pop($valueParts);
             $parts = array_merge($timeParts, $valueParts);
             $data = [];
             foreach ($result as $row) {
                 $ref =& $data;
                 foreach ($parts as $part) {
                     $part = $row[$part];
                     if (!isset($ref[$part])) {
                         $ref[$part] = [];
                     }
                     $ref =& $ref[$part];
                 }
                 $ref[$row[$lastPart]] = $row[$valuePart];
             }
             break;
     }
     switch ($dataFormat) {
         case 'json':
             $serialized = $this->serializer->serialize($data, 'json');
             $response->headers->set('Content-Type', sprintf('application/json; charset=UTF-8'));
             $response->setContent($serialized);
             break;
         case 'yml':
             $serialized = $this->serializer->serialize($data, 'yml');
             $response->headers->set('Content-Type', sprintf('text/yaml; charset=UTF-8'));
             $response->setContent($serialized);
             break;
         default:
             throw new FileNotFoundException($request->getPathInfo());
     }
     return $response;
 }