get() 공개 메소드

This method is mainly useful for libraries that want to provide some flexibility. If you don't need the flexibility in controllers, it is better to explicitly get request parameters from the appropriate public property instead (attributes, query, request). Order of precedence: PATH (routing placeholders or custom attributes), GET, BODY
public get ( string $key, mixed $default = null ) : mixed
$key string the key
$default mixed the default value if the parameter key does not exist
리턴 mixed
예제 #1
1
파일: Records.php 프로젝트: Twiebie/bolt
 /**
  * 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]);
 }
 /**
  * @Route("/stock/api/variation/update/qty")
  * @Method("POST")
  */
 public function updateStockItemsByApiAction(Request $request)
 {
     $response = new Response();
     $response->headers->set('Content-Type', 'application/json');
     $id = (int) $request->get('id');
     $newQty = (int) $request->get('qtyStock');
     $em = $this->getDoctrine()->getManager();
     $entity = $em->getRepository('HypersitesStockBundle:ProductVariation')->find($id);
     if ($entity === null) {
         $response->setStatusCode(204, "The requested variation did not exist");
         return $response;
     }
     $oldQtyStock = $entity->getQtyStock();
     if ($oldQtyStock > $newQty) {
         $diference = $oldQtyStock - $newQty;
         $items = $entity->getItems();
     } else {
         $diference = $newQty - $oldQtyStock;
         for ($interations = 0; $interations < $diference; $interations++) {
             $item = new Item();
             $item->setProductVariation($entity);
             $em->persist($item);
         }
     }
     $entity->setQtyStock($newQty);
     $em->persist($entity);
     $em->flush();
     $response->setContent("New quantity is {$entity->getQtyStock()}");
     return $response;
 }
예제 #3
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);
 }
 /**
  * @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);
 }
 /**
  * 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);
 }
 public function indexAction(Request $request, SessionInterface $session)
 {
     Util::checkUserIsLoggedInAndRedirect();
     $clientId = $session->get('client/id');
     $workflowId = $request->get('id');
     $stepIdFrom = $request->get('step_id_from');
     $stepIdTo = $request->get('step_id_to');
     $projectId = $request->get('project_id');
     $issueId = $request->get('issue_id');
     $assignableUsers = $this->getRepository(YongoProject::class)->getUsersWithPermission($projectId, Permission::PERM_ASSIGNABLE_USER);
     $projectData = $this->getRepository(YongoProject::class)->getById($projectId);
     $issue = $this->getRepository(Issue::class)->getByIdSimple($issueId);
     $workflowData = $this->getRepository(Workflow::class)->getDataByStepIdFromAndStepIdTo($workflowId, $stepIdFrom, $stepIdTo);
     $screenId = $workflowData['screen_id'];
     $allUsers = $this->getRepository(UbirimiUser::class)->getByClientId($session->get('client/id'));
     $screenData = $this->getRepository(Screen::class)->getDataById($screenId);
     $screenMetadata = $this->getRepository(Screen::class)->getMetaDataById($screenId);
     $resolutions = $this->getRepository(IssueSettings::class)->getAllIssueSettings('resolution', $clientId);
     $projectComponents = $this->getRepository(YongoProject::class)->getComponents($projectId);
     $projectVersions = $this->getRepository(YongoProject::class)->getVersions($projectId);
     $htmlOutput = '';
     $htmlOutput .= '<table class="modal-table">';
     $reporterUsers = $this->getRepository(YongoProject::class)->getUsersWithPermission($projectId, Permission::PERM_CREATE_ISSUE);
     $fieldCodeNULL = null;
     $fieldData = $this->getRepository(YongoProject::class)->getFieldInformation($projectData['issue_type_field_configuration_id'], $issue['type_id'], 'array');
     return $this->render(__DIR__ . '/../../Resources/views/issue/TransitionDialog.php', get_defined_vars());
 }
 public function storeAction(NotificationConfiguration $notificationConfiguration, Request $request)
 {
     $this->assertUserRights(UserRole::ROLE_ADMIN);
     $notificationConfiguration->setNotificationCondition($request->get('condition'));
     if ($request->get('notify_ack') === "true") {
         $notificationConfiguration->setNotifyAcknowledge(true);
     } else {
         $notificationConfiguration->setNotifyAcknowledge(false);
     }
     if ($request->get('notify_all') === "true") {
         $notificationConfiguration->setNotifyAll(true);
         $notificationConfiguration->clearConnectedTools();
     } else {
         $notificationConfiguration->setNotifyAll(false);
         $notificationConfiguration->clearConnectedTools();
         $tools = $request->get('tools');
         if (!is_null($tools)) {
             foreach ($tools as $toolId => $value) {
                 $tool = $this->getDoctrine()->getRepository('KoalamonIncidentDashboardBundle:Tool')->find((int) $toolId);
                 /** @var Tool $tool */
                 if ($tool->getProject() == $this->getProject()) {
                     $notificationConfiguration->addConnectedTool($tool);
                 }
             }
         }
     }
     $em = $this->getDoctrine()->getManager();
     $em->persist($notificationConfiguration);
     $em->flush();
     return $this->redirectToRoute('koalamon_notification_alerts_home');
 }
 /**
  * {@inheritdoc}
  */
 public function listAction(Request $request = null)
 {
     if (false === $this->admin->isGranted('LIST')) {
         throw new AccessDeniedException();
     }
     if ($listMode = $request->get('_list_mode', 'mosaic')) {
         $this->admin->setListMode($listMode);
     }
     $datagrid = $this->admin->getDatagrid();
     $filters = $request->get('filter');
     // set the default context
     if (!$filters || !array_key_exists('context', $filters)) {
         $context = $this->admin->getPersistentParameter('context', $this->get('sonata.media.pool')->getDefaultContext());
     } else {
         $context = $filters['context']['value'];
     }
     $datagrid->setValue('context', null, $context);
     // retrieve the main category for the tree view
     $category = $this->container->get('sonata.classification.manager.category')->getRootCategory($context);
     if (!$filters) {
         $datagrid->setValue('category', null, $category->getId());
     }
     if ($request->get('category')) {
         $contextInCategory = $this->container->get('sonata.classification.manager.category')->findBy(array('id' => (int) $request->get('category'), 'context' => $context));
         if (!empty($contextInCategory)) {
             $datagrid->setValue('category', null, $request->get('category'));
         } else {
             $datagrid->setValue('category', null, $category->getId());
         }
     }
     $formView = $datagrid->getForm()->createView();
     // set the theme for the current Admin Form
     $this->get('twig')->getExtension('form')->renderer->setTheme($formView, $this->admin->getFilterTheme());
     return $this->render($this->admin->getTemplate('list'), array('action' => 'list', 'form' => $formView, 'datagrid' => $datagrid, 'root_category' => $category, 'csrf_token' => $this->getCsrfToken('sonata.batch')));
 }
예제 #9
0
 /**
  * @param \Symfony\Component\HttpFoundation\Request $request
  *
  * @return array
  */
 public function indexAction(Request $request)
 {
     $idPage = $this->castId($request->get(CmsPageTable::REQUEST_ID_PAGE));
     $idForm = (int) $request->get(self::ID_FORM);
     $type = CmsConstants::RESOURCE_TYPE_PAGE;
     $block = $this->getQueryContainer()->queryBlockByIdPage($idPage)->findOne();
     $cmsPageEntity = $this->findCmsPageById($idPage);
     $localeTransfer = $this->getLocaleTransfer($cmsPageEntity);
     $fkLocale = $this->getLocaleByCmsPage($cmsPageEntity);
     if ($block === null) {
         $title = $cmsPageEntity->getUrl();
     } else {
         $type = CmsConstants::RESOURCE_TYPE_BLOCK;
         $title = $block->getName();
     }
     $placeholders = $this->findPagePlaceholders($cmsPageEntity);
     $glossaryMappingArray = $this->extractGlossaryMapping($idPage, $localeTransfer);
     $forms = [];
     $formViews = [];
     foreach ($placeholders as $place) {
         $form = $this->createPlaceholderForm($request, $glossaryMappingArray, $place, $idPage, $fkLocale);
         $forms[] = $form;
         $formViews[] = $form->createView();
     }
     if ($idForm !== null && $request->isXmlHttpRequest()) {
         return $this->handleAjaxRequest($forms, $idForm, $localeTransfer);
     }
     return ['idPage' => $idPage, 'title' => $title, 'type' => $type, 'forms' => $formViews, 'localeTransfer' => $localeTransfer];
 }
 /**
  * Get token created by Stripe and order amount from the form & save them in session
  */
 public function getStripeTokenAndAmount()
 {
     // Get Stripe token
     $this->request->getSession()->set('stripeToken', $this->request->get('thelia_order_payment')['stripe_token']);
     // Get order amount
     $this->request->getSession()->set('stripeAmount', $this->request->get('thelia_order_payment')['stripe_amount']);
 }
예제 #11
0
 public function facility(Application $app, Request $request)
 {
     $ret = ['tasks' => []];
     $job = new RecordMoverJob(null, null, $this->translator);
     switch ($request->get('ACT')) {
         case 'CALCTEST':
             $sxml = simplexml_load_string($request->get('xml'));
             if (isset($sxml->tasks->task)) {
                 foreach ($sxml->tasks->task as $sxtask) {
                     $ret['tasks'][] = $job->calcSQL($app, $sxtask, false);
                 }
             }
             break;
         case 'PLAYTEST':
             $sxml = simplexml_load_string($request->get('xml'));
             if (isset($sxml->tasks->task)) {
                 foreach ($sxml->tasks->task as $sxtask) {
                     $ret['tasks'][] = $job->calcSQL($app, $sxtask, true);
                 }
             }
             break;
         case 'CALCSQL':
             $sxml = simplexml_load_string($request->get('xml'));
             if (isset($sxml->tasks->task)) {
                 foreach ($sxml->tasks->task as $sxtask) {
                     $ret['tasks'][] = $job->calcSQL($app, $sxtask, false);
                 }
             }
             break;
         default:
             throw new NotFoundHttpException('Route not found.');
     }
     return $app->json($ret);
 }
 /**
  * @param Request $request
  *
  * @return array
  * @throws LibratoException
  */
 protected function getConfig(Request $request)
 {
     $name = $request->get('name');
     if (empty($name)) {
         throw new LibratoException('Empty chart name');
     }
     $apiUser = $request->get('apiUser');
     if (empty($apiUser)) {
         throw new LibratoException('Empty apiUser');
     }
     $apiToken = $request->get('apiToken');
     if (empty($apiToken)) {
         throw new LibratoException('Empty apiToken');
     }
     $action = $request->get('action');
     if (empty($action)) {
         throw new LibratoException('Empty action');
     }
     $begin = $request->get('begin', '-30minutes');
     if (!isset($this->methodsMap[$action])) {
         throw new LibratoException('Unrecognized action');
     }
     $method = $this->methodsMap[$action]['method'];
     $template = $this->methodsMap[$action]['template'];
     if (!method_exists($this->libratoService, $method)) {
         throw new LibratoException('Unrecognized method');
     }
     return ['name' => $name, 'apiUser' => $apiUser, 'apiToken' => $apiToken, 'method' => $method, 'template' => $template, 'begin' => $begin];
 }
 /**
  * @param Request $request
  * @param array   $mapping
  *
  * @return PaginateFinderConfiguration
  */
 public static function generateFromRequest(Request $request, array $mapping = array())
 {
     $configuration = new static();
     $configuration->setSearch($request->get('search'));
     $configuration->setPaginateConfiguration($request->get('order'), $request->get('start'), $request->get('length'), $mapping);
     return $configuration;
 }
예제 #14
0
 public function download(Request $request)
 {
     $startdate = $request->get("startdate");
     $enddate = $request->get("enddate");
     if (!$startdate) {
         throw new \Exception("startdate parameter is required");
     }
     if (!$enddate) {
         throw new \Exception("enddate parameter is required");
     }
     $records = $this->storageInterface->between($startdate, $enddate);
     $headerSent = false;
     $output = "";
     foreach ($records as $row) {
         if ($row["data"] == 'null') {
             continue;
         }
         $data = json_decode($row["data"], true);
         ksort($data);
         $outputData = ["datetime" => $row["datetime"]];
         $outputData = array_merge($outputData, $data);
         if (!$headerSent) {
             $output .= "\"" . implode("\",\"", array_keys($outputData)) . "\"\n";
             $headerSent = true;
         }
         $output .= "\"" . implode("\",\"", array_values($outputData)) . "\"\n";
     }
     return new Response($output, 200, ["Content-Type" => "application/octet-stream", "Content-Disposition" => "attachment; filename=\"boiler.csv\""]);
 }
예제 #15
0
 /**
  * @Rest\View
  * @Rest\Patch("/tools/{id}")
  */
 public function updateToolAction($id, Request $request)
 {
     /** @var $currentUser User */
     $currentUser = $this->container->get('security.context')->getToken()->getUser();
     $em = $this->getDoctrine()->getManager();
     /** @var $tool Tool */
     $tool = $em->find('AcmeEdelaBundle:Tool', $id);
     if (!$tool) {
         return $this->createNotFoundException();
     }
     $userTool = $tool->getUserTools()->matching(Criteria::create()->where(Criteria::expr()->eq('user', $currentUser)))->first();
     if (!$userTool) {
         $userTool = new UserTool();
         $userTool->setUser($currentUser)->setTool($tool);
     }
     if ($request->get('is_enabled')) {
         if ($userTool->getIsAvailable() || !$tool->getCost() && $currentUser->getLevel() > $tool->getMinLevel()) {
             $userTool->setIsAvailable(true);
             $currentEnable = $userTool->getIsEnabled();
             $userTool->setIsEnabled(!$currentEnable);
         }
     }
     if ($request->get('buy_exp')) {
         if (!$userTool->getIsAvailable() && $currentUser->getExpBill() >= $tool->getCost() && $currentUser->getLevel() >= $tool->getMinLevel()) {
             $em->getRepository('AcmeUserBundle:User')->spendExp($currentUser, $tool->getCost());
             $userTool->setIsAvailable(true);
         }
     }
     $em->persist($userTool);
     $em->flush();
     $serializer = $this->get('jms_serializer');
     $toolArray = json_decode($serializer->serialize($tool, 'json'), true);
     $userToolArray = json_decode($serializer->serialize($userTool, 'json'), true);
     return ['success' => true, 'data' => array_merge($toolArray, $userToolArray)];
 }
예제 #16
0
 public function indexAction(Request $request, SessionInterface $session)
 {
     Util::checkUserIsLoggedInAndRedirect();
     $screenId = $request->get('id');
     $screenMetadata = $this->getRepository(Screen::class)->getMetaDataById($screenId);
     if ($screenMetadata['client_id'] != $session->get('client/id')) {
         return new RedirectResponse('/general-settings/bad-link-access-denied');
     }
     $position = $request->get('position');
     $fieldId = $request->get('field_id');
     if ($fieldId && $position) {
         $this->getRepository(Screen::class)->updatePositionForField($screenId, $fieldId, $position);
         return new RedirectResponse('/yongo/administration/screen/configure/' . $screenId);
     }
     $fields = $this->getRepository(Field::class)->getByClient($session->get('client/id'));
     if ($request->request->has('add_screen_field')) {
         $fieldId = Util::cleanRegularInputField($request->request->get('field'));
         if ($fieldId != -1) {
             $currentDate = Util::getServerCurrentDateTime();
             $lastOrder = $this->getRepository(Screen::class)->getLastOrderNumber($screenId);
             $this->getRepository(Screen::class)->addData($screenId, $fieldId, $lastOrder + 1, $currentDate);
             $this->getLogger()->addInfo('UPDATE Yongo Screen Data ' . $screenMetadata['name'], $this->getLoggerContext());
             return new RedirectResponse('/yongo/administration/screen/configure/' . $screenId);
         }
     }
     $screenData = $this->getRepository(Screen::class)->getDataById($screenId);
     $menuSelectedCategory = 'issue';
     $source = $request->get('source');
     $projectId = null;
     if ($source == 'project_screen' || $source == 'project_field') {
         $projectId = $request->get('project_id');
     }
     $sectionPageTitle = $session->get('client/settings/title_name') . ' / ' . SystemProduct::SYS_PRODUCT_YONGO_NAME . ' / Update Screen';
     return $this->render(__DIR__ . '/../../../Resources/views/administration/screen/Configure.php', get_defined_vars());
 }
 /**
  * @param Request $request
  * @param string $hashOrHeight
  * @return \Symfony\Component\HttpFoundation\Response
  */
 public function __invoke(Request $request, $hashOrHeight)
 {
     // Port from: https://github.com/blockcypher/explorer/blob/master/blocks/views.py#L19
     $BLOCKCYPHER_PUBLIC_KEY = 'c0afcccdde5081d6429de37d16166ead';
     $token = $request->get('token');
     if (!$token) {
         //$this->createAccessDeniedException();
         $token = $BLOCKCYPHER_PUBLIC_KEY;
         // TODO: get from app parameters.yml
     }
     // TODO: if not valid address redirect to coinSymbol overview
     $coinSymbol = $request->get('coinSymbol');
     // Transactions pagination
     $params = array('instart' => 1, 'outstart' => 1, 'limit' => 1);
     $blockDetailsArray = $this->blockServiceFacade->getBlockDetails($hashOrHeight, $params, $coinSymbol, $token);
     // TODO: It seems Python version does some kind of short with transactions.
     // https://github.com/blockcypher/blockcypher-python/blob/e5dfd5fb1065fb54f8464f2c04279dc90aed86d1/blockcypher/api.py#L652
     $template = $this->getBaseTemplatePrefix() . ':BlockOverview:block_overview.html';
     // TODO
     $currentPage = 1;
     $maxPages = 0;
     // get_max_pages(num_items=block_details['n_tx'], items_per_page=TXNS_PER_PAGE),
     $apiUrl = "https://api.blockcypher.com/v1/{$coinSymbol}/block/{$hashOrHeight}/";
     // TODO: get base url from php-client const?
     return $this->templating->renderResponse($template . '.' . $this->getEngine(), array('is_home' => false, 'user' => array('is_authenticated' => true), 'messages' => array(), 'coin_symbol' => $coinSymbol, 'api_url' => $apiUrl, 'block_details' => $blockDetailsArray, 'current_page' => $currentPage, 'max_pages' => $maxPages));
 }
    /**
     * {@inheritdoc}
     */
    protected function attemptAuthentication(Request $request)
    {
        if ($this->options['post_only'] && 'post' !== strtolower($request->getMethod())) {
            if (null !== $this->logger) {
                $this->logger->debug(sprintf('Authentication method not supported: %s.', $request->getMethod()));
            }

            return null;
        }

        if (null !== $this->csrfProvider) {
            $csrfToken = $request->get($this->options['csrf_parameter']);

            if (false === $this->csrfProvider->isCsrfTokenValid($this->options['csrf_page_id'], $csrfToken)) {
                throw new InvalidCsrfTokenException('Invalid CSRF token.');
            }
        }

        $username = trim($request->get($this->options['username_parameter']));
        $password = $request->get($this->options['password_parameter']);

        $request->getSession()->set(SecurityContextInterface::LAST_USERNAME, $username);

        return $this->authenticationManager->authenticate(new UsernamePasswordToken($username, $password, $this->providerKey));
    }
예제 #19
0
 /**
  * Create Pipeline entities via ajax.
  *
  * @Route("/nodeadd", name="ajax_createnode")
  * @Method("GET")
  */
 public function ajaxCreateNode(Request $request)
 {
     $em = $this->getDoctrine()->getManager();
     $description = $request->get('description');
     $idBl = $request->get('idBl');
     $node = $request->get('node');
     $edge = $request->get('edge');
     $port = $request->get('port');
     $object = new \BL\SGIBundle\Entity\Pipeline();
     $object->setDescription($description);
     $object->setIdBl($idBl);
     $object->setNode($node);
     $object->setEdge($edge);
     $object->setPort($port);
     $em->persist($object);
     $em->flush();
     /*$id_field=$em->getReference('BL\SGIBundle\Entity\FieldsAltinv', intval($object->getId()));     
          
          $id_altinv = $em->getReference('BL\SGIBundle\Entity\Altinv', $request->get('id_altinv'));     
       
          $object= new BlAltinv();
          $object->setIdField($id_field);
          $object->setIdAltinv( $id_altinv);
          $em->persist($object);
          $em->flush();
          */
     return new JsonResponse('...Autosaved');
     //return new JsonResponse($object->getId());
 }
예제 #20
0
 public function loginAction(Request $request, Application $app)
 {
     $username = $app->escape($request->get('username'));
     $password = $app->escape($request->get('password'));
     $rememberMe = $app->escape($request->get('rememberMe'));
     if (!$username || !$password) {
         $app->abort(Response::HTTP_BAD_REQUEST, 'Missing parameters');
     }
     $user = $app['repository.user']->findByUsername($username);
     if (!$user) {
         $app->abort(Response::HTTP_NOT_FOUND, 'User not found');
     }
     if (password_verify($password, $user->getPassword())) {
         $user->setLastSeen(new \DateTime('now'));
         $user->setLastIP($request->headers->get('referer'));
         $user->setFailedLogins(0);
         $app['repository.user']->save($user);
         //$access_query = 'SELECT user_level FROM users_access WHERE user_id = ' . $account['id'];
         //$access       = $app['db']->fetchAssoc($access_query);
         $permissions = [];
         //foreach ($access as $accessLevel) {
         //    array_push($permissions, $app['api.accessLevels'][$accessLevel]);
         //}
         $exp = $rememberMe ? time() + 60 * 60 * 24 * 30 : time() + 60 * 60 * 24;
         // expire in 30 days or 24h
         $user = ['id' => $user->getId(), 'username' => $user->getUsername(), 'permissions' => $permissions, 'rememberMe' => $rememberMe];
         $token = $app['jwt']->createToken($request, $exp, $user);
     } else {
         $user->setFailedLogins($user->getFailedLogins() + 1);
         $app['repository.user']->save($user);
         $app->abort(Response::HTTP_FORBIDDEN, 'Wrong password');
     }
     return json_encode(['token' => $token], JSON_NUMERIC_CHECK);
 }
 /**
  * Update progression of a User.
  *
  * @param User                           $user
  * @param \Innova\PathBundle\Entity\Step $step
  * @param Request                        $request
  *
  * @return \Symfony\Component\HttpFoundation\JsonResponse
  *
  * @Route(
  *     "",
  *     name = "innova_path_progression_update"
  * )
  * @Method("PUT")
  */
 public function updateAction(User $user, Step $step, Request $request)
 {
     $status = $request->get('user_progression_status');
     $authorized = $request->get('user_progression_authorized');
     $progression = $this->userProgressionManager->update($step, $user, $status, $authorized);
     return new JsonResponse(['progression' => $progression]);
 }
예제 #22
0
 public function processResetAction(Request $req)
 {
     $user_id = $req->get('user_id');
     $reset_code = $req->get('reset_code');
     if (empty($reset_code)) {
         throw new Exception();
     }
     $form_options = ['user_id' => $user_id, 'reset_code' => $reset_code];
     $form = $this->service('form.factory')->create(new ResetForm(), $form_options);
     if (!$form->isValid()) {
         return $this->render('user/reset_password.twig', ['form' => $form->createView()]);
     }
     $errorMessage = "The reset you have requested appears to be invalid, please try again.";
     $error = 0;
     try {
         /* @var Sentry $sentry */
         $sentry = $this->service('sentry');
         $user = $sentry->getUserProvider()->findById($req->get('user_id'));
     } catch (UserNotFoundException $e) {
         $error++;
     }
     if (!$user->checkResetPasswordCode($req->get('reset_code'))) {
         $error++;
     }
     if ($error > 0) {
         $this->service('session')->set('flash', ['type' => 'error', 'short' => 'Error', 'ext' => $errorMessage]);
     }
     return $this->redirectTo('forgot_password');
 }
예제 #23
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);
 }
 /**
  * @Route("/newPagePart", name="KunstmaanPagePartBundle_admin_newpagepart")
  * @Template("KunstmaanPagePartBundle:PagePartAdminTwigExtension:pagepart.html.twig")
  *
  * @param \Symfony\Component\HttpFoundation\Request $request
  *
  * @return array
  */
 public function newPagePartAction(Request $request)
 {
     $em = $this->getDoctrine()->getManager();
     $pageId = $request->get('pageid');
     $pageClassName = $request->get('pageclassname');
     $context = $request->get('context');
     $pagePartClass = $request->get('type');
     $page = $em->getRepository($pageClassName)->findOneById($pageId);
     $pagePartConfigurationReader = new PagePartConfigurationReader($this->container->get('kernel'));
     $pagePartAdminConfigurators = $pagePartConfigurationReader->getPagePartAdminConfigurators($page);
     $pagePartAdminConfigurator = null;
     foreach ($pagePartAdminConfigurators as $ppac) {
         if ($context == $ppac->getContext()) {
             $pagePartAdminConfigurator = $ppac;
         }
     }
     if (is_null($pagePartAdminConfigurator)) {
         throw new \RuntimeException(sprintf('No page part admin configurator found for context "%s".', $context));
     }
     $pagePartAdmin = new PagePartAdmin($pagePartAdminConfigurator, $em, $page, $context, $this->container);
     $pagePart = new $pagePartClass();
     $formFactory = $this->container->get('form.factory');
     $formBuilder = $formFactory->createBuilder(FormType::class);
     $pagePartAdmin->adaptForm($formBuilder);
     $id = 'newpp_' . time();
     $data = $formBuilder->getData();
     $data['pagepartadmin_' . $id] = $pagePart;
     $adminType = $pagePart->getDefaultAdminType();
     $adminTypeFqn = ClassUtils::getClass($adminType);
     $formBuilder->add('pagepartadmin_' . $id, $adminTypeFqn);
     $formBuilder->setData($data);
     $form = $formBuilder->getForm();
     $formview = $form->createView();
     return array('id' => $id, 'form' => $formview, 'pagepart' => $pagePart, 'pagepartadmin' => $pagePartAdmin, 'editmode' => true);
 }
예제 #25
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'));
 }
예제 #26
0
 public function authorizeAction(Request $request)
 {
     if (!$request->get('client_id')) {
         throw new NotFoundHttpException("Client id parameter {$request->get('client_id')} is missing.");
     }
     $clientManager = $this->container->get('fos_oauth_server.client_manager.default');
     $client = $clientManager->findClientByPublicId($request->get('client_id'));
     if (!$client instanceof Client) {
         throw new NotFoundHttpException("Client {$request->get('client_id')} is not found.");
     }
     $user = $this->container->get('security.context')->getToken()->getUser();
     $form = $this->container->get('newscoop.gimme.authorize.form');
     $formHandler = $this->container->get('newscoop.gimme.authorize.form_handler');
     $event = $this->container->get('event_dispatcher')->dispatch(OAuthEvent::PRE_AUTHORIZATION_PROCESS, new OAuthEvent($user, $this->getClient()));
     if ($event->isAuthorizedClient()) {
         $scope = $this->container->get('request')->get('scope', null);
         return $this->container->get('fos_oauth_server.server')->finishClientAuthorization(true, $user, $request, $scope);
     }
     if (($response = $formHandler->process()) !== false) {
         if (true === $this->container->get('session')->get('_fos_oauth_server.ensure_logout')) {
             $this->container->get('security.context')->setToken(null);
             $this->container->get('session')->invalidate();
         }
         $this->container->get('event_dispatcher')->dispatch(OAuthEvent::POST_AUTHORIZATION_PROCESS, new OAuthEvent($user, $this->getClient(), $formHandler->isAccepted()));
     }
     $templatesService = $this->container->get('newscoop.templates.service');
     $smarty = $templatesService->getSmarty();
     $smarty->assign('client', $client);
     return new Response($templatesService->fetchTemplate('oauth_authorize.tpl'));
 }
예제 #27
0
 /**
  * @Route(
  *      "/page-move",
  *      name="orob2b_cms_page_move"
  * )
  * @Method({"PUT"})
  * @AclAncestor("orob2b_cms_page_update")
  *
  * @param Request $request
  * @return JsonResponse
  */
 public function pageMoveAction(Request $request)
 {
     $nodeId = (int) $request->get('id');
     $parentId = (int) $request->get('parent');
     $position = (int) $request->get('position');
     return new JsonResponse($this->get('orob2b_cms.page_tree_handler')->moveNode($nodeId, $parentId, $position));
 }
 /**
  * Get json routing information for feasibility, for example:
  * /service/ride/repeatedFeasible?fromDate=01.06.2014&toDate=01.07.2025
  *      &weekday=1&time=12:23&direction=1&duration=23&additionalTime=2
  *
  * @Route("/ride/repeatedFeasible", name="tixiapp_service_ride_repeated_feasible")
  * @Method({"GET"})
  * @param Request $request
  * @return \Symfony\Component\HttpFoundation\JsonResponse
  */
 public function getRepeatedFeasibilityAction(Request $request)
 {
     /**@var $rideManagement RideManagement */
     $rideManagement = $this->container->get('tixi_app.ridemanagement');
     $fromDateStr = $request->get('fromDate');
     $toDateStr = $request->get('toDate');
     $timeStr = $request->get('time');
     $dayTime = \DateTime::createFromFormat('d.m.Y H:i', $fromDateStr . ' ' . $timeStr);
     if ($toDateStr !== '') {
         $toDate = \DateTime::createFromFormat('d.m.Y', $toDateStr);
     } else {
         $toDate = DateTimeService::getMaxDateTime();
     }
     if (!$dayTime) {
         $response = new JsonResponse();
         $response->setData(array('status' => '-1'));
         return $response;
     }
     $weekday = $request->get('weekday');
     $direction = $request->get('direction');
     $duration = $request->get('duration');
     $additionalTime = $request->get('additionalTime');
     try {
         $isFeasible = $rideManagement->checkRepeatedFeasibility($dayTime, $toDate, $weekday, $direction, $duration, $additionalTime);
     } catch (\Exception $e) {
         $response = new JsonResponse();
         $response->setData(array('status' => '-1'));
         return $response;
     }
     $response = new JsonResponse();
     $response->setData(array('status' => '0', 'isFeasible' => $isFeasible));
     return $response;
 }
예제 #29
0
파일: CsvHandler.php 프로젝트: sulu/sulu
 /**
  * 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;
 }
예제 #30
0
 public function edit(Request $request, Application $app)
 {
     $em = $app['orm.em'];
     $projectId = $request->get('projectId');
     $clientId = $request->get('clientId');
     $client = null;
     $clients = null;
     $project = null;
     $companyId = $app['session']->get('companyId');
     $company = $app['orm.em']->getRepository('Orcamentos\\Model\\Company')->find($companyId);
     if (isset($clientId)) {
         $client = $app['orm.em']->getRepository('Orcamentos\\Model\\Client')->find($clientId);
     }
     if (isset($projectId)) {
         $project = $em->getRepository('Orcamentos\\Model\\Project')->find($projectId);
         $client = $project->getClient();
     }
     if ($project && $project->getCompany()->getId() != $companyId) {
         return $this->redirectMessage($app, 'Projeto inválido', '/project');
     }
     if (!$client) {
         $clients = $app['orm.em']->getRepository('Orcamentos\\Model\\Client')->findBy(array('company' => $company));
     }
     return $app['twig']->render('project/edit.twig', array('clients' => $clients, 'client' => $client, 'project' => $project, 'active_page' => 'project'));
 }