src/Controller/ApiController.php line 243

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use Symfony\Component\HttpFoundation\Request;
  4. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  5. use Symfony\Component\Routing\Annotation\Route;
  6. use Symfony\Component\HttpFoundation\JsonResponse;
  7. use Symfony\Component\HttpFoundation\Response;
  8. use Doctrine\ORM\EntityManagerInterface;
  9. use App\Entity\Tracking;
  10. use App\Entity\Mdmrdblog;
  11. use App\Entity\Device;
  12. use App\Entity\Gptype;
  13. use App\Service\AppHelper;
  14. use App\Entity\Specialization;
  15. class ApiController extends AbstractController
  16. {
  17.     /**
  18.      * @Route("/api/data.json")
  19.      */
  20.     public function dataApi(Request $requestAppHelper $appHelperString $gmapApikeyString $appquarterUrlString $nappUrl)
  21.     {
  22.         $em      $this->getDoctrine()->getManager();
  23.         $error   $this->validateRequest($request);
  24.         $arrResp = [];
  25.         if (count($error) > 0)
  26.         {
  27.             return $this->createErrorResponse($error);
  28.         }
  29.         if ($request->headers->has('X-i42Device') && $request->headers->has('X-i42Customer'))
  30.         {
  31.             $i42Device   $request->headers->get('X-i42Device'false);
  32.             $i42Customer $request->headers->get('X-i42Customer'false);
  33.             if (
  34.                 $i42Device && $i42Customer &&
  35.                 isset($this->requestData['data']) && isset($this->requestData['data']['device']) &&
  36.                 is_array($this->requestData['data']['device']) && count($this->requestData['data']['device'])
  37.             )
  38.             {
  39.                 foreach ($this->requestData['data']['device'] as $data)
  40.                 {
  41.                     $lCountry null;
  42.                     $sql      'SELECT country FROM tracking ';
  43.                     $sql     .= 'WHERE device_token = "'.$i42Device.'" AND customer_token = "'.$i42Customer.'" AND ';
  44.                     $sql     .= 'country != "" AND country IS NOT NULL ORDER BY id DESC';
  45.                     $stm      $em->getConnection()->executeQuery($sql);
  46.                     $lEntry   $stm->fetch();
  47.                     if (is_array($lEntry) && isset($lEntry['country']))
  48.                     {
  49.                         $lCountry $lEntry['country'];
  50.                     }
  51.                     $address $appHelper->getAdressByPositionFromGoogle($gmapApikey$data['latitude'], $data['longitude']);
  52.                     $country '';
  53.                     $fAdress 'unknown address';
  54.                     if (isset($address['formatted_address']))
  55.                     {
  56.                         $fAdress $address['formatted_address'];
  57.                         foreach ($address['address_components'] as $_component)
  58.                         {
  59.                             $component = (array) $_component;
  60.                             foreach ($component['types'] as $type)
  61.                             {
  62.                                 if ($type == 'country')
  63.                                 {
  64.                                     $country $component['short_name'];
  65.                                 }
  66.                             }
  67.                         }
  68.                     }
  69.                     $track = new Tracking();
  70.                     $track->setDeviceToken($i42Device);
  71.                     $track->setCustomerToken($i42Customer);
  72.                     $track->setDeviceState($data['userState']);
  73.                     $track->setEmergencyState($data['emergency']);
  74.                     $track->setLat($data['latitude']);
  75.                     $track->setLng($data['longitude']);
  76.                     $track->setAccuracy(number_format($data['accuracy'], 4));
  77.                     $track->setAltitude(number_format($data['altitude'], 4));
  78.                     $track->setAddress($fAdress);
  79.                     $track->setCountry($country);
  80.                     $track->setCreatedAt(\DateTime::createFromFormat('U'$data['timestamp']));
  81.                     $em->persist($track);
  82.                     $em->flush();
  83.                     if (
  84.                         !empty($lCountry) && (!empty($country) && ($lCountry != $country))
  85.                     )
  86.                     {
  87.                         $curl curl_init();
  88.                         curl_setopt_array($curl, array(
  89.                           CURLOPT_URL            => $appquarterUrl.'/pnb/api/changed_location',
  90.                           CURLOPT_RETURNTRANSFER => true,
  91.                           CURLOPT_ENCODING       => '',
  92.                           CURLOPT_MAXREDIRS      => 10,
  93.                           CURLOPT_TIMEOUT        => 0,
  94.                           CURLOPT_FOLLOWLOCATION => true,
  95.                           CURLOPT_HTTP_VERSION   => CURL_HTTP_VERSION_1_1,
  96.                           CURLOPT_SSL_VERIFYPEER => 0,
  97.                           CURLOPT_CUSTOMREQUEST  => 'POST',
  98.                           CURLOPT_POSTFIELDS     =>'{
  99.                             "data": {
  100.                                 "currentCountry": "'.$country.'",
  101.                                 "deviceId": "'.$i42Device.'"
  102.                             }
  103.                         }',
  104.                           CURLOPT_HTTPHEADER => array(
  105.                             'Content-Type: application/json',
  106.                             'X-i42AccountToken: 42'
  107.                           ),
  108.                         ));
  109.                         curl_exec($curl);
  110.                         curl_close($curl);
  111.                     }
  112.                     $nappCurlOptions = array(
  113.                         CURLOPT_URL => $nappUrl.'/api/data.json',
  114.                         CURLOPT_RETURNTRANSFER => true,
  115.                         CURLOPT_ENCODING       => '',
  116.                         CURLOPT_MAXREDIRS      => 10,
  117.                         CURLOPT_TIMEOUT        => 0,
  118.                         CURLOPT_FOLLOWLOCATION => true,
  119.                         CURLOPT_HTTP_VERSION   => CURL_HTTP_VERSION_1_1,
  120.                         CURLOPT_SSL_VERIFYPEER => 0,
  121.                         CURLOPT_CUSTOMREQUEST  => 'POST',
  122.                         CURLOPT_POSTFIELDS     => '',
  123.                         CURLOPT_HTTPHEADER     => array(),
  124.                         CURLOPT_POSTFIELDS =>'{
  125.                             "apiTimestamp": "'.$this->requestData['apiTimestamp'].'",
  126.                             "appTimestamp": "'.$this->requestData['appTimestamp'].'",
  127.                             "responseApi": "'.$this->requestData['responseApi'].'",
  128.                             "requestApi": "'.$this->requestData['requestApi'].'",
  129.                             "data": {
  130.                                 "device": [
  131.                                     {
  132.                                         "latitude": "'.$data['latitude'].'",
  133.                                         "longitude": "'.$data['longitude'].'",
  134.                                         "userState": '.$data['userState'].',
  135.                                         "emergency": '.$data['emergency'].',
  136.                                         "timestamp": '.$data['timestamp'].',
  137.                                         "accuracy": '.$data['accuracy'].',
  138.                                         "altitude": '.$data['altitude'].'
  139.                                     }
  140.                                 ]
  141.                             }
  142.                         }',
  143.                         CURLOPT_HTTPHEADER => array(
  144.                             'Content-Type: application/json',
  145.                             'X-i42Device: '.$i42Device,
  146.                             'X-i42Customer: '.$i42Customer
  147.                         )
  148.                     );
  149.                     $curl curl_init();
  150.                     curl_setopt_array($curl$nappCurlOptions);
  151.                     $arrResp json_decode(curl_exec($curl), true);
  152.                     curl_close($curl);
  153.                 }
  154.             }
  155.             else
  156.             {
  157.                 $arrResp $this->createErrorMessage(21'not all necessary data submitted');
  158.             }
  159.         }
  160.         return $this->createJsonResponse($arrResp);
  161.     }
  162.     /**
  163.      * @Route("/api/route.json")
  164.      *
  165.      * @param type $request
  166.      * @return type
  167.      */
  168.     public function routeAction(Request $request)
  169.     {
  170.         $em     $this->getDoctrine()->getManager();
  171.         $error  $this->validateRequest($request);
  172.         $arrRes = [];
  173.         if (count($error) > 0)
  174.         {
  175.             return $this->createErrorResponse$error );
  176.         }
  177.         if ($request->headers->has('X-i42AccountToken'))
  178.         {
  179.             $i42AccountToken $request->headers->get('X-i42AccountToken'false);
  180.             if ($i42AccountToken)
  181.             {
  182.                 if (
  183.                     is_array($this->requestData) && count($this->requestData) && isset($this->requestData['data']) &&
  184.                     isset($this->requestData['data']['device_token'])  && !empty($this->requestData['data']['device_token'])
  185.                 )
  186.                 {
  187.                     $deviceToken $this->requestData['data']['device_token'];
  188.                     $sql  'SELECT * FROM tracking WHERE device_token = "'.$deviceToken.'" ';
  189.                     if (isset($this->requestData['data']['timerange']))
  190.                     {
  191.                         $sql .= 'AND created_at >= "'.date("Y-m-d H:i:s"time() - $this->requestData['data']['timerange']).'" ';
  192.                     }
  193.                     $sql .= 'AND lat <> 0 AND lng <> 0 ORDER BY created_at';
  194.                     $stm     $em->getConnection()->executeQuery($sql);
  195.                     $arrResp $stm->fetchAll();
  196.                     if ($arrResp)
  197.                     {
  198.                         foreach ($arrResp as $res)
  199.                         {
  200.                             $resSet                 = [];
  201.                             $resSet['id']           = $res['id'];
  202.                             $resSet['lat']          = $res['lat'];
  203.                             $resSet['lng']          = $res['lng'];
  204.                             $arrRes[]               = $resSet;
  205.                         }
  206.                     }
  207.                     $arrResp = array('results' => $arrRes);
  208.                 }
  209.                 else
  210.                 {
  211.                     $arrResp $this->createErrorMessage(21'not all necessary data submitted');
  212.                 }
  213.             }
  214.             else
  215.             {
  216.                 $arrResp $this->createErrorMessage(19'unregistered account token');
  217.             }
  218.         }
  219.         else
  220.         {
  221.             $arrResp $this->createErrorMessage(18'unregistered account');
  222.         }
  223.         return $this->createJsonResponse($arrResp);
  224.     }
  225.     /**
  226.      * @Route("/api/wakeup.json")
  227.      *
  228.      * @param type $request
  229.      * @return type
  230.      */
  231.     public function wakeupAction(Request $requestString $appquarterUrl)
  232.     {
  233.         $em      $this->getDoctrine()->getManager();
  234.         $error   $this->validateRequest($requesttruefalse);
  235.         $arrResp = [];
  236.         if (count($error) > 0)
  237.         {
  238.             return $this->createErrorResponse($error);
  239.         }
  240.         if ($request->headers->has('X-i42Device') && $request->headers->has('X-i42Customer'))
  241.         {
  242.             $i42Device   $request->headers->get('X-i42Device'false);
  243.             $i42Customer $request->headers->get('X-i42Customer'false);
  244.             if ($i42Device && $i42Customer)
  245.             {
  246.                 $wat     = new \DateTime();
  247.                 $device  $em->getRepository(Device::class)->findOneBy(['deviceToken' => $i42Device'customerToken' => $i42Customer]);
  248.                 if (!$device)
  249.                 {
  250.                     $device = new Device();
  251.                     $device->setDeviceToken($i42Device);
  252.                     $device->setCustomerToken($i42Customer);
  253.                     $device->setCreatedAt($wat);
  254.                 }
  255.                 if (
  256.                     isset($this->requestData['data']) && isset($this->requestData['data']['config']) &&
  257.                     is_array($this->requestData['data']['config']) && count($this->requestData['data']['config'])
  258.                 )
  259.                 {
  260.                     $device->setDeviceConfig(json_encode($this->requestData['data']['config']));
  261.                 }
  262.                 $device->setUpdatedAt($wat);
  263.                 $em->persist($device);
  264.                 $em->flush();
  265.             }
  266.             return $this->createJsonResponse($arrResp);
  267.         }
  268.     }
  269.     /**
  270.      * @Route(
  271.      *     "/api/places.json",
  272.      *     name="api_places",
  273.      *     methods={"POST", "OPTIONS"}
  274.      * )
  275.      */
  276.     public function placesAction(Request $requestString $accountToken)
  277.     {
  278.         $em        $this->getDoctrine()->getManager();
  279.         $inputData $request->getContent();
  280.         $arrData   json_decode($inputDatatrue);
  281.         $arrRet    = [];
  282.         if (!$request->isMethod('POST')) {
  283.             $arrRet['message'] = 'Request method is not correct!';
  284.             return $this->createJsonResponse($arrRet);
  285.         }
  286.         if (!$request->headers->has('X-i42AccountToken')) {
  287.             $arrRet['message'] = 'Account token is missing!';
  288.             return $this->createJsonResponse($arrRet);
  289.         }
  290.         $i42AccountToken $request->headers->get('X-i42AccountToken');
  291.         if ($i42AccountToken != $accountToken) {
  292.             $arrRet['message'] = 'Unregistered account token!';
  293.             return $this->createJsonResponse($arrRet);
  294.         }
  295.         if (!(
  296.             is_array($arrData)           &&
  297.             isset($arrData['lat'])       && !empty($arrData['lat'])        && is_numeric($arrData['lat']) &&
  298.             isset($arrData['lng'])       && !empty($arrData['lng'])        && is_numeric($arrData['lng']) &&
  299.             isset($arrData['distance'])  && !empty($arrData['distance'])   && ctype_digit((string) $arrData['distance'])
  300.         )) {
  301.             $arrRet['message'] = 'Not all necessary data submitted!';
  302.             return $this->createJsonResponse($arrRet);
  303.         }
  304.         $lat      $arrData['lat'];
  305.         $lng      $arrData['lng'];
  306.         $distance $arrData['distance'];
  307.         if (isset($arrData['type']) && !empty(trim($arrData['type'])) && $arrData['type']!=='' ){
  308.             $typeId     $arrData['type'];
  309.         }
  310.         $distClmn '(6371*acos(cos(radians('.$lat.'))*cos(radians(gp.lat))*cos(radians(gp.lng)-radians('.$lng.'))+sin(radians('.$lat.'))*sin(radians(gp.lat)))) AS distance';
  311.         $sql      'SELECT gp.*, '.$distClmn.' FROM gplace AS gp ';
  312.         if (isset($arrData['specialist']) && $arrData['specialist']) {
  313.             $sql .= ' Where gp.specialist = true ';
  314.         }
  315.         if (isset($arrData['gender']) && !empty(trim($arrData['gender']))) {
  316.             if (isset($arrData['specialist']) && $arrData['specialist']) {
  317.                 $sql .= ' AND (gp.gender = "' trim($arrData['gender']) . '" OR gp.gender = "female / male")';
  318.             } else {
  319.                 $sql .= ' WHERE (gp.gender = "' trim($arrData['gender']) . '" OR gp.gender = "female / male") ';
  320.             }
  321.         }
  322.         $sql     .= 'HAVING distance <= '.$distance.' ';
  323.         $sql     .= 'ORDER BY distance ASC';
  324.         
  325.         if (isset($arrData['type']) && !empty(trim($arrData['type'])) && $arrData['type']!=='' ){
  326.             $sql      'SELECT gp.*, '.$distClmn.' FROM gplace AS gp ';
  327.             $sql     .= 'LEFT JOIN gplace_gptype AS gpgpt ON gp.id = gpgpt.gplace_id ';
  328.             $sql     .= 'LEFT JOIN gptype AS gpt ON gpgpt.gptype_id = gpt.id ';
  329.             $sql     .= 'WHERE gpt.id = "'.$typeId.'" ';
  330.             if (isset($arrData['specialist'])) {
  331.                 $sql .= ' AND gp.specialist = true ';
  332.             }
  333.             if (isset($arrData['gender']) && !empty(trim($arrData['gender']))) {
  334.                 $sql .= ' AND (gp.gender = "' trim($arrData['gender']) . '" OR gp.gender = "female / male") ';
  335.             }
  336.             $sql     .= 'HAVING distance <= '.$distance.' ';
  337.             $sql     .= 'ORDER BY distance ASC';
  338.         }
  339.         
  340.         if (isset($arrData['specialization']) && !empty($arrData['specialization']) && $arrData['specialization'][0]!==''){
  341.             $sql      'SELECT gp.*, '.$distClmn.' FROM gplace AS gp ';
  342.             $sql     .= 'INNER JOIN gplace_specialization AS gpspec ON gp.id = gpspec.gplace_id ';
  343.             
  344.             if (is_array($arrData['specialization'])) {
  345.                 for ($i 0;$i<count($arrData['specialization']);$i++){
  346.                     if ($i === 0){
  347.                         $sql .= 'WHERE (gpspec.specialization_id='.$arrData['specialization'][$i];
  348.                     } else {
  349.                         $sql .= ' OR gpspec.specialization_id=' $arrData['specialization'][$i];
  350.                     }
  351.                     if ($i===count($arrData['specialization'])-1){
  352.                         $sql .= ')';
  353.                     }
  354.                 } 
  355.                 if (isset($arrData['specialist']) && $arrData['specialist']) {
  356.                     $sql .= ' AND gp.specialist = true ';
  357.                 }
  358.                 if (isset($arrData['gender']) && !empty(trim($arrData['gender']))) {
  359.                     $sql .= ' AND (gp.gender = "' trim($arrData['gender']) . '" OR gp.gender = "female / male") ';
  360.                 }
  361.                     $sql     .= ' Group BY gp.id ';
  362.                     $sql     .= ' HAVING (((distance <= '.$distance.')) AND ((Count(DISTINCT gpspec.specialization_id) = ' .  Count($arrData['specialization']) . ')))';
  363.                     $sql     .= ' ORDER BY distance ASC';
  364.             }
  365.         }
  366.         if (isset($arrData['type']) && !empty(trim($arrData['type'])) && $arrData['type']!=='' && (isset($arrData['specialization']) && !empty($arrData['specialization']) && $arrData['specialization'][0]!=='')){
  367.             $sql      'SELECT DISTINCT gp.*, '.$distClmn.' FROM gplace AS gp ';
  368.             $sql     .= 'INNER JOIN gplace_specialization AS gpspec ON gp.id = gpspec.gplace_id ';
  369.             $sql     .= 'LEFT JOIN gplace_gptype AS gpgpt ON gp.id = gpgpt.gplace_id ';
  370.             $sql     .= 'LEFT JOIN gptype AS gpt ON gpgpt.gptype_id = gpt.id ';
  371.             $sql     .= 'WHERE gpt.id = "'.$typeId.'" ';
  372.             if (isset($arrData['specialist']) && $arrData['specialist']) {
  373.                 $sql .= ' AND gp.specialist = true ';
  374.             }
  375.             if (isset($arrData['gender']) && !empty(trim($arrData['gender']))) {
  376.                 $sql .= ' AND (gp.gender = "' trim($arrData['gender']) . '" OR gp.gender = "female / male") ';
  377.             }
  378.         
  379.             if (is_array($arrData['specialization'])) {
  380.                 for ($i 0;$i<count($arrData['specialization']);$i++){
  381.                     if ($i === 0){
  382.                         $sql .= 'AND (gpspec.specialization_id='.$arrData['specialization'][$i];
  383.                     } else {
  384.                         $sql .= ' OR gpspec.specialization_id=' $arrData['specialization'][$i];
  385.                     }
  386.                     if ($i===count($arrData['specialization'])-1){
  387.                         $sql .= ')';
  388.                     }
  389.                 } 
  390.                     $sql     .= ' Group BY gp.id ';
  391.                     $sql     .= ' HAVING (((distance <= '.$distance.')) AND ((Count(DISTINCT gpspec.specialization_id) = ' .  Count($arrData['specialization']) . ')))';
  392.                     $sql     .= ' ORDER BY distance ASC';
  393.             }
  394.         }
  395.         $stm     $em->getConnection()->executeQuery($sql);
  396.         $arrRess $stm->fetchAll();
  397.         if ($arrRess)
  398.         {
  399.             foreach ($arrRess as $idx => $res)
  400.             {
  401.                 $arrRet[$idx] = $res;
  402.                 $arrRet[$idx]['lat'] = (float) $arrRet[$idx]['lat'];
  403.                 $arrRet[$idx]['lng'] = (float) $arrRet[$idx]['lng'];
  404.                 $arrRet[$idx]['opening_hour'] = nl2br($arrRet[$idx]['opening_hour']);
  405.             }
  406.         }
  407.         $arrRet = array('results' => $arrRet);
  408.         return $this->createJsonResponse($arrRet);
  409.     }
  410.     /**
  411.      * @Route(
  412.      *     "/api/research.json",
  413.      *     name="api_research",
  414.      *     methods={"POST", "OPTIONS"}
  415.      * )
  416.      */
  417.     public function researchAction(Request $requestAppHelper $appHelperString $gmapApikeyString $accountToken)
  418.     {
  419.         $em        $this->getDoctrine()->getManager();
  420.         $inputData $request->getContent();
  421.         $arrData   json_decode($inputDatatrue);
  422.         $arrRet    = [];
  423.         if (!$request->isMethod('POST')) {
  424.             $arrRet['message'] = 'Request method is not correct!';
  425.             return $this->createJsonResponse($arrRet);
  426.         }
  427.         if (!$request->headers->has('X-i42AccountToken')) {
  428.             $arrRet['message'] = 'Account token is missing!';
  429.             return $this->createJsonResponse($arrRet);
  430.         }
  431.         $i42AccountToken $request->headers->get('X-i42AccountToken');
  432.         if ($i42AccountToken != $accountToken) {
  433.             $arrRet['message'] = 'Unregistered account token!';
  434.             return $this->createJsonResponse($arrRet);
  435.         }
  436.         if (!(
  437.             is_array($arrData)                 &&
  438.             isset($arrData['zipcode'])         && !empty(trim($arrData['zipcode']))        &&
  439.             isset($arrData['distance'])        && !empty($arrData['distance'])             && ctype_digit((string) $arrData['distance']) &&
  440.             isset($arrData['specialization'])  && !empty(trim($arrData['specialization'])) &&
  441.             isset($arrData['limit'])           && !empty($arrData['limit'])                && ctype_digit((string) $arrData['limit'])
  442.         )) {
  443.             $arrRet['message'] = 'Not all necessary data submitted!';
  444.             return $this->createJsonResponse($arrRet);
  445.         }
  446.         $rdblog = new Mdmrdblog();
  447.         $rdblog->setZipcode((string) $arrData['zipcode']);
  448.         $rdblog->setDistance((string) $arrData['distance']);
  449.         $rdblog->setSpecialization((string) $arrData['specialization']);
  450.         $rdblog->setCountlimit((string) $arrData['limit']);
  451.         $rdblog->setOnlyfemaledoctor((string) $arrData['only_female_doctor']);
  452.         $rdblog->setOnlymaledoctor((string) $arrData['only_male_doctor']);
  453.         $rdblog->setLegal('NaN');
  454.         $rdblog->setPrivate('NaN');
  455.         $rdblog->setCreatedAt(new \DateTime());
  456.         $legal false;
  457.         if (isset($arrData['legal']))
  458.         {
  459.             $legal $arrData['legal'];
  460.             $rdblog->setLegal((string) $arrData['legal']);
  461.         }
  462.         $private false;
  463.         if (isset($arrData['private']))
  464.         {
  465.             $private $arrData['private'];
  466.             $rdblog->setPrivate((string) $arrData['private']);
  467.         }
  468.         $em->persist($rdblog);
  469.         $em->flush();
  470.         $location $appHelper->getPositionByZipcodeFromGoogle($this->getParameter('gmap_apikey'''), $arrData['zipcode']);
  471.         if (count($location) && isset($location['lat']) && isset($location['lng']))
  472.         {
  473.             $lat      $location['lat'];
  474.             $lng      $location['lng'];
  475.             $distance $arrData['distance'];
  476.             $distClmn '(6371*acos(cos(radians('.$lat.'))*cos(radians(gp.lat))*cos(radians(gp.lng)-radians('.$lng.'))+sin(radians('.$lat.'))*sin(radians(gp.lat)))) AS distance';
  477.             $sql      'SELECT DISTINCT gp.*, '.$distClmn.' FROM gplace AS gp ';
  478.             $sql     .= 'LEFT JOIN gplace_specialization AS gpspec ON gp.id = gpspec.gplace_id ';
  479.             $sql     .= 'LEFT JOIN specialization AS spec ON gpspec.specialization_id = spec.id ';
  480.             if (isset($arrData['only_female_doctor']) && $arrData['only_female_doctor']) {
  481.                 $sql .= ' WHERE (gp.gender = "female" OR gp.gender = "female / male") ';
  482.             } elseif (isset($arrData['only_male_doctor']) && $arrData['only_male_doctor']) {
  483.                 $sql .= ' WHERE (gp.gender = "male" OR gp.gender = "female / male") ';
  484.             }
  485.             $arrSpecs explode(','$arrData['specialization']);
  486.             if (is_array($arrSpecs)) {
  487.                 for ($i 0;$i<count($arrSpecs);$i++){
  488.                     if ($i === 0){
  489.                         if ((isset($arrData['only_female_doctor']) && $arrData['only_female_doctor']) || (isset($arrData['only_male_doctor']) && $arrData['only_male_doctor'])){
  490.                             $sql .= 'AND (gpspec.specialization_id='.$arrSpecs[$i];
  491.                         } else {
  492.                             $sql .= 'WHERE (gpspec.specialization_id='.$arrSpecs[$i];
  493.                         }
  494.                     } else {
  495.                         $sql .= ' OR gpspec.specialization_id=' $arrSpecs[$i];
  496.                     }
  497.                     if ($i===count($arrSpecs)-1){
  498.                         $sql .= ')';
  499.                     }
  500.                 } 
  501.                     $sql     .= ' Group BY gp.id ';
  502.                     $sql     .= ' HAVING (((distance <= '.$distance.')) AND ((Count(DISTINCT gpspec.specialization_id) = ' .  Count($arrSpecs) . ')))';
  503.                     $sql     .= ' ORDER BY distance ASC LIMIT 1,'.$arrData['limit'];
  504.             }
  505.  
  506.             $stm     $em->getConnection()->executeQuery($sql);
  507.             $arrRess $stm->fetchAll();
  508.             if ($arrRess)
  509.             {
  510.                 foreach ($arrRess as $idx => $res)
  511.                 {
  512.                     $arrRet[$idx]['name']                      = $res['name'];
  513.                     $arrRet[$idx]['Fachrichtungen']            = $res['specialization'];
  514.                     $arrRet[$idx]['Strasse']                   = $res['street'].' '.$res['street_nr'];
  515.                     $arrRet[$idx]['PLZ']                       = $res['zipcode'];
  516.                     if ($res['country'] == 'DE' && strlen($res['zipcode']) == 4)
  517.                     {
  518.                         $arrRet[$idx]['PLZ']                   = '0'.$res['zipcode'];
  519.                     }
  520.                     $arrRet[$idx]['Ort']                       = $res['city'];
  521.                     $arrRet[$idx]['Telefon Nummer']            = $res['phonenumber'];
  522.                     $arrRet[$idx]['Fax Nummer']                = '';
  523.                     $arrRet[$idx]['Webseite']                  = $res['website'];
  524.                     if (!$res['website'] || empty($res['website']))
  525.                     {
  526.                         $arrRet[$idx]['Webseite']              = "";
  527.                     }
  528.                     $arrRet[$idx]['Email']                     = '';
  529.                     $arrRet[$idx]['Öffnungszeiten Montag']     = '';
  530.                     $arrRet[$idx]['Öffnungszeiten Dienstag']   = '';
  531.                     $arrRet[$idx]['Öffnungszeiten Mittwoch']   = '';
  532.                     $arrRet[$idx]['Öffnungszeiten Donnerstag'] = '';
  533.                     $arrRet[$idx]['Öffnungszeiten Freitag']    = '';
  534.                     $arrRet[$idx]['Öffnungszeiten Samstag']    = '';
  535.                     $arrRet[$idx]['Öffnungszeiten Sonntag']    = '';
  536.                     $arrRet[$idx]['Gesetzlich']                = '';
  537.                     $arrRet[$idx]['Privat']                    = '';
  538.                 }
  539.             }
  540.             $arrRet = array('results' => $arrRet);
  541.         }
  542.         return $this->createJsonResponse($arrRet);
  543.     }
  544.     /**
  545.      * @Route(
  546.      *     "/api/research_old.json",
  547.      *     name="api_research_old",
  548.      *     methods={"POST", "OPTIONS"}
  549.      * )
  550.      */
  551.     public function researchActionOld(Request $requestAppHelper $appHelperString $gmapApikeyString $accountToken)
  552.     {
  553.         $em        $this->getDoctrine()->getManager();
  554.         $inputData $request->getContent();
  555.         $arrData   json_decode($inputDatatrue);
  556.         $arrRet    = [];
  557.         if (!$request->isMethod('POST')) {
  558.             $arrRet['message'] = 'Request method is not correct!';
  559.             return $this->createJsonResponse($arrRet);
  560.         }
  561.         if (!$request->headers->has('X-i42AccountToken')) {
  562.             $arrRet['message'] = 'Account token is missing!';
  563.             return $this->createJsonResponse($arrRet);
  564.         }
  565.         $i42AccountToken $request->headers->get('X-i42AccountToken');
  566.         if ($i42AccountToken != $accountToken) {
  567.             $arrRet['message'] = 'Unregistered account token!';
  568.             return $this->createJsonResponse($arrRet);
  569.         }
  570.         if (!(
  571.             is_array($arrData)                 &&
  572.             isset($arrData['zipcode'])         && !empty(trim($arrData['zipcode']))        &&
  573.             isset($arrData['distance'])        && !empty($arrData['distance'])             && ctype_digit((string) $arrData['distance']) &&
  574.             isset($arrData['specialization'])  && !empty(trim($arrData['specialization'])) &&
  575.             isset($arrData['limit'])           && !empty($arrData['limit'])                && ctype_digit((string) $arrData['limit'])
  576.         )) {
  577.             $arrRet['message'] = 'Not all necessary data submitted!';
  578.             return $this->createJsonResponse($arrRet);
  579.         }
  580.         $rdblog = new Mdmrdblog();
  581.         $rdblog->setZipcode((string) $arrData['zipcode']);
  582.         $rdblog->setDistance((string) $arrData['distance']);
  583.         $rdblog->setSpecialization((string) $arrData['specialization']);
  584.         $rdblog->setCountlimit((string) $arrData['limit']);
  585.         $rdblog->setOnlyfemaledoctor('NaN');
  586.         $rdblog->setOnlymaledoctor('NaN');
  587.         $rdblog->setLegal('NaN');
  588.         $rdblog->setPrivate('NaN');
  589.         $rdblog->setCreatedAt(new \DateTime());
  590.         $onlyMaleDoctor false;
  591.         if (isset($arrData['only_male_doctor']))
  592.         {
  593.             $onlyMaleDoctor $arrData['only_male_doctor'];
  594.             $rdblog->setOnlymaledoctor((string) $arrData['only_male_doctor']);
  595.         }
  596.         $onlyFemaleDoctor false;
  597.         if (isset($arrData['only_female_doctor']))
  598.         {
  599.             $onlyFemaleDoctor $arrData['only_female_doctor'];
  600.             $rdblog->setOnlyfemaledoctor((string) $arrData['only_male_doctor']);
  601.         }
  602.         $legal false;
  603.         if (isset($arrData['legal']))
  604.         {
  605.             $legal $arrData['legal'];
  606.             $rdblog->setLegal((string) $arrData['legal']);
  607.         }
  608.         $private false;
  609.         if (isset($arrData['private']))
  610.         {
  611.             $private $arrData['private'];
  612.             $rdblog->setPrivate((string) $arrData['private']);
  613.         }
  614.         $em->persist($rdblog);
  615.         $em->flush();
  616.         $location $appHelper->getPositionByZipcodeFromGoogle($this->getParameter('gmap_apikey'''), $arrData['zipcode']);
  617.         if (count($location) && isset($location['lat']) && isset($location['lng']))
  618.         {
  619.             $lat      $location['lat'];
  620.             $lng      $location['lng'];
  621.             $distance $arrData['distance'];
  622.             $distClmn '(6371*acos(cos(radians('.$lat.'))*cos(radians(gp.lat))*cos(radians(gp.lng)-radians('.$lng.'))+sin(radians('.$lat.'))*sin(radians(gp.lat)))) AS distance';
  623.             $sql      'SELECT DISTINCT gp.*, '.$distClmn.' FROM gplace AS gp ';
  624.             $sql     .= 'LEFT JOIN gplace_specialization AS gpspec ON gp.id = gpspec.gplace_id ';
  625.             $sql     .= 'LEFT JOIN specialization AS spec ON gpspec.specialization_id = spec.id ';
  626.             $arrSpecs explode(','$arrData['specialization']);
  627.             if (!empty($arrData['specialization']))
  628.             {
  629.                 $sql .= 'WHERE gpspec.specialization_id IN ('.implode(','$arrSpecs).') ';
  630.             }
  631.             $sql     .= 'HAVING distance <= '.$distance.' ';
  632.             $sql     .= 'ORDER BY distance ASC LIMIT 1,'.$arrData['limit'];
  633.             $stm     $em->getConnection()->executeQuery($sql);
  634.             $arrRess $stm->fetchAll();
  635.             if ($arrRess)
  636.             {
  637.                 foreach ($arrRess as $idx => $res)
  638.                 {
  639.                     $arrRet[$idx]['name']                      = $res['name'];
  640.                     $arrRet[$idx]['Fachrichtungen']            = $res['specialization'];
  641.                     $arrRet[$idx]['Strasse']                   = $res['street'].' '.$res['street_nr'];
  642.                     $arrRet[$idx]['PLZ']                       = $res['zipcode'];
  643.                     if ($res['country'] == 'DE' && strlen($res['zipcode']) == 4)
  644.                     {
  645.                         $arrRet[$idx]['PLZ']                   = '0'.$res['zipcode'];
  646.                     }
  647.                     $arrRet[$idx]['Ort']                       = $res['city'];
  648.                     $arrRet[$idx]['Telefon Nummer']            = $res['phonenumber'];
  649.                     $arrRet[$idx]['Fax Nummer']                = '';
  650.                     $arrRet[$idx]['Webseite']                  = $res['website'];
  651.                     if (!$res['website'] || empty($res['website']))
  652.                     {
  653.                         $arrRet[$idx]['Webseite']              = "";
  654.                     }
  655.                     $arrRet[$idx]['Email']                     = '';
  656.                     $arrRet[$idx]['Öffnungszeiten Montag']     = '';
  657.                     $arrRet[$idx]['Öffnungszeiten Dienstag']   = '';
  658.                     $arrRet[$idx]['Öffnungszeiten Mittwoch']   = '';
  659.                     $arrRet[$idx]['Öffnungszeiten Donnerstag'] = '';
  660.                     $arrRet[$idx]['Öffnungszeiten Freitag']    = '';
  661.                     $arrRet[$idx]['Öffnungszeiten Samstag']    = '';
  662.                     $arrRet[$idx]['Öffnungszeiten Sonntag']    = '';
  663.                     $arrRet[$idx]['Gesetzlich']                = '';
  664.                     $arrRet[$idx]['Privat']                    = '';
  665.                 }
  666.             }
  667.             $arrRet = array('results' => $arrRet);
  668.         }
  669.         return $this->createJsonResponse($arrRet);
  670.     }
  671.     /**
  672.      * @Route(
  673.      *     "/api/gp_type.json",
  674.      *     name="api_gp_typelist",
  675.      *     methods={"POST", "OPTIONS"}
  676.      * )
  677.      */
  678.     public function gp_typelistAction(Request $requestString $accountToken)
  679.     {
  680.         $em        $this->getDoctrine()->getManager();
  681.         $arrRet    = [];
  682.         if (!$request->isMethod('POST')) {
  683.             $arrRet['message'] = 'Request method is not correct!';
  684.             return $this->createJsonResponse($arrRet);
  685.         }
  686.         if (!$request->headers->has('X-i42AccountToken')) {
  687.             $arrRet['message'] = 'Account token is missing!';
  688.             return $this->createJsonResponse($arrRet);
  689.         }
  690.         $i42AccountToken $request->headers->get('X-i42AccountToken');
  691.         if ($i42AccountToken != $accountToken) {
  692.             $arrRet['message'] = 'Unregistered account token!';
  693.             return $this->createJsonResponse($arrRet);
  694.         }
  695.         $types $em->getRepository(Gptype::class)->findBy(array(), array('type' => 'ASC'));
  696.         
  697.         foreach ($types as $type)
  698.         {
  699.             $arrRet[$type->getId()] = $type->getType();
  700.         }
  701.         return $this->createJsonResponse($arrRet);
  702.     }
  703.     /**
  704.      * @Route(
  705.      *     "/api/specializationlist.json",
  706.      *     name="api_specializationlist",
  707.      *     methods={"POST", "OPTIONS"}
  708.      * )
  709.      */
  710.     public function specializationlistAction(Request $requestString $accountToken)
  711.     {
  712.         $em        $this->getDoctrine()->getManager();
  713.         $inputData $request->getContent();
  714.         $arrData   json_decode($inputDatatrue);
  715.         $arrRet    = [];
  716.         if (!$request->isMethod('POST')) {
  717.             $arrRet['message'] = 'Request method is not correct!';
  718.             return $this->createJsonResponse($arrRet);
  719.         }
  720.         if (!$request->headers->has('X-i42AccountToken')) {
  721.             $arrRet['message'] = 'Account token is missing!';
  722.             return $this->createJsonResponse($arrRet);
  723.         }
  724.         $i42AccountToken $request->headers->get('X-i42AccountToken');
  725.         if ($i42AccountToken != $accountToken) {
  726.             $arrRet['message'] = 'Unregistered account token!';
  727.             return $this->createJsonResponse($arrRet);
  728.         }
  729.         $language 'de';
  730.         if (is_array($arrData) && isset($arrData['language']) && $arrData['language'] == 'en')
  731.         {
  732.             $language 'en';
  733.         }
  734.         if ($language == 'en')
  735.         {
  736.             $specializations $em->getRepository(Specialization::class)->findBy(array('is_active' => true), array('nameEn' => 'ASC'));
  737.         }
  738.         else
  739.         {
  740.             $specializations $em->getRepository(Specialization::class)->findBy(array('is_active' => true), array('name' => 'ASC'));
  741.         }
  742.         
  743.         foreach ($specializations as $specialization)
  744.         {
  745.             if ($language == 'en')
  746.             {
  747.                 $arrRet[$specialization->getId()] = $specialization->getNameEn();
  748.             }
  749.             else
  750.             {
  751.                 $arrRet[$specialization->getId()] = $specialization->getName();
  752.             }
  753.         }
  754.         return $this->createJsonResponse($arrRet);
  755.     }
  756.     /**
  757.      * A basic validation of the received request data
  758.      *
  759.      * @param Request $request
  760.      * @return false|array
  761.      */
  762.     protected function validateRequest(Request $request$validateContentType true$bodycheck true)
  763.     {
  764.         $e = array();
  765.         //check content-type
  766.         if( $validateContentType && $request->headers->get('Content-Type') != "application/json" )
  767.         {
  768.             $e[] = $this->createErrorMessage(11'invalid content type');
  769.         }
  770.         //check method
  771.         if( $request->getMethod() != Request::METHOD_POST )
  772.         {
  773.             $e[] = $this->createErrorMessage(12'invalid request method');
  774.         }
  775.         //check i43-header information
  776.         if ($request->headers->has('X-i43AccountToken'))
  777.         {
  778.             $i43AccountToken $request->headers->get('X-i43AccountToken''');
  779.             if ($i43AccountToken !== 'DE955A86-69FF-42D9-9B77-7F00CD69EF4E')
  780.             {
  781.                 $e[]  = $this->createErrorMessage(21'auth information fault');
  782.             }
  783.         }
  784.         //check body data
  785.         $this->requestData = array();
  786.         $inputData         $request->getContent();
  787.         if ($bodycheck)
  788.         {
  789.             if (strlen($inputData) == 0)
  790.             {
  791.                 $e[] = $this->createErrorMessage(13'no data found in the body');
  792.             }
  793.         }
  794.         if (strlen($inputData))
  795.         {
  796.             $this->requestData json_decode($inputDatatrue);
  797.             if(json_last_error())
  798.             {
  799.                 $e[] = $this->createErrorMessage(17'json error: '.json_last_error_msg());
  800.             }
  801.         }
  802.         return $e;
  803.     }
  804.     
  805.     protected function createErrorMessage($errorCode$msg)
  806.     {
  807.         $data = [];
  808.         $data['error']['code'] = $errorCode;
  809.         $data['error']['msg']  = $msg;
  810.         return $data;
  811.     }
  812.     protected function createJsonResponse($data)
  813.     {
  814.         $response = new Response();
  815.         $response->headers->set('Content-Type''application/json');
  816.         $response->headers->set('Access-Control-Allow-Credentials'true);
  817.         $response->headers->set('Access-Control-Allow-Origin''*');
  818.         $response->headers->set('Access-Control-Allow-Headers''*');
  819.         if (is_array($data) && count($data))
  820.         {
  821.             return $response->setContent(json_encode($data));
  822.         }
  823.         else
  824.         {
  825.             return $response->setContent('{}');
  826.         }
  827.     }
  828.     /**
  829.      * Creates the json from given error list
  830.      *
  831.      * @param type $errorList
  832.      * @return type
  833.      */
  834.     protected function createErrorResponse($errorList)
  835.     {
  836.         return $this->createJsonResponse(array_shift($errorList));
  837.     }
  838. }