Example #1
0
 /**
  * Building error message
  *
  * @param string $message
  */
 private function buildErrorMessage($message)
 {
     $response = new JsonResponse();
     $response->setData(['error' => $message]);
     $response->send();
     die;
 }
 static function defaultAction(Request $request, Service $service, $repositoryName)
 {
     $repository = $service->getRepository($repositoryName);
     if ($repository) {
         $response = new JsonResponse();
         $etag = md5($repository->getLastModifiedDate());
         $response->setEtag($etag);
         if ($response->isNotModified($request)) {
             $response->send();
             return $response;
         }
         $result = [];
         $result['content'] = [];
         foreach ($repository->getContentTypeDefinitions() as $definition) {
             $result['content'][$definition->getName()]['title'] = $definition->getTitle() ? $definition->getTitle() : $definition->getName();
             $result['content'][$definition->getName()]['lastchange_content'] = $repository->getLastModifiedDate($definition->getName());
             $result['content'][$definition->getName()]['lastchange_cmdl'] = 0;
             // TODO
         }
         $response->setContent(json_encode($result, JSON_PRETTY_PRINT));
         $response->setEtag($etag);
         $response->setPublic();
         return $response;
     }
 }
Example #3
0
 public function serializePropelOutput($output)
 {
     $sanatizedOutput = array();
     foreach ($output as $key => $value) {
         $sanatizedOutput[lcfirst($key)] = $this->serializePropelChildObjects($value);
     }
     $response = new JsonResponse($sanatizedOutput);
     $response->send();
 }
Example #4
0
 /**
  * Loads the user for the given username.
  *
  * This method must throw UsernameNotFoundException if the user is not
  * found.
  *
  * @param string $email The username
  *
  * @return AuthorEntity
  *
  * @see UsernameNotFoundException
  *
  * @throws UsernameNotFoundException if the user is not found
  *
  */
 public function loadUserByUsername($email)
 {
     $user = $this->_em->createQueryBuilder()->select('u')->from('Yasoon\\Site\\Entity\\AuthorEntity', 'u')->where('u.name = :username OR u.email = :email')->setParameter('username', $email)->setParameter('email', $email)->getQuery()->getResult();
     if (count($user) == 0) {
         $response = new JsonResponse(['error' => true, 'errorType' => 'nouser'], 200);
         $response->send();
         die;
     }
     return $user[0];
 }
 /**
  * @inheritDoc
  */
 public function run()
 {
     /** @var RouteCollection $router */
     $router = $this->serviceManager->get('Router');
     $request = Request::createFromGlobals();
     try {
         $response = $router->getDispatcher()->dispatch($request->getMethod(), $request->getPathInfo());
     } catch (\Exception $e) {
         $response = new JsonResponse(['status_code' => 500, 'message' => $e->getMessage(), 'trace' => $e->getTrace()]);
         $response->setStatusCode(Response::HTTP_BAD_REQUEST);
     }
     $response->send();
 }
 /**
  * email: Email
  * password: Password
  * password_confirm: Password Confirmaition
  * @param Request $req
  * @param JsonResponse $res
  */
 public function accountRegistrationAction(Request $req, JsonResponse $res)
 {
     /** @var $accountService AccountRegistrationServiceInterface */
     $accountService = $this->getContainer()->get("account_service");
     $response = new ResponseHelper();
     try {
         $accountService->registration($req->request->get("email"), $req->request->get("password"), $req->request->get("password_confirm"));
         $response->is_good = true;
     } catch (Exception $e) {
         $response->is_good = false;
         $response->errors[] = $e->getMessage();
     }
     $res->setData($response);
     $res->send();
 }
Example #7
0
 /**
  * {@inheritdoc}
  */
 public function serve($params = null)
 {
     $return = $params ? true : false;
     $key = $this->request->request->get('key');
     $callback = $this->request->query->get('callback');
     $configString = $this->request->request->get('data');
     if ($callback && $this->request->isXmlHttpRequest()) {
         $configString = $this->request->query->get('data');
     }
     $publicMethods = array($this->request->query->get('method'), $this->request->request->get('method'));
     $response = new JsonResponse();
     $response->setCallback($callback);
     $response->headers->set('Access-Control-Allow-Headers', 'origin, content-type, accept');
     $response->headers->set('Access-Control-Allow-Origin', '*');
     $response->headers->set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS');
     if ($this->request->isXmlHttpRequest()) {
         $key = $this->request->query->get('key');
     }
     $data = array('error' => true, 'message' => 'Invalid config');
     $serviceHandler = get_class($this->serviceHandler);
     $server = new $serviceHandler($this->authentication, $this->connectionStrings, $this->logDir);
     if (in_array('getAvailableDrivers', $publicMethods)) {
         $data = $server->getAvailableDrivers();
     } elseif ($configString) {
         $configString = json_decode($configString, true);
         if (is_array($configString) && isset($configString['config'])) {
             $config = isset($configString['config']) ? $configString['config'] : array();
             $sql = isset($configString['sql']) ? $configString['sql'] : '';
             $limit = isset($configString['limit']) ? intval($configString['limit']) : 500;
             $offset = isset($configString['offset']) ? intval($configString['offset']) : 0;
             $single = isset($configString['single']) ? (bool) $configString['single'] : false;
             $data = $server->getResult($config, $sql, $limit, $offset, $single, $key, 'array');
             if (in_array('getServerVersion', $publicMethods)) {
                 $data = $server->getServerVersion();
             }
         }
     }
     $response->setData($data);
     if (!$return) {
         $response->send();
     } else {
         return $response;
     }
 }
Example #8
0
 /**
  * Handle route
  *
  * @param Request $request
  */
 public function handle(Request $request)
 {
     $context = new RequestContext();
     $context->fromRequest($request);
     $matcher = new UrlMatcher($this->routes, $context);
     try {
         $attributes = $matcher->match($request->getPathInfo());
     } catch (ResourceNotFoundException $e) {
         $response = new JsonResponse();
         $response->setData(['error' => 'Route not found.']);
         $response->send();
         return;
     }
     $controller = $attributes['controller'];
     $method = $attributes['method'];
     unset($attributes['method']);
     unset($attributes['controller']);
     $parameters = array_merge(['container' => $this->container], $attributes);
     $route = new RouteFound($controller, $method, $parameters);
     $route->render();
 }
Example #9
0
            }
        } else {
            if ('insertentry' == $do) {
                unset($recordData['id']);
                unset($recordData['revision_id']);
                $revision_id = 1;
                $record_id = $faq->addRecord($recordData);
                if ($record_id) {
                    $faq->createChangeEntry($record_id, $user->getUserId(), nl2br($changed), $recordData['lang']);
                    $visits = new PMF_Visits($faqConfig);
                    $visits->add($record_id);
                    $faq->addCategoryRelations($categories['rubrik'], $record_id, $recordData['lang']);
                    if ($tags != '') {
                        $tagging->saveTags($record_id, explode(',', $tags));
                    }
                    $faq->addPermission('user', $record_id, $restricted_users);
                    $category->addPermission('user', $categories['rubrik'], $restricted_users);
                    if ($faqConfig->get('security.permLevel') != 'basic') {
                        $faq->addPermission('group', $record_id, $restricted_groups);
                        $category->addPermission('group', $categories['rubrik'], $restricted_groups);
                    }
                }
            }
        }
        $response->setData(array('msg' => sprintf("Item autosaved at revision %d", $revision_id), 'revision_id' => $revision_id, 'record_id' => $record_id));
    }
} else {
    $response->setData(array("msg" => "Unsuficcient article rights"));
}
$response->send();
Example #10
0
 /**
  * Send a JSON HTTP 400 response
  *
  * @param string $msg    The error message (not displayed to the user)
  * @param int    $status The HTTP status code
  * @return void
  */
 public function respondWithError($msg, $status = 400)
 {
     $response = new JsonResponse(['error' => $msg], $status);
     $this->response_sent = true;
     $response->send();
 }
Example #11
0
 /**
  * @param string $command POSTs to /console/cache/[command] to perform various cache operations.
  *                        Currently, the only operation available at this time is "flush",
  *                        which clears the cache for the core.
  *
  *                        Example: POST http://dsp.local/console/cache/flush
  *
  * @return bool
  * @throws \CHttpException
  */
 public function actionCache($command)
 {
     if (null === ($_result = Option::get(static::$_cacheCommandMap, $command))) {
         throw new \CHttpException(HttpResponse::BadRequest, 'Invalid command "' . $command . '"');
     }
     $this->layout = false;
     $_result = static::$_cacheCommandMap[$command];
     $_response = new JsonResponse(array('command' => $command, 'success' => $_result));
     $_response->send();
     return Pii::end();
 }
Example #12
0
 /**
  * Send immediately
  */
 public function renderJson()
 {
     $totalCount = $this->getDatasource()->totalCount();
     $rows = $this->getDatasource()->listRows();
     $tmpData = [];
     foreach ($rows as $row) {
         $tmp = [];
         foreach ($this->getColumns() as $column) {
             $tmp[$column->getName()] = $column->format($row);
         }
         $tmpData[] = $tmp;
     }
     $data = ['draw' => $this->getRequest()->get('draw'), 'recordsTotal' => $totalCount, 'recordsFiltered' => $totalCount, 'data' => $tmpData];
     $response = new JsonResponse();
     $response->setData($data);
     $response->send();
     exit;
 }
Example #13
0
 /**
  * Send a jsonp response with given content.
  *
  * @param array $content
  * @param string $jsonCallback
  */
 public function jsonp($content = [], $jsonCallback = 'callback')
 {
     $response = new JsonResponse();
     $response->setData($content);
     $response->setCallback($jsonCallback);
     $response->send();
 }
 /**
  * Passes valuta-model conversion amount to response
  * @return String|Json
  */
 public function convertValutaAction()
 {
     $result = ["ConversionAmountResult" => 0];
     $dateTime = new DateTime();
     $parameters = ['CurrencyFrom' => $this->request->get("CurrencyFrom"), 'CurrencyTo' => $this->request->get("CurrencyTo"), 'RateDate' => $dateTime->format("Y-m-d"), 'Amount' => $this->request->get("Amount")];
     try {
         $soapClientService = new App\SoapClientService();
         $soapClientService->addProvider(new Kowabunga());
         $soapClientService->addProvider(new Webservicex());
         $result["ConversionAmountResult"] = $soapClientService->getConversionAmount($parameters);
         $response = new JsonResponse($result);
     } catch (Exception $e) {
         $response = new JsonResponse(["error" => $e->getMessage()]);
     }
     return $response->send();
 }
Example #15
0
 /**
  * Method is used before any other actions in this controller
  */
 public function _init()
 {
     parent::_init();
     # Set access to mobile app for this
     if (isset($_SERVER['HTTP_ORIGIN'])) {
         header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
         header('Access-Control-Allow-Credentials: true');
         header('Access-Control-Max-Age: 86400');
         // cache for 1 day
     }
     try {
         if ($this->request->isMethod('POST')) {
             $this->version = $this->request->get('version', 1);
             $this->sessionId = $this->request->get('unique', null);
             $this->type = $this->request->get('type', null);
             $appId = $this->request->get('app_id', null);
             $data = $this->request->get('data', null);
             # If required arg no exist return json with error
             if (!($this->sessionId && $this->type && $appId)) {
                 $response = new JsonResponse(array('success' => false, 'msg' => 'Once of required arguments is null, valid structure is (String unique, String type, String app_id, Object data = null)'));
                 $response->send();
                 exit;
             }
             # if data json is not null then create array from this
             if ($data) {
                 $this->data = json_decode($data, true);
             }
             # App object
             $this->app = $this->em->getRepository('BallyEntityBundle:App')->find($appId);
             # If can't find app by id, we must break because it's required value
             if (!$this->app) {
                 $response = new JsonResponse(array('success' => false, 'msg' => 'App with code: ' . $appId . ' no exist!!!'));
                 $response->send();
                 exit;
             }
             $this->statistics = $this->em->getRepository('BallyEntityBundle:Statistics')->findOneBy(array('sessionId' => $this->sessionId, 'app' => $this->app->getId()));
             # if all ok, can save statistics if no exist
         } else {
             # return error if it's no post method
             $response = new JsonResponse(array('success' => false, 'msg' => 'Only post method allowed for api !!'));
             $response->send();
             exit;
         }
     } catch (\Exception $e) {
         $response = new JsonResponse(array('success' => false, 'msg' => 'An error occured', 'error' => $e->getMessage()));
         $response->send();
         exit;
     }
 }
Example #16
0
 /**
  * приватная инфа для редактирования профиля
  *
  * @return array
  * @throws \Symfony\Component\Security\Core\Exception\AccessDeniedException
  */
 public function getPrivateInfo()
 {
     //        $access = 'ADMIN';
     //
     //        return ['access' => $access, 'data' => $result];
     $authorId = $this->securityContext->getToken()->getUsername();
     //echo $authorId; die;
     if (!(int) $authorId) {
         $response = new JsonResponse(false, 200);
         $response->send();
         die;
     }
     $data = $this->em->getRepository('Yasoon\\Site\\Entity\\AuthorEntity')->find($authorId);
     $post = $this->em->getRepository('Yasoon\\Site\\Entity\\PostEntity')->createQueryBuilder('p')->leftJoin('p.author', 'a')->where('a.id = ' . $authorId)->setMaxResults(1)->setFirstResult(0)->orderBy('p.date', 'desc')->getQuery()->getResult();
     if ($post) {
         $post_date = $post[0]->getDate()->format('d/m/Y');
     } else {
         $post_date = null;
     }
     $ask_questions_data = $this->em->getRepository('Yasoon\\Site\\Entity\\QuestionEntity')->findBy(array('ask_authorId' => $authorId));
     $ask_questions = [];
     foreach ($ask_questions_data as $q) {
         $ask_questions[] = $q->getId();
     }
     //$followers = $this->em->getRepository('Yasoon\Site\Entity\FriendsEntity')->findBy(array('writerId' => $data->getId()));
     $followers = $data->getFriends();
     $friends = [];
     foreach ($followers as $follower) {
         $friends[] = ['id' => $follower->getId(), 'date' => $follower->getPublicationDate()->format('d/m/Y')];
     }
     $timeline = null;
     $timeline_data = $this->em->getRepository('Yasoon\\Site\\Entity\\TimelineEntity')->findBy(array('author_id' => $data->getId()));
     if ($timeline_data) {
         $timeline = ['posts_count' => $timeline_data[0]->getPostsCount(), 'answers_count' => $timeline_data[0]->getAnswersCount(), 'question_count' => $timeline_data[0]->getQuestionsCount()];
     }
     $result = ['id' => $data->getId(), 'name' => $data->getName(), 'email' => $data->getEmail(), 'avatarImg' => $data->getImg(), 'interviewCaption' => $data->getInterviewCaption(), 'job' => $data->getJob(), 'homepage' => $data->getHomepage(), 'interest' => $data->getInterest(), 'last_publish_date' => $post_date, 'dream' => $data->getDream(), 'ask_questions' => $ask_questions, 'friends' => $friends, 'timeline' => $timeline, 'roles' => $data->getRoles(), 'regFrom' => $data->getRegFrom()];
     //        $access = $this->getAccessLevel($authorId);
     //
     //        return ['access' => $access, 'data' => $result];
     return $result;
 }