PHP symfony\component\httpfoundation Request Examples

PHP symfony\component\httpfoundation Request - 30 examples found. These are the top rated real world PHP examples of symfony\component\httpfoundation\Request extracted from open source projects. You can rate examples to help us improve the quality of examples.
The methods dealing with URL accept / return a raw path (% encoded): * getBasePath * getBaseUrl * getPathInfo * getRequestUri * getUri * getUriForPath
Author: Fabien Potencier (fabien@symfony.com)
Example #1
0
 /**
  * Writes a new Entry to the database
  *
  * @param Request $request Current http request
  *
  * @return \Symfony\Component\HttpFoundation\Response $response Result of action with data (if successful)
  */
 public function postAction(Request $request)
 {
     $response = $this->getResponse();
     $entityClass = $this->getModel()->getEntityClass();
     $record = new $entityClass();
     // Insert the new record
     $record = $this->getModel()->insertRecord($record);
     // store id of new record so we dont need to reparse body later when needed
     $request->attributes->set('id', $record->getId());
     $file = $this->saveFile($record->getId(), $request->getContent());
     // update record with file metadata
     $meta = new FileMetadata();
     $meta->setSize((int) $file->getSize())->setMime($request->headers->get('Content-Type'))->setCreatedate(new \DateTime());
     $record->setMetadata($meta);
     $record = $this->getModel()->updateRecord($record->getId(), $record);
     // Set status code and content
     $response->setStatusCode(Response::HTTP_CREATED);
     $routeName = $request->get('_route');
     $routeParts = explode('.', $routeName);
     $routeType = end($routeParts);
     if ($routeType == 'post') {
         $routeName = substr($routeName, 0, -4) . 'get';
     }
     $response->headers->set('Location', $this->getRouter()->generate($routeName, array('id' => $record->getId())));
     return $response;
 }
 /**
  * Reference purchase summary
  *
  * @Route()
  * @Method({"GET", "POST"})
  * @Template()
  *
  * @param Request $request
  * @return \Symfony\Component\HttpFoundation\Response
  */
 public function indexAction(Request $request)
 {
     $previouslyPostedData = null;
     // if we are not posting new data, and a request for $this->formType is stored in the session, prepopulate the form with the stored request
     $storedRequest = unserialize($request->getSession()->get($this->formType->getName()));
     if ($request->isMethod('GET') && $storedRequest instanceof Request) {
         $previouslyPostedData = $this->createForm($this->formType)->handleRequest($storedRequest)->getData();
     }
     $form = $this->createForm($this->formType, $previouslyPostedData);
     if ($request->isMethod('POST')) {
         $form->submit($request);
         if ($form->isValid()) {
             // Persist the case to IRIS
             /** @var ReferencingCase $case */
             $case = $form->getData()['case'];
             $this->irisEntityManager->persist($case);
             /** @var ReferencingApplication $application */
             foreach ($case->getApplications() as $application) {
                 // Always default
                 $application->setSignaturePreference(SignaturePreference::SCAN_DECLARATION);
                 $this->irisEntityManager->persist($application, array('caseId' => $case->getCaseId()));
                 // Persist each guarantor of the application
                 if (null !== $application->getGuarantors()) {
                     foreach ($application->getGuarantors() as $guarantor) {
                         $this->irisEntityManager->persist($guarantor, array('applicationId' => $application->getApplicationId()));
                     }
                 }
             }
             $request->getSession()->set('submitted-case', serialize($case));
             // Send the user to the success page
             return $this->redirect($this->generateUrl('barbon_hostedapi_agent_reference_newreference_tenancyagreement_index'), 301);
         }
     }
     return array('form' => $form->createView());
 }
Example #3
0
 /**
  *@Security("has_role('ROLE_USER')")
  */
 public function addAction(Request $request, Intervention $intervention)
 {
     $em = $this->getDoctrine()->getManager();
     $intervention = $em->getRepository('MdyGstBundle:Intervention')->find($intervention->getId());
     if ($intervention == null) {
         throw new NotFoundHttpException("La demande [" . $id . "] n'a pas été trouvée.");
     }
     $remarque = new Remarque();
     $remarque->setIntervention($intervention);
     $user = $this->container->get('security.context')->getToken()->getUser();
     $remarque->setAuteur($user);
     $form = $this->get('form.factory')->create(new RemarqueType(), $remarque);
     if ($request->getMethod() == 'POST') {
         $form->bind($request);
         if ($form->isValid()) {
             $this->get('session')->getFlashBag()->add('confirm', 'La remarque a été ajoutée avec succès !');
             $em->persist($remarque);
             $em->flush();
             return $this->redirect($this->generateUrl('mdy_gst_listIntervention'));
         } else {
             $request->getSession()->getFlashBag()->add('info', 'Le formulaire n\'est pas valide !');
         }
     }
     return $this->render('MdyGstBundle:Gst:Remarque/add.html.twig', array('form' => $form->createView()));
 }
 /**
  * @Route("/{applicationId}")
  * @Method({"GET", "POST"})
  * @Template()
  * @param Request $request
  * @param $applicationId
  * @return array
  */
 public function indexAction(Request $request, $applicationId)
 {
     // Validate the $applicationId, throws Exception if invalid.
     $application = $this->getApplication($this->irisEntityManager, $applicationId);
     // Get the Case for this Tenant and put in the session, as it's needed throughout
     $case = $this->getCase($this->irisEntityManager, $application->getCaseId());
     $request->getSession()->set('submitted-case', serialize($case));
     // Create an empty ReferencingGuarantor object.
     $guarantor = new ReferencingGuarantor();
     $guarantor->setCaseId($application->getCaseId());
     // Build the form.
     $form = $this->createForm($this->formType, $guarantor, array('guarantor_decorator' => $this->referencingGuarantorDecoratorBridgeSubscriber->getGuarantorDecorator(), 'attr' => array('id' => 'generic_step_form', 'class' => 'referencing branded individual-guarantor-form', 'novalidate' => 'novalidate')));
     // Process a client round trip, if necessary
     if ($request->isXmlHttpRequest()) {
         $form->submit($request);
         return $this->render('BarbonHostedApiLandlordReferenceBundle:NewReference/Guarantor/Validate:index.html.twig', array('form' => $form->createView()));
     }
     // Submit the form.
     $form->handleRequest($request);
     if ($form->isValid()) {
         $case = $this->getCase($this->irisEntityManager, $application->getCaseId());
         // Dispatch the new guarantor reference event.
         $this->eventDispatcher->dispatch(NewReferenceEvents::GUARANTOR_REFERENCE_CREATED, new NewGuarantorReferenceEvent($case, $application, $guarantor));
         // Send the user to the success page.
         return $this->redirectToRoute('barbon_hostedapi_landlord_reference_newreference_guarantor_confirmation_index', array('applicationId' => $applicationId));
     }
     return array('form' => $form->createView());
 }
Example #5
0
 /**
  * Perform an action on a Contenttype record.
  *
  * The action part of the POST request should take the form:
  * [
  *     contenttype => [
  *         id => [
  *             action => [field => value]
  *         ]
  *     ]
  * ]
  *
  * For example:
  * [
  *     'pages'   => [
  *         3 => ['modify' => ['status' => 'held']],
  *         5 => null,
  *         4 => ['modify' => ['status' => 'draft']],
  *         1 => ['delete' => null],
  *         2 => ['modify' => ['status' => 'published']],
  *     ],
  *     'entries' => [
  *         4 => ['modify' => ['status' => 'published']],
  *         1 => null,
  *         5 => ['delete' => null],
  *         2 => null,
  *         3 => ['modify' => ['title' => 'Drop Bear Attacks']],
  *     ]
  * ]
  *
  * @param Request $request Symfony Request
  *
  * @return Response
  */
 public function action(Request $request)
 {
     //         if (!$this->checkAntiCSRFToken($request->get('bolt_csrf_token'))) {
     //             $this->app->abort(Response::HTTP_BAD_REQUEST, Trans::__('Something went wrong'));
     //         }
     $contentType = $request->get('contenttype');
     $actionData = $request->get('actions');
     if ($actionData === null) {
         throw new \UnexpectedValueException('No content action data provided in the request.');
     }
     foreach ($actionData as $contentTypeSlug => $recordIds) {
         if (!$this->getContentType($contentTypeSlug)) {
             // sprintf('Attempt to modify invalid ContentType: %s', $contentTypeSlug);
             continue;
         } else {
             $this->app['storage.request.modify']->action($contentTypeSlug, $recordIds);
         }
     }
     $referer = Request::create($request->server->get('HTTP_REFERER'));
     $taxonomy = null;
     foreach (array_keys($this->getOption('taxonomy', [])) as $taxonomyKey) {
         if ($referer->query->get('taxonomy-' . $taxonomyKey)) {
             $taxonomy[$taxonomyKey] = $referer->query->get('taxonomy-' . $taxonomyKey);
         }
     }
     $options = (new ListingOptions())->setOrder($referer->query->get('order'))->setPage($referer->query->get('page_' . $contentType))->setFilter($referer->query->get('filter'))->setTaxonomies($taxonomy);
     $context = ['contenttype' => $this->getContentType($contentType), 'multiplecontent' => $this->app['storage.request.listing']->action($contentType, $options), 'filter' => array_merge((array) $taxonomy, (array) $options->getFilter()), 'permissions' => $this->getContentTypeUserPermissions($contentType, $this->users()->getCurrentUser())];
     return $this->render('@bolt/async/record_list.twig', ['context' => $context]);
 }
 public function newarticleAction(Request $request)
 {
     $em = $this->getDoctrine()->getManager();
     $article = new Article();
     $form = $this->createForm(new ArticleType($em), $article);
     if ($request->isMethod('POST')) {
         $form->handleRequest($request);
         $thumbnail = $article->getThumbnail();
         $thumbnailName = md5(uniqid()) . '.' . $thumbnail->guessExtension();
         $thumbnailDir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/thumbnail';
         $thumbnail->move($thumbnailDir, $thumbnailName);
         $article->setThumbnail('uploads/thumbnail/' . $thumbnailName);
         $banner = $article->getBanner();
         $bannerName = md5(uniqid()) . '.' . $banner->guessExtension();
         $bannerDir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/banner';
         $banner->move($bannerDir, $bannerName);
         $article->setBanner('uploads/banner/' . $bannerName);
         $article->setDate(new \DateTime("now"));
         $article->setUser($this->get('security.token_storage')->getToken()->getUser());
         if (!$form->isValid()) {
             return $this->redirectToRoute('aved_new_article');
         }
         $em->persist($article);
         $em->flush();
         return $this->redirectToRoute('aved_new_article');
     }
     return $this->render('AvedBlogBundle:Default:new_article.html.twig', array('form' => $form->createView()));
 }
 /**
  * @Route("/report", name="report", methods={"GET", "POST"} )
  */
 public function indexAction(Request $request)
 {
     $fromDate = $request->get('fromDate') ?: '1 month ago';
     $toDate = $request->get('toDate') ?: 'now';
     $parameters = array('timeEntriesGroupedByDate' => $this->getDoctrine()->getRepository('AppBundle:TimeEntry')->getTimeEntriesGroupedByDayForDates($fromDate, $toDate), 'fromDate' => new \DateTime($fromDate), 'toDate' => new \DateTime($toDate));
     return $this->render('::report.html.twig', $parameters);
 }
Example #8
0
 /**
  * @param $data array
  * @param format string, either rss or atom
  */
 protected function createFeed(View $view, Request $request)
 {
     $feed = new Feed();
     $data = $view->getData();
     $item = current($data);
     $annotationData = $this->reader->read($item);
     if ($item && ($feedData = $annotationData->getFeed())) {
         $class = get_class($item);
         $feed->setTitle($feedData->getName());
         $feed->setDescription($feedData->getDescription());
         $feed->setLink($this->urlGen->generateCollectionUrl($class));
         $feed->setFeedLink($this->urlGen->generateCollectionUrl($class, $request->getRequestFormat()), $request->getRequestFormat());
     } else {
         $feed->setTitle('Camdram feed');
         $feed->setDescription('Camdram feed');
     }
     $lastModified = null;
     $accessor = PropertyAccess::createPropertyAccessor();
     // Add one or more entries. Note that entries must be manually added once created.
     foreach ($data as $document) {
         $entry = $feed->createEntry();
         $entry->setTitle($accessor->getValue($document, $feedData->getTitleField()));
         $entry->setLink($this->urlGen->generateUrl($document));
         $entry->setDescription($this->twig->render($feedData->getTemplate(), array('entity' => $document)));
         if ($accessor->isReadable($document, $feedData->getUpdatedAtField())) {
             $entry->setDateModified($accessor->getValue($document, $feedData->getUpdatedAtField()));
         }
         $feed->addEntry($entry);
         if (!$lastModified || $entry->getDateModified() > $lastModified) {
             $lastModified = $entry->getDateModified();
         }
     }
     $feed->setDateModified($lastModified);
     return $feed->export($request->getRequestFormat());
 }
 /**
  * Generates the robots administration form and fills it with a default value if needed.
  *
  * @Route(path="/", name="KunstmaanSeoBundle_settings_robots")
  * @Template(template="@KunstmaanSeo/Admin/Settings/robotsSettings.html.twig")
  * @param Request $request
  * @return array|RedirectResponse
  */
 public function robotsSettingsAction(Request $request)
 {
     $this->checkPermission();
     $em = $this->getDoctrine()->getManager();
     $repo = $this->getDoctrine()->getRepository("KunstmaanSeoBundle:Robots");
     $robot = $repo->findOneBy(array());
     $default = $this->container->getParameter('robots_default');
     $isSaved = true;
     if (!$robot) {
         $robot = new Robots();
     }
     if ($robot->getRobotsTxt() == NULL) {
         $robot->setRobotsTxt($default);
         $isSaved = false;
     }
     $form = $this->createForm(new RobotsType(), $robot);
     if ($request->isMethod('POST')) {
         $form->handleRequest($request);
         if ($form->isValid()) {
             $em->persist($robot);
             $em->flush();
             return new RedirectResponse($this->generateUrl('KunstmaanSeoBundle_settings_robots'));
         }
     }
     if (!$isSaved) {
         $warning = $this->get('translator')->trans('seo.robots.warning');
         $this->get('session')->getFlashBag()->add('warning', $warning);
     }
     return array('form' => $form->createView());
 }
 /**
  * {@inheritdoc}
  *
  * This method looks for a '_controller' request attribute that represents
  * the controller name (a string like ClassName::MethodName).
  */
 public function getController(Request $request)
 {
     if (!($controller = $request->attributes->get('_controller'))) {
         if (null !== $this->logger) {
             $this->logger->warning('Unable to look for the controller as the "_controller" parameter is missing.');
         }
         return false;
     }
     if (is_array($controller)) {
         return $controller;
     }
     if (is_object($controller)) {
         if (method_exists($controller, '__invoke')) {
             return $controller;
         }
         throw new \InvalidArgumentException(sprintf('Controller "%s" for URI "%s" is not callable.', get_class($controller), $request->getPathInfo()));
     }
     if (false === strpos($controller, ':')) {
         if (method_exists($controller, '__invoke')) {
             return $this->instantiateController($controller);
         } elseif (function_exists($controller)) {
             return $controller;
         }
     }
     $callable = $this->createController($controller);
     if (!is_callable($callable)) {
         throw new \InvalidArgumentException(sprintf('The controller for URI "%s" is not callable. %s', $request->getPathInfo(), $this->getControllerError($callable)));
     }
     return $callable;
 }
Example #11
0
 private function indexAction(Request $req)
 {
     $user = $this->app['sentry']->getUser();
     // How many admins make for a majority?
     $mapper = $this->app['spot']->mapper('OpenCFP\\Domain\\Entity\\User');
     $admin_count = $mapper->all()->where(['permissions' => '{"admin":1}'])->count();
     $admin_majority = (int) ($admin_count * 0.501) + 1;
     // Get list of talks where majority of admins 'favorited' them
     $mapper = $this->app['spot']->mapper('OpenCFP\\Domain\\Entity\\Talk');
     $favorite_talks = $mapper->getAdminFavorites($user->id, $admin_majority);
     // Set up our page stuff
     $adapter = new \Pagerfanta\Adapter\ArrayAdapter($favorite_talks);
     $pagerfanta = new \Pagerfanta\Pagerfanta($adapter);
     $pagerfanta->setMaxPerPage(20);
     $pagerfanta->getNbResults();
     if ($req->get('page') !== null) {
         $pagerfanta->setCurrentPage($req->get('page'));
     }
     // Create our default view for the navigation options
     $routeGenerator = function ($page) {
         return '/admin/review?page=' . $page;
     };
     $view = new TwitterBootstrap3View();
     $pagination = $view->render($pagerfanta, $routeGenerator, array('proximity' => 3));
     $template_data = ['pagination' => $pagination, 'talks' => $pagerfanta, 'page' => $pagerfanta->getCurrentPage(), 'totalRecords' => count($favorite_talks)];
     return $this->render('admin/review/index.twig', $template_data);
 }
 /**
  * @param Request $request
  * @return null|RedirectResponse
  */
 public function onLogoutSuccess(Request $request)
 {
     // Chamilo logout
     $request->getSession()->remove('_locale');
     $request->getSession()->remove('_locale_user');
     if (api_is_global_chat_enabled()) {
         $chat = new \Chat();
         $chat->setUserStatus(0);
     }
     $userId = $this->storage->getToken()->getUser()->getId();
     $tbl_track_login = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
     $sql = "SELECT login_id, login_date\n                FROM {$tbl_track_login}\n                WHERE login_user_id = {$userId}\n                ORDER BY login_date DESC\n                LIMIT 0,1";
     $row = Database::query($sql);
     $loginId = null;
     if (Database::num_rows($row) > 0) {
         $loginId = Database::result($row, 0, "login_id");
     }
     $loginAs = $this->checker->isGranted('ROLE_PREVIOUS_ADMIN');
     if (!$loginAs) {
         $current_date = api_get_utc_datetime();
         $sql = "UPDATE {$tbl_track_login}\n                    SET logout_date='" . $current_date . "'\n        \t\t    WHERE login_id='{$loginId}'";
         Database::query($sql);
     }
     $online_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ONLINE);
     $query = "DELETE FROM " . $online_table . " WHERE login_user_id = {$userId}";
     Database::query($query);
     require_once api_get_path(SYS_PATH) . 'main/chat/chat_functions.lib.php';
     exit_of_chat($userId);
     $login = $this->router->generate('home');
     $response = new RedirectResponse($login);
     return $response;
 }
 /**
  * @param $id
  * @param Request     $request
  * @param Application $app
  *
  * @return Response
  */
 public function editAction($id, Request $request, Application $app)
 {
     if (!$app['security']->isGranted('ROLE_POSTS_EDITOR') && !$app['security']->isGranted('ROLE_ADMIN')) {
         $app->abort(403);
     }
     $post = $app['orm.em']->find('Application\\Entity\\PostEntity', $id);
     if (!$post) {
         $app->abort(404);
     }
     $form = $app['form.factory']->create(new PostType(), $post);
     if ($request->getMethod() == 'POST') {
         $form->handleRequest($request);
         if ($form->isValid()) {
             $postEntity = $form->getData();
             if ($postEntity->getRemoveImage()) {
                 $postEntity->setImageUrl(null);
             }
             /*** Image ***/
             $postEntity->setImageUploadPath($app['baseUrl'] . '/assets/uploads/')->setImageUploadDir(WEB_DIR . '/assets/uploads/')->imageUpload();
             $app['orm.em']->persist($postEntity);
             $app['orm.em']->flush();
             $app['flashbag']->add('success', $app['translator']->trans('The post was successfully edited!'));
             return $app->redirect($app['url_generator']->generate('members-area.posts.edit', array('id' => $postEntity->getId())));
         }
     }
     return new Response($app['twig']->render('contents/members-area/posts/edit.html.twig', array('form' => $form->createView(), 'post' => $post)));
 }
Example #14
0
 function it_throws_exception_if_product_with_given_id_does_not_exist($productRepository, CartItemInterface $item, Request $request)
 {
     $request->isMethod('POST')->willReturn(true);
     $request->get('id')->willReturn(5);
     $productRepository->findOneBy(['id' => 5, 'channels' => null])->willReturn(null);
     $this->shouldThrow(ItemResolvingException::class)->duringResolve($item, $request);
 }
 /**
  * @Route("/login", name="plusbelle_login")
  * @Template()
  */
 public function loginAction(Request $request)
 {
     $session = $request->getSession();
     if (class_exists('\\Symfony\\Component\\Security\\Core\\Security')) {
         $authErrorKey = Security::AUTHENTICATION_ERROR;
         $lastUsernameKey = Security::LAST_USERNAME;
     } else {
         // BC for SF < 2.6
         $authErrorKey = SecurityContextInterface::AUTHENTICATION_ERROR;
         $lastUsernameKey = SecurityContextInterface::LAST_USERNAME;
     }
     // get the error if any (works with forward and redirect -- see below)
     if ($request->attributes->has($authErrorKey)) {
         $error = $request->attributes->get($authErrorKey);
     } elseif (null !== $session && $session->has($authErrorKey)) {
         $error = $session->get($authErrorKey);
         $session->remove($authErrorKey);
     } else {
         $error = null;
     }
     if (!$error instanceof AuthenticationException) {
         $error = null;
         // The value does not come from the security component.
     }
     // last username entered by the user
     $lastUsername = null === $session ? '' : $session->get($lastUsernameKey);
     //ladybug_dump($error);
     return array('last_username' => $lastUsername, 'error' => $error);
     /*ladybug_dump($error);
       return array(
           'last_username' => $request->getSession()->get(SecurityContext::LAST_USERNAME),
           'errors'         => $error,
       );*/
 }
 /**
  * Render the provided content.
  *
  * When using the publish workflow, enable the publish_workflow.request_listener
  * of the core bundle to have the contentDocument as well as the route
  * checked for being published.
  * We don't need an explicit check in this method.
  *
  * @param Request $request
  * @param object  $contentDocument
  * @param string  $contentTemplate Symfony path of the template to render
  *                                 the content document. If omitted, the
  *                                 default template is used.
  *
  * @return Response
  */
 public function indexAction(Request $request, $contentDocument, $contentTemplate = null)
 {
     $contentTemplate = $contentTemplate ?: $this->defaultTemplate;
     $contentTemplate = str_replace(array('{_format}', '{_locale}'), array($request->getRequestFormat(), $request->getLocale()), $contentTemplate);
     $params = $this->getParams($request, $contentDocument);
     return $this->renderResponse($contentTemplate, $params);
 }
Example #17
0
 public function add(Application $app, Request $request)
 {
     $productClassId = $request->get('product_class_id');
     $quantity = $request->request->has('quantity') ? $request->get('quantity') : 1;
     $app['eccube.service.cart']->addProduct($productClassId, $quantity)->save();
     return $app->redirect($app->url('cart'));
 }
Example #18
0
 public function mobileSelectAction(Request $request)
 {
     $operationMobile = $this->getSettingService()->get('operation_mobile', array());
     $courseGrids = $this->getSettingService()->get('operation_course_grids', array());
     $settingMobile = $this->getSettingService()->get('mobile', array());
     $default = array('courseIds' => '');
     $mobile = array_merge($default, $courseGrids);
     if ($request->getMethod() == 'POST') {
         $courseGrids = $request->request->all();
         $mobile = array_merge($operationMobile, $settingMobile, $courseGrids);
         $this->getSettingService()->set('operation_mobile', $operationMobile);
         $this->getSettingService()->set('operation_course_grids', $courseGrids);
         $this->getSettingService()->set('mobile', $mobile);
         $this->getLogService()->info('system', 'update_settings', "更新移动客户端设置", $mobile);
         $this->setFlashMessage('success', '移动客户端设置已保存!');
     }
     $courseIds = explode(",", $mobile['courseIds']);
     $courses = $this->getCourseService()->findCoursesByIds($courseIds);
     $courses = ArrayToolkit::index($courses, 'id');
     $sortedCourses = array();
     foreach ($courseIds as $value) {
         if (!empty($value)) {
             $sortedCourses[] = $courses[$value];
         }
     }
     return $this->render('TopxiaAdminBundle:System:course-select.html.twig', array('mobile' => $mobile, 'courses' => $sortedCourses));
 }
 /**
  * {@inheritdoc}
  */
 public function filter(RouteCollection $collection, Request $request)
 {
     // The Content-type header does not make sense on GET requests, because GET
     // requests do not carry any content. Nothing to filter in this case.
     if ($request->isMethod('GET')) {
         return $collection;
     }
     $format = $request->getContentType();
     foreach ($collection as $name => $route) {
         $supported_formats = array_filter(explode('|', $route->getRequirement('_content_type_format')));
         if (empty($supported_formats)) {
             // No restriction on the route, so we move the route to the end of the
             // collection by re-adding it. That way generic routes sink down in the
             // list and exact matching routes stay on top.
             $collection->add($name, $route);
         } elseif (!in_array($format, $supported_formats)) {
             $collection->remove($name);
         }
     }
     if (count($collection)) {
         return $collection;
     }
     // We do not throw a
     // \Symfony\Component\Routing\Exception\ResourceNotFoundException here
     // because we don't want to return a 404 status code, but rather a 415.
     throw new UnsupportedMediaTypeHttpException('No route found that matches "Content-Type: ' . $request->headers->get('Content-Type') . '"');
 }
 public function postAction(Request $request)
 {
     $repo = $this->get('tekstove.user.repository');
     /* @var $repo \Tekstove\ApiBundle\Model\User\UserRepository */
     $recaptchaSecret = $this->container->getParameter('tekstove_api.recaptcha.secret');
     $requestData = \json_decode($request->getContent(), true);
     $userData = $requestData['user'];
     $recaptchaData = $requestData['recaptcha'];
     $user = new User();
     try {
         $recaptcha = new \ReCaptcha\ReCaptcha($recaptchaSecret);
         $recaptchaResponse = $recaptcha->verify($recaptchaData['g-recaptcha-response']);
         if (!$recaptchaResponse->isSuccess()) {
             $recaptchaException = new UserHumanReadableException("Recaptcha validation failed");
             $recaptchaException->addError("recaptcha", "Validation failed");
             throw $recaptchaException;
         }
         $user->setUsername($userData['username']);
         $user->setMail($userData['mail']);
         $user->setPassword($this->hashPassword($userData['password']));
         $user->setapiKey(sha1(str_shuffle(uniqid())));
         $repo->save($user);
     } catch (UserHumanReadableException $e) {
         $view = $this->handleData($request, $e->getErrors());
         $view->setStatusCode(400);
         return $view;
     }
 }
 /**
  * {@inheritDoc}
  *
  * This will return any document found at the url or up the path to the
  * prefix. If any of the documents does not extend the symfony Route
  * object, it is filtered out. In the extreme case this can also lead to an
  * empty list being returned.
  */
 public function getRouteCollectionForRequest(Request $request)
 {
     $url = $request->getPathInfo();
     $candidates = $this->getCandidates($url);
     $collection = new RouteCollection();
     if (empty($candidates)) {
         return $collection;
     }
     try {
         $routes = $this->dm->findMany($this->className, $candidates);
         // filter for valid route objects
         // we can not search for a specific class as PHPCR does not know class inheritance
         // but optionally we could define a node type
         foreach ($routes as $key => $route) {
             if ($route instanceof SymfonyRoute) {
                 if (preg_match('/.+\\.([a-z]+)$/i', $url, $matches)) {
                     if ($route->getDefault('_format') === $matches[1]) {
                         continue;
                     }
                     $route->setDefault('_format', $matches[1]);
                 }
                 // SYMFONY 2.1 COMPATIBILITY: tweak route name
                 $key = trim(preg_replace('/[^a-z0-9A-Z_.]/', '_', $key), '_');
                 $collection->add($key, $route);
             }
         }
     } catch (RepositoryException $e) {
         // TODO: how to determine whether this is a relevant exception or not?
         // for example, getting /my//test (note the double /) is just an invalid path
         // and means another router might handle this.
         // but if the PHPCR backend is down for example, we want to alert the user
     }
     return $collection;
 }
Example #22
0
 /**
  * @Route("/search", name="search")
  * @param Request $request
  * @return JsonResponse
  */
 public function indexAction(Request $request)
 {
     $searchStr = $request->get('search');
     $url = $this->container->getParameter('api')['search_url'] . $searchStr;
     $httpResponse = $this->get('buzz.curl')->request($url);
     return new JsonResponse(json_decode($httpResponse->getContent(), true));
 }
 /**
  * @param FormInterface $form
  * @param Request $request
  * @return AccountUser|bool
  */
 public function process(FormInterface $form, Request $request)
 {
     if ($request->isMethod('POST')) {
         $form->submit($request);
         if ($form->isValid()) {
             $email = $form->get('email')->getData();
             /** @var AccountUser $user */
             $user = $this->userManager->findUserByUsernameOrEmail($email);
             if ($this->validateUser($form, $email, $user)) {
                 if (null === $user->getConfirmationToken()) {
                     $user->setConfirmationToken($user->generateToken());
                 }
                 try {
                     $this->userManager->sendResetPasswordEmail($user);
                     $user->setPasswordRequestedAt(new \DateTime('now', new \DateTimeZone('UTC')));
                     $this->userManager->updateUser($user);
                     return $user;
                 } catch (\Exception $e) {
                     $this->addFormError($form, 'oro.email.handler.unable_to_send_email');
                 }
             }
         }
     }
     return false;
 }
Example #24
0
 public function indexAction(Request $request, SessionInterface $session)
 {
     Util::checkUserIsLoggedInAndRedirect();
     $projectId = $request->get('id');
     $project = $this->getRepository(YongoProject::class)->getById($projectId);
     $emptyName = false;
     $alreadyExists = false;
     if ($request->request->has('confirm_new_release')) {
         $name = Util::cleanRegularInputField($request->request->get('name'));
         $description = Util::cleanRegularInputField($request->request->get('description'));
         if (empty($name)) {
             $emptyName = true;
         }
         $releasesDuplicate = $this->getRepository(YongoProject::class)->getVersionByName($projectId, $name);
         if ($releasesDuplicate) {
             $alreadyExists = true;
         }
         if (!$emptyName && !$alreadyExists) {
             $currentDate = Util::getServerCurrentDateTime();
             $this->getRepository(YongoProject::class)->addVersion($projectId, $name, $description, $currentDate);
             $this->getLogger()->addInfo('ADD Project Version ' . $name, $this->getLoggerContext());
             return new RedirectResponse('/yongo/administration/project/versions/' . $projectId);
         }
     }
     $menuSelectedCategory = 'project';
     $sectionPageTitle = $session->get('client/settings/title_name') . ' / ' . SystemProduct::SYS_PRODUCT_YONGO_NAME . ' / Create Project Version';
     return $this->render(__DIR__ . '/../../../../Resources/views/administration/project/version/Add.php', get_defined_vars());
 }
Example #25
0
 public function processAction(Request $req, Application $app)
 {
     $template_data = [];
     $code = Response::HTTP_OK;
     try {
         $page = new Login($app['sentry']);
         if ($page->authenticate($req->get('email'), $req->get('password'))) {
             // This is for redirecting to OAuth endpoint if we arrived
             // as part of the Authorization Code Grant flow.
             if ($this->app['session']->has('redirectTo')) {
                 return new RedirectResponse($this->app['session']->get('redirectTo'));
             }
             return $this->redirectTo('dashboard');
         }
         $errorMessage = $page->getAuthenticationMessage();
         $template_data = ['email' => $req->get('email')];
         $code = Response::HTTP_BAD_REQUEST;
     } catch (Exception $e) {
         $errorMessage = $e->getMessage();
         $template_data = ['email' => $req->get('email')];
         $code = Response::HTTP_BAD_REQUEST;
     }
     // Set Success Flash Message
     $this->app['session']->set('flash', ['type' => 'error', 'short' => 'Error', 'ext' => $errorMessage]);
     $template_data['flash'] = $this->getFlash($app);
     return $this->render('login.twig', $template_data, $code);
 }
 /**
  * @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;
 }
 /**
  * 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;
     }
 }
 /**
  * Get a single product
  *
  * @param Request $request
  * @param string  $identifier
  *
  * @ApiDoc(
  *      description="Get a single product",
  *      resource=true
  * )
  *
  * @return Response
  */
 public function getAction(Request $request, $identifier)
 {
     $userContext = $this->get('pim_user.context.user');
     $availableChannels = array_keys($userContext->getChannelChoicesWithUserChannel());
     $availableLocales = $userContext->getUserLocaleCodes();
     $channels = $request->get('channels', $request->get('channel', null));
     if ($channels !== null) {
         $channels = explode(',', $channels);
         foreach ($channels as $channel) {
             if (!in_array($channel, $availableChannels)) {
                 return new Response(sprintf('Channel "%s" does not exist or is not available', $channel), 403);
             }
         }
     }
     $locales = $request->get('locales', $request->get('locale', null));
     if ($locales !== null) {
         $locales = explode(',', $locales);
         foreach ($locales as $locale) {
             if (!in_array($locale, $availableLocales)) {
                 return new Response(sprintf('Locale "%s" does not exist or is not available', $locale), 403);
             }
         }
     }
     return $this->handleGetRequest($identifier, $channels, $locales);
 }
Example #29
0
 /**
  * Handles response for csv-request.
  *
  * @param ViewHandler $handler
  * @param View $view
  * @param Request $request
  * @param string $format
  *
  * @return Response
  *
  * @throws ObjectNotSupportedException
  */
 public function createResponse(ViewHandler $handler, View $view, Request $request, $format)
 {
     if (!$view->getData() instanceof ListRepresentation) {
         throw new ObjectNotSupportedException($view);
     }
     $viewData = $view->getData();
     $data = new CallbackCollection($viewData->getData(), [$this, 'prepareData']);
     $fileName = sprintf('%s.csv', $viewData->getRel());
     $config = new ExporterConfig();
     $exporter = new Exporter($config);
     $data->rewind();
     if ($row = $data->current()) {
         $config->setColumnHeaders(array_keys($row));
     }
     $config->setDelimiter($this->convertValue($request->get('delimiter', ';'), self::$delimiterMap));
     $config->setNewline($this->convertValue($request->get('newLine', '\\n'), self::$newLineMap));
     $config->setEnclosure($request->get('enclosure', '"'));
     $config->setEscape($request->get('escape', '\\'));
     $response = new StreamedResponse();
     $disposition = $response->headers->makeDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $fileName, $fileName);
     $response->headers->set('Content-Type', 'text/csv');
     $response->headers->set('Content-Disposition', $disposition);
     $response->setCallback(function () use($data, $exporter) {
         $exporter->export('php://output', $data);
     });
     $response->send();
     return $response;
 }
 /**
  * Deletes a UserEvent entity.
  *
  * @Route("/{idEvent}", name="userevent_delete")
  * @Method({"GET", "DELETE"})
  */
 public function deleteAction($idEvent, Request $request)
 {
     $userEventService = $this->get("user_event_manager");
     $userEventService->deleteUserEvent($idEvent);
     $request->getSession()->getFlashBag()->add('success', 'Sėkmingai palikote renginį');
     return $this->redirectToRoute('homepage');
 }