예제 #1
0
 public function onKernelRequest(GetResponseEvent $event)
 {
     $this->logger->debug('Entity builder listener: catch kernel.request event');
     // If this is not a master request, skip handling
     if (!$event->isMasterRequest()) {
         $this->logger->debug('Entity builder listener: this is not master request, skip');
         return;
     }
     // If content already prepared
     if ($event->hasResponse()) {
         $this->logger->debug('Entity builder listener: event already has response, skip');
         return;
     }
     // Getting request
     $request = $event->getRequest();
     // Getting action
     $apiServerAction = $event->getRequest()->attributes->get('apiAction');
     /* @var $apiServerAction ApiServerAction */
     // Something wrong
     if (!$apiServerAction) {
         $this->logger->error('Request parser listener: request has no apiAction attribute, throwing access denied exception');
         throw new AccessDeniedHttpException();
     }
     // Creating request data entity
     try {
         $apiEntity = $apiServerAction->getRequestedEntity($request->attributes->get('apiData'));
     } catch (\Exception $e) {
         $this->logger->notice(sprintf('Request parser listener: unable to convert apiData to entity ("%s"), apiEntity set tu null', $e->getMessage()));
         $apiEntity = null;
     }
     // Setting request attributes
     $request->attributes->set('requestData', $apiEntity);
     // Cleaning request attributes
     $request->attributes->remove('apiData');
 }
예제 #2
0
 public function onKernelException(GetResponseForExceptionEvent $event)
 {
     $this->logger->notice(sprintf('Exceptions catcher listener: catch kernel.exception event (exception: %s)', $event->getException()->getMessage()));
     // If this is not a master request, skip handling
     if (!$event->isMasterRequest()) {
         $this->logger->debug('Exceptions catcher listener: this is not master request, skip');
         return;
     }
     // If content already prepared
     if ($event->hasResponse()) {
         $this->logger->debug('Exceptions catcher listener: event already has response, skip');
         return;
     }
     // Getting action
     $apiServerAction = $event->getRequest()->attributes->get('apiAction');
     /* @var $apiServerAction ApiServerAction */
     // Something wrong
     if (!$apiServerAction) {
         $this->logger->error('Request parser listener: request has no apiAction attribute, sending empty response');
         $event->setResponse(new JsonResponse([]));
         return;
     }
     // Getting api server interface
     $apiServerInterface = $apiServerAction->getApiServerInterface();
     // Creating api response
     $apiResponse = $apiServerInterface->getExceptionResponse($event->getException()->getMessage());
     // Setting response
     $event->setResponse(new JsonResponse($apiResponse->export()));
 }
 public function __construct(ContainerInterface $container, EntityManager $entityManager, Logger $logger, $interfaceName, array $config)
 {
     $this->entityManager = $entityManager;
     $this->logger = $logger;
     $this->name = $interfaceName;
     $this->configure($container, $config);
     $this->logger->debug('Interface ' . $this->getName() . ': initialized');
 }
예제 #4
0
 /**
  * @Route("/sitemap.xml", name="sitemap_route", defaults={"_format"="xml"})
  * @return \Symfony\Component\HttpFoundation\Response
  */
 public function getSitemapAction()
 {
     /** @var PageEleveurBranch[] $pageEleveurBranchess */
     $pageEleveurBranches = $this->peBranchRepository->findAll();
     $this->logger->info('generation de la sitemap', ['count' => count($pageEleveurBranches)]);
     $this->logger->debug('contenu de la sitemap', ['pageEleveurBranches' => $pageEleveurBranches]);
     return $this->templating->renderResponse('sitemap.xml.twig', ['pageEleveurBranches' => $pageEleveurBranches]);
 }
 public function __construct(ApiServerInterface $apiServerInterface, Logger $logger, ApiUserProviderInterface $apiUserProviderInterface, ApiServerCipher $apiServerCipher = null, $tokenLiveTime, $tokenRenewTime, ApiClientInterface $apiClient, $apiUserToken = null)
 {
     $this->apiServerInterface = $apiServerInterface;
     $this->logger = $logger;
     $this->apiUserProviderInterface = $apiUserProviderInterface;
     $this->apiServerCipher = $apiServerCipher;
     $this->apiClient = $apiClient;
     $this->apiUser = null;
     $this->newApiUserToken = null;
     $this->configure($tokenLiveTime, $tokenRenewTime);
     $this->logger->debug('Connection: initialized');
     $this->authenticate($apiUserToken);
     $this->logger->debug('Connection: authenticated');
 }
예제 #6
0
 private function configure($controllersNamespace, $defaultController, $defaultAction, $requestAction)
 {
     // checking base controller namespace
     if (!$controllersNamespace) {
         $this->logger->critical('Action: interface namespace is not configured');
         throw new ApiServerException(sprintf('Action of interface "%s" error: controllers namespace not configured', $this->getInterfaceName()));
     }
     // reset variables
     $path = [];
     $controller = null;
     $action = null;
     // parsing request action
     $requestAction = str_replace(['/', '\\'], ':', $requestAction);
     $requestAction = trim($requestAction, ':');
     if ($requestAction) {
         $requestActionParts = explode(':', $requestAction);
         if (count($requestActionParts) < 2) {
             $controller = ucfirst($requestActionParts[0]);
         } else {
             $action = lcfirst(array_pop($requestActionParts));
             $controller = ucfirst(array_pop($requestActionParts));
             $path = $requestActionParts;
         }
     }
     if (!$controller) {
         $controller = ucfirst($defaultController);
     }
     if (!$action) {
         $action = lcfirst($defaultAction);
     }
     if (!$controller || !$action) {
         $this->logger->notice(sprintf('Action: unable to route action "%s"', $requestAction));
         throw new ApiServerException(sprintf('Action of interface "%s" error: unable to route action "%s"', $this->getInterfaceName(), $requestAction));
     }
     foreach ($path as &$subPath) {
         $subPath = ucfirst($subPath);
     }
     // calculating local class name
     $localClassName = $path;
     array_unshift($localClassName, 'Request');
     array_push($localClassName, $controller);
     array_push($localClassName, ucfirst($action) . 'Data');
     $this->localClassName = implode('\\', $localClassName);
     // calculating controller class name, method and symfony action route
     $controllerClassName = $path;
     array_unshift($controllerClassName, Standard::normalizeNamespace($controllersNamespace));
     array_push($controllerClassName, $controller . 'Controller');
     $controllerClassName = implode('\\', $controllerClassName);
     if (!class_exists($controllerClassName)) {
         $this->logger->notice(sprintf('Action: unable to route action "%s" because class "%s" not exists', $requestAction, $controllerClassName));
         throw new ApiServerException(sprintf('Action of interface "%s" error: unable to find "%s" class', $this->getInterfaceName(), $controllerClassName));
     }
     $controllerMethodName = $action . 'Action';
     if (!method_exists($controllerClassName, $controllerMethodName)) {
         $this->logger->notice(sprintf('Action: unable to route action "%s" because class "%s" does not has method "%s"', $requestAction, $controllerClassName, $controllerMethodName));
         throw new ApiServerException(sprintf('Action of interface "%s" error: controller "%s" has no method "%s"', $this->getInterfaceName(), $controllerClassName, $controllerMethodName));
     }
     $this->actionRoute = $controllerClassName . '::' . $controllerMethodName;
     $this->logger->debug(sprintf('Action: route set to "%s"', $this->actionRoute));
 }
예제 #7
0
 /**
  * Generate pdf document and return it as string
  *
  * @return string
  */
 public function generate()
 {
     if (!$this->mpdf) {
         $this->init();
     }
     // Better to avoid having mpdf set any headers as these can interfer with symfony responses
     $output = $this->mpdf->Output('', 'S');
     $time = microtime(true) - $this->start_time;
     $this->logger->debug("sasedev_mpdf: pdf generation took " . $time . " seconds");
     return $output;
 }
 /**
  * @param $awsPath aws file  to delete
  * @return mixed|null
  * @throws Exception
  */
 private function deleteObject($bucket, $awsPath)
 {
     $this->logger->debug('delete ' . $awsPath . ' from ' . $bucket . ' bucket ...');
     $result = $this->s3->deleteObject(array('Bucket' => $bucket, 'Key' => $awsPath));
     try {
         return $result;
         $this->logger->debug('delete ' . $awsPath . ' from ' . $bucket . ' bucket ! done');
     } catch (AwsException $e) {
         throw $e;
     }
 }
예제 #9
0
 public function onKernelRequest(GetResponseEvent $event)
 {
     $this->logger->debug('Request parser listener: catch kernel.request event');
     // If this is not a master request, skip handling
     if (!$event->isMasterRequest()) {
         $this->logger->debug('Request parser listener: this is not master request, skip');
         return;
     }
     // If content already prepared
     if ($event->hasResponse()) {
         $this->logger->debug('Request parser listener: event already has response, skip');
         return;
     }
     // getting request
     $request = $event->getRequest();
     // getting content
     $content = $request->getContent();
     $this->logger->debug(sprintf('Request parser listener: request content >>> %s', $content));
     $content = @json_decode($content, true);
     if (!is_array($content)) {
         $this->logger->notice('Request parser listener: request content is not in the JSON format, throwing access denied exception');
         throw new AccessDeniedHttpException();
     }
     // creating ApiRequest
     $apiRequest = new ApiRequest($content);
     $this->logger->debug(sprintf('Request parser listener: request params. Token: "%s", user token: "%s", action: "%s"', $apiRequest->getToken(), $apiRequest->getUserToken(), $apiRequest->getAction()));
     if (!$apiRequest->getToken()) {
         $this->logger->notice('Request parser listener: request has no token, throwing access denied exception');
         throw new AccessDeniedHttpException();
     }
     // Calculating interface name
     $host = strtolower($request->server->get('SERVER_NAME'));
     $interfaceName = array_key_exists($host, $this->interfacesHosts) ? $this->interfacesHosts[$host] : $this->defaultInterface;
     if (!$interfaceName) {
         $this->logger->notice(sprintf('Request parser listener: interface for hostname "%s" not detected, throwing access denied exception', $host));
         throw new AccessDeniedHttpException();
     }
     $this->logger->debug(sprintf('Request parser listener: "%s" interface selected for handling connection from "%s"', $interfaceName, $host));
     // Building interface
     $apiServerInterface = $this->apiServerInterfaceFactory->buildInterface($interfaceName);
     // Building action
     $apiServerAction = $apiServerInterface->buildAction($apiRequest->getAction());
     $this->logger->debug(sprintf('Request parser listener: action route selected >>> %s', $apiServerAction->getActionRoute()));
     // Setting request attributes
     $request->attributes->set('apiClientToken', $apiRequest->getToken());
     $request->attributes->set('apiUserToken', $apiRequest->getUserToken());
     $request->attributes->set('apiAction', $apiServerAction);
     $request->attributes->set('apiData', $apiRequest->getData());
     // Setting route
     $request->attributes->set('_controller', $apiServerAction->getActionRoute());
 }
예제 #10
0
 public function onKernelView(GetResponseForControllerResultEvent $event)
 {
     $this->logger->debug('Response builder listener: catch kernel.request event');
     // If this is not a master request, skip handling
     if (!$event->isMasterRequest()) {
         $this->logger->debug('Response builder listener: this is not master request, skip');
         return;
     }
     // If content already prepared
     if ($event->hasResponse()) {
         $this->logger->debug('Response builder listener: event already has response, skip');
         return;
     }
     // Getting controller result
     $result = $event->getControllerResult();
     // If result is Response instance
     if ($result instanceof Response) {
         $this->logger->debug('Response builder listener: controller result is already an instance of Response, skip');
         return;
     }
     // Getting action
     $apiServerAction = $event->getRequest()->attributes->get('apiAction');
     /* @var $apiServerAction ApiServerAction */
     // Something wrong
     if (!$apiServerAction) {
         $this->logger->error('Response parser listener: request has no apiAction attribute, throwing access denied exception');
         throw new AccessDeniedHttpException();
     }
     // Getting api server interface
     $apiServerInterface = $apiServerAction->getApiServerInterface();
     // Getting connection
     $apiServerConnection = $event->getRequest()->attributes->get('apiConnection');
     /* @var $apiServerConnection ApiServerConnection */
     // Something wrong
     if (!$apiServerConnection) {
         $this->logger->error('Response parser listener: request has no apiConnection attribute, throwing access denied exception');
         throw new AccessDeniedHttpException();
     }
     // Creating api response
     try {
         $apiResponse = $apiServerInterface->getApiResponse($result);
         $newApiUserToken = $apiServerConnection->getNewApiUserToken();
         if ($newApiUserToken) {
             $this->logger->debug('Response builder listener: applying new api user token to response');
             $apiResponse->setUserToken($newApiUserToken);
         }
     } catch (\Exception $e) {
         $this->logger->error(sprintf('Response parser listener: problem with building response ("%s"), sending exception response', $e->getMessage()));
         $apiResponse = $apiServerInterface->getExceptionResponse($e->getMessage());
     }
     // Setting response
     $event->setResponse(new JsonResponse($apiResponse->export()));
     $this->logger->debug('Response builder listener: response built');
 }
예제 #11
0
 public function testCountErrorsWithDebugHandler()
 {
     $handler = new DebugHandler();
     $logger = new Logger(__METHOD__, array($handler));
     $this->assertTrue($logger->debug('test message'));
     $this->assertTrue($logger->info('test message'));
     $this->assertTrue($logger->notice('test message'));
     $this->assertTrue($logger->warning('test message'));
     $this->assertTrue($logger->error('test message'));
     $this->assertTrue($logger->critical('test message'));
     $this->assertTrue($logger->alert('test message'));
     $this->assertTrue($logger->emergency('test message'));
     $this->assertSame(4, $logger->countErrors());
 }
예제 #12
0
 private function authenticate()
 {
     $this->logger->debug('SecurityManager: authentication and identifying');
     // Reset variables
     $this->user = null;
     $this->userCard = null;
     // If no token set... let's get card information from session
     if (!$this->apiClient->isUserTokenSet()) {
         $this->logger->debug('SecurityManager: no token set');
         return $this->loadUserCardFromSession();
     }
     // Token set, ok
     $now = new \DateTime();
     $userDataExpiresAt = $this->getSession()->get('leoza_api_server.security.userDataExpiresAt');
     // If no user data expire information
     if (!$userDataExpiresAt) {
         $this->logger->debug('SecurityManager: no expiration info in the session');
         return $this->authenticateUserWithUpdateOrLoadUserCardFromSession();
     }
     // We have an expire info
     $userDataExpiresAt = new \DateTime($userDataExpiresAt);
     $isExpired = $userDataExpiresAt < $now;
     // If this info is expired
     if ($isExpired) {
         $this->logger->debug('SecurityManager: session info has expired');
         return $this->authenticateUserWithUpdateOrLoadUserCardFromSession();
     }
     // Cool, info is actual
     $userData = $this->getSession()->get('leoza_api_server.security.userData');
     $user = $userData ? new $this->userClass($userData) : null;
     /* @var $user UserInterface */
     // If info is invalid...
     if (!$user || !$user->getId()) {
         $this->logger->error('SecurityManager: session info is invalid');
         return $this->authenticateUserWithUpdateOrLoadUserCardFromSession();
     }
     // Yeah!
     $this->user = $user;
     $this->userCard = new $this->userCardClass($this->user);
     $this->logger->debug(sprintf('SecurityManager: user authenticated as %s [id: %d] using session info', $this->user->getName(), $this->user->getId()));
     return true;
 }
 /**
  * @param $referenceFull
  *
  * @return Response
  *
  * @throws MediaStorageClientApiException
  */
 public function getMedia($referenceFull)
 {
     if (empty($referenceFull)) {
         throw new MediaStorageClientApiException('Param referenceFull is empty');
     }
     try {
         $request = new FormRequest();
         $request->setMethod(FormRequest::METHOD_GET);
         $request->setHost($this->getApiUrlConfig('base_url'));
         $url = $this->getApiUrlConfig('get_media_by_reference_full_url') . '/' . ltrim($referenceFull, '/');
         $request->setResource($url);
         $this->logger->debug('Send ' . $this->getApiUrlConfig('base_url') . $url);
         /** @var Response $response */
         $response = $this->client->send($request, null);
         $this->logger->debug('Response: ' . $response->getStatusCode() . ' ' . substr($response->getContent(), 0, 300));
     } catch (\Exception $e) {
         throw new MediaStorageClientApiException($e->getMessage());
     }
     return $response;
 }
예제 #14
0
 /**
  * Connect to LDAP service
  *
  * @throws InvalidLdapConnectionException, InvalidLdapTlsConnectionException, InvalidLdapBindException
  */
 public function connect()
 {
     // Don't permit multiple connect() calls to run
     if ($this->ldapResource) {
         return $this->ldapResource;
     }
     $this->ldapResource = $this->ldap->connect($this->uri);
     if ($this->ldapResource === false) {
         throw new InvalidLdapConnectionException('Unable to enable establish LDAP connection.');
     }
     $this->ldap->setOption($this->ldapResource, LDAP_OPT_PROTOCOL_VERSION, 3);
     // Switch to TLS, if configured
     if ($this->useTLS) {
         if (!$this->ldap->startTls($this->ldapResource)) {
             throw new InvalidLdapTlsConnectionException('Unable to enable TLS for LDAP connection.');
         }
         $this->logger->info('TLS enabled for LDAP connection.');
     }
     if (!$this->ldap->bind($this->ldapResource, $this->bindDN, $this->password)) {
         throw new InvalidLdapBindException('Cannot connect to LDAP server: ' . $this->uri . ' as ' . $this->bindDN . '/"' . $this->password . '".');
     }
     $this->logger->debug('Connected to LDAP server: ' . $this->uri . ' as ' . $this->bindDN . ' .');
 }
예제 #15
0
 /**
  * @param $action
  * @param Entity $data
  * @return ApiResponse
  */
 public function request($action, Entity $data = null)
 {
     $apiRequest = new ApiRequest();
     $apiRequest->setAction($action)->setToken($this->token)->setUserToken($this->userToken)->setData($data);
     $this->profiler->log('api_client.' . $this->getName() . '.request', $apiRequest);
     $apiRequestContent = $apiRequest->__toString();
     curl_setopt($this->curl, CURLOPT_POSTFIELDS, $apiRequestContent);
     $this->logger->debug(sprintf('Api client %s: request "%s" >>> %s', $this->getName(), $action, $apiRequestContent));
     $result = curl_exec($this->curl);
     $responseData = json_decode($result, true);
     $apiResponse = new ApiResponse($responseData);
     $this->profiler->log('api_client.' . $this->getName() . '.response', $apiResponse);
     $newUserToken = $apiResponse->getUserToken();
     if ($newUserToken) {
         $this->profiler->log('api_client.' . $this->getName() . '.new_token', $newUserToken);
         $this->userToken = $newUserToken;
         foreach ($this->newUserTokenListeners as $userTokenListener) {
             /* @var $userTokenListener NewUserTokenListenerInterface */
             $userTokenListener->setNewUserToken($newUserToken);
         }
     }
     $this->logger->debug(sprintf('Api client %s: %s response >>> %s', $this->getName(), $apiResponse->getStatus() ? 'SUCCESS' : 'FAIL', $result));
     return $apiResponse;
 }
예제 #16
0
 /**
  * @param AuthenticationEvent $event
  */
 public function onSuccess(AuthenticationEvent $event)
 {
     $this->logger->debug('SUCCESS : ' . $event->getAuthenticationToken()->getUsername());
 }
 public function generateResponsiveSvg($uri, $config = [])
 {
     $default = ['offsetX' => 0, 'offsetY' => 0, 'class' => ''];
     $config = array_merge($default, (array) $config);
     list($file, $identifier) = explode('#', $uri);
     $pathResolved = $this->resolvePath($file);
     $urlResolved = $this->resolveUrl($file);
     $href = $urlResolved;
     if ($this->config['inline']) {
         $href = '';
     }
     if (strlen($identifier) > 0) {
         $href .= '#' . $identifier;
     }
     // Parse svg file and read viewBox attribute.
     $svg = $this->loadContent($pathResolved);
     if ($svg === false) {
         $this->logger->debug('Cannot find svg ' . $uri);
         return '';
     }
     $crawler = new Crawler($svg);
     if (strlen($identifier) > 0) {
         $item = $crawler->filter('#' . $identifier);
     } else {
         $item = $crawler;
     }
     if (!$item->count()) {
         $this->logger->debug('Cannot find svg element for ' . $uri);
         return '';
     }
     $viewBox = $item->attr('viewBox');
     if (strlen($viewBox) == 0) {
         $this->logger->debug('Cannot find viewBox attribute in ' . $uri);
         return '';
     }
     // Build markup
     list($x, $y, $width, $height) = explode(' ', $viewBox);
     $width += $config['offsetX'];
     $height += $config['offsetY'];
     if (isset($config['width'])) {
         $width = $config['width'];
     }
     if (isset($config['height'])) {
         $height = $config['height'];
     }
     $padding = round($height / $width * 100, 5);
     $classes = array_merge(['responsive-svg'], explode(' ', $config['class']));
     $dom = new \DOMDocument();
     $wrapper = $dom->createElement('div');
     $wrapper->setAttribute('class', implode(' ', $classes));
     $wrapper->setAttribute('style', 'position: relative;');
     $filler = $dom->createElement('div');
     $filler->setAttribute('style', 'width: 100%; height: 0; overflow-hidden; padding-bottom: ' . $padding . '%');
     $wrapper->appendChild($filler);
     if (strlen($identifier) > 0) {
         $svg = $dom->createElement('svg');
         $svg->setAttribute('viewBox', '0 0 ' . $width . ' ' . $height);
         $use = $dom->createElement('use');
         $use->setAttribute('xlink:href', $href);
         $svg->appendChild($use);
     } else {
         $svg = $dom->createElement('object');
         $svg->setAttribute('type', 'image/svg+xml');
         $svg->setAttribute('data', $href);
     }
     $svg->setAttribute('style', 'position: absolute; top: 0; bottom: 0; left: 0; right: 0;');
     $wrapper->appendChild($svg);
     $dom->appendChild($wrapper);
     return $dom->saveHTML();
 }