protected function doKernelResponse(Request $request, Response $response) { if (!$response instanceof DataResponse) { return; } $routeName = $request->attributes->get('_route'); $route = $this->routes->get($routeName); if (!$route) { return; } $acceptedFormat = $route->getOption(RouteOptions::ACCEPTED_FORMAT); if (!$acceptedFormat) { $response->setContent(''); $response->setStatusCode(406); } if ($this->encoder->supportsEncoding($acceptedFormat) && $acceptedFormat === 'json') { $contentType = $request->getMimeType($acceptedFormat); $jsonResponse = new JsonResponse($response->getContent()); $response->setContent($jsonResponse->getContent()); $response->headers->set('Content-Type', $contentType); } elseif ($this->encoder->supportsEncoding($acceptedFormat)) { $contentType = $request->getMimeType($acceptedFormat); $content = $this->encoder->encode($response->getContent(), $acceptedFormat); $response->setContent($content); $response->headers->set('Content-Type', $contentType); } }
/** * @param string $content * @param int $status * @param array $headers * @return Response */ function response_json($content, $status = Response::HTTP_OK, array $headers = []) { // We have to do a little trick and do not allow WHMCS to sent all it's content. $response = new JsonResponse($content, $status, $headers); $response->sendHeaders(); die($response->getContent()); }
public function testConstructorWithSimpleTypes() { $response = new JsonResponse('foo'); $this->assertSame('"foo"', $response->getContent()); $response = new JsonResponse(0); $this->assertSame('0', $response->getContent()); $response = new JsonResponse(0.1); $this->assertSame('0.1', $response->getContent()); $response = new JsonResponse(true); $this->assertSame('true', $response->getContent()); }
/** * @param Request $request * @param mixed $data * * @return JsonResponse */ protected function getJsonResponse(Request $request, $data = null) { $date = new \DateTime(); $date->modify('+1 day'); $response = new JsonResponse($data); $response->setExpires($date); $response->setETag(md5($response->getContent())); $response->setPublic(); $response->isNotModified($request); $response->headers->set('X-Proudly-Crafted-By', "LesPolypodes.com"); // It's nerdy, I know that. return $response; }
public function getListAction(Application $app) { $userList = $this->repository->findAll(); $date = new \DateTime(); $date->modify('+' . self::MAX_AGE . ' seconds'); $response = new JsonResponse($userList, JsonResponse::HTTP_OK); $responseHash = sha1($response->getContent()); $response->setMaxAge(self::MAX_AGE); $response->setSharedMaxAge(self::MAX_AGE); $response->setExpires($date); $response->setETag($responseHash); $response->isNotModified($app['request']); return $response; }
public function testFailedPostUserRegistrationAction() { $this->configHandler->shouldReceive('getParameter')->with('allow_self_registration')->once()->andReturn(true); $bag = $this->getUserParameterBag(); $this->request->request = $bag; $error = $this->mock('Symfony\\Component\\Validator\\ConstraintViolation'); $error->shouldReceive('getPropertyPath')->once()->andReturn('username'); $error->shouldReceive('getMessage')->once()->andReturn('message'); $errorList = array($error); $this->validator->shouldReceive('validate')->once()->with(m::on(function (User $user) { return $user->getPlainPassword() === 'password' && $user->getUsername() === 'username' && $user->getFirstName() === 'firstname' && $user->getLastName() === 'lastname' && $user->getMail() === '*****@*****.**'; }))->andReturn($errorList); $response = new JsonResponse(array(array('property' => 'username', 'message' => 'message')), 422); $this->assertEquals($response->getContent(), $this->controller->postUserRegistrationAction('json')->getContent()); $this->assertInstanceOf('Symfony\\Component\\HttpFoundation\\JsonResponse', $this->controller->postUserRegistrationAction('json')); }
protected function uploadImage(Request $request, $user_type, $action) { $upl = $this->get('image_uploader'); $upl->setPicDir($this->container->getParameter('picture_dir')); $r = ['ok' => false]; try { $ret = $upl->upload($request, $user_type, $action); $r['ok'] = true; $r['id'] = $ret['id']; $r['src'] = $ret['uri']; unset($r['errors']); } catch (\Exception $e) { $r['errors'] = $e->getMessage(); } $response = new JsonResponse($r); return new Response($response->getContent()); //т.к. приемник - ифрейм, это эмуляция аякса(иначе поломается) }
/** * Undeletes the entity * * @param int $objectId * * @return JsonResponse */ public function undeleteAction($objectId) { $session = $this->factory->getSession(); $formId = $this->request->query->get('formId'); $fields = $session->get('mautic.form.' . $formId . '.fields.modified', array()); $delete = $session->get('mautic.form.' . $formId . '.fields.deleted', array()); //ajax only for form fields if (!$this->request->isXmlHttpRequest() || !$this->factory->getSecurity()->isGranted(array('form:forms:editown', 'form:forms:editother', 'form:forms:create'), 'MATCH_ONE')) { return $this->accessDenied(); } $formField = array_key_exists($objectId, $fields) ? $fields[$objectId] : null; if ($this->request->getMethod() == 'POST' && $formField !== null) { //set custom params from event if applicable $customParams = !empty($formField['isCustom']) ? $formField['customParameters'] : array(); //add the field to the delete list if (in_array($objectId, $delete)) { $key = array_search($objectId, $delete); unset($delete[$key]); $session->set('mautic.form.' . $formId . '.fields.deleted', $delete); } if (!empty($customParams)) { $template = $customParams['template']; } else { $template = 'MauticFormBundle:Field:' . $formField['type'] . '.html.php'; } //prevent undefined errors $entity = new Field(); $blank = $entity->convertToArray(); $formField = array_merge($blank, $formField); $dataArray = array('mauticContent' => 'formField', 'success' => 1, 'target' => '#mauticform_' . $objectId, 'route' => false, 'fieldId' => $objectId, 'fieldHtml' => $this->renderView($template, array('inForm' => true, 'field' => $formField, 'id' => $objectId, 'deleted' => false, 'formId' => $formId))); } else { $dataArray = array('success' => 0); } $response = new JsonResponse($dataArray); $response->headers->set('Content-Length', strlen($response->getContent())); return $response; }
/** * Deletes the entity * * @param $objectId * * @return \Symfony\Component\HttpFoundation\JsonResponse|\Symfony\Component\HttpFoundation\RedirectResponse */ public function deleteAction($leadId, $objectId) { $lead = $this->checkLeadAccess($leadId, 'view'); if ($lead instanceof Response) { return $lead; } $model = $this->factory->getModel('lead.note'); $note = $model->getEntity($objectId); if ($note === null || !$this->factory->getSecurity()->hasEntityAccess('lead:leads:editown', 'lead:leads:editother', $lead->getOwner()) || $model->isLocked($note) || $this->request->getMethod() != 'POST') { return $this->accessDenied(); } $model->deleteEntity($note); $response = new JsonResponse(array('deleteId' => $objectId, 'mauticContent' => 'leadNote', 'downNoteCount' => 1)); $response->headers->set('Content-Length', strlen($response->getContent())); return $response; }
public function editAction($objectId) { $session = $this->factory->getSession(); $type = $this->request->get('type', $session->get('ddi.lead_actions.task.form.type', '')); $session->set('ddi.lead_actions.task.form.type', $type); $model = $this->factory->getModel('plugin.customCrm.task'); $task = $model->getEntity($objectId); $action = $this->generateUrl('mautic_task_action', array('objectAction' => 'edit', 'objectId' => $objectId)); $form = $model->createForm($task, $this->get('form.factory'), $action); $valid = false; $closeModal = false; if ($this->request->getMethod() == 'POST') { if (!($cancelled = $this->isFormCancelled($form))) { if ($valid = $this->isFormValid($form)) { $closeModal = true; // Save task $em = $this->getDoctrine()->getManager(); $em->flush(); } } else { $closeModal = true; } } if ($closeModal) { $passthroughVars = array('closeModal' => 1, 'mauticContent' => 'task'); if ($valid && !$cancelled) { $passthroughVars['upTaskCount'] = 0; $passthroughVars['html'] = $this->renderView('CustomCrmBundle:Task:task.html.php', array('task' => $task)); $passthroughVars['taskId'] = $task->getId(); } if ($type) { $response = new JsonResponse($passthroughVars); $response->headers->set('Content-Length', strlen($response->getContent())); return $response; } else { $page = $this->factory->getSession()->get('mautic.task.page', 1); $returnUrl = $this->generateUrl('ddi_lead_actions_task_index', array('page' => $page)); return $this->postActionRedirect(array('returnUrl' => $returnUrl, 'viewParameters' => array('page' => $page), 'contentTemplate' => 'CustomCrmBundle:Task:index', 'passthroughVars' => $passthroughVars)); } } else { return $this->delegateView(array('viewParameters' => array('form' => $form->createView()), 'contentTemplate' => 'CustomCrmBundle:Task:form.html.php')); } }
public function deleteAction($objectId) { $page = $this->factory->getSession()->get('customcrm.opportunity.page', 1); $returnUrl = $this->generateUrl('mautic_customcrm_opportunity_index', array('page' => $page)); $postActionVars = array('returnUrl' => $returnUrl, 'viewParameters' => array('page' => $page), 'contentTemplate' => 'CustomCrmBundle:Opportunity:index', 'passthroughVars' => array('activeLink' => '#mautic_customcrm_opportunity_index', 'mauticContent' => 'opportunity')); if ($this->request->getMethod() == 'POST') { /** @var \MauticPlugin\CustomCrmBundle\Model\OpportunityModel $model */ $model = $this->factory->getModel('plugin.customCrm.opportunity'); $entity = $model->getEntity($objectId); if ($entity === null) { $this->addFlash('mautic.customcrm.opportunity.error.notfound', array('%id%' => $objectId), 'error'); } $model->deleteEntity($entity); $this->addFlash('mautic.core.notice.deleted', array('%name%' => 'Opportunity #' . $objectId), 'notice'); } //else don't do anything if ($this->request->get('qf', false)) { $passthroughVars = array('closeModal' => 1, 'mauticContent' => 'opportunity', 'upOpportunityCount' => -1); $passthroughVars['opportunityId'] = $objectId; $passthroughVars['deleted'] = 1; $passthroughVars['flashes'] = $this->getFlashContent(); $response = new JsonResponse($passthroughVars); $response->headers->set('Content-Length', strlen($response->getContent())); return $response; } return $this->postActionRedirect($postActionVars); }
public function testSetEncodingOptions() { $response = new JsonResponse(); $response->setData(array(array(1, 2, 3))); $this->assertEquals('[[1,2,3]]', $response->getContent()); $response->setEncodingOptions(JSON_FORCE_OBJECT); $this->assertEquals('{"0":{"0":1,"1":2,"2":3}}', $response->getContent()); }
/** * Undeletes the entity * * @param $objectId * * @return \Symfony\Component\HttpFoundation\JsonResponse|\Symfony\Component\HttpFoundation\RedirectResponse */ public function undeleteAction($objectId) { $campaignId = $this->request->query->get('campaignId'); $session = $this->factory->getSession(); $modifiedEvents = $session->get('mautic.campaign.' . $campaignId . '.events.modified', array()); $deletedEvents = $session->get('mautic.campaign.' . $campaignId . '.events.deleted', array()); //ajax only for form fields if (!$this->request->isXmlHttpRequest() || !$this->factory->getSecurity()->isGranted(array('campaign:campaigns:edit', 'campaign:campaigns:create'), 'MATCH_ONE')) { return $this->accessDenied(); } $event = array_key_exists($objectId, $modifiedEvents) ? $modifiedEvents[$objectId] : null; if ($this->request->getMethod() == 'POST' && $event !== null) { $events = $this->factory->getModel('campaign')->getEvents(); $event['settings'] = $events[$event['eventType']][$event['type']]; //add the field to the delete list if (in_array($objectId, $deletedEvents)) { $key = array_search($objectId, $deletedEvents); unset($deletedEvents[$key]); $session->set('mautic.campaign.' . $campaignId . '.events.deleted', $deletedEvents); } $template = empty($event['settings']['template']) ? 'MauticCampaignBundle:Event:generic.html.php' : $event['settings']['template']; //prevent undefined errors $entity = new Event(); $blank = $entity->convertToArray(); $event = array_merge($blank, $event); $dataArray = array('mauticContent' => 'campaignEvent', 'success' => 1, 'route' => false, 'eventId' => $objectId, 'eventHtml' => $this->renderView($template, array('event' => $event, 'id' => $objectId, 'campaignId' => $campaignId))); } else { $dataArray = array('success' => 0); } $response = new JsonResponse($dataArray); $response->headers->set('Content-Length', strlen($response->getContent())); return $response; }
/** * Some post processing on the generated result. Replacing some variables. * * @param JsonResponse $response * @return JsonResponse */ private function postProcessing(JsonResponse $response) { $apiUrl = $this->getServiceContainer()->getPreferenceLoader()->getSystemPreferences()->getApiUrl(); $response->setContent(str_replace('%apiurl%', $apiUrl, $response->getContent())); return $response; }
public function testJsonEncodeFlags() { $response = new JsonResponse('<>\'&"'); $this->assertEquals('"\\u003C\\u003E\\u0027\\u0026\\u0022"', $response->getContent()); }
/** * Undeletes the entity * * @param $objectId * * @return JsonResponse */ public function undeleteAction($objectId) { $session = $this->factory->getSession(); $formId = $this->request->query->get('formId'); $actions = $session->get('mautic.form.' . $formId . '.actions.modified', array()); $delete = $session->get('mautic.form.' . $formId . '.actions.deleted', array()); //ajax only for form fields if (!$this->request->isXmlHttpRequest() || !$this->factory->getSecurity()->isGranted(array('form:forms:editown', 'form:forms:editother', 'form:forms:create'), 'MATCH_ONE')) { return $this->accessDenied(); } $formAction = array_key_exists($objectId, $actions) ? $actions[$objectId] : null; if ($this->request->getMethod() == 'POST' && $formAction !== null) { //add the field to the delete list if (in_array($objectId, $delete)) { $key = array_search($objectId, $delete); unset($delete[$key]); $session->set('mautic.form.' . $formId . '.actions.deleted', $delete); } //take note if this is a submit button or not if ($formAction['type'] == 'button') { $properties = $formAction['properties']; if ($properties['type'] == 'submit') { $submits = $session->get('mautic.formactions.submits', array()); $submits[] = $objectId; $session->set('mautic.formactions.submits', $submits); } } $template = !empty($formAction['settings']['template']) ? $formAction['settings']['template'] : 'MauticFormBundle:Action:generic.html.php'; //prevent undefined errors $entity = new Action(); $blank = $entity->convertToArray(); $formAction = array_merge($blank, $formAction); $dataArray = array('mauticContent' => 'formAction', 'success' => 1, 'target' => '#mauticform_' . $objectId, 'route' => false, 'actionId' => $objectId, 'actionHtml' => $this->renderView($template, array('inForm' => true, 'action' => $formAction, 'id' => $objectId, 'deleted' => false, 'formId' => $formId))); } else { $dataArray = array('success' => 0); } $response = new JsonResponse($dataArray); $response->headers->set('Content-Length', strlen($response->getContent())); return $response; }
public function editAction($objectId = 0) { $model = $this->factory->getModel('addon.mauticChat.channel'); $entity = $model->getEntity($objectId); $closeModal = $valid = false; //not found if ($entity === null) { return $this->forward('MauticChatBundle:Default:index'); } elseif (!$this->factory->getSecurity()->hasEntityAccess(true, false, $entity->getCreatedBy())) { return $this->modalAccessDenied(); } $action = $this->generateUrl('mautic_chatchannel_action', array('objectAction' => 'edit', 'objectId' => $objectId)); $form = $model->createForm($entity, $this->get('form.factory'), $action); if ($this->request->getMethod() == 'POST') { if (!($cancelled = $this->isFormCancelled($form))) { $valid = $this->isFormValid($form); if ($valid) { $model->saveEntity($entity); $closeModal = true; } } else { $closeModal = true; } } if ($closeModal) { $vars = array('closeModal' => 1); if ($valid && !$cancelled) { $newChannelResponse = $this->forward('MauticChatBundle:Default:index', array('ignoreAjax' => true, 'ignoreModal' => true)); $vars['chatHtml'] = $newChannelResponse->getContent(); $vars['mauticContent'] = "chatChannel"; } $response = new JsonResponse($vars); $response->headers->set('Content-Length', strlen($response->getContent())); return $response; } else { return $this->delegateView(array('viewParameters' => array('form' => $form->createView()), 'contentTemplate' => 'MauticChatBundle:Channel:form.html.php')); } }
/** * Exports the widgets of current user into a json file * * @return \Symfony\Component\HttpFoundation\JsonResponse|\Symfony\Component\HttpFoundation\Response */ public function exportAction() { /** @var \Mautic\DashboardBundle\Model\DashboardModel $model */ $model = $this->factory->getModel('dashboard'); $widgetsPaginator = $model->getWidgets(); $usersName = $this->factory->getUser()->getName(); $dateTime = new \DateTime(); $dateStamp = $dateTime->format('Y-m-d H:i:s'); $name = $this->request->get('name', 'dashboard-of-' . str_replace(' ', '-', $usersName) . '-' . $dateStamp); $description = $this->get('translator')->trans('mautic.dashboard.generated_by', array('%name%' => $usersName, '%date%' => $dateStamp)); $dashboard = array('name' => $name, 'description' => $description, 'widgets' => array()); foreach ($widgetsPaginator as $widget) { $dashboard['widgets'][] = array('name' => $widget->getName(), 'width' => $widget->getWidth(), 'height' => $widget->getHeight(), 'ordering' => $widget->getOrdering(), 'type' => $widget->getType(), 'params' => $widget->getParams(), 'template' => $widget->getTemplate()); } // Make the filename safe $filename = InputHelper::alphanum($name, false, '_') . '.json'; if ($this->request->get('save', false)) { // Save to the user's folder $dir = $this->factory->getSystemPath('dashboard.user'); file_put_contents($dir . '/' . $filename, json_encode($dashboard)); return $this->redirect($this->get('router')->generate('mautic_dashboard_action', array('objectAction' => 'import'))); } $response = new JsonResponse($dashboard); $response->setEncodingOptions($response->getEncodingOptions() | JSON_PRETTY_PRINT); $response->headers->set('Content-Length', strlen($response->getContent())); $response->headers->set('Content-Type', 'application/force-download'); $response->headers->set('Content-Type', 'application/octet-stream'); $response->headers->set('Content-Disposition', 'attachment; filename="' . $filename . '"'); $response->headers->set('Expires', 0); $response->headers->set('Cache-Control', 'must-revalidate'); $response->headers->set('Pragma', 'public'); return $response; }
// Bootstrap should be ran just once when deploying to pregen tokens, this needs to be moved out. $app->before(function (Request $request, Silex\Application $app) { $app['ratelimit']->createUserBucket('tom.cooper'); if (!$app['ratelimit']->consumeAll($seconds)) { $data = array('message' => 'Too many requests, try again in ' . ceil($seconds) . ' seconds.', 'retry-after' => ceil($seconds)); $rendered = $app['twig']->render('api.json', array('data' => $data)); $rendered = preg_replace('/[\\t]+/', '', preg_replace('/[\\r\\n]+/', '', $rendered)); $rendered = json_decode($rendered); $response = new JsonResponse($rendered, 429); $response->headers->set('Retry-After', ceil($seconds)); return $response; } }, Silex\Application::EARLY_EVENT); $app->after(function (Request $request, Response $response, Silex\Application $app) { // apply the current reponse code and status to the return envelope $message = $response->getContent(); $message = preg_replace('/[\\t]+/', '', preg_replace('/[\\r\\n]+/', '', $message)); $message = json_decode($message); // make sure the response is a standard envelope if (is_object($message) and property_exists($message, 'meta')) { $code = $response->getStatusCode(); $message->meta->code = $code; if (substr($code, 0, 1) === '2') { $message->meta->success = true; } $response->setContent(json_encode($message)); } }); $app->error(function (\Exception $e, $code) use($app) { if ($app['debug']) { return;
/** * Return response with debug trace. * * @param \Exception $exception * @param int $statusCode * * @return Response */ private function getDebugTraceResponse(\Exception $exception, $statusCode) { $request = $this->application->getRequest(); $response = (new \Symfony\Component\Debug\ExceptionHandler())->createResponse($exception); $response->setStatusCode($statusCode); if (in_array('application/json', $request->getAcceptableContentTypes())) { $response = new JsonResponse($response->getContent(), $response->getStatusCode(), $response->headers->all()); } return $response; }