public function eventsListJSONAction() { $repository = $this->getRepository(); $request = $this->getRequest(); $locationId = $request->query->get('locationId', $this->getConfigResolver('content.tree_root.location_id')); $location = $repository->getLocationService()->loadLocation($locationId); $contentTypeService = $repository->getContentTypeService(); $contentType = $contentTypeService->loadContentType($location->getContentInfo()->contentTypeId); $params = array('start' => $request->query->get('start', false), 'end' => $request->query->get('end', false)); switch ($contentType->identifier) { case 'agenda_folder': $jsonData = $this->getAgendaFolderContentRepository()->getJsonData($location, $params); break; case 'agenda': $jsonData = $this->getAgendaContentRepository()->getJsonData($location, $params); break; default: $jsonData = array(); } $response = new Response(); $response->headers->set('Content-Type', 'application/json'); $response->headers->set('Access-Control-Allow-Origin', '*'); $response->headers->set('Access-Control-Expose-Headers', 'Cache-Control,Content-Encoding'); $response->setContent(json_encode($jsonData)); return $response; }
/** * @param Response $response */ protected function assertForm(Response $response) { $this->assertEquals(200, $response->getStatusCode()); $this->assertRegExp('/form/', $response->getContent()); $this->assertNotRegExp('/<html/', $response->getContent()); $this->assertNotRegExp('/_username/', $response->getContent()); }
/** * Export the workbook. * * @param null|string $filename * * @throws \Exception * @return mixed|void */ public function export($filename = null) { $filename = $this->getFilename($filename); $output = $this->getExportable()->getDriver()->getOutputFromHtml($this->convertToHtml($this->getExportable())); $response = new Response($output, 200, ['Content-Type' => 'application/pdf', 'Content-Disposition' => 'attachment; filename="' . $filename . '.' . $this->getExtension() . '"']); return $response->send(); }
/** * 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); } }
public function createHttpResponse() { $httpResponse = new HttpResponse(); $httpResponse->setContent(json_encode($this)); $httpResponse->headers->set('Content-Type', 'application/json'); return $httpResponse; }
public function action(RouterInterface $router, RequestContext $context) { $request = Request::createFromGlobals(); $bPath = $context->getPathInfo(); try { $parameters = $router->match($bPath); var_dump($parameters); $_controller = $parameters["_controller"]; $_controller = explode(":", $_controller); $class = $_controller[0]; $action = strtolower($_controller[1]) . "Action"; $class = new $class(); ob_start(); if (method_exists($class, $action)) { $class->{$action}($request, new JsonResponse()); $response = new Response(ob_get_clean()); } else { $response = new Response('Not Found', 404); } } catch (ResourceNotFoundException $e) { $response = new Response('Not Found', 404); } catch (Exception $e) { $response = new Response('An error occurred', 500); } $response->send(); }
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; }
/** * Renders page header links with cache control * * @return \Symfony\Component\HttpFoundation\Response */ public function userLinksAction() { $response = new Response(); $response->setSharedMaxAge(3600); $response->setVary('Cookie'); return $this->render("BCPageLayoutOverrideTestBundle::page_header_links.html.twig", array(), $response); }
/** * Clear authorization Cookie * * @param string $authDomain */ private function clearCookie(Request $request, Response $response, $authDomain) { if ($request->cookies->has($authDomain)) { $response->headers->clearCookie($authDomain); $response->send(); } }
public function indexAction() { $response = new Response(); $response->setMaxAge(60); $response->setStatusCode(Response::HTTP_OK); return $response; }
/** * {@inheritdoc} */ public function start(Request $request, AuthenticationException $authException = null) { $response = new Response(); $response->headers->set('WWW-Authenticate', sprintf('Basic realm="%s"', $this->realmName)); $response->setStatusCode(401); return $response; }
public function handle(GetResponseEvent $event) { $request = $event->getRequest(); $wsseHeader = $request->headers->get(self::WSSE_HEADER, false); if (!$wsseHeader || 1 !== preg_match(self::WSSE_REGEX, $wsseHeader, $matches)) { $event->setResponse(new Response('', Response::HTTP_FORBIDDEN, array('WWW-Authenticate' => 'WSSE realm="webservice", profile="ApplicationToken"'))); return; } $token = new WsseUserToken(); $token->setUser($matches[1]); $token->digest = $matches[2]; $token->nonce = $matches[3]; $token->created = $matches[4]; try { $authToken = $this->authenticationManager->authenticate($token); $this->securityContext->setToken($authToken); return; } catch (NonceExpiredException $failed) { $this->logger->debug("Nonce expired: " . $wsseHeader); } catch (AuthenticationException $failed) { $this->logger->debug("Authentication failed: " . $failed->getMessage()); } $token = $this->securityContext->getToken(); if ($token instanceof WsseUserToken) { $this->securityContext->setToken(null); } $response = new Response(); $response->setStatusCode(Response::HTTP_UNAUTHORIZED); $event->setResponse($response); }
function apiIntroAction() { $response = new Response(); $response->setPublic(); $response->setMaxAge($this->container->getParameter('cache_expiration')); return $this->render('AppBundle:Default:apiIntro.html.twig', array("pagetitle" => "API", "game_name" => $this->container->getParameter('game_name'), "publisher_name" => $this->container->getParameter('publisher_name')), $response); }
/** * Chunk the request into parts as * desired by the request range header. * * @param Response $response * @param FileInterface $file */ protected function chunk(Response $response, FileInterface $file) { $size = $chunkStart = $file->getSize(); $end = $chunkEnd = $size; $response->headers->set('Content-length', $size); $response->headers->set('Content-Range', "bytes 0-{$end}/{$size}"); if (!($range = array_get($_SERVER, 'HTTP_RANGE'))) { return; } list(, $range) = explode('=', $_SERVER['HTTP_RANGE'], 2); if (strpos($range, ',') !== false) { $response->setStatusCode(416, 'Requested Range Not Satisfiable'); $response->headers->set('Content-Range', "bytes 0-{$end}/{$size}"); } if ($range == '-') { $chunkStart = $size - substr($range, 1); } else { $range = explode('-', $range); $chunkStart = $range[0]; $chunkEnd = isset($range[1]) && is_numeric($range[1]) ? $range[1] : $size; } $chunkEnd = $chunkEnd > $end ? $end : $chunkEnd; if ($chunkStart > $chunkEnd || $chunkStart > $size || $chunkEnd >= $size) { $response->setStatusCode(416, 'Requested Range Not Satisfiable'); $response->headers->set('Content-Range', "bytes 0-{$end}/{$size}"); } }
/** * 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; }
/** * @Route("/ipn-no-notification") * @Template() */ public function indexAction() { //getting ipn service registered in container $this->paypal_ipn = $this->get('orderly_pay_pal_ipn'); //validate ipn (generating response on PayPal IPN request) if ($this->paypal_ipn->validateIPN()) { // Succeeded, now let's extract the order $this->paypal_ipn->extractOrder(); // And we save the order now (persist and extract are separate because you might only want to persist the order in certain circumstances). $this->paypal_ipn->saveOrder(); // Now let's check what the payment status is and act accordingly if ($this->paypal_ipn->getOrderStatus() == Ipn::PAID) { /* HEALTH WARNING: * * Please note that this PAID block does nothing. In other words, this controller will not respond to a successful order * with any notification such as email or similar. You will have to identify paid orders by checking your database. * * If you want to send email notifications on successful receipt of an order, please see the alternative, Twig template- * based example controller: TwigEmailNotification.php */ } } else { return $this->redirect('/'); } $this->triggerEvent(Events\PayPalEvents::RECEIVED); $response = new Response(); $response->setStatusCode(200); return $response; }
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; }
/** * 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 frontendResetAction($id = false) { $response = new Response(); $response->headers->setCookie(new Cookie("subscriber_id", false)); $response->sendHeaders(); return $this->redirect($this->generateUrl('subscriber_frondend_submit', array('id' => $id))); }
/** * Handles HTTP validation headers. */ public function onKernelController(FilterControllerEvent $event) { $request = $event->getRequest(); if (!($configuration = $request->attributes->get('_cache'))) { return; } $response = new Response(); $lastModifiedDate = ''; if ($configuration->getLastModified()) { $lastModifiedDate = $this->getExpressionLanguage()->evaluate($configuration->getLastModified(), $request->attributes->all()); $response->setLastModified($lastModifiedDate); } $etag = ''; if ($configuration->getETag()) { $etag = hash('sha256', $this->getExpressionLanguage()->evaluate($configuration->getETag(), $request->attributes->all())); $response->setETag($etag); } if ($response->isNotModified($request)) { $event->setController(function () use($response) { return $response; }); } else { if ($etag) { $this->etags[$request] = $etag; } if ($lastModifiedDate) { $this->lastModifiedDates[$request] = $lastModifiedDate; } } }
private function evaluateGoodXML(Response $response) { $dom_doc = new \DOMDocument(); $dom_doc->loadXML($response->getContent()); $this->assertInstanceOf('DOMDocument', $dom_doc); $this->assertEquals($dom_doc->saveXML(), $response->getContent()); }
/** * 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; } } } }
/** * @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; }
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; }
/** * @return Response */ private function getEmptyXmlResponse() { $response = new Response(null, Response::HTTP_OK, ['Content-type' => 'text/xml', 'X-Robots-Tag' => 'noindex']); $sharedMaxAge = $this->getServiceContainer()->getParameter('werkspot.sitemap.cache.shared_max_age'); $response->setSharedMaxAge($sharedMaxAge); return $response; }
/** * {@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; }
/** * Parses the requested route to fetch * - the resource (databox, basket, record etc ..) * - general action (list, add, search) * - the action (setstatus, setname etc..) * - the aspect (collections, related, content etc..) * * @param ApiLog $log * @param Request $request * @param Response $response */ private function setDetails(ApiLog $log, Request $request, Response $response) { $chunks = explode('/', trim($request->getPathInfo(), '/')); if (false === $response->isOk() || sizeof($chunks) === 0) { return; } switch ($chunks[0]) { case ApiLog::DATABOXES_RESOURCE: $this->hydrateDataboxes($log, $chunks); break; case ApiLog::RECORDS_RESOURCE: $this->hydrateRecords($log, $chunks); break; case ApiLog::BASKETS_RESOURCE: $this->hydrateBaskets($log, $chunks); break; case ApiLog::FEEDS_RESOURCE: $this->hydrateFeeds($log, $chunks); break; case ApiLog::QUARANTINE_RESOURCE: $this->hydrateQuarantine($log, $chunks); break; case ApiLog::STORIES_RESOURCE: $this->hydrateStories($log, $chunks); break; case ApiLog::MONITOR_RESOURCE: $this->hydrateMonitor($log, $chunks); break; } }
/** * Controller for top menu * @param int $currentLocationId * * @return Response */ public function topMenuAction($currentLocationId) { $rootLocationId = $this->getConfigResolver()->getParameter('content.tree_root.location_id'); $response = new Response(); $parameters = array(); $helper = $this->get('bananamanu_simple_design.subelement_helper'); $menu = $helper->getSubElementLocation($rootLocationId); // Get current master try { $currentLocation = $this->getRepository()->getLocationService()->loadLocation($currentLocationId); $pathString = explode('/', $currentLocation->pathString); if ((int) $pathString[3] > 0) { $currentMasterLocationId = $pathString[3]; } else { $currentMasterLocationId = $rootLocationId; } } catch (\Exception $e) { $currentMasterLocationId = $rootLocationId; } // Get current user $user = $this->getRepository()->getCurrentUser(); // Cache control $response->setSharedMaxAge(84600); $response->setVary('X-User-Hash'); $response->setPublic(); $parameters['menu'] = $menu; $parameters['user'] = $user; $parameters['currentMasterLocationId'] = $currentMasterLocationId; return $this->render('BananamanuSimpleDesignBundle::page_topmenu.html.twig', $parameters, $response); }
/** * Displays an Error 503 (Service unavailable) page. * * @return \Symfony\Component\HttpFoundation\Response * Returns the response with a special header. */ public function updateError() { $response = new Response(); $response->setStatusCode(503); $response->headers->set('Status', '503 Service unavailable'); return $response; }
public function uploadAction(Request $request) { $request = $this->container->get('request'); $data1 = $request->query->get('file'); //$data2 = $request->query->get('data2'); $document = new Upload(); $form = $this->createFormBuilder($document)->add('file')->getForm(); $form->handleRequest($request); if ($form->isValid()) { $document->Upload(); //prepare the response, e.g. //$response = array("code" => 100, "success" => true); //you can return result as JSON //return new Response(json_encode($response)); $response = new Response(); $response->setContent('<html><body><h1>Hello world!</h1></body></html>'); $response->setStatusCode(200); $response->headers->set('Content-Type', 'text/html'); $response->send(); //you can return result as JSON //return new Response(json_encode($response)); //return new Response($this->generateUrl('chakosh_upload_homepage')); //return new Response($this->redirect($this->generateUrl('chakosh_upload_homepage'))); } return $this->render('ChakoshUploadBundle:Default:index.html.twig', array('form' => $form->createView())); }