src/Controller/WS/ReadFilesDataController.php line 7317

Open in your IDE?
  1. <?php
  2. namespace App\Controller\WS;
  3. use App\Websocket\PusherManager;
  4. use Symfony\Component\Process\Process;
  5. use Symfony\Component\HttpFoundation\Request;
  6. use Symfony\Component\HttpFoundation\Response;
  7. use Symfony\Component\Console\Input\ArrayInput;
  8. use Symfony\Component\HttpFoundation\JsonResponse;
  9. use Symfony\Component\Console\Output\BufferedOutput;
  10. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  11. use App\Util\WS\Util;
  12. use App\Util\NewUtil;
  13. use App\Util\Util as Utilx;
  14. use App\Util\UUIDGeneratorUtil;
  15. use App\Util\WS\ForcedAsynchronousCommandsUtil;
  16. use stdClass;
  17. use App\Structure\Usuario;
  18. use App\Structure\RegistActions;
  19. use App\Entity\User;
  20. use App\Entity\PushSent;
  21. use App\Entity\GiftCard;
  22. use App\Entity\MasterSync;
  23. use App\Entity\WebService;
  24. use App\Entity\ReadFilesData;
  25. use App\Entity\AccountLicense;
  26. use App\Entity\ReadFilesDataWeb;
  27. use App\Entity\SyncReportedError;
  28. use App\Entity\LogAndroidEmailSent;
  29. use App\Entity\GiftCardTransaction;
  30. use App\Entity\ThirdPartyAPIRecords;
  31. use App\Entity\AndroidErrorsHistory;
  32. use App\Entity\SyncAllCallStatus;
  33. use App\Entity\ErrorAndroidEmailSent;
  34. use App\Entity\NotificationInLicensorBell;
  35. use App\Transformer\SyncWebTransformer;
  36. use App\Transformer\DemoForLoginTransformer;
  37. use App\Transformer\SublicensesListTransformer;
  38. use App\Transformer\LicensorGenericTransformer;
  39. use App\Transformer\UpdateAndroidCommandTransformer;
  40. use App\Transformer\UploadSyncJsonNotifyTransformer;
  41. use App\Transformer\UpdateMobileInsertJsonTransformer;
  42. use App\Transformer\RespondedNotificationPushTransformer;
  43. use App\Controller\Application\Service\ArmorService;
  44. use App\Controller\Application\Service\Log\Log;
  45. use App\Controller\Application\Service\Util\Encryptor;
  46. use Symfony\Bundle\FrameworkBundle\Console\Application;
  47. use DateTime;
  48. use App\SynchronizationUtil\SyncWebUtil;
  49. use Exception;
  50. use App\Command\Websocket\SyncAllWebsocketVersionCommand;
  51. use App\Consumer\WS\SyncFullCallConsumer;
  52. use App\Entity\ActionHistory;
  53. use App\Util\UtilSync;
  54. /**
  55.  * Description of ReadFilesDataController
  56.  * @author
  57.  */
  58. class ReadFilesDataController extends ApiController {
  59.     /**
  60.      * Esta funcion permite validar el acceso a la aplicacion web de level
  61.      * validando codigo de usuario y contraseña y generando el apiKey
  62.      * necesario para toda la aplicacion movil
  63.      * @author Aealan Z <lrobledo@kijho.com> 08/10/15
  64.      * @param \Symfony\Component\HttpFoundation\Request $request datos de la solicitud
  65.      * @return Response Json con la informacion de respuesta
  66.      */
  67.     public function loginMobil(Request $request) {
  68.         
  69.         if ($request->getMethod() !== WebService::REQUEST_METHOD_POST) {
  70.             return $this->errorNotAllowedMethod('Method not allowed. Use ' WebService::REQUEST_METHOD_POST " method");
  71.         }
  72.         if (!(=== strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_STRUCTURE) || === strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_TEXT))) {
  73.             return $this->errorWrongArgs('Wrong Content.'WebService::CODE_WRONG_ARGUMENTS);
  74.         }
  75.         $path Util::getValidActiveLogByBaseName($this->realContainer'InitialAndroidLoginWS''InitialAndroidLoginWS0.txt');
  76.         $this->createFileJson($path"\r" 'Login Mobile: ' $request->getContent() . "\r");
  77.         try {
  78.             $arrayEncryptResult Util::decryptDataForAndroid($this->realContainer$request->getContent());
  79.             $data json_decode($arrayEncryptResult['data'], true);
  80.             if (!isset($data['alLicenseUsername']) || !isset($data['password']) || !isset($data['username']) || !isset($data['uid'])) {
  81.                 return $this->errorWrongArgs('Wrong Arguments.'WebService::CODE_WRONG_ARGUMENTS);
  82.             }
  83.             $licenseUserName = ['alLicenseUsername' => $data['alLicenseUsername']];
  84.             $em $this->getDoctrine()->getManager();
  85.             
  86.             $accountLicenseData $em->getRepository('App\Entity\AccountLicense')->findBy($licenseUserName);
  87.             $countResult count($accountLicenseData);
  88.             
  89.             if ($countResult <= 0) {
  90.                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  91.                                 ->respondWithError('Invalid nickname'WebService::CODE_COULD_NOT_AUTHENTICATE);
  92.             }
  93.             if ($accountLicenseData[0]->getAlAccountLicense()->getDeleted()) {
  94.                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  95.                                 ->respondWithError('Inactive Account'WebService::CODE_ACCOUNT_SUSPENDED);
  96.             }
  97.             if ($accountLicenseData[0]->getAlLicenseStatus() == AccountLicense::LICENSE_STATUS_INACTIVE) {
  98.                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  99.                                 ->respondWithError('Inactive License'WebService::CODE_ACCOUNT_SUSPENDED);
  100.             }
  101.             if ($accountLicenseData[0]->getAlLicenseStatus() == AccountLicense::LICENSE_STATUS_PENDING) {
  102.                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  103.                                 ->respondWithError('Pending License'WebService::CODE_ACCOUNT_SUSPENDED);
  104.             }
  105.             $oldUID $accountLicenseData[0]->getDeviceUid();
  106.             $oldLoguedDeviceKind $accountLicenseData[0]->getLastloguedDeviceKind();
  107.             $alreadyUsingLastVersion false;
  108.             $deviceUIDWasSetted false;
  109.             $arrayGoodWayUpdate = [];
  110.             $arrayWrongWayUpdate = [];
  111.             $theVersionArrayForOldUsers = [];
  112.             $accountLicenseData[0]->setHasAndroid(true);
  113.             $country $accountLicenseData[0]->getCity()->getCiState()->getStCountry()->getCoVal();
  114.             $isCallCenter $accountLicenseData[0]->getIsCallCenter();
  115.             $language Util::getLanguageCodeByCountryCode($country);
  116.             $theRespArray['language'] = $language;
  117.             $pathXD $this->realContainer->getParameter('level_directory_logs') . 'ip_man.json';
  118.             $this->createFileJson($pathXD$this->realContainer->get('request_stack')->getCurrentRequest()->getClientIp() . ' -> ' $data['alLicenseUsername'] . ' |L| ');
  119.             if (isset($data['isLiteDevice'])) {
  120.                 $accountLicenseByUID $em->getRepository('App\Entity\AccountLicense')->findBy(['deviceUid' => $data['uid']]);
  121.                 if (empty($accountLicenseByUID) && $accountLicenseData[0]->getLastloguedDeviceKind() == AccountLicense::DEVICE_LITE_TYPE) {
  122.                     $deviceUIDWasSetted true;
  123.                     $accountLicenseData[0]->setHasAndroid(true);
  124.                     $accountLicenseData[0]->setDeviceUid($data['uid']);
  125.                 } else {
  126.     //                dump('Hola chingo!');
  127.                     $accountLicenseData[0]->setHasAndroid(true);
  128.                     if (!($accountLicenseData[0]->getDeviceUid() && $accountLicenseData[0]->getLastloguedDeviceKind() != AccountLicense::DEVICE_LITE_TYPE)) {
  129.     //                    dump('Jumm!');
  130.                         if (isset($accountLicenseByUID[0]) && isset($accountLicenseData[0]) && ($accountLicenseData[0]->getId() == $accountLicenseByUID[0]->getId()) && $accountLicenseByUID[0]->getLastloguedDeviceKind() == AccountLicense::DEVICE_LITE_TYPE) {
  131.     //                        dump('Jumm x2!');
  132.                             $accountLicenseByUID[0]->setDeviceUid(null);
  133.                             $accountLicenseByUID[0]->setWsResourceIdVerifiedAfterLogin(0);
  134.                             $em->persist($accountLicenseByUID[0]);
  135.                             $em->flush();
  136.                             $accountLicenseData[0]->setDeviceUid($data['uid']);
  137.                         } elseif (isset($accountLicenseByUID[0]) && (!$accountLicenseData[0]->getDeviceUid() || $accountLicenseData[0]->getDeviceUid() == '')) {
  138.                             $auxLicenseFoundCounter 1;
  139.                             $auxLicenseUID $accountLicenseByUID[0]->getDeviceUid() . '_aux_lite_' $accountLicenseByUID[0]->getAlLicenseUsername() . '_' $auxLicenseFoundCounter;
  140.                             $deviceSplitAux explode("_aux_lite_"$auxLicenseUID);
  141.                             do {
  142.                                 $auxLicenseUID $deviceSplitAux[0] . '_aux_lite_' $accountLicenseByUID[0]->getAlLicenseUsername() . '_' $auxLicenseFoundCounter;
  143.                                 $accountLicenseByUID $em->getRepository('App\Entity\AccountLicense')->findBy(['deviceUid' => $auxLicenseUID]);
  144.                                 ++$auxLicenseFoundCounter;
  145.                             } while (isset($accountLicenseByUID[0]));
  146.                             $accountLicenseData[0]->setDeviceUid($auxLicenseUID);
  147.                             $accountLicenseData[0]->setHasAndroid(true);
  148.                         } else if (!isset($accountLicenseByUID[0]) && (!$accountLicenseData[0]->getDeviceUid() || $accountLicenseData[0]->getDeviceUid() == '')) {
  149.                             $accountLicenseData[0]->setDeviceUid($data['uid']);
  150.                             $accountLicenseData[0]->setHasAndroid(true);
  151.                         }
  152.                         $accountLicenseData[0]->setLastloguedDeviceKind(AccountLicense::DEVICE_LITE_TYPE);
  153.                     }
  154.                 }
  155.     //            dump('Casillo!?');
  156.     //            die;
  157.                 $em->persist($accountLicenseData[0]);
  158.                 $em->flush();
  159.             } else {
  160.     //            dump(isset($data['uid']), $data['uid']);
  161.     //            dump($accountLicenseData[0]->getDeviceUid() == '');
  162.     //            dump(null == $accountLicenseData[0]->getDeviceUid());
  163.     //            die;
  164.                 if (isset($data['uid']) && ($accountLicenseData[0]->getDeviceUid() == '' || null == $accountLicenseData[0]->getDeviceUid())) {
  165.                     $accountLicenseByUID $em->getRepository('App\Entity\AccountLicense')->findBy(['deviceUid' => $data['uid']]);
  166.                     // dump($accountLicenseByUID);
  167.                     if (!empty($accountLicenseByUID)) {
  168.                         $alreadyWithTheSameUIDLicense $accountLicenseByUID[0];
  169.                         if ($accountLicenseData[0]->getAlLicenseUsername() != $accountLicenseByUID[0]->getAlLicenseUsername() && $accountLicenseByUID[0]->getLastloguedDeviceKind() != AccountLicense::DEVICE_LITE_TYPE) {
  170.                             return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  171.                                             ->respondWithError("Device UID '" $data['uid'] . "' already registed with '" $accountLicenseByUID[0] . "' license using a non lite app"WebService::CODE_COULD_NOT_AUTHENTICATE);
  172.                         } elseif ($accountLicenseData[0]->getAlLicenseUsername() != $accountLicenseByUID[0]->getAlLicenseUsername()) {
  173.                             $auxLicenseFoundCounter 1;
  174.                             $auxLicenseUID $accountLicenseByUID[0]->getDeviceUid() . '_aux_lite_' $accountLicenseByUID[0]->getAlLicenseUsername() . '_' $auxLicenseFoundCounter;
  175.                             $deviceSplitAux explode("_aux_lite_"$auxLicenseUID);
  176.                             do {
  177.                                 $auxLicenseUID $deviceSplitAux[0] . '_aux_lite_' $accountLicenseByUID[0]->getAlLicenseUsername() . '_' $auxLicenseFoundCounter;
  178.                                 $accountLicenseByUID $em->getRepository('App\Entity\AccountLicense')->findBy(['deviceUid' => $auxLicenseUID]);
  179.                                 ++$auxLicenseFoundCounter;
  180.                             } while (isset($accountLicenseByUID[0]));
  181.                             $alreadyWithTheSameUIDLicense->setDeviceUid($auxLicenseUID);
  182.                             $alreadyWithTheSameUIDLicense->setHasAndroid(true);
  183.                             $em->persist($alreadyWithTheSameUIDLicense);
  184.                             $em->flush();
  185.                             $auxLevEm Util::emLicenseConnection($this->realContainer$em$alreadyWithTheSameUIDLicense);
  186.                             $configuracionForAll $auxLevEm->getRepository('App\Structure\Configuracion')->findAll();
  187.                             if (!empty($configuracionForAll)) {
  188.                                 $configuracion $configuracionForAll[0];
  189.                             }
  190.                             if ($configuracion) {
  191.                                 $configuracion->setConfHasAndriod(true);
  192.                                 $configuracion->setConfDeviceUid($alreadyWithTheSameUIDLicense->getDeviceUid());
  193.                                 $this->createFileJson($path"\r" '1 SETEO DE LEVEL UUID CONFIG: ' $alreadyWithTheSameUIDLicense->getDeviceUid() . ' HAS ANDROID : TRUE' "\r");
  194.                                 $auxLevEm->persist($configuracion);
  195.                                 $auxLevEm->flush();
  196.                                 $auxLevEm->close();
  197.                             }
  198.                         }
  199.                     }
  200.                     $deviceUIDWasSetted true;
  201.                     $accountLicenseData[0]->setHasAndroid(true);
  202.                     $accountLicenseData[0]->setDeviceUid($data['uid']);
  203.                 } else {
  204.                     if (isset($data['uid']) && $accountLicenseData[0]->getDeviceUid() != $data['uid'] && $accountLicenseData[0]->getLastloguedDeviceKind() != AccountLicense::DEVICE_LITE_TYPE) {
  205.                         return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  206.                                         ->respondWithError("There is another server device with the UID '" $accountLicenseData[0]->getDeviceUid() . "' registered with this license"WebService::CODE_INVALID_UID);
  207.                     } else {
  208.                         $accountLicenseByUID $em->getRepository('App\Entity\AccountLicense')->findBy(['deviceUid' => $data['uid']]);
  209.                         if (!empty($accountLicenseByUID)) {
  210.                             if ($accountLicenseData[0]->getAlLicenseUsername() != $accountLicenseByUID[0]->getAlLicenseUsername() && ($accountLicenseData[0]->getLastloguedDeviceKind() != AccountLicense::DEVICE_LITE_TYPE || $accountLicenseByUID[0]->getLastloguedDeviceKind() != AccountLicense::DEVICE_LITE_TYPE)) {
  211.                                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  212.                                                 ->respondWithError("Device UID '" $data['uid'] . "' already registed with '" $accountLicenseByUID[0] . "' license"WebService::CODE_COULD_NOT_AUTHENTICATE);
  213.                             } else {
  214.                                 $accountLicenseByUID[0]->setDeviceUid(null);
  215.                                 $accountLicenseByUID[0]->setHasAndroid(null);
  216.                                 $accountLicenseByUID[0]->setWsResourceIdVerifiedAfterLogin(0);
  217.                                 $em->persist($accountLicenseByUID[0]);
  218.                                 $em->flush();
  219.                             }
  220.                         }
  221.                         $deviceUIDWasSetted true;
  222.                         $accountLicenseData[0]->setHasAndroid(true);
  223.                         $accountLicenseData[0]->setDeviceUid($data['uid']);
  224.                     }
  225.                 }
  226.                 $accountLicenseData[0]->setLastloguedDeviceKind(AccountLicense::DEVICE_ANDROID_TYPE);
  227.             }
  228.             $liteUsername '';
  229.             $responseArrOmt = [];
  230.             /**
  231.              * Allows to add the apikey to the user of lite level this exported in OMT
  232.              */
  233.             if ($accountLicenseData[0]->getHasLogedOMT() == true || $accountLicenseData[0]->getIsLevelLight() == true || (isset($data['isLiteDevice']) && $data['isLiteDevice']) ) {
  234.                 $this->createFileJson($path'Util::doOMTDashboardLoginToGetToken 1!' "\r");
  235.                 
  236.                 $levelLiteUser $accountLicenseData[0]->getLevelLightUser();
  237.                 // $apikey = Util::doOMTDashboardLoginToGetToken($this->realContainer, $levelLiteUser, $path, $accountLicenseData[0]->getLoginType());
  238.                 if (!empty($apikey)) {
  239.                     $levelLiteUser['apikey'] = $apikey;
  240.                     $responseArrOmt['userToOmt']['apikey'] = $apikey;
  241.                 }
  242.                 if (!empty($apikey)) {
  243.                     $levelLiteUser['apikey'] = $apikey;
  244.                     $accountLicenseData[0]->setLevelLightUser($levelLiteUser);
  245.                 }
  246.                 $liteUsername $levelLiteUser['username'];
  247.                 $responseArrOmt['userToOmt']['username'] = $liteUsername;
  248.                 $responseArrOmt['userToOmt']['password'] = $levelLiteUser['realPass'];
  249.             }
  250.             if (isset($data['version'])) {
  251.                 $data['version'] = trim($data['version']);
  252.             }
  253.             if (isset($data['version']) && !isset($data['isLiteDevice'])) {
  254.                 if (strpos($data['version'], '-')) {
  255.                     $this->createFileJson($path'Is a testing version...?  ' $data['version'] . "\r");
  256.                     $data['version'] = explode('-'$data['version'])[0];
  257.                 }
  258.                 if (!preg_match('/^(\d+\.)(\d+\.)(\d+)$/'$data['version'])) {
  259.                     return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  260.                                     ->respondWithError('Invalid version format'WebService::CODE_COULD_NOT_AUTHENTICATE);
  261.                 }
  262.                 $accountLicenseData[0]->setAndroidVersionName($data['version']);
  263.                 $accountLicenseData[0]->setVersionUpdatedDate(Util::getCurrentDate());
  264.                 $theRespArray Util::getLastVersionByDirNow($this->realContainerfalse$path);
  265.                 $theRespArray['bigbag'] = true;
  266.                 $theRespArray['language'] = $language;
  267.                 if (isset($theRespArray['updateAppError']) && $theRespArray['updateAppError']) {
  268.                     return $this->setStatusCode(WebService::HTTP_CODE_SERVICE_UNAVAILABLE)
  269.                                     ->respondWithError('Error finding last version'WebService::CODE_OBJECT_NOT_FOUND);
  270.                 }
  271.                 if (isset($theRespArray['newVersion'])) {
  272.                     $newVersionString Util::validateNewerVersion($data['version'], $theRespArray['newVersion']);
  273.                     if ($newVersionString != $data['version']) {
  274.                         $theRespArray['success'] = WebService::CODE_SUCCESS;
  275.                         $theRespArray['country'] = $country;
  276.                         $theRespArray['iscallcenter'] = (int) $isCallCenter;
  277.                         $theUrlTrSt = new UpdateAndroidCommandTransformer($this->realContainer$theRespArray);
  278.                         $xxArray $theUrlTrSt->transform();
  279.                         $jsonContent json_encode($xxArray);
  280.                         return $this->respondWithItem($jsonContent$theUrlTrSt);
  281.                     } else {
  282.                         $arrayWrongWayUpdate['case'] = 'Android client is already updated!';
  283.                         $alreadyUsingLastVersion true;
  284.                     }
  285.                 } else {
  286.                     $arrayWrongWayUpdate['case'] = 'Android client is already updated!';
  287.                     $alreadyUsingLastVersion true;
  288.                 }
  289.             } elseif (!isset($data['isLiteDevice'])) {
  290.                 $userOldVersion $accountLicenseData[0]->getAndroidVersionName();
  291.                 if (null != $userOldVersion && $userOldVersion != '') {
  292.                     $theVersionArrayForOldUsers Util::getLastVersionByDirAvailableVersions($this->realContainer$userOldVersiontrue$path);
  293.                 } else {
  294.                     $theVersionArrayForOldUsers Util::getLastVersionByDirAvailableVersions($this->realContainer'1.0.0'true$path);
  295.                 }
  296.                 if (isset($theVersionArrayForOldUsers['updateAppIsNeeded']) && $theVersionArrayForOldUsers['updateAppIsNeeded'] === true) {
  297.                     $arrayGoodWayUpdate['apkurl'] = $theVersionArrayForOldUsers['updateRequestApk'];
  298.                     $arrayGoodWayUpdate['lastversion'] = $theVersionArrayForOldUsers['newVersion'];
  299.                 } else {
  300.                     $arrayGoodWayUpdate['apkurl'] = '';
  301.                     $arrayGoodWayUpdate['lastversion'] = '';
  302.                 }
  303.             }
  304.             $unsetDownUrl false;
  305.             $em->persist($accountLicenseData[0]);
  306.             $em->flush();
  307.             
  308.             $emLev Util::emLicenseConnection($this->realContainer$em$accountLicenseData[0]);
  309.             // Verifica si es un usuario de leveLite y si este pertenece a la licencia a la cual se esta accediendo  
  310.             if(isset($levelLiteUser) && isset($levelLiteUser["username"]) && isset($data['isLiteDevice']) ){
  311.                 if (strtolower($data['username']) === strtolower($levelLiteUser["username"]) && $data['isLiteDevice'] == '1'){
  312.                     // Limpia lista de usuarios levelLite
  313.                     // Revisar se estalla al borrar usuarios
  314.                     // $emLev->getRepository('App\Structure\Usuario')->cleanWrongUsers($levelLiteUser["username"]);   
  315.                 }
  316.             }
  317.             $configuracionForAll $emLev->getRepository('App\Structure\Configuracion')->findAll();
  318.             if (!empty($configuracionForAll)) {
  319.                 $configuracion $configuracionForAll[0]; 
  320.             }
  321.             if (($configuracion && $deviceUIDWasSetted) || !$configuracion->getConfDeviceUid() || $configuracion->getConfDeviceUid() == '' || $configuracion->getConfDeviceUid() == "") {
  322.                 $configuracion->setConfHasAndriod(true);
  323.                 $configuracion->setConfDeviceUid($data['uid']);
  324.                 $this->createFileJson($path"\r" '2 SETEO DE LEVEL UUID IN CONFIG: ' $data['uid'] . ' HAS ANDROID : TRUE' "\r");
  325.                 $emLev->persist($configuracion);
  326.                 $emLev->flush();
  327.                 $maxUIDPollingCounter 0;
  328.                 do {
  329.                     ++$maxUIDPollingCounter;
  330.                     $configuracionForAll $emLev->getRepository('App\Structure\Configuracion')->findAll();
  331.                     if (!empty($configuracionForAll)) {
  332.                         $configuracion $configuracionForAll[0];
  333.                     } else {
  334.                         return $this->setStatusCode(WebService::HTTP_CODE_SERVICE_UNAVAILABLE)
  335.                                         ->respondWithError('Error finding configuration LEVEL database record'WebService::CODE_OBJECT_NOT_FOUND);
  336.                     }
  337.                     $configuracion->setConfHasAndriod(true);
  338.                     $configuracion->setConfDeviceUid($data['uid']);
  339.                     $emLev->persist($configuracion);
  340.                     $emLev->flush();
  341.                     $emLev->clear();
  342.                     sleep(1);
  343.                     $configuracionForAllCheck $emLev->getRepository('App\Structure\Configuracion')->findBy(['confDeviceUid' => $data['uid']]);
  344.                 } while (!isset($configuracionForAllCheck[0]) && $maxUIDPollingCounter 7);
  345.                 $this->createFileJson($path"\r" '2 SETEO DE LEVEL UUID IN CONFIG CHECKEADO Y FULL PARA: ' $data['uid'] . ' HAS ANDROID : TRUE' "\r");
  346.             }
  347.             $cliente $emLev->getRepository('App\Structure\Usuario')->validateUser($data);
  348.             $emLev->clear();
  349.             $emLev->close();
  350.             // dump($data);
  351.             // dump($cliente);
  352.             // die;
  353.             if (!empty($cliente)) {
  354.                 if (isset($data['isLiteDevice']) && strtolower($data['username']) != $liteUsername) {
  355.                     $this->createFileJson($path"Error: Invalid username for LEVELLite");
  356.                     return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  357.                                     ->respondWithError('Invalid username for LEVELLite'WebService::CODE_UNAUTHORIZED);
  358.                 }
  359.                 if (strtolower($data['username']) != 'admin') {
  360.                     $isDirectoryReady Util::createLicenseDirectory($this->realContainer$accountLicenseData[0], $data['alLicenseUsername']);
  361.                     $theAccountLicenseDirector $isDirectoryReady['directory'];
  362.                     if (!isset($isDirectoryReady['result']) || $isDirectoryReady['result'] == '__KO__') {
  363.                         $msnError 'An error occurred while creating your directory in server ';
  364.                         $this->createFileJson($path$msnError);
  365.                         return $this->setStatusCode(WebService::CODE_INTERNAL_ERROR)
  366.                                         ->respondWithError($msnErrorWebService::CODE_INTERNAL_ERROR);
  367.                     }
  368.                     $em $this->getDoctrine()->getManager();
  369.                     $licenseDB $em->getRepository("App\Entity\LicenseDataBase")->findBy(['license' => $accountLicenseData[0]->getId()]);
  370.                     $splitedLogin = isset($data['splitedLogin']) ? $data['splitedLogin'] : 0;
  371.                     if (!empty($licenseDB)) {
  372.                         if (!isset($data['isLiteDevice'])) {
  373.                             $useMetadataCacheInLogin false;
  374.                             if (isset($data['useMetadataCache'])) {
  375.                                 $useMetadataCacheInLogin true;
  376.                             } 
  377.                             if (isset($data['splitedLogin'])) {
  378.                                 $this->createFileJson($path"Notice: pre fileJsonFromSelectEntities with 'splitedLogin' -> " $data['splitedLogin']);
  379.                                 $auxResponseArray Util::fileJsonFromSelectEntities($this->realContainer$em$theAccountLicenseDirector$licenseDB[0], nulltruefalsetrue$data['splitedLogin'], $useMetadataCacheInLogin);
  380.                             } else {
  381.                                 $this->createFileJson($path"Notice: pre fileJsonFromSelectEntities ");
  382.                                 $auxResponseArray Util::fileJsonFromSelectEntities($this->realContainer$em$theAccountLicenseDirector$licenseDB[0], nulltruefalsetruenull$useMetadataCacheInLogin);
  383.                             }
  384.                             $responseArr $auxResponseArray[0];
  385.                             $responseArr['bigbag'] = true;
  386.                             $responseArr['language'] = $language;
  387.                             $newSetWebRecordToSync $auxResponseArray[1]['entity'];
  388.                             if (isset($responseArrOmt) && isset($responseArrOmt['userToOmt'])) {
  389.                                 $responseArr['userToOmt'] = $responseArrOmt['userToOmt'];
  390.                             }
  391.                             $actualDate Util::getCurrentDate();
  392.                             $accountLicenseData[0]->setLastLoginWasOk(false);
  393.                             $accountLicenseData[0]->setLastLoginDate($actualDate);
  394.                             $newNotificationSeed = new NotificationInLicensorBell();
  395.                             $newNotificationSeed->setDateCreated($actualDate);
  396.                             $newNotificationSeed->setIterativeNotification(true);
  397.                             $newNotificationSeed->setLicense($accountLicenseData[0]);
  398.                             $newNotificationSeed->setTypeRoleToNotify(NotificationInLicensorBell::ROLE_LICENSE_MANAGER);
  399.                             $newNotificationSeed->setContext(NotificationInLicensorBell::CONTEXT_NOTIFICATION_ANDROID_LOGIN);
  400.                             $em->persist($newNotificationSeed);
  401.                             $em->persist($accountLicenseData[0]);
  402.                             $em->flush();
  403.                             if ($newSetWebRecordToSync) {
  404.                                 Util::updateWebSyncUploadResponseFile($em$newSetWebRecordToSync);
  405.                             } else {
  406.                                 $unsetDownUrl true;
  407.                                 unset($data['splitedLogin']);
  408.                                 unset($responseArr['splitedLogin']);
  409.                                 Utilx::closeAllStuckedWebSync($em$accountLicenseData[0]);
  410.                             }
  411.                         }
  412.                     } else {
  413.                         $this->createFileJson($path"Error: No DB conection data found!");
  414.                         return $this->setStatusCode(WebService::HTTP_CODE_SERVICE_UNAVAILABLE)
  415.                                         ->respondWithError('No DB conection data found!'WebService::CODE_OBJECT_NOT_FOUND);
  416.                     }
  417.                     $userLite $accountLicenseData[0]->getLevelLightUser();
  418.                     // dump($responseArr, strtolower($data['username']), $userLite["username"]);die;
  419.                     if (isset($responseArr['status']) && $responseArr['status']==200 && strtolower($data['username']) !== $userLite["username"]) {
  420.                         if ($accountLicenseData[0]->getHasLogedOMT() && !isset($data['isLiteDevice'])) {
  421.                             $emLev Util::emLicenseConnection($this->realContainer$em$accountLicenseData[0]);
  422.                             // Util::createSyncRecordsToOmtByUpdate($emLev, $accountLicenseData[0]);
  423.                             $curlResponse Util::makeOwnSyncWebCurl($this->realContainer, ['nickname' => $data['alLicenseUsername']], $path);
  424.                             $data['rwid'] = $curlResponse;
  425.                             ForcedAsynchronousCommandsUtil::consumeUpDownSyncCommand($this->realContainer$datatrue);
  426.                             $emLev->clear();
  427.                             $emLev->close();
  428.                         }
  429.                         $responseArr['urlBase'] = $this->realContainer->getParameter('level_directory_data_base_url') . $accountLicenseData[0]->getAlAccountLicense() . '/' $data['alLicenseUsername'] . $responseArr['urlBase'];
  430.                         $responseArr['urlBase'] = str_replace(' ''_'$responseArr['urlBase']);
  431.                         if (isset($arrayWrongWayUpdate['case'])) {
  432.                             $responseArr['case'] = $arrayWrongWayUpdate['case'];
  433.                         } else {
  434.                             $responseArr['case'] = '';
  435.                         }
  436.                         if (!$alreadyUsingLastVersion && !isset($data['isLiteDevice'])) {
  437.                             $theVersionArrayForOldUsers Util::getLastVersionByDirNow($this->realContainertrue$path);
  438.                             if (isset($theVersionArrayForOldUsers['updateAppIsNeeded']) && $theVersionArrayForOldUsers['updateAppIsNeeded'] === true) {
  439.                                 $responseArr['apkurl'] = $theVersionArrayForOldUsers['updateRequestApk'];
  440.                                 $responseArr['lastversion'] = $theVersionArrayForOldUsers['newVersion'];
  441.                             } else {
  442.                                 $responseArr['apkurl'] = '';
  443.                                 $responseArr['lastversion'] = '';
  444.                             }
  445.                         } else {
  446.                             $responseArr['apkurl'] = '';
  447.                             $responseArr['lastversion'] = '';
  448.                         }
  449.                         $emLev Util::emLicenseConnection($this->realContainer$em$accountLicenseData[0]);
  450.                         $clienteForWebAndroidLogin $emLev->getRepository('App\Structure\Usuario')->findBy(['usuLogin' => 'admin']);
  451.                         $emLev->clear();
  452.                         $emLev->close();
  453.                         $auxArrayUserAndroidWebLogin = [];
  454.                         if (isset($clienteForWebAndroidLogin[0])) {
  455.                             $auxArrayUserAndroidWebLogin['user'] = 'admin';
  456.                             $auxArrayUserAndroidWebLogin['pass'] = $clienteForWebAndroidLogin[0]->getUsuPass();
  457.                         }
  458.                         $pushServicesKeysArray Util::buildTheServicesKeysArray($this->realContainer$accountLicenseData[0], $auxArrayUserAndroidWebLogin); 
  459.                         if ($accountLicenseData[0]->getAwsTopicARN() && $accountLicenseData[0]->getAwsTopicARN() != '' && $accountLicenseData[0]->getAwsTopicARN() != "" ) {
  460.                             if (isset($pushServicesKeysArray['awsPush'])) {
  461.                                 $pushServicesKeysArray['awsPush']['TopicArn'] = $accountLicenseData[0]->getAwsTopicARN();
  462.                             }
  463.                         }
  464.                         $responseArr['country'] = $country;
  465.                         $responseArr['iscallcenter'] = (int) $isCallCenter;
  466.                         $isSplitedAgain false;
  467.                         if (isset($data['splitedLogin'])) {
  468.                             
  469.                             $responseArr['splitedLogin'] = $data['splitedLogin'];
  470.                             $isSplitedAgain true;
  471.                         }
  472.                         $responseArr['push_services'] = $pushServicesKeysArray;
  473.                         // $responseArr['uploadurl'] = $this->generateUrl('level_web_service_respond_sync_web', [], UrlGeneratorInterface::ABSOLUTE_URL);
  474.                         $responseArr['uploadurl'] = $this->realContainer->getParameter('level_scheme') . '://' $this->realContainer->getParameter('level_host') . $this->generateUrl('level_web_service_respond_sync_web');
  475.                         $responseArr['downloadurl'] = $this->realContainer->getParameter('level_directory_data_base_url') . $accountLicenseData[0]->getAlAccountLicense() . '/' $data['alLicenseUsername'] . '/' $auxResponseArray[1]['fileConfigName'];
  476.                         $responseArr['downloadurl'] = str_replace(' ''_'$responseArr['downloadurl']);
  477.                         if (isset($auxResponseArray[1]['fileExpectedName'])) {
  478.                             $responseArr['expected'] = $this->realContainer->getParameter('level_directory_data_base_url') . $accountLicenseData[0]->getAlAccountLicense() . '/' $data['alLicenseUsername'] . '/' $auxResponseArray[1]['fileExpectedName'];
  479.                             $responseArr['expected'] = str_replace(' ''_'$responseArr['expected']);
  480.                         } else {
  481.                             $responseArr['expected'] = '';
  482.                         }
  483.                         if ($accountLicenseData[0]->getLevelLightUser() && isset($data['isLiteDevice']) && $accountLicenseData[0]->getHasLogedOMT() == true) {
  484.                             $this->createFileJson($path'Util::doOMTDashboardLoginToGetToken 2!' "\r");
  485.                             
  486.                             $userData $accountLicenseData[0]->getLevelLightUser();
  487.                             $apikey Util::doOMTDashboardLoginToGetToken($this->realContainer$userData$path$accountLicenseData[0]->getLoginType());
  488.                             if (!empty($apikey)) {
  489.                                 $responseArr['userToOmt']['apikey'] = $apikey;
  490.                             }
  491.                             $responseArr['userToOmt']['username'] = $userData['username'];
  492.                             $responseArr['userToOmt']['password'] = $userData['realPass'];
  493.                         }
  494.                         if ($unsetDownUrl) {
  495.                             $responseArr['downloadurl'] = '';
  496.                         }
  497.                         $theUrlTrSt = new UpdateMobileInsertJsonTransformer($this->realContainer$responseArr);
  498.                         $xxArray $theUrlTrSt->transform();
  499.                         if ($accountLicenseData[0]->getLoginType() == AccountLicense::LOGGED_OUT) {
  500.                             $accountLicenseData[0]->setLoginType(AccountLicense::LOGGED_BY_LEVEL_ANDROID);
  501.                         } else if ($accountLicenseData[0]->getLoginType() == AccountLicense::LOGGED_BY_LEVEL_LITE) {
  502.                             $accountLicenseData[0]->setLoginType(AccountLicense::LOGGED_BY_LEVEL_LITE_AND_ANDROID);
  503.                         }
  504.                         $em->persist($accountLicenseData[0]);
  505.                         $em->flush();
  506.                         if ($accountLicenseData[0]->getLevelLightUser() && isset($data['isLiteDevice'])) {
  507.                             $this->createFileJson($path'Util::doOMTDashboardLoginToGetToken 3!' "\r");
  508.                             $userData $accountLicenseData[0]->getLevelLightUser();
  509.                             $apykey Util::doOMTDashboardLoginToGetToken($this->realContainer$userData$path$accountLicenseData[0]->getLoginType());
  510.                             if (!empty($apykey)) {
  511.                                 $xxArray['userToOmt']['apykey'] = $apykey;
  512.                             }
  513.                             $xxArray['userToOmt']['username'] = $userData['username'];
  514.                             if (isset($userData['password'])) {
  515.                                 $xxArray['userToOmt']['password'] = $userData['password'];
  516.                             }
  517.                         }
  518.                         $jsonContent json_encode($xxArray);
  519.                         // $splitedLogin = json_decode($jsonContent)->splitedLogin ?? null;
  520.                         // dump($splitedLogin);
  521.                         // dump(Util::definitionInitialMultipartLogin(0, true));
  522.                         // die;
  523.                         if ($splitedLogin === (Util::definitionInitialMultipartLogin(0true) - 1)) {
  524.                             // dump("Holaa!");
  525.                             // die;
  526.                             $freeLicnesesToPairWithStations $em->getRepository('App\Entity\LicenseDevice')->getLicenseDeviceServerRecordForInitialLogin($accountLicenseData[0]->getId());
  527.                             $historyResponse = [];
  528.                             $historyResponse["status"] = 200;
  529.                             if (isset($freeLicnesesToPairWithStations[0])) {
  530.                                 $licenseSold $freeLicnesesToPairWithStations[0];
  531.                                 $this->createFileJson($path"Updating old license device record with '" $licenseSold->getId() . "' id..." "\r");
  532.                                 $licenseSold->setLdUpdateDate($actualDate);
  533.                                 $licenseSold->setLdStationUID($data['uid']);
  534.                                 $em->persist($licenseSold);
  535.                                 $em->flush();
  536.                                 $historyResponse["actions"] = "Server station updated by initial login";
  537.                                 Util::logAction(
  538.                                     $em'LicenseDevice'
  539.                                     $licenseSold->getId(), ActionHistory::ACTION_STATION_UPDATE'System', [
  540.                                         'data' => $historyResponse
  541.                                 ]);
  542.                             }
  543.                             ///// Limpiado de los otros dispositivos autorizados para el inicio de registro de estaciones de parte de una licencia
  544.                             $this->createFileJson($path"Limpiado de dispositivos para que se permita el registro de nuevas estaciones segun dispositivos autorizados en '" $accountLicenseData[0] . "'" "\r");
  545.                             $em->getRepository('App\Entity\LicenseDevice')->clearLicenseDeviceNonServerRecordsForInitialLogin($accountLicenseData[0]->getId());
  546.                             
  547.                             Util::logAction(
  548.                                 $em'AccountLicense'
  549.                                 $accountLicenseData[0]->getId(), ActionHistory::INITIAL_LOGIN'System', [
  550.                                     'data' => "Login completed successfully for license: " $accountLicenseData[0]->getAlLicenseUsername()
  551.                             ]);
  552.                         }
  553.                         $this->createFileJson($pathXD"splitedLogin => " $splitedLogin "\r");
  554.                         $data['license'] = $accountLicenseData[0]->getId();
  555.                         $data['isForSync'] = 1;
  556.                         $data['unactiveActiveZipcodes'] = 1;
  557.                         $data['validationByEdition'] = 0;
  558.                         $pushSendRepository $em->getRepository('App\Entity\PushSent');
  559.                         $pushSendRepository->respondOldPushesForLicense(PushSent::PUSH_TYPE_LICENSE_RESET_UID$accountLicenseData[0]->getId());
  560.                         $this->createFileJson($pathXD"Has Loged OMT" ' => ' $accountLicenseData[0]->getHasLogedOMT());
  561.                         $emLev Util::emLicenseConnection($this->realContainer$em$accountLicenseData[0]);
  562.                         $configuracion $emLev->getRepository('App\Structure\Configuracion')->findAll();
  563.                         if (isset($configuracion[0])) {
  564.                             $configuracion[0]->setConfDeviceUid($accountLicenseData[0]->getDeviceUid());
  565.                             $emLev->persist($configuracion[0]);
  566.                             $emLev->flush();
  567.                         }
  568.                         if ($accountLicenseData[0]->getHasLogedOMT()) {
  569.                             $this->createFileJson($pathXD"For call => makeSyncCleanseBecauseNewLogin");
  570.                             Util::makeSyncCleanseBecauseNewLogin($this->realContainer$em$path$accountLicenseData[0]);
  571.                             $emLev Util::emLicenseConnection($this->realContainer$em$accountLicenseData[0]);
  572.                             // Util::createSyncRecordsToOmtByUpdate($emLev, $accountLicenseData[0]);
  573.                             $emLev->clear();
  574.                             $emLev->close();
  575.                             Util::makeOwnSyncWebCurl($this->realContainer, ['nickname' => $data['alLicenseUsername']], $path);
  576.                         }
  577.                         if ($accountLicenseData[0]->getNeedZipcodes() && !$isSplitedAgain) {
  578.                             ForcedAsynchronousCommandsUtil::validateZipcodesToSyncAfterLogin($this->realContainer$datatrue);
  579.                         }
  580.                         $this->createFileJson($path'Login response -> ' $jsonContent "\r");
  581.                         $accountLicenseData[0]->setLastLoginDate(Util::getCurrentDate());
  582.                         $isThisLicenseVersion Util::validateNewerVersion($accountLicenseData[0]->getAndroidVersionName(), $this->realContainer->getParameter('default_break_android_with_pusher'));
  583.                         if ($isThisLicenseVersion === $accountLicenseData[0]->getAndroidVersionName()) {
  584.                             $newPusherTokenCallResult NewUtil::generateNewPusherVerificationToken($this->realContainer$em$accountLicenseData[0], $path);
  585.                             if (is_string($newPusherTokenCallResult)) {
  586.                                 $this->createFileJson($path'Error creating new pusher token -> ' $newPusherTokenCallResult "\r");
  587.                             } else {
  588.                                 $this->createFileJson($path'New pusher token created!'"\r");
  589.                             }
  590.                         }
  591.                         if (!isset(json_decode($jsonContent)->splitedLogin)) {
  592.                             $accountLicenseData[0]->setLoginType(AccountLicense::LOGGED_BY_LEVEL_ANDROID);
  593.                             $accountLicenseData[0]->setHasAndroid(true);
  594.                         }
  595.                         // if ($accountLicenseData[0]->getLoginType() == AccountLicense::LOGGED_OUT) {
  596.                         //     $accountLicenseData[0]->setLoginType(AccountLicense::LOGGED_BY_LEVEL_ANDROID);
  597.                         // } else if ($accountLicenseData[0]->getLoginType() == AccountLicense::LOGGED_BY_LEVEL_LITE) {
  598.                         //     $accountLicenseData[0]->setLoginType(AccountLicense::LOGGED_BY_LEVEL_LITE_AND_ANDROID);
  599.                         // }
  600.                         $em->persist($accountLicenseData[0]);
  601.                         $em->flush();
  602.                         // Se valida que el parametro timeZone exista para guardarlo en las Tablas Configuracion y AccountLicense
  603.                         if (isset($data['timeZone']) && trim($data['timeZone']) !== '') {
  604.                             $timeZone trim($data['timeZone']);
  605.                             $configuracion $emLev->getRepository('App\Structure\Configuracion')->findAll();
  606.                             if (isset($configuracion[0])) {
  607.                                 $configuracion[0]->setTimeZoneRes($timeZone);
  608.                                 $emLev->persist($configuracion[0]);
  609.                                 $emLev->flush();
  610.                             }
  611.                             $accountLicenseData[0]->setTimeZoneRes($timeZone);
  612.                             $em->persist($accountLicenseData[0]);
  613.                             $em->flush();
  614.                         }
  615.                         $emLev Util::emLicenseConnection($this->realContainer$em$accountLicenseData[0]);
  616.                         $deleteRegistActionPauseOrder $emLev->getRepository('App\Structure\RegistActions')->deleteRegistActionPauseOrder($emLev);
  617.                         $emLev->clear();
  618.                         $emLev->close();
  619.                         return $this->respondWithItem($jsonContent$theUrlTrSt);
  620.                     } elseif ($accountLicenseData[0]->getLevelLightUser() && isset($data["isLiteDevice"])) {
  621.                         /**  Flujo de un login correcto para level lite */
  622.                         /**  dump('Joder!'); */
  623.                         if ($accountLicenseData[0]->getLoginType() == AccountLicense::LOGGED_OUT) {
  624.                             $accountLicenseData[0]->setLoginType(AccountLicense::LOGGED_BY_LEVEL_LITE);
  625.                         } else if ($accountLicenseData[0]->getLoginType() == AccountLicense::LOGGED_BY_LEVEL_ANDROID) {
  626.                             $accountLicenseData[0]->setLoginType(AccountLicense::LOGGED_BY_LEVEL_LITE_AND_ANDROID);
  627.                         }
  628.                         $em->persist($accountLicenseData[0]);
  629.                         $em->flush();
  630.                         $userData $accountLicenseData[0]->getLevelLightUser();
  631.                         $this->createFileJson($path'Util::doOMTDashboardLoginToGetToken 4!' "\r");
  632.                         
  633.                         $apikey Util::doOMTDashboardLoginToGetToken($this->realContainer$userData$path$accountLicenseData[0]->getLoginType());
  634.                         if (!empty($apikey)) {
  635.                             $responseArr['userToOmt']['apikey'] = $apikey;
  636.                         }
  637.                         $responseArr['userToOmt']['username'] = $userData['username'];
  638.                         $responseArr['userToOmt']['password'] = $userData['realPass'];
  639.                         if (!isset($userData['realPass'])) {
  640.                             if ($accountLicenseData[0]->getHasLogedOMT() || $accountLicenseData[0]->getIsLevelLight() == true) {
  641.                                 $msnError "The default OMT dashboard user doesn't have a password, please check the OMT database...";
  642.                                 $this->createFileJson($path"\r" 'LevelLite Error: ' $msnError "\r");
  643.                                 return $this->setStatusCode(WebService::HTTP_CODE_FORBIDDEN)
  644.                                                 ->respondWithError($msnErrorWebService::CODE_COULD_NOT_AUTHENTICATE);
  645.                             } else {
  646.                                 if ($accountLicenseData[0]->getLastloguedDeviceKind() == AccountLicense::DEVICE_LITE_TYPE && $accountLicenseData[0]->getDeviceUid()) {
  647.                                     $accountLicenseData[0]->setDeviceUid(null);
  648.                                     $accountLicenseData[0]->setHasAndroid(null);
  649.                                     $accountLicenseData[0]->setWsResourceIdVerifiedAfterLogin(0);
  650.                                     $em->persist($accountLicenseData[0]);
  651.                                     $em->flush();
  652.                                 }
  653.                                 $msnError $accountLicenseData[0] . " restaurant needs to be exported to OMT first!";
  654.                                 $this->createFileJson($path"\r" 'LevelLite Error: ' $msnError "\r");
  655.                                 return $this->setStatusCode(WebService::HTTP_CODE_FORBIDDEN)
  656.                                                 ->respondWithError($msnErrorWebService::CODE_COULD_NOT_AUTHENTICATE);
  657.                             }
  658.                         }
  659.                         $emLev Util::emLicenseConnection($this->realContainer$em$accountLicenseData[0]);
  660.                         //// If para asegurarse de la coincidencia de uids entre el license account y la configuracion para permitir la coreecta syn desde level web
  661.                         if ($accountLicenseData[0]->getLastloguedDeviceKind() == AccountLicense::DEVICE_LITE_TYPE) {
  662.                             $this->createFileJson($path'Setting of UID in configuration! :' $accountLicenseData[0]->getDeviceUid() . "\r");
  663.                             $configuracion $emLev->getRepository('App\Structure\Configuracion')->findAll();
  664.                             if (isset($configuracion[0])) {
  665.                                 $configuracion[0]->setConfDeviceUid($accountLicenseData[0]->getDeviceUid());
  666.                                 $emLev->persist($configuracion[0]);
  667.                                 $emLev->flush();
  668.                             }
  669.                         }
  670.                         //dump(':O');
  671.                         //die;
  672.                         $responseArr['status'] = WebService::HTTP_CODE_SUCCESS;
  673.                         $responseArr['msg'] = 'Valid level lite license!';
  674.                         $responseArr['bigbag'] = true;
  675.                         $responseArr['language'] = $language;
  676.                         if ($accountLicenseData[0]->getHasLogedOMT()) {
  677.                             // Util::createSyncRecordsToOmtByUpdate($emLev, $accountLicenseData[0]);
  678.                             $curlResponse Util::makeOwnSyncWebCurl($this->realContainer, ['nickname' => $data['alLicenseUsername']], $path);
  679.                             $data['rwid'] = $curlResponse;
  680.                             ForcedAsynchronousCommandsUtil::consumeUpDownSyncCommand($this->realContainer$datatrue);
  681.                         }
  682.                         $emLev->clear();
  683.                         $emLev->close();
  684.                         $theUrlTrSt = new LicensorGenericTransformer($this->realContainer$responseArr);
  685.                         $xxArray $theUrlTrSt->transform();
  686.                         $jsonContent json_encode($xxArray);
  687.                         $splitedLogin json_decode($jsonContent)->splitedLogin ?? null;
  688.                         if ($splitedLogin === (Util::definitionInitialMultipartLogin(0true) - 1)) {
  689.                             Util::logAction(
  690.                                 $em'AccountLicense'
  691.                                 $accountLicenseData[0]->getId(), ActionHistory::LEVELLITE_INITIAL_LOGIN'System', [
  692.                                     'data' => "Level Lite Login completed successfully for license: " $accountLicenseData[0]->getAlLicenseUsername()
  693.                             ]);
  694.                         }
  695.                         $this->createFileJson($pathXD"level lite splitedLogin => " $splitedLogin "\r");
  696.                         $accountLicenseData[0]->setLastLoginDate(Util::getCurrentDate());
  697.                         $em->persist($accountLicenseData[0]);
  698.                         $em->flush();
  699.                         return $this->respondWithItem($jsonContent$theUrlTrSt);
  700.                     } else if (!isset($data["isLiteDevice"]) && strtolower($data['username']) == $userLite["username"]) {
  701.                         $accountLicenseData[0]->setLastloguedDeviceKind($oldLoguedDeviceKind);
  702.                         $em->persist($accountLicenseData[0]);
  703.                         $em->flush();
  704.                         // dump(isset($data["isLiteDevice"]),$data, $userLite);die;
  705.                         $this->createFileJson($path"Error: User not valid for this platform");
  706.                         return $this->setStatusCode(WebService::HTTP_CODE_INTERNAL_ERROR)
  707.                                         ->respondWithError('User not valid for this platform'WebService::CODE_INTERNAL_ERROR);
  708.                     } else {
  709.                         $accountLicenseData[0]->setLastloguedDeviceKind($oldLoguedDeviceKind);
  710.                         $em->persist($accountLicenseData[0]);
  711.                         $em->flush();
  712.                         $this->createFileJson($path"Error: Error creating json file");
  713.                         return $this->setStatusCode(WebService::HTTP_CODE_INTERNAL_ERROR)
  714.                                         ->respondWithError('Error creating json file'WebService::CODE_INTERNAL_ERROR);
  715.                     }
  716.                 } else {
  717.                     $emLev Util::emLicenseConnection($this->realContainer$em$accountLicenseData[0]);
  718.                     $configuracion $emLev->getRepository('App\Structure\Configuracion')->find(1);
  719.                     if (null == $oldUID || $oldUID == '') {
  720.                         $accountLicenseData[0]->setDeviceUid(null);
  721.                         $accountLicenseData[0]->setWsResourceIdVerifiedAfterLogin(0);
  722.                         $configuracion->setConfDeviceUid(null);
  723.                         $this->createFileJson($path"\r" '3 SETEO DE LEVEL UUID  IN CONFIG: IS NULL AND  HAS ANDROID : NULL' "\r");
  724.                     
  725.                     } else {
  726.                         $this->createFileJson($path"\r" '4 SETEO DE LEVEL UUID  IN CONFIG: ' $oldUID ' AND  HAS ANDROID : NULL' "\r");
  727.                         $accountLicenseData[0]->setDeviceUid($oldUID);
  728.                         $configuracion->setConfDeviceUid($oldUID);
  729.                     }
  730.                     $emLev->persist($configuracion);
  731.                     $emLev->flush();
  732.                     $em->persist($accountLicenseData[0]);
  733.                     $em->flush();
  734.                     $emLev->clear();
  735.                     $emLev->close();
  736.                     $this->createFileJson($path"Error: Username not found");
  737.                     return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  738.                                     ->respondWithError('Username not found'WebService::CODE_UNAUTHORIZED);
  739.                 }
  740.             } else {
  741.                 if (null == $oldUID || $oldUID == '') {
  742.                     $emLev Util::emLicenseConnection($this->realContainer$em$accountLicenseData[0]);
  743.                     $configuracion $emLev->getRepository('App\Structure\Configuracion')->find(1);
  744.                     $accountLicenseData[0]->setDeviceUid(null);
  745.                     $accountLicenseData[0]->setWsResourceIdVerifiedAfterLogin(0);
  746.                     $configuracion->setConfDeviceUid(null);
  747.                     $this->createFileJson($path"\r" '5 SETEO DE LEVEL UUID  IN CONFIG: IS OLDUID IS EMPTY AND  HAS ANDROID : NULL' "\r");
  748.                     $accountLicenseData[0]->setHasAndroid(false);
  749.                     $configuracion->setConfHasAndriod(false);
  750.                     $emLev->persist($configuracion);
  751.                     $emLev->flush();
  752.                     $em->persist($accountLicenseData[0]);
  753.                     $em->flush();
  754.                     $emLev->clear();
  755.                     $emLev->close();
  756.                 } else {
  757.                     $accountLicenseData[0]->setDeviceUid($oldUID);
  758.                     $configuracion->setConfDeviceUid($oldUID);
  759.                     $this->createFileJson($path"\r" '6 SETEO DE LEVEL UUID  IN CONFIG: IS OLDUID ' $oldUID ' AND  HAS ANDROID : NULL' "\r");
  760.                 }
  761.                 $this->createFileJson($path"Error: Invalid login data please try again");
  762.                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)->respondWithError('Invalid login data please try again'WebService::CODE_UNAUTHORIZED);
  763.             }
  764.         } catch (\Exception $th) {
  765.             $errorCode uniqid();
  766.             $err = [
  767.                 'Error Message' => $th->getMessage(), 'Error Line' => $th->getLine(),
  768.                 'Error File' => $th->getFile(), 'Error Trace' => $th->getTrace()
  769.             ];
  770.             $this->createFileJson($path"\r" "Error Code => "$errorCode "\r");
  771.             $this->createFileJson($path"\r" json_encode($err) . "\r");
  772.             return $this->setStatusCode(WebService::HTTP_CODE_INTERNAL_ERROR)->respondWithError('Internal Server Error, Please, Contact Team Licensor, Error Code: '$errorCodeWebService::HTTP_CODE_INTERNAL_ERROR);
  773.         }
  774.     }
  775.     /**
  776.      * Esta funcion permite al cliente adroid notificar que termino de
  777.      * subir el archivo de sincronizacion
  778.      * @author Aealan Z <lrobledo@kijho.com> 30/04/15
  779.      * @param \Symfony\Component\HttpFoundation\Request $request datos de la solicitud
  780.      * @return Response Json con la informacion de respuesta
  781.      */
  782.     public function uploadSyncServiceUrl(Request $request) {
  783.         // dump('Die');
  784.         // die;
  785.         if ($request->getMethod() === WebService::REQUEST_METHOD_POST) {
  786.             $arrayRequestEncripted = [];
  787.             $arrayRequestEncripted['nickname'] = $request->request->get('nickname');
  788.             $arrayRequestEncripted['uid'] = $request->request->get('uid');
  789.             $arrayRequestEncripted['numberOfSyncDataRecords'] = $request->request->get('numberOfSyncDataRecords');
  790.             $path Util::getValidActiveLogByBaseName($this->realContainer'syncDownUpWS''syncDownUpWS0.txt');
  791.             $this->createFileJson($path"\r" 'The request ' json_encode($arrayRequestEncripted) . "\r");
  792.             try {
  793.                 $parameters $request->request->all();
  794.                 $this->createFileJson($path'All parameters in request -> ' json_encode($parameters) . "\r");
  795.                 $data = [];
  796.                 $arrayEncryptResult Util::decryptDataForUploadsFiles($this->realContainer$request->request->get('nickname'));
  797.                 $data['nickname'] = $arrayEncryptResult['data'];
  798.                 $arrayEncryptResult Util::decryptDataForUploadsFiles($this->realContainer$request->request->get('uid'));
  799.                 $data['uid'] = $arrayEncryptResult['data'];
  800.                 $arrayEncryptResult Util::decryptDataForUploadsFiles($this->realContainer$request->request->get('numberOfSyncDataRecords'));
  801.                 $data['numberOfSyncDataRecords'] = $arrayEncryptResult['data'];
  802.                 $arrayEncryptResult Util::decryptDataForUploadsFiles($this->realContainer$request->request->get('prioritySMSOrderSync'));
  803.                 $data['prioritySMSOrderSync'] = $arrayEncryptResult['data'];
  804.                 $this->createFileJson($path'Decripted ' json_encode($data) . "\r");
  805.                 $theTrueNameFile $request->files->get('file')->getClientOriginalName();
  806.                 $this->createFileJson($path'The Client IP -> ' $request->getClientIp() . "\r");
  807.                 $this->createFileJson($path'The File -> ' $theTrueNameFile "\r");
  808.                 $licenseUserName = ['alLicenseUsername' => $data['nickname']];
  809.                 $em $this->getDoctrine()->getManager();
  810.                 $accountLicenseData $em->getRepository('App\Entity\AccountLicense')->findByAlLicenseUsername($licenseUserName);
  811.                 $forcedValidationPassed false;
  812.                 if (empty($accountLicenseData) && (null == $data['nickname'] ||
  813.                         empty($data['nickname']) || $data['nickname'] == 'null') &&
  814.                         (int) $this->realContainer->getParameter('device_recognition_by_ip_enabled') &&
  815.                         !empty($theTrueNameFile) && $theTrueNameFile != '') {
  816.                     $this->createFileJson($path'Forcing server android autentication... ' "\r");
  817.                     $accountLicenseData $em->getRepository('App\Entity\AccountLicense')->findBy(['androidIP' => $request->getClientIp()]);
  818.                     if (empty($accountLicenseData) || (int) $accountLicenseData[0]->getTimesCheckedIP() < (int) $this->realContainer->getParameter('ip_recognition_times_to_valid_check')) {
  819.                         $accountLicenseData = [];
  820.                     } else {
  821.                         $forcedValidationPassed true;
  822.                         $this->createFileJson($path'Forced autentication succeeded! ' "\r");
  823.                     }
  824.                 }
  825.                 $countResult count($accountLicenseData);
  826.                 $this->createFileJson($path'Number of license found -> ' $countResult "\r");
  827.                 if ($countResult 0) {
  828.                     if ($accountLicenseData[0]->getAlAccountLicense()->getDeleted()) {
  829.                         $this->createFileJson($path'Salio 1! ' "\r");
  830.                         return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  831.                                         ->respondWithError('Account is inactive'WebService::CODE_ACCOUNT_SUSPENDED);
  832.                     }
  833.                     if (!$forcedValidationPassed && $accountLicenseData[0]->getDeviceUid() != $data['uid']) {
  834.                         $this->createFileJson($path'Salio 2! ' "\r");
  835.                         return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  836.                                         ->respondWithError('Unknown device'WebService::CODE_ACCOUNT_SUSPENDED);
  837.                     }
  838.                     if ($accountLicenseData[0]->getAlLicenseStatus() == AccountLicense::LICENSE_STATUS_ACTIVE) {
  839.                         $this->notifyLastSyncByLicense($em$accountLicenseData[0]);
  840.                         $this->createFileJson($path'License active! ' "\r");
  841.                         if (isset($data['numberOfSyncDataRecords'])) {
  842.                             $accountLicenseData[0]->setNumberOfSyncDataRecords((int) $data['numberOfSyncDataRecords']);
  843.                             $em->persist($accountLicenseData[0]);
  844.                             $em->flush();
  845.                             $licenseDataBaseEntity $em->getRepository('App\Entity\LicenseDataBase')->findOneBy(['license' => $accountLicenseData[0]->getId()]);
  846.                             if (!is_null($licenseDataBaseEntity)) {
  847.                                 $this->createFileJson($path'Creating license database connection for => '$data['nickname'] . "\r");
  848.                                 $dataOptionsRoot = [
  849.                                     'dbname' => $licenseDataBaseEntity->getDbname(),
  850.                                     'user' => $licenseDataBaseEntity->getDbuser(),
  851.                                     'password' => $licenseDataBaseEntity->getDbpass(),
  852.                                     'host' => $licenseDataBaseEntity->getDbhost(),
  853.                                     'driver' => 'pdo_mysql',
  854.                                 ];
  855.     
  856.                                 $emLev Util::emCreateConfiguration($this->realContainer$dataOptionsRoot);
  857.                                 $configuracion $emLev->getRepository('App\Structure\Configuracion')->find(1);
  858.                                 $configuracion->setNumberOfSyncDataRecords((int) $data['numberOfSyncDataRecords']);
  859.                                 $configuracion->setMaxRecordsSyncUpDown((int) $this->realContainer->getParameter('max_records_sync_up_down'));
  860.                                 $configuracion->setMaxRecordsSyncDownUp((int) $this->realContainer->getParameter('max_records_sync_down_up'));
  861.                                 $emLev->persist($configuracion);
  862.                                 $emLev->flush();
  863.                             }else{
  864.                                 $this->createFileJson($path'License database configuration not found from => '$data['nickname'] . "\r");
  865.                             }
  866.                         }
  867.                         $masterBlockingByDBUpdate $em->getRepository('App\Entity\MasterSync')->findBy(['msLicense' => $accountLicenseData[0]->getId(), 'msType' => MasterSync::MASTER_SYNC_TYPE_DB_UPDATE'msStatus' => MasterSync::MASTER_STATUS_INITIALIZATED]);
  868.                         if (!empty($masterBlockingByDBUpdate)) {
  869.                             $this->createFileJson($path'Se Fue DB blocked!' "\r");
  870.                             return $this->setStatusCode(WebService::CODE_OBJECT_NOT_FOUND)
  871.                                             ->respondWithError('Synchronization blocked by DB update, please wait...'WebService::NOTHING_TO_WEB_SYNCHRONIZE);
  872.                         }
  873.                         $masterSyncRecords $em->getRepository('App\Entity\MasterSync')->findMastersSyncsDownUpInProcessToBlockNewSyncs($accountLicenseData[0]->getId());
  874.                         $statusArryMsg = [];
  875.                         $statusArryMsg['status'] = WebService::CODE_SUCCESS;
  876.                         $statusArryMsg['msg'] = '';
  877.                         if (!empty($masterSyncRecords)) {
  878.                             $auxArrayResponse Utilx::validateAndUnblockSyncsWithErrors($this->realContainer$masterSyncRecords$em$accountLicenseData[0], $path);
  879.                             if (isset($auxArrayResponse['continue']) && isset($auxArrayResponse['msg']) && !$auxArrayResponse['continue']) {
  880.                                 $statusArryMsg['msg'] = $auxArrayResponse['msg'];
  881.                                 $theUrlTrSt = new UploadSyncJsonNotifyTransformer($this->realContainer$statusArryMsg);
  882.                                 $jsonTransform $theUrlTrSt->transform();
  883.                                 $jsonContent json_encode($jsonTransform);
  884.                                 return $this->respondWithItem($jsonContent$theUrlTrSt);
  885.                             }
  886.                         }
  887.                         $readFilesDataEntity $em->getRepository('App\Entity\ReadFilesData')->findBy(['rfStatus' => ReadFilesData::STATUS_UPLOADED'rfLicenseId' => $accountLicenseData[0]->getId(), 'hasPersistentError' => false]);
  888.                         if (!empty($readFilesDataEntity)) {
  889.                             $this->createFileJson($path'There is another sync petition in process, please wait until is finished' "\r");
  890.                             $statusArryMsg['msg'] = 'There is another sync petition in process, please wait until is finished';
  891.                             $theUrlTrSt = new UploadSyncJsonNotifyTransformer($this->realContainer$statusArryMsg);
  892.                             $jsonTransform $theUrlTrSt->transform();
  893.                             $jsonContent json_encode($jsonTransform);
  894.                             return $this->respondWithItem($jsonContent$theUrlTrSt);
  895.                         }
  896.                         $readFilesDataEntity $em->getRepository('App\Entity\ReadFilesData')->findBy(['rfStatus' => ReadFilesData::STATUS_UPLOADED'rfLicenseId' => $accountLicenseData[0]->getId(), 'hasPersistentError' => true]);
  897.                         if (!empty($readFilesDataEntity)) {
  898.                             $this->createFileJson($path'There is another sync petition for this license with a problem in the sever, please contact your system supplier for more information' "\r");
  899.                             $statusArryMsg['msg'] = 'There is another sync petition for this license with a problem in the sever, please contact your system supplier for more information';
  900.                             $theUrlTrSt = new UploadSyncJsonNotifyTransformer($this->realContainer$statusArryMsg);
  901.                             $jsonTransform $theUrlTrSt->transform();
  902.                             $jsonContent json_encode($jsonTransform);
  903.                             return $this->respondWithItem($jsonContent$theUrlTrSt);
  904.                         }
  905.                         $numberOfOtherSyncsInProccess $em->getRepository('App\Entity\ReadFilesData')->findMaxAmountOfIncomingAndroidSyncs();
  906.                         if ($numberOfOtherSyncsInProccess >= (int) $this->realContainer->getParameter('max_concurret_down_up_sync')) {
  907.                             $this->createFileJson($path"There are '$numberOfOtherSyncsInProccess' another sync proccess in server, please try it later" "\r");
  908.                             $statusArryMsg['msg'] = "There are '$numberOfOtherSyncsInProccess' another sync proccess in server, please try it later";
  909.                             $theUrlTrSt = new UploadSyncJsonNotifyTransformer($this->realContainer$statusArryMsg);
  910.                             $jsonTransform $theUrlTrSt->transform();
  911.                             $jsonContent json_encode($jsonTransform);
  912.                             return $this->respondWithItem($jsonContent$theUrlTrSt);
  913.                         }
  914.                         $isDirectoryReady Util::createLicenseDirectory($this->realContainer$accountLicenseData[0], $accountLicenseData[0]->getAlLicenseUsername());
  915.                         $theAccountLicenseDirector $isDirectoryReady['directory'];
  916.                         if (!isset($isDirectoryReady['result']) || $isDirectoryReady['result'] == '__KO__') {
  917.                             $msnError 'An error occurred while creating your directory in server ';
  918.                             return $this->setStatusCode(WebService::CODE_INTERNAL_ERROR)
  919.                                             ->respondWithError($msnErrorWebService::CODE_INTERNAL_ERROR);
  920.                         }
  921.                         $this->createFileJson($path'The license dir ' $theAccountLicenseDirector "\r");
  922.                         $uploadFileResponse Utilx::uploadFileTo($request$theAccountLicenseDirector$path);
  923.                         if (!isset($uploadFileResponse['result']) || !isset($uploadFileResponse['msg'])) {
  924.                             $this->createFileJson($path'Unknown error uploading file ' "\r");
  925.                             return $this->setStatusCode(WebService::HTTP_CODE_INTERNAL_ERROR)
  926.                                             ->respondWithError('Unknown error uploading file'WebService::CODE_INTERNAL_ERROR);
  927.                         }
  928.                         if (isset($uploadFileResponse['result']) && isset($uploadFileResponse['msg']) && $uploadFileResponse['result'] == '__KO__') {
  929.                             $this->createFileJson($path$uploadFileResponse['msg'] . "\r");
  930.                             return $this->setStatusCode(WebService::HTTP_CODE_INTERNAL_ERROR)
  931.                                             ->respondWithError($uploadFileResponse['msg'], WebService::CODE_INTERNAL_ERROR);
  932.                         }
  933.                         $readFilesDataEntityByLicense $em->getRepository('App\Entity\ReadFilesData')->findBy(['rfLicenseId' => $accountLicenseData[0]->getId(), 'rfStatus' => ReadFilesData::STATUS_STANDBY], ['rfDateSincAsk' => 'DESC']);
  934.                         $this->createFileJson($path'The ReadFilesData count 1 -> ' count($readFilesDataEntityByLicense) . "\r");
  935.                         if (empty($readFilesDataEntityByLicense)) {
  936.                             $readFilesDataEntityByLicense[0] = $this->setRegistNewFile($accountLicenseData[0]);
  937.                         }
  938.                         ///////////////// por aca iria la lectura del archivo subido para la prueba del NO_DATA
  939.                         // dump($uploadFileResponse['fileDir']);
  940.                         // dump(file_get_contents($uploadFileResponse['fileDir']));
  941.                         // die;
  942.                         $auxNoDataStringFromFile file_get_contents($uploadFileResponse['fileDir']);
  943.                         if (strpos($auxNoDataStringFromFile"NO_DATA") && strlen($auxNoDataStringFromFile) < 40) {
  944.                             $this->createFileJson($path"No data file detected, closing opened sync... \r");
  945.                             $masterSyncRecordToClose $em->getRepository('App\Entity\MasterSync')->findBy(['msSyncRecord' => $readFilesDataEntityByLicense[0]->getId()]);
  946.                             if (isset($masterSyncRecordToClose[0])) {
  947.                                 $masterSyncRecordToClose[0]->setMsStatus(MasterSync::MASTER_STATUS_RESPONDED);
  948.                                 $this->createFileJson($path"Closing MasterSync with '" $masterSyncRecordToClose[0]->getId() . "' id \r");
  949.                                 $em->persist($masterSyncRecordToClose[0]);
  950.                             } else {
  951.                                 $this->createFileJson($path'Dafuq! o.O! ' "\r");
  952.                             }
  953.                             $readFilesDataEntityByLicense[0]->setRfStatus(ReadFilesData::STATUS_DELIVERED);
  954.                             $this->createFileJson($path"Closing ReadFilesData with '" $readFilesDataEntityByLicense[0]->getId() . "' id \r");
  955.                             $accountLicenseData[0]->setNoDataFileDetected(1);
  956.                             $em->persist($accountLicenseData[0]);
  957.                             $em->persist($readFilesDataEntityByLicense[0]);
  958.                             $em->flush();
  959.                             $statusArryMsg['msg'] = 'No data file detected, closing opened sync...';
  960.                             $theUrlTrSt = new UploadSyncJsonNotifyTransformer($this->realContainer$statusArryMsg);
  961.                             $jsonTransform $theUrlTrSt->transform();
  962.                             $jsonContent json_encode($jsonTransform);
  963.                             $this->createFileJson($path'Track X! ' "\r");
  964.                             $this->createFileJson($path'WS Response: ' $jsonContent "\r");
  965.                             return $this->respondWithItem($jsonContent$theUrlTrSt);
  966.                         } else {
  967.                             $this->createFileJson($path"Restoring NoDatFileDetectedFlag for '" $accountLicenseData[0] . "' restaurant \r");
  968.                             $accountLicenseData[0]->setNoDataFileDetected(0);
  969.                             $em->persist($accountLicenseData[0]);
  970.                             $em->flush();
  971.                         }
  972.                         $bucketFileLocation Util::uploadSyncFileToS3Service($this->realContainer$accountLicenseData[0], $uploadFileResponse['fileName'], $uploadFileResponse['fileDir'], $path);
  973.                         $syncFileS3URI 'https://' $this->realContainer->getParameter('s3_bucket_name') . '.' $this->realContainer->getParameter('s3_default_bucket_domain') . '/' $bucketFileLocation;
  974.                         $registerStatus $this->updateRegistUploadFile($readFilesDataEntityByLicense[0], $uploadFileResponse['fileName'], $syncFileS3URI);
  975.                         if ($registerStatus) {
  976.                             $statusArryMsg['msg'] = 'File has been uploaded and the record updated';
  977.                             $this->createFileJson($path'File has been uploaded and the record updated' "\r");
  978.                         } else {
  979.                             $this->createFileJson($path'Salio 9! ' "\r");
  980.                             return $this->setStatusCode(WebService::HTTP_CODE_NOT_FOUND)
  981.                                             ->respondWithError('Error updating syncronization control record'WebService::CODE_OBJECT_NOT_FOUND);
  982.                         }
  983.                         $licenseDataBaseEntity $em->getRepository('App\Entity\LicenseDataBase')->findBy(['license' => $accountLicenseData[0]->getId()]);
  984.                         if (!empty($licenseDataBaseEntity)) {
  985.                             $pushSendRepository $em->getRepository('App\Entity\PushSent');
  986.                             $pushSendRepository->respondOldPushesForLicense(PushSent::PUSH_TYPE_SYNC_DOWNUP$accountLicenseData[0]->getId());
  987.                             $usernameByNickname $licenseDataBaseEntity[0]->getLicense();
  988.                             $theAccountPath $this->realContainer->getParameter('level_directory_data_android') . $usernameByNickname->getAlAccountLicense()->getAcName() . '/' $usernameByNickname->getAlLicenseUsername();
  989.                             $theAccountPath str_replace(' ''_'$theAccountPath);
  990.                             $dataOptionsRoot = [
  991.                                 'dbname' => $licenseDataBaseEntity[0]->getDbname(),
  992.                                 'user' => $licenseDataBaseEntity[0]->getDbuser(),
  993.                                 'password' => $licenseDataBaseEntity[0]->getDbpass(),
  994.                                 'host' => $licenseDataBaseEntity[0]->getDbhost(),
  995.                                 'driver' => 'pdo_mysql',
  996.                             ];
  997.                             $msg = [
  998.                                 'id' => $readFilesDataEntityByLicense[0]->getId(),
  999.                                 'dataOptionsRoot' => $dataOptionsRoot,
  1000.                                 'path' => $theAccountPath,
  1001.                                 'fileName' => $readFilesDataEntityByLicense[0]->getRfNameFile(),
  1002.                                 'AccountLicense' => $usernameByNickname->getAlAccountLicense()->getAcName(),
  1003.                                 'pushchanel' => $usernameByNickname->getAlLicenseUsername()
  1004.                             ];
  1005.                             $readFilesDataEntityByLicense[0]->setIsReadedByServer(true);
  1006.                             $em->persist($readFilesDataEntityByLicense[0]);
  1007.                             $em->flush();
  1008.                             if (isset($data['prioritySMSOrderSync']) && $data['prioritySMSOrderSync']) {
  1009.                                 $this->get('priority_android_sync_producer')->setContentType('application/json');
  1010.                                 $this->get('priority_android_sync_producer')->setDeliveryMode(2);
  1011.                                 $this->get('priority_android_sync_producer')->publish(json_encode($msg));
  1012.                             } else {
  1013.                                 $this->get('incoming_android_sync_producer')->setContentType('application/json');
  1014.                                 $this->get('incoming_android_sync_producer')->setDeliveryMode(2);
  1015.                                 $this->get('incoming_android_sync_producer')->publish(json_encode($msg));
  1016.                             }
  1017.                             if (!$request->request->get('hold')) {
  1018.                                 $statusArryMsg['msg'] = 'File has been uploaded and the sync process triggered';
  1019.                                 $this->createFileJson($path'File has been uploaded and the sync process triggered' "\r");
  1020.                                 $data['readFilesDataId'] = $readFilesDataEntityByLicense[0]->getId();
  1021.                                 
  1022.                                 ForcedAsynchronousCommandsUtil::consumeDownUpSyncCommand($this->realContainer$datatrue);
  1023.                             } else {
  1024.                                 $statusArryMsg['msg'] = 'File has been uploaded and the sync process is ready to start';
  1025.                                 $this->createFileJson($path'File has been uploaded and the sync process is ready to start' "\r");
  1026.                             }
  1027.                         }
  1028.                         $this->createFileJson($path'Track 7! ' "\r");
  1029.                         $theUrlTrSt = new UploadSyncJsonNotifyTransformer($this->realContainer$statusArryMsg);
  1030.                         $jsonTransform $theUrlTrSt->transform();
  1031.                         $jsonContent json_encode($jsonTransform);
  1032.                         $this->createFileJson($path'Track 8! ' "\r");
  1033.                         $this->createFileJson($path'UploadSyncJsonNotifyTransformer json to respond' $jsonContent "\r");
  1034.                         return $this->respondWithItem($jsonContent$theUrlTrSt);
  1035.                     } else {
  1036.                         $this->createFileJson($path'Salio 3! ' "\r");
  1037.                         return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  1038.                                         ->respondWithError('Inactive License'WebService::CODE_ACCOUNT_SUSPENDED);
  1039.                     }
  1040.                 } else {
  1041.                     return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  1042.                                     ->respondWithError('Invalid nickname'WebService::CODE_COULD_NOT_AUTHENTICATE);
  1043.                 }
  1044.             } catch (\Exception $th) {
  1045.                 $this->createFileJson($path'Error Message => '$th->getMessage() . ' Error Line => '$th->getLine() . ' Error Trace => '$th->getTraceAsString() . "\r");
  1046.                 return $this->setStatusCode(WebService::HTTP_CODE_INTERNAL_ERROR)
  1047.                                     ->respondWithError($th->getMessage(), WebService::HTTP_CODE_INTERNAL_ERROR);
  1048.             }
  1049.         } else {
  1050.             return $this->errorNotAllowedMethod('Method not allowed. Use ' WebService::REQUEST_METHOD_POST " method");
  1051.         }
  1052.     }
  1053.     /**
  1054.      * Esta funcion permite validar el acceso a la aplicacion web de level
  1055.      * validando codigo de usuario y contraseña y generando el apiKey
  1056.      * necesario para toda la aplicacion movil
  1057.      * @author Aealan Z <lrobledo@kijho.com> 28/03/15
  1058.      * @param \Symfony\Component\HttpFoundation\Request $request datos de la solicitud
  1059.      * @return Response Json con la informacion de respuesta
  1060.      */
  1061.     public function syncFromWeb(Request $request) {
  1062.         $path Util::getValidActiveLogByBaseName($this->realContainer'requestFromWeb''requestFromWeb0.txt');
  1063.         if ($request->getMethod() === WebService::REQUEST_METHOD_POST) {
  1064.             if (!== strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_TEXT) && !== strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_STRUCTURE)) {
  1065.                 $this->createFileJson($path'Se Fue 6' "\r");
  1066.                 return $this->errorWrongArgs('Wrong Arguments.'WebService::CODE_WRONG_ARGUMENTS);
  1067.             }
  1068.             $params json_decode($request->getContent(), true);
  1069.             $this->createFileJson($path"\r" 'Coming Content New Age: ' json_encode($params) . "\r");
  1070.             $decodeInfo Util::decodeInfo($params['nickname']);
  1071.             $this->createFileJson($path'Decode info: ' $decodeInfo "\r");
  1072.             $data = ['alLicenseUsername' => $decodeInfo];
  1073.             $em $this->getDoctrine()->getManager();
  1074.             $accountLicenseData $em->getRepository('App\Entity\AccountLicense')->findByAlLicenseUsername($data);
  1075.             $countResult count($accountLicenseData);
  1076.             $this->createFileJson($path'Count found: ' $countResult "\r");
  1077.             if ($countResult <= 0) {
  1078.                 $this->createFileJson($path'Se Fue 5' "\r");
  1079.                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  1080.                                 ->respondWithError('Invalid nickname'WebService::CODE_COULD_NOT_AUTHENTICATE);
  1081.             }
  1082.             $this->createFileJson($path'Entro coño! ' $accountLicenseData[0]->getAlAccountLicense()->getDeleted() . "\r");
  1083.             if ($accountLicenseData[0]->getAlAccountLicense()->getDeleted() === true) {
  1084.                 $this->createFileJson($path'Se Fue 1: Account is inactive' "\r");
  1085.                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  1086.                                 ->respondWithError('Account is inactive'WebService::CODE_ACCOUNT_SUSPENDED);
  1087.             }
  1088.             if ($accountLicenseData[0]->getAlLicenseStatus() != AccountLicense::LICENSE_STATUS_ACTIVE) {
  1089.                 $this->createFileJson($path'Se Fue 4' "\r");
  1090.                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  1091.                                 ->respondWithError('Inactive License'WebService::CODE_ACCOUNT_SUSPENDED);
  1092.             }
  1093.             $priorityFlag null;
  1094.             if (isset($params['priorityFlag'])) {
  1095.                 $priorityFlag = (int) $params['priorityFlag'];
  1096.             } 
  1097.             $this->createFileJson($path'pre notifyLastSyncByLicense ' "\r");
  1098.             $this->notifyLastSyncByLicense($em$accountLicenseData[0]);
  1099.             $masterBlockingByDBUpdate $em->getRepository('App\Entity\MasterSync')->findBy(['msLicense' => $accountLicenseData[0]->getId(), 'msType' => MasterSync::MASTER_SYNC_TYPE_DB_UPDATE'msStatus' => MasterSync::MASTER_STATUS_INITIALIZATED]);
  1100.             if (!empty($masterBlockingByDBUpdate)) {
  1101.                 $this->createFileJson($path'Se Fue DB blocked!' "\r");
  1102.                 return $this->setStatusCode(WebService::CODE_OBJECT_NOT_FOUND)
  1103.                                 ->respondWithError('Synchronization blocked by DB update, please wait...'WebService::NOTHING_TO_WEB_SYNCHRONIZE);
  1104.             }
  1105.             $emLev Util::emLicenseConnection($this->realContainer$em$accountLicenseData[0]);
  1106.             $registActionRepository $emLev->getRepository('App\Structure\RegistActions');
  1107.             $this->createFileJson($path'pre existCategoryRegistActionRecordToSync ' "\r");
  1108.             $hasCategoryToSync $registActionRepository->existCategoryRegistActionRecordToSync($this->realContainer->getParameter('max_records_sync_up_down'));
  1109.             if ($accountLicenseData[0]->getHasLogedOMT() && (int) $hasCategoryToSync) {
  1110.                 $this->createFileJson($path'pre validateMenuCategoryForOutgoingOMTSyncs ' "\r");
  1111.                 Util::validateMenuCategoryForOutgoingOMTSyncs($emLev$pathfalse);
  1112.             }
  1113.             $this->createFileJson($path'pre validateIfRestaurantCaDoAndroidDatabaseCleanse ' "\r");
  1114.             $canSyncCleanseRecords Util::validateIfRestaurantCaDoAndroidDatabaseCleanse($accountLicenseData[0], $emLev$path);
  1115.             if (is_string($canSyncCleanseRecords)) {
  1116.                 $recordType RegistActions::TYPE_GENERAL;
  1117.                 $this->createFileJson($path'Full sync with cleanse if there is one' "\r");
  1118.                 $pendingToSyncDownRecord $registActionRepository->alternateSmartGetRegistActionForUpDownSync($this->realContainerRegistActions::STATUS_NOTREADEDRegistActions::TYPE_GENERAL$this->realContainer->getParameter('max_records_sync_up_down'), $priorityFlag$path);
  1119.                 // $pendingToSyncDownRecord = $registActionRepository->findBy(['reacStatus' => RegistActions::STATUS_NOTREADED, 'reacType' => RegistActions::TYPE_GENERAL], ['reacRegistFk' => 'DESC'], $this->realContainer->getParameter('max_records_sync_up_down'));
  1120.             } else {
  1121.                 $recordType null;
  1122.                 $this->createFileJson($path'Without cleanse' "\r");
  1123.                 $pendingToSyncDownRecord $registActionRepository->alternateSmartGetRegistActionForUpDownSync($this->realContainerRegistActions::STATUS_NOTREADEDnull$this->realContainer->getParameter('max_records_sync_up_down'), $priorityFlag$path);
  1124.                 // $pendingToSyncDownRecord = $registActionRepository->findBy(['reacStatus' => RegistActions::STATUS_NOTREADED], ['reacRegistFk' => 'DESC'], $this->realContainer->getParameter('max_records_sync_up_down'));
  1125.             }
  1126.             // dump($pendingToSyncDownRecord);
  1127.             $recordsCount count($pendingToSyncDownRecord);
  1128.             $auxRecordCount $this->realContainer->getParameter('max_records_sync_up_down') - count($pendingToSyncDownRecord);
  1129.             if ($auxRecordCount && $priorityFlag !== false) {
  1130.                 $this->createFileJson($path'Completing max regist action records for sync ;) ' "\r");
  1131.                 if (!empty($path)) {
  1132.                     $this->createFileJson($path"'$recordsCount' total priority records were found... filling with normal records XD " "\r");
  1133.                 }
  1134.                 $otherComplementingRegistActionRecords $registActionRepository->alternateSmartGetRegistActionForUpDownSync($this->realContainerRegistActions::STATUS_NOTREADED$recordType$auxRecordCountfalse$path);
  1135.                 $pendingToSyncDownRecord array_merge($pendingToSyncDownRecord$otherComplementingRegistActionRecords);
  1136.             }
  1137.             // dump($pendingToSyncDownRecord);
  1138.             $this->createFileJson($path'pre countPendigRecordsToPickupAndSync ' "\r");
  1139.             $totalSyncRecords $registActionRepository->countPendigRecordsToPickupAndSync();
  1140.             $countTotalSyncRecords = (int) $totalSyncRecords;
  1141.             $hasMoreRecordsToSync false;
  1142.             $syncsToPerform 1;
  1143.             if ($countTotalSyncRecords $this->realContainer->getParameter('max_records_sync_up_down')) {
  1144.                 $hasMoreRecordsToSync true;
  1145.                 $syncsToPerform = (int) ceil($countTotalSyncRecords $this->realContainer->getParameter('max_records_sync_up_down'));
  1146.             }
  1147.             $responseArray = [];
  1148.             $responseArray['status'] = WebService::CODE_SUCCESS;
  1149.             $responseArray['result'] = '__OK__';
  1150.             $responseArray['wait'] = '__NO__';
  1151.             $responseArray['bigbag'] = true;
  1152.             $responseArray['hasMoreRecords'] = $hasMoreRecordsToSync;
  1153.             $responseArray['syncsToPerform'] = $syncsToPerform;
  1154.             $this->createFileJson($path'Count records to notify x2: ' count($pendingToSyncDownRecord) . "\r");
  1155.             if (!empty($pendingToSyncDownRecord)) {
  1156.                 $this->createFileJson($path'The syncFK: ' $pendingToSyncDownRecord[0]->getReacRegistFk() . "\r");
  1157.                 if (null == $pendingToSyncDownRecord[0]->getReacRegistFk() || $pendingToSyncDownRecord[0]->getReacRegistFk() == 0) {
  1158.                     $this->createFileJson($path'Records not picked yet! ' "\r");
  1159.                     $auxResponseArray Utilx::setRegistNewSyncWeb($this->realContainer$em$accountLicenseData[0], nullnullnull$syncsToPerform$priorityFlag);
  1160.                     $responseArray['result'] = $auxResponseArray['result'];
  1161.                     $responseArray['rid'] = $auxResponseArray['rid'];
  1162.                     $this->createFileJson($path'The new record sync id to handle! ' $responseArray['rid'] . "\r");
  1163.                 } else {
  1164.                     // $pendignMasterSyncRecord = $em->getRepository('App\Entity\MasterSync')->findBy(['msSyncWebRecord' => $pendingToSyncDownRecord[0]->getReacRegistFk(), 'msStatus' => MasterSync::MASTER_STATUS_INITIALIZATED]);
  1165.                     $pendignMasterSyncRecord $em->getRepository('App\Entity\MasterSync')->findBy(['msSyncWebRecord' => $pendingToSyncDownRecord[0]->getReacRegistFk()]);
  1166.                     // $responseArray['hasMoreRecords'] = $hasMoreRecordsToSync;
  1167.                     //////
  1168.                     if (!empty($pendignMasterSyncRecord)) {
  1169.                         if ($pendignMasterSyncRecord[0]->getMsType() == MasterSync::MASTER_SYNC_TYPE_UPDOWN && $pendignMasterSyncRecord[0]->getMsStatus() == MasterSync::MASTER_STATUS_CLOSED && $pendignMasterSyncRecord[0]->getMsOMTStatus() == MasterSync::MASTER_STATUS_CLOSED) {
  1170.                             $this->createFileJson($path'Records about to be picked by validation, generating another web sync record! ' "\r");
  1171.                             $auxResponseArray Utilx::setRegistNewSyncWeb($this->realContainer$em$accountLicenseData[0], nullnullnull$syncsToPerform$priorityFlag);
  1172.                             $responseArray['result'] = $auxResponseArray['result'];
  1173.                             $responseArray['rid'] = $auxResponseArray['rid'];
  1174.                             $this->createFileJson($path'The new records to sync with! ' $responseArray['rid'] . "\r");
  1175.                         } else {
  1176.                             $responseArray['rid'] = $pendingToSyncDownRecord[0]->getReacRegistFk();
  1177.                             $this->createFileJson($path'Records picked by: ' $responseArray['rid'] . "\r");
  1178.                         }
  1179.                     } else {
  1180.                         $this->createFileJson($path'Records about to be picked, generating another web sync record! ' "\r");
  1181.                         $auxResponseArray Utilx::setRegistNewSyncWeb($this->realContainer$em$accountLicenseData[0], nullnullnull$syncsToPerform$priorityFlag);
  1182.                         $responseArray['result'] = $auxResponseArray['result'];
  1183.                         $responseArray['rid'] = $auxResponseArray['rid'];
  1184.                         $this->createFileJson($path'The new records to sync with! ' $responseArray['rid'] . "\r");
  1185.                     }
  1186.                 }
  1187.                 // dump($pendingToSyncDownRecord);
  1188.                 // die;
  1189.                 $recordsJustForOMT true;
  1190.                 $arrRegistActionsToDeleteAlready = [];
  1191.                 $arrAlreadyCheckedRegistActionRecord = [];
  1192.                 $auxArrayForRealRegistActionsRecordsToSync = [];
  1193.                 foreach ($pendingToSyncDownRecord as $registActionRecord) {
  1194.                     if (array_search($registActionRecord->getId(), $arrAlreadyCheckedRegistActionRecord) === false) {
  1195.                         $registActionRecord->setReacRegistFk($responseArray['rid']);
  1196.                         if (!$registActionRecord->getReacType() && !$registActionRecord->getReacOMTRegistFk()) {
  1197.                             $registActionRecord->setReacOMTRegistFk($responseArray['rid']);
  1198.                         }
  1199.                         $androidtname Util::getAndroidTableName($registActionRecord->getReacTableName());
  1200.                         if ($recordsJustForOMT && (Util::getRepoServerNameByAndroidTableName($androidtname) || Util::getStructureEntityDirForForLicensorCorrespondigTable($androidtname))) {
  1201.                             $this->createFileJson($path'Has Android records to sync!!' "\r");
  1202.                             $recordsJustForOMT false;
  1203.                         }
  1204.                         array_push($arrRegistActionsToDeleteAlready$registActionRecord->getId());
  1205.                         array_push($arrAlreadyCheckedRegistActionRecord$registActionRecord->getId());
  1206.                         array_push($auxArrayForRealRegistActionsRecordsToSync$registActionRecord);
  1207.                         $emLev->persist($registActionRecord);
  1208.                     }
  1209.                 }
  1210.                 $pendingToSyncDownRecord $auxArrayForRealRegistActionsRecordsToSync;
  1211.                 // dump($pendingToSyncDownRecord);
  1212.                 if ($recordsJustForOMT) {
  1213.                     $this->createFileJson($path'Direct sync for OMT detected, moving forward with validations.... -_- ' "\r");
  1214.                 }
  1215.                 // die;
  1216.                 $emLev->flush();
  1217.                 $this->createFileJson($path'New sync web fk?? -> ' $responseArray['rid'] . "\r");
  1218.                 $masterSyncRecords $em->getRepository('App\Entity\MasterSync')->findBy(['msSyncWebRecord' => $responseArray['rid']]);
  1219.                 if (!empty($masterSyncRecords) && !$recordsJustForOMT) {
  1220.                     $responseArray['msg'] = 'Processing new data..';
  1221.                     $responseArray['wait'] = '__NO__';
  1222.                     $responseArray['master_sync'] = $masterSyncRecords[0]->getId();
  1223.                     $responseArray['response_code'] = WebService::PROCESSING_UNNOTIFIED_WEB_DATA;
  1224.                     $webSyncWaiting $masterSyncRecords[0]->getMsSyncWebRecord();
  1225.                     $this->createFileJson($path'Master sync record: ' $masterSyncRecords[0]->getId() . "\r");
  1226.                     $this->createFileJson($path'One IF Status: ' $webSyncWaiting->getRfwStatus() . ' Error: ' . !(boolean) $webSyncWaiting->getHasPersistentError() . "\r");
  1227.                     if ($webSyncWaiting->getRfwStatus() == ReadFilesDataWeb::STATUS_NOTIFIED && !(boolean) $webSyncWaiting->getHasPersistentError()) {
  1228.                         $isDirectoryReady Util::createLicenseDirectory($this->realContainer$accountLicenseData[0], $decodeInfo);
  1229.                         if (isset($isDirectoryReady['result']) && $isDirectoryReady['result'] == '__KO__') {
  1230.                             $this->createFileJson($path'Se Fue 1 ' "\r");
  1231.                             $msnError 'An error occurred while creating license directory in server ';
  1232.                             return $this->setStatusCode(WebService::CODE_INTERNAL_ERROR)
  1233.                                             ->respondWithError($msnErrorWebService::CODE_INTERNAL_ERROR);
  1234.                         }
  1235.                         $this->createFileJson($path'Web ready sync: ' $webSyncWaiting->getId() . "\r");
  1236.                         if ($webSyncWaiting->getIsReadedByServer()) {
  1237.                             $this->createFileJson($path'Web already picked by rabbit: TRUE' "\r");
  1238.                             $responseArray['msg'] = 'Server is already synchronizing the new data to the android device, please wait.';
  1239.                             $responseArray['wait'] = '__YES__';
  1240.                             $responseArray['response_code'] = WebService::SERVER_ALREADY_WORKING_WEB_SYNC;
  1241.                             $theUrlTrSt = new SyncWebTransformer($responseArray);
  1242.                             $jsonTransform $theUrlTrSt->transform();
  1243.                             $jsonContent json_encode($jsonTransform);
  1244.                             return $this->respondWithURLWithoutEncriptControl($jsonContent$theUrlTrSt);
  1245.                         }
  1246.                         $em->clear();
  1247.                         if (isset($params['waitTime']) && !(boolean) $params['waitTime'] && isset($responseArray['rid']) && $responseArray['rid'] != 0) {
  1248.                             ForcedAsynchronousCommandsUtil::produceUpDownSyncCommand($this->realContainer$responseArraytrue);
  1249.                             $this->createFileJson($path'No wait request triggered...' "\r");
  1250.                         }
  1251.                         $theUrlTrSt = new SyncWebTransformer($responseArray);
  1252.                         $jsonTransform $theUrlTrSt->transform();
  1253.                         $jsonContent json_encode($jsonTransform);
  1254.                         $this->createFileJson($path'WS Response: ' $jsonContent "\r");
  1255.                         return $this->respondWithURLWithoutEncriptControl($jsonContent$theUrlTrSt);
  1256.                     } else {
  1257.                         $pushRelatedRecord $masterSyncRecords[0]->getMsPushRecord();
  1258.                         $responseArray['rid'] = 0;
  1259.                         $responseArray['response_code'] = 0;
  1260.                         $responseArray['master_sync'] = $masterSyncRecords[0]->getId();
  1261.                         if (!$pushRelatedRecord) {
  1262.                             $this->createFileJson($path'No push related to the master sync record' "\r");
  1263.                             $responseArray['msg'] = 'Processing unnotified data..';
  1264.                             $responseArray['rid'] = $webSyncWaiting->getId();
  1265.                             $responseArray['response_code'] = WebService::PROCESSING_UNNOTIFIED_WEB_DATA;
  1266.                             if (isset($pendingToSyncDownRecord[0]) && $pendingToSyncDownRecord[0]->getReacStatus() == RegistActions::STATUS_NOTREADED && ReadFilesDataWeb::STATUS_RESPONSE_READED == $webSyncWaiting->getRfwStatus()) {
  1267.                                 ///// analizar si la licencia tiene OMT logueado y verificar si dichos registros son para OMT, si si, entonces enviarla desde aca directamente a OMT, si no, borrar los registros del regist action y asi evitar la inconsistencia
  1268.                                 
  1269.                                 if ($recordsJustForOMT && !$accountLicenseData[0]->getHasLogedOMT()) {
  1270.                                     $this->createFileJson($path'Deleting OMT RegistAction records to for non OMT license ;) ' "\r");
  1271.                                     SyncWebUtil::deleteValidatedRegistAction($arrRegistActionsToDeleteAlready, [], $registActionRepositoryfalsetrue$path);
  1272.                                     $this->createFileJson($path'Closing the related sync records ;) ' "\r");
  1273.                                     $masterSyncRecords[0]->setMsStatus(MasterSync::MASTER_STATUS_CLOSED);
  1274.                                     $webSyncWaiting->setRfwStatus(ReadFilesDataWeb::STATUS_RESPONSE_READED);
  1275.                                     $webSyncWaiting->setIsReadedByServer(true);
  1276.                                     $em->persist($masterSyncRecords[0]);
  1277.                                     $em->persist($webSyncWaiting);
  1278.                                     $em->flush();
  1279.                                     $this->createFileJson($path'Preparing a propper ws response for this case ;) ' "\r");
  1280.                                     $responseArray['msg'] = 'Cleaning web sync records, please try again in a few seconds...';
  1281.                                     $responseArray['wait'] = '__NO__';
  1282.                                     $responseArray['askAgain'] = 1;
  1283.                                     $responseArray['response_code'] = WebService::SERVER_ALREADY_WORKING_WEB_SYNC;
  1284.                                 } elseif ($recordsJustForOMT && $accountLicenseData[0]->getHasLogedOMT()) {
  1285.                                     //// amerita en elseif en donde se mande directo a OMT si la licencia si tiene OMT y estos registros andan asi como raros o mal cerrados
  1286.                                     $this->createFileJson($path'Sending forced sync direct to OMT!' "\r");
  1287.                                     $data['rid'] = $webSyncWaiting->getId();
  1288.                                     $data['masterSyncId'] = $masterSyncRecords[0]->getId();
  1289.                                     $data['restaurantNickname'] = $data['alLicenseUsername'];
  1290.                                     $masterSyncRecords[0]->setMsStatus(MasterSync::MASTER_STATUS_CLOSED);
  1291.                                     if ($webSyncWaiting) {
  1292.                                         $webSyncWaiting->setRfwStatus(ReadFilesDataWeb::STATUS_RESPONSE_READED);
  1293.                                         $webSyncWaiting->setIsReadedByServer(true);
  1294.                                         $em->persist($webSyncWaiting);
  1295.                                     }
  1296.                                     $em->persist($masterSyncRecords[0]);
  1297.                                     $em->flush();
  1298.                                     $typeSync UtilSync::hybridSync2OMT($this->realContainer$em$path$data['alLicenseUsername']);
  1299.                                     // se valida el tipo de sync que se va a realizar
  1300.                                     if($typeSync){
  1301.                                         ForcedAsynchronousCommandsUtil::produceUpDownOMTSyncCommand($this->realContainer$datatrue);
  1302.                                     }else{
  1303.                                         // comando de cola para sync masiva
  1304.                                         ForcedAsynchronousCommandsUtil::produceUpDownOMTSyncMassiveCommand($this->realContainer$data$pathtrue);
  1305.                                     }
  1306.                                     $responseArray['msg'] = 'Direct sync to OMT';
  1307.                                     $responseArray['wait'] = '__NO__';
  1308.                                     $responseArray['askAgain'] = 1;
  1309.                                     $responseArray['master_sync'] = $masterSyncRecords[0]->getId();
  1310.                                     $responseArray['response_code'] = WebService::SERVER_ALREADY_WORKING_WEB_SYNC;
  1311.                                 } else {
  1312.                                     $this->createFileJson($path'Records bad closed by support, generating another web sync record! ' "\r");
  1313.                                     // $auxResponseArray = Utilx::setRegistNewSyncWeb($this->realContainer, $em, $accountLicenseData[0], null, null, null, $syncsToPerform);
  1314.                                     $responseArray['result'] = $auxResponseArray['result'];
  1315.                                     $responseArray['rid'] = $auxResponseArray['rid'];
  1316.                                     $responseArray['master_sync'] = $masterSyncRecords[0]->getId();
  1317.                                     $responseArray['msg'] = 'Scheduling unprocessed sync records, please try to sync again in a few seconds';
  1318.                                     $this->createFileJson($path'The new records to sync with! ' $responseArray['rid'] . " second chance \r");
  1319.                                     
  1320.                                     foreach ($pendingToSyncDownRecord as $registActionRecord) {
  1321.                                         $registActionRecord->setReacRegistFk($responseArray['rid']);
  1322.                                         if (!$registActionRecord->getReacType() && !$registActionRecord->getReacOMTRegistFk()) {
  1323.                                             $registActionRecord->setReacOMTRegistFk($responseArray['rid']);
  1324.                                         }
  1325.                                         $emLev->persist($registActionRecord);
  1326.                                     }
  1327.                                     $emLev->flush();
  1328.                                     $this->createFileJson($path'New sync web fk second chance?? -> ' $responseArray['rid'] . "\r");
  1329.                                 }
  1330.                                 
  1331.                             } else {
  1332.                                 ////mandar a la cola de rabbit para que recoja los registros aun no procesados
  1333.                                 ForcedAsynchronousCommandsUtil::produceUpDownSyncCommand($this->realContainer$responseArraytrue);
  1334.                                 $this->createFileJson($path'No wait request triggered alternate 1 ...' "\r");
  1335.                             }
  1336.                         } else {
  1337.                             if ($pushRelatedRecord->getPushStatus() == PushSent::STATUS_PUSH_PENDING) {
  1338.                                 $this->createFileJson($path'Pending for response push: ' $pushRelatedRecord->getId() . "\r");
  1339.                                 $responseArray['msg'] = 'Push notification unconfirmed by android device, forwarding push to complete the synchronization process... ';
  1340.                                 $responseArray['wait'] = '__NO__';
  1341.                                 $responseArray['response_code'] = WebService::FORWARDING_UNNOTIFIED_WEB_PUSH;
  1342.                                 $responseArray['master_sync'] = $masterSyncRecords[0]->getId();
  1343.                                 $actualDate Util::getCurrentDate();
  1344.                                 $actualDate->modify($this->realContainer->getParameter('maximum_minutes_to_validate_push_sending') . ' minutes');
  1345.                                 if ($pushRelatedRecord->getResendDate() < $actualDate) {
  1346.                                     $data['pushId'] = $pushRelatedRecord->getId();
  1347.                                     ForcedAsynchronousCommandsUtil::resendPushCommand($this->realContainer$datatrue);
  1348.                                 }
  1349.                             } else {
  1350.                                 if (isset($pendingToSyncDownRecord[0]) && $pendingToSyncDownRecord[0]->getReacStatus() == RegistActions::STATUS_NOTREADED && ReadFilesDataWeb::STATUS_RESPONSE_READED == $webSyncWaiting->getRfwStatus()) {
  1351.                                     if ($recordsJustForOMT && !$accountLicenseData[0]->getHasLogedOMT()) {
  1352.                                         $this->createFileJson($path'Deleting OMT RegistAction records to for non OMT license ;)) ' "\r");
  1353.                                         SyncWebUtil::deleteValidatedRegistAction($arrRegistActionsToDeleteAlready, [], $registActionRepositoryfalsetrue$path);
  1354.                                         $this->createFileJson($path'Closing the related sync records ;)) ' "\r");
  1355.                                         $masterSyncRecords[0]->setMsStatus(MasterSync::MASTER_STATUS_CLOSED);
  1356.                                         $masterSyncRecords[0]->setMsOMTStatus(MasterSync::MASTER_STATUS_CLOSED);
  1357.                                         $webSyncWaiting->setRfwStatus(ReadFilesDataWeb::STATUS_RESPONSE_READED);
  1358.                                         $webSyncWaiting->setIsReadedByServer(true);
  1359.                                         $em->persist($masterSyncRecords[0]);
  1360.                                         $em->persist($webSyncWaiting);
  1361.                                         $em->flush();
  1362.                                         $this->createFileJson($path'Preparing a propper ws response for this case ;)) ' "\r");
  1363.                                         $responseArray['msg'] = 'Cleaning web sync records, please try again in a few seconds...';
  1364.                                         $responseArray['wait'] = '__NO__';
  1365.                                         $responseArray['askAgain'] = 1;
  1366.                                         $responseArray['master_sync'] = $masterSyncRecords[0]->getId();
  1367.                                         $responseArray['response_code'] = WebService::SERVER_ALREADY_WORKING_WEB_SYNC;
  1368.                                     } elseif ($recordsJustForOMT && $accountLicenseData[0]->getHasLogedOMT()) {
  1369.                                         $this->createFileJson($path'Sending forced sync direct to OMT!!' "\r");
  1370.                                         $data['rid'] = $webSyncWaiting->getId();
  1371.                                         $data['masterSyncId'] = $masterSyncRecords[0]->getId();
  1372.                                         $data['restaurantNickname'] = $data['alLicenseUsername'];
  1373.                                         $masterSyncRecords[0]->setMsStatus(MasterSync::MASTER_STATUS_CLOSED);
  1374.                                         $webSyncWaiting->setRfwStatus(ReadFilesDataWeb::STATUS_RESPONSE_READED);
  1375.                                         $webSyncWaiting->setIsReadedByServer(true);
  1376.                                         $em->persist($masterSyncRecords[0]);
  1377.                                         $em->persist($webSyncWaiting);
  1378.                                         $em->flush();
  1379.                                         $typeSync UtilSync::hybridSync2OMT($this->container$em$path$data['alLicenseUsername']);
  1380.                                         // se valida el tipo de sync que se va a realizar
  1381.                                         if($typeSync){
  1382.                                             $this->createFileJson($path'Sending standard sync direct to OMT 1 !!' "\r");
  1383.                                             ForcedAsynchronousCommandsUtil::produceUpDownOMTSyncCommand($this->container$datatrue);
  1384.                                         }else{
  1385.                                             // comando de cola para sync masiva
  1386.                                             $this->createFileJson($path'Sending hybrid sync direct to OMT 1 !!' "\r");
  1387.                                             ForcedAsynchronousCommandsUtil::produceUpDownOMTSyncMassiveCommand($this->container$data$pathtrue);
  1388.                                         }
  1389.                                         $responseArray['msg'] = 'Direct sync to OMT';
  1390.                                         $responseArray['wait'] = '__NO__';
  1391.                                         $responseArray['askAgain'] = 1;
  1392.                                         $responseArray['master_sync'] = $masterSyncRecords[0]->getId();
  1393.                                         $responseArray['response_code'] = WebService::SERVER_ALREADY_WORKING_WEB_SYNC;
  1394.                                     } else {
  1395.                                         $this->createFileJson($path'Records bad closed by support, generating another web sync record! ' "\r");
  1396.                                         // $auxResponseArray = Utilx::setRegistNewSyncWeb($this->realContainer, $em, $accountLicenseData[0], null, null, null, $syncsToPerform);
  1397.                                         $responseArray['result'] = $auxResponseArray['result'];
  1398.                                         $responseArray['rid'] = $auxResponseArray['rid'];
  1399.                                         $responseArray['msg'] = 'Scheduling unprocessed sync records, please try to sync again in a few seconds';
  1400.                                         $responseArray['master_sync'] = $masterSyncRecords[0]->getId();
  1401.                                         $this->createFileJson($path'The new records to sync with! ' $responseArray['rid'] . " second chance \r");
  1402.                                         
  1403.                                         foreach ($pendingToSyncDownRecord as $registActionRecord) {
  1404.                                             $registActionRecord->setReacRegistFk($responseArray['rid']);
  1405.                                             if (!$registActionRecord->getReacType() && !$registActionRecord->getReacOMTRegistFk()) {
  1406.                                                 $registActionRecord->setReacOMTRegistFk($responseArray['rid']);
  1407.                                             }
  1408.                                             $emLev->persist($registActionRecord);
  1409.                                         }
  1410.                                         $emLev->flush();
  1411.                                         $this->createFileJson($path'New sync web fk second chance?? -> ' $responseArray['rid'] . "\r");
  1412.                                     }
  1413.                                 } else {
  1414.                                     $this->createFileJson($path'Sync unresponded by android device: ' $pushRelatedRecord->getId() . "\r");
  1415.                                     $responseArray['msg'] = 'Forwarding push with new code to complete the synchronization process...';
  1416.                                     $responseArray['wait'] = '__YES__';
  1417.                                     $responseArray['response_code'] = WebService::FORWARDING_UNNOTIFIED_WEB_PUSH;
  1418.                                     $actualDate Util::getCurrentDate();
  1419.                                     $actualDate->modify($this->realContainer->getParameter('maximum_minutes_to_validate_push_sending') . ' minutes');
  1420.                                     if ($pushRelatedRecord->getResendDate() < $actualDate) {
  1421.                                         $data['pushId'] = $pushRelatedRecord->getId();
  1422.                                         $data['forcePushNewCode'] = true;
  1423.                                         ForcedAsynchronousCommandsUtil::resendPushCommand($this->realContainer$datatrue);
  1424.                                     }
  1425.                                 }
  1426.                             }
  1427.                         }
  1428.                     }
  1429.                     $theUrlTrSt = new SyncWebTransformer($responseArray);
  1430.                     $jsonTransform $theUrlTrSt->transform();
  1431.                     $jsonContent json_encode($jsonTransform);
  1432.                     $this->createFileJson($path'WS Response: ' $jsonContent "\r");
  1433.                     return $this->respondWithURLWithoutEncriptControl($jsonContent$theUrlTrSt);
  1434.                 } elseif (!empty($masterSyncRecords) && $recordsJustForOMT) {
  1435.                     $responseArray['master_sync'] = $masterSyncRecords[0]->getId();
  1436.                     $webSyncWaiting $masterSyncRecords[0]->getMsSyncWebRecord();
  1437.                     if (!$accountLicenseData[0]->getHasLogedOMT()) {
  1438.                         $this->createFileJson($path'Deleting OMT RegistAction records to for non OMT license ;)) ' "\r");
  1439.                         SyncWebUtil::deleteValidatedRegistAction($arrRegistActionsToDeleteAlready, [], $registActionRepositoryfalsetrue$path);
  1440.                         $this->createFileJson($path'Closing the related sync records ;)) ' "\r");
  1441.                         $masterSyncRecords[0]->setMsStatus(MasterSync::MASTER_STATUS_CLOSED);
  1442.                         $masterSyncRecords[0]->setMsOMTStatus(MasterSync::MASTER_STATUS_CLOSED);
  1443.                         if ($webSyncWaiting) {
  1444.                             $webSyncWaiting->setRfwStatus(ReadFilesDataWeb::STATUS_RESPONSE_READED);
  1445.                             $webSyncWaiting->setIsReadedByServer(true);
  1446.                             $em->persist($webSyncWaiting);
  1447.                         }
  1448.                         $em->persist($masterSyncRecords[0]);
  1449.                         $em->flush();
  1450.                         $this->createFileJson($path'Preparing a propper ws response for this case ;)) ' "\r");
  1451.                         $responseArray['msg'] = 'Cleaning web sync records, please try again in a few seconds...';
  1452.                         $responseArray['wait'] = '__NO__';
  1453.                         $responseArray['askAgain'] = 1;
  1454.                         $responseArray['response_code'] = WebService::SERVER_ALREADY_WORKING_WEB_SYNC;
  1455.                     } else {
  1456.                         $this->createFileJson($path'Sending forced sync direct to OMT!!' "\r");
  1457.                         $data['rid'] = $webSyncWaiting->getId();
  1458.                         $data['masterSyncId'] = $masterSyncRecords[0]->getId();
  1459.                         $data['restaurantNickname'] = $data['alLicenseUsername'];
  1460.                         $masterSyncRecords[0]->setMsStatus(MasterSync::MASTER_STATUS_CLOSED);
  1461.                         if ($webSyncWaiting) {
  1462.                             $webSyncWaiting->setRfwStatus(ReadFilesDataWeb::STATUS_RESPONSE_READED);
  1463.                             $webSyncWaiting->setIsReadedByServer(true);
  1464.                             $em->persist($webSyncWaiting);
  1465.                         }
  1466.                         $em->persist($masterSyncRecords[0]);
  1467.                         $em->flush();
  1468.                         $typeSync UtilSync::hybridSync2OMT($this->realContainer$em$path$data['alLicenseUsername']);
  1469.                         // se valida el tipo de sync que se va a realizar
  1470.                         if($typeSync){
  1471.                             $this->createFileJson($path'Sending standard sync direct to OMT 2 !!' "\r");
  1472.                             ForcedAsynchronousCommandsUtil::produceUpDownOMTSyncCommand($this->realContainer$datatrue);
  1473.                         }else{
  1474.                             // comando de cola para sync masiva
  1475.                             $this->createFileJson($path'Sending hybrid sync direct to OMT 2 !!' "\r");
  1476.                             ForcedAsynchronousCommandsUtil::produceUpDownOMTSyncMassiveCommand($this->realContainer$data$pathtrue);
  1477.                         }
  1478.                         $responseArray['msg'] = 'Direct sync to OMT';
  1479.                         $responseArray['wait'] = '__NO__';
  1480.                         $responseArray['askAgain'] = 1;
  1481.                         $responseArray['response_code'] = WebService::SERVER_ALREADY_WORKING_WEB_SYNC;
  1482.                     }
  1483.                 } else {
  1484.                     $this->createFileJson($path'Se Fue 2' "\r");
  1485.                     $msnError 'Nothing to synchronize! ';
  1486.                     return $this->setStatusCode(WebService::CODE_OBJECT_NOT_FOUND)
  1487.                                     ->respondWithError($msnErrorWebService::NOTHING_TO_WEB_SYNCHRONIZE);
  1488.                 }
  1489.                 $theUrlTrSt = new SyncWebTransformer($responseArray);
  1490.                 $jsonTransform $theUrlTrSt->transform();
  1491.                 $jsonContent json_encode($jsonTransform);
  1492.                 $this->createFileJson($path'WS Response: ' $jsonContent "\r");
  1493.                 return $this->respondWithURLWithoutEncriptControl($jsonContent$theUrlTrSt);
  1494.             } else {
  1495.                 $masterSyncRecords $em->getRepository('App\Entity\MasterSync')->findBy(['msLicense' => $accountLicenseData[0]->getId(), 'msType' => MasterSync::MASTER_SYNC_TYPE_UPDOWN'msStatus' => MasterSync::MASTER_STATUS_PROCESSED], ['id' => 'ASC']);
  1496.                 if (!empty($masterSyncRecords)) {
  1497.                     $this->createFileJson($path'Uncomplet master record found -> ' $masterSyncRecords[0]->getId() . "\r");
  1498.                     $webSyncWaiting $masterSyncRecords[0]->getMsSyncWebRecord();
  1499.                     $pushRelatedRecord $masterSyncRecords[0]->getMsPushRecord();
  1500.                     $responseArray['rid'] = 0;
  1501.                     $responseArray['master_sync'] = $masterSyncRecords[0]->getId();
  1502.                     if (!$pushRelatedRecord) {
  1503.                         $this->createFileJson($path'No push related to the master sync record' "\r");
  1504.                         $responseArray['msg'] = 'Processing unnotified data..';
  1505.                         $responseArray['rid'] = $webSyncWaiting->getId();
  1506.                         $responseArray['response_code'] = WebService::PROCESSING_UNNOTIFIED_WEB_DATA;
  1507.                     } else {
  1508.                         if ($pushRelatedRecord->getPushStatus() == PushSent::STATUS_PUSH_PENDING) {
  1509.                             $this->createFileJson($path'Pending for response push: ' $pushRelatedRecord->getId() . "\r");
  1510.                             $responseArray['msg'] = 'Push notification unconfirmed by android device, forwarding push to complete the synchronization process... ';
  1511.                             $responseArray['wait'] = '__NO__';
  1512.                             $responseArray['response_code'] = WebService::FORWARDING_UNNOTIFIED_WEB_PUSH;
  1513.                             $actualDate Util::getCurrentDate();
  1514.                             $actualDate->modify($this->realContainer->getParameter('maximum_minutes_to_validate_push_sending') . ' minutes');
  1515.                             if ($pushRelatedRecord->getResendDate() < $actualDate) {
  1516.                                 $data['pushId'] = $pushRelatedRecord->getId();
  1517.                                 ForcedAsynchronousCommandsUtil::resendPushCommand($this->realContainer$datatrue);
  1518.                             }
  1519.                         } else {
  1520.                             $this->createFileJson($path'Sync unresponded by android device: ' $pushRelatedRecord->getId() . "\r");
  1521.                             $responseArray['msg'] = 'Forwarding push with new code to complete the synchronization process...';
  1522.                             $responseArray['wait'] = '__YES__';
  1523.                             $responseArray['response_code'] = WebService::FORWARDING_UNNOTIFIED_WEB_PUSH;
  1524.                             $actualDate Util::getCurrentDate();
  1525.                             $actualDate->modify($this->realContainer->getParameter('maximum_minutes_to_validate_push_sending') . ' minutes');
  1526.                             if ($pushRelatedRecord->getResendDate() < $actualDate) {
  1527.                                 $data['pushId'] = $pushRelatedRecord->getId();
  1528.                                 $data['forcePushNewCode'] = true;
  1529.                                 ForcedAsynchronousCommandsUtil::resendPushCommand($this->realContainer$datatrue);
  1530.                             }
  1531.                         }
  1532.                     }
  1533.                 } else {
  1534.                     $masterBlockingByFalseSync $em->getRepository('App\Entity\MasterSync')->findBy(['msLicense' => $accountLicenseData[0]->getId(), 'msType' => MasterSync::MASTER_SYNC_TYPE_UPDOWN'msStatus' => MasterSync::MASTER_STATUS_INITIALIZATED]);
  1535.                     foreach ($masterBlockingByFalseSync as $falseMasterSync) {
  1536.                         Utilx::updateRegistCloseByEmptySyncFile($em$falseMasterSync$path);
  1537.                     }
  1538.                     $this->createFileJson($path'Se Fue 3' "\r");
  1539.                     $msnError 'Nothing to synchronize! ';
  1540.                     return $this->setStatusCode(WebService::CODE_OBJECT_NOT_FOUND)
  1541.                                     ->respondWithError($msnErrorWebService::NOTHING_TO_WEB_SYNCHRONIZE);
  1542.                 }
  1543.                 $theUrlTrSt = new SyncWebTransformer($responseArray);
  1544.                 $jsonTransform $theUrlTrSt->transform();
  1545.                 $jsonContent json_encode($jsonTransform);
  1546.                 $this->createFileJson($path'WS Response: ' $jsonContent "\r");
  1547.                 return $this->respondWithURLWithoutEncriptControl($jsonContent$theUrlTrSt);
  1548.             }
  1549.         } else {
  1550.             $this->createFileJson($path'Se Fue 7' "\r");
  1551.             return $this->errorNotAllowedMethod('Method not allowed. Use ' WebService::REQUEST_METHOD_POST " method");
  1552.         }
  1553.     }
  1554.     /**
  1555.      * Funcion tipo polling para activar el consumidor de una sincronizacion de
  1556.      * arriba a abajo ya encolada por medio de la solicitud de un ajax
  1557.      * @author Aealan Z <lrobledo@kijho.com> 11/06/2016
  1558.      * @param Request $request peticion realizada por medio de un ajax
  1559.      * @param type $id id del registro de sincronizacion web de esa licencia
  1560.      * @return type repuesta de la sincronizacion para el ajax en formato json
  1561.      */
  1562.     public function activateWebConsumerByAjax(Request $request$id) {
  1563.         $em $this->getDoctrine()->getManager();
  1564.         $path Util::getValidActiveLogByBaseName($this->realContainer'requestFromWebYYY''requestFromWebYYY0.txt');
  1565.         $paramNick $request->request->get('nickname');
  1566.         if ($paramNick == null) {
  1567.             $paramNick $request->query->get('nickname');
  1568.         }
  1569.         $this->createFileJson($path'Searching sync with id: ' $id "\r");
  1570.         $syncWebRecord $em->getRepository('App\Entity\ReadFilesDataWeb')->find($id);
  1571.         $this->createFileJson($path'Instant Request Auch -> Llego Llego!' "\r");
  1572.         if ($syncWebRecord) {
  1573.             for ($i 0$i <= 4$i++) {
  1574.                 if ($paramNick != $syncWebRecord->getRfwLicenseId()->getAlLicenseUsername()) {
  1575.                     $responseToAjax['msg'] = 'License Not Found!';
  1576.                     $responseToAjax['result'] = '__KO__';
  1577.                     return $this->respondJsonAjax($responseToAjax);
  1578.                 }
  1579.                 $responseToAjax['result'] = '__OK__';
  1580.                 sleep(4);
  1581.                 $this->createFileJson($path'Instant Request Auch -> ' $syncWebRecord->getIsReadedByServer() . ' | ' $syncWebRecord->getRfwStatus() . "\r");
  1582.                 $statusReadFileWeb $em->getRepository('App\Entity\ReadFilesDataWeb')->find($id);
  1583.                 $statusSyncMaster $em->getRepository('App\Entity\MasterSync')->findBy(['msSyncWebRecord' => $id]);
  1584.                 if ($statusSyncMaster[0]->getMsType() == MasterSync::MASTER_SYNC_TYPE_UPDOWN &&
  1585.                 $statusSyncMaster[0]->getMsStatus() == MasterSync::MASTER_STATUS_PROCESSED &&
  1586.                 $statusSyncMaster[0]->getMsPushRecord() !== null &&
  1587.                 ReadFilesDataWeb::STATUS_READED_DELIVERED == $statusReadFileWeb->getRfwStatus()) {
  1588.                     $em->clear();
  1589.                     $this->createFileJson($path'Instant Request Processed!' "\r");
  1590.                     $responseToAjax['msg'] = 'Data for the Android server send, please check for the new data!';
  1591.                     $responseToAjax['response_code'] = WebService::WEB_DATA_SENDED_TO_ANDROID;
  1592.                     break;
  1593.                 } else if ($syncWebRecord->getIsReadedByServer() && ReadFilesDataWeb::STATUS_NOTIFIED == $syncWebRecord->getRfwStatus()) {
  1594.                     $em->clear();
  1595.                     $data['rwid'] = $syncWebRecord->getId();
  1596.                     ForcedAsynchronousCommandsUtil::consumeUpDownSyncCommand($this->realContainer$datatrue);
  1597.                     $this->createFileJson($path'Instant Request Processed!' "\r");
  1598.                     $responseToAjax['msg'] = 'The data is being processed, please verify the changes in a few seconds...';
  1599.                     $responseToAjax['response_code'] = WebService::WEB_DATA_SENDED_TO_ANDROID;
  1600.                     break;
  1601.                 } else {
  1602.                     $responseToAjax['msg'] = 'Server is working... Please try 20 seconds latter!';
  1603.                     $responseToAjax['response_code'] = WebService::SERVER_ALREADY_WORKING_WEB_SYNC;
  1604.                 }
  1605.             }
  1606.         } else {
  1607.             if ($id == 0) {
  1608.                 $this->createFileJson($path'Instant Request Push Resend -> XD' "\r");
  1609.                 sleep(4);
  1610.                 $responseToAjax['msg'] = 'Push forwarded, please check the Android server!';
  1611.                 $responseToAjax['result'] = '__KO__';
  1612.                 $responseToAjax['response_code'] = WebService::FORWARDING_UNNOTIFIED_WEB_PUSH;
  1613.             } else {
  1614.                 $this->createFileJson($path'Instant Request Auch -> License sync web record not found!' "\r");
  1615.                 $responseToAjax['msg'] = 'License sync web record not found!';
  1616.                 $responseToAjax['result'] = '__KO__';
  1617.             }
  1618.             return $this->respondJsonAjax($responseToAjax);
  1619.         }
  1620.         return $this->respondJsonAjax($responseToAjax);
  1621.     }
  1622.     /**
  1623.      * Funcion que solicitar una sincronizacion de arriba a abajo a un servidor
  1624.      * android por medio de un push
  1625.      * @author Aealan Z <lrobledo@kijho.com> 11/06/2016
  1626.      * @param Request $request solicitud que llega por ajax pidiendo una sincronizacion de abajo a arriba
  1627.      * @param type $id id de la licencia a la cual se le solicita la sincronizacion
  1628.      * @return type respuesta del envio del push que solicita la sincronizacion de tipo json para un ajax
  1629.      */
  1630.     public function activateAndroidSyncManually(Request $request$id) {
  1631.         $em $this->getDoctrine()->getManager();
  1632.         $path Util::getValidActiveLogByBaseName($this->realContainer'requestForManuallySync''requestForManuallySync0.txt');
  1633.         $paramNick $request->request->get('nickname');
  1634.         if ($paramNick == null) {
  1635.             $paramNick $request->query->get('nickname');
  1636.         }
  1637.         $this->createFileJson($path"\r" 'Sync Android Up Manually: ' $paramNick "\r");
  1638.         $licenseToSync $em->getRepository('App\Entity\AccountLicense')->find($id);
  1639.         if ($licenseToSync) {
  1640.             if ($paramNick != $licenseToSync->getAlLicenseUsername()) {
  1641.                 $this->createFileJson($path'Bad nickname!' "\r");
  1642.                 $responseToAjax['msg'] = 'License not found!';
  1643.                 $responseToAjax['result'] = '__KO__';
  1644.                 return $this->respondJsonAjax($responseToAjax);
  1645.             }
  1646.             $this->createFileJson($path'Sync Android Up Manually: License Found!' "\r");
  1647.             $masterBlockingByDBUpdate $em->getRepository('App\Entity\MasterSync')->findBy(['msLicense' => $licenseToSync->getId(), 'msType' => MasterSync::MASTER_SYNC_TYPE_DB_UPDATE'msStatus' => MasterSync::MASTER_STATUS_INITIALIZATED]);
  1648.             if (!empty($masterBlockingByDBUpdate)) {
  1649.                 $this->createFileJson($path'Synchronization blocked by DB update, please wait...' "\r");
  1650.                 $responseToAjax['msg'] = 'Synchronization blocked by DB update, please wait...';
  1651.                 $responseToAjax['result'] = '__KO__';
  1652.                 $responseToAjax['response_code'] = WebService::SYNC_BLOQUED_DB;
  1653.                 return $this->respondJsonAjax($responseToAjax);
  1654.             }
  1655.             $this->createFileJson($path'No blocked synchronization by DB update, moving forward...' "\r");
  1656.             $infiniteSyncIdentified false;
  1657.             if ($licenseToSync->getAlLockedByInfiniteSync() == false && $licenseToSync->getLastLoginDate() != null) {
  1658.                 $resultCheck Utilx::validateAndLockLicenseWithInfiniteSync($em$this->realContainer$licenseToSync);
  1659.                 $infiniteSyncIdentified = !$resultCheck["continue"] ;
  1660.             }
  1661.             if ($infiniteSyncIdentified == true || $licenseToSync->getAlLockedByInfiniteSync() == true) {
  1662.                 $this->createFileJson($path'Sync blocked by infinite loop problems issues' "\r");
  1663.                 $responseToAjax['msg'] = 'Sync blocked by infinite loop problems issues';
  1664.                 $responseToAjax['result'] = '__KO__';
  1665.                 $responseToAjax['response_code'] = WebService::SYNC_LOCKED_BY_INFINITE_LOOP;
  1666.                 return $this->respondJsonAjax($responseToAjax);
  1667.             }
  1668.             $this->createFileJson($path'No blocked synchronization by by infinite loop issues, moving forward...' "\r");
  1669.             $masterSyncRecords $em->getRepository('App\Entity\MasterSync')->findMastersSyncsDownUpInProcessToBlockNewSyncs($licenseToSync->getId());
  1670.             if (!empty($masterSyncRecords)) {
  1671.                 $auxArrayResponse Utilx::validateAndUnblockSyncsWithErrors($this->realContainer$masterSyncRecords$em$licenseToSync$path);
  1672.                 if (isset($auxArrayResponse['continue']) && isset($auxArrayResponse['msg']) && !$auxArrayResponse['continue']) {
  1673.                     
  1674.                     $this->createFileJson($path$auxArrayResponse['msg'] . "\r");
  1675.                     $responseToAjax['msg'] = $auxArrayResponse['msg'];
  1676.                     $responseToAjax['result'] = '__KO__';
  1677.                     $responseToAjax['response_code'] = WebService::ANOTHER_SYNC_IN_PROCESS;
  1678.                     return $this->respondJsonAjax($responseToAjax);
  1679.                 }
  1680.             }
  1681.             $lastReadDataForLicense $em->getRepository('App\Entity\ReadFilesData')->findLastSyncPetitionIdByLicense($id);
  1682.             $responseToAjax['result'] = '__OK__';
  1683.             $responseToAjax['lastId'] = (int) $lastReadDataForLicense;
  1684.             $isInProssesASync $em->getRepository('App\Entity\ReadFilesData')->findBy(['id' => $lastReadDataForLicense'isReadedByServer' => true'hasPersistentError' => false'rfStatus' => ReadFilesData::STATUS_UPLOADED]);
  1685.             if (!empty($isInProssesASync)) {
  1686.                 $responseToAjax['result'] = '__KO__';
  1687.                 $this->createFileJson($path'An Android server synchronization is already in process.. Please check if the new data has been uploaded in one minute!' "\r");
  1688.                 
  1689.                 $responseToAjax['msg'] = 'An Android server synchronization is already in process.. Please check if the new data has been uploaded in one minute!';
  1690.                 $responseToAjax['response_code'] = WebService::SYNC_ALREADY_IN_PROCESS;
  1691.             }
  1692.             $this->createFileJson($path'Ready to send push asking for down up synchronization!' "\r");
  1693.             $dataResponse = [];
  1694.             $dataResponse["status"] = WebService::CODE_SUCCESS;
  1695.             $dataResponse["actions"] = "updatedb";
  1696.             $dataResponse['uploadurl'] = $this->realContainer->getParameter('level_scheme') . '://' $this->realContainer->getParameter('level_host') . $this->generateUrl('level_web_service_sync_upload_data_android');
  1697.             $typePush PushSent::PUSH_TYPE_SYNC_DOWNUP;
  1698.             
  1699.             Util::sendSuperPush($this->realContainer$em$dataResponse$typePush$licenseToSync$path);
  1700.         } else {
  1701.             $responseToAjax['msg'] = 'License not found!';
  1702.             $responseToAjax['result'] = '__KO__';
  1703.             return $this->respondJsonAjax($responseToAjax);
  1704.         }
  1705.         return $this->respondJsonAjax($responseToAjax);
  1706.     }
  1707.     /**
  1708.      * Funcion para hacer el polling para un ajax verificando si la peticion
  1709.      * de sincronizacion manual de abajo a arriba fue completada con exito
  1710.      * @author Aealan Z <lrobledo@kijho.com> 11/06/2016
  1711.      * @param Request $request peticion recivida por ajax
  1712.      * @param type $id id de la licencia a la que se le solicito la sincronizacion
  1713.      * @return type json con la respuesta del polling formateada para el ajax
  1714.      */
  1715.     public function checkAndroidSyncManuallyCompleted(Request $request$id) {
  1716.         $em $this->getDoctrine()->getManager();
  1717.         $path Util::getValidActiveLogByBaseName($this->realContainer'requestForManuallySyncXXX''requestForManuallySyncXXX0.txt');
  1718.         $this->createFileJson($path'Sync Android Up Manually: Llego al check! ' "\r");
  1719.         $paramNick $request->request->get('nickname');
  1720.         if ($paramNick == null) {
  1721.             $paramNick $request->query->get('nickname');
  1722.         }
  1723.         $paramLastId $request->request->get('lastId');
  1724.         if ($paramLastId == null) {
  1725.             $paramLastId $request->query->get('lastId');
  1726.         }
  1727.         $this->createFileJson($path'Sync Android Up Manually: nickname' $paramNick "\r");
  1728.         $this->createFileJson($path'Sync Android Up Manually: lastId' $paramLastId "\r");
  1729.         if (null != $paramLastId && (int) $paramLastId >= 0) {
  1730.             $licenseToSync $em->getRepository('App\Entity\AccountLicense')->find($id);
  1731.             $this->createFileJson($path'Sync Android Up Manually: Entro 1' $paramLastId "\r");
  1732.             if ($licenseToSync) {
  1733.                 $this->createFileJson($path'Sync Android Up Manually: Entro 2' $paramLastId "\r");
  1734.                 if ($paramNick != $licenseToSync->getAlLicenseUsername()) {
  1735.                     $responseToAjax['msg'] = 'License not found!';
  1736.                     $responseToAjax['result'] = '__KO__';
  1737.                     return $this->respondJsonAjax($responseToAjax);
  1738.                 }
  1739.                 $responseToAjax['result'] = '__OK__';
  1740.                 $pollingResultArray $this->checkForDownUpPolling($id$paramLastId$path);
  1741.                 $responseToAjax['msg'] = $pollingResultArray['msg'];
  1742.                 $responseToAjax['response_code'] = $pollingResultArray['response_code'];
  1743.                 $this->createFileJson($path'Sync Android Up Manually: Super!' $paramLastId "\r");
  1744.             } else {
  1745.                 $responseToAjax['msg'] = 'License not found!';
  1746.                 $responseToAjax['result'] = '__KO__';
  1747.                 $this->createFileJson($path'Sync Android Up Manually: Chango1 ' $paramLastId "\r");
  1748.                 return $this->respondJsonAjax($responseToAjax);
  1749.             }
  1750.         } else {
  1751.             $this->createFileJson($path'Sync Android Up Manually: Chango2 ' $paramLastId "\r");
  1752.             $responseToAjax['msg'] = 'License not found!';
  1753.             $responseToAjax['result'] = '__KO__';
  1754.             return $this->respondJsonAjax($responseToAjax);
  1755.         }
  1756.         return $this->respondJsonAjax($responseToAjax);
  1757.     }
  1758.     /**
  1759.      * Esta funcion permite al cliente adroid notificar que termino de
  1760.      * subir el archivo de sincronizacion
  1761.      * @author Aealan Z <lrobledo@kijho.com> 30/04/15
  1762.      * @param \Symfony\Component\HttpFoundation\Request $request datos de la solicitud
  1763.      * @return Response Json con la informacion de respuesta
  1764.      */
  1765.     public function uploadAndoridSyncWebResponse(Request $request) {
  1766.         if ($request->getMethod() === WebService::REQUEST_METHOD_POST) {
  1767.             $path Util::getValidActiveLogByBaseName($this->realContainer'requestRespondForWebSyncFromAndroid''requestRespondForWebSyncFromAndroid0.txt');
  1768.             try {
  1769.                 $this->createFileJson($path"\r" 'Upload Sync Up-Down Andorid Response File: Llego? ' "\r");
  1770.                 $this->createFileJson($path'Whole request -> ' $request "\r");
  1771.                 $this->createFileJson($path'Maybe some content here...? -> ' $request->getContent() . "\r");
  1772.                 $parameters $request->request->all();
  1773.                 $this->createFileJson($path'All parameters in request -> ' json_encode($parameters) . "\r");
  1774.                 $this->createFileJson($path'Nickname -> ' $request->request->get('nickname') . "\r");
  1775.                 $this->createFileJson($path'UID -> ' $request->request->get('uid') . "\r");
  1776.                 $data = [];
  1777.                 $dataForTrack = [];
  1778.                 $arrayEncryptResult Util::decryptDataForUploadsFiles($this->realContainer$request->request->get('nickname'));
  1779.                 $data['nickname'] = $arrayEncryptResult['data'];
  1780.                 $dataForTrack['nick_encrypt'] = $request->request->get('nickname');
  1781.                 $dataForTrack['nick_decrypt'] = $arrayEncryptResult['data'];
  1782.                 $arrayEncryptResult Util::decryptDataForUploadsFiles($this->realContainer$request->request->get('uid'));
  1783.                 $data['uid'] = $arrayEncryptResult['data'];
  1784.                 $dataForTrack['uid_encrypt'] = $request->request->get('uid');
  1785.                 $dataForTrack['uid_decrypt'] = $arrayEncryptResult['data'];
  1786.                 $arrayEncryptResult Util::decryptDataForUploadsFiles($this->realContainer$request->request->get('NO_DATA'));
  1787.                 $data['NO_DATA'] = $arrayEncryptResult['data'];
  1788.                 $dataForTrack['uid_encrypt'] = $request->request->get('NO_DATA');
  1789.                 $dataForTrack['uid_decrypt'] = $arrayEncryptResult['data'];
  1790.                 $this->createFileJson($path'Full -> ' json_encode($dataForTrack) . "\r");
  1791.                 $this->createFileJson($path'The Client IP -> ' $request->getClientIp() . "\r");
  1792.                 $hasFile false;
  1793.                 if ($request->files->get('file')) {
  1794.                     $hasFile true;
  1795.                     $this->createFileJson($path'The File -> ' $request->files->get('file')->getClientOriginalName() . "\r");
  1796.                 } else {
  1797.                     $this->createFileJson($path'No file uploaded, returning ' "\r");
  1798.                 }
  1799.                 $licenseUserName = ['alLicenseUsername' => $data['nickname']];
  1800.                 $em $this->getDoctrine()->getManager();
  1801.                 $accountLicenseData $em->getRepository('App\Entity\AccountLicense')->findBy($licenseUserName);
  1802.                 $countResult count($accountLicenseData);
  1803.                 if ($countResult && $hasFile) {
  1804.                     if ($accountLicenseData[0]->getAlAccountLicense()->getDeleted()) {
  1805.                         $this->createFileJson($path'Licensia borrada! o.O' "\r");
  1806.                         return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  1807.                                         ->respondWithError('Account is inactive'WebService::CODE_ACCOUNT_SUSPENDED);
  1808.                     }
  1809.                     if ($accountLicenseData[0]->getDeviceUid() != $data['uid']) {
  1810.                         $this->createFileJson($path'UID diferente! o.O' "\r");
  1811.                         return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  1812.                                         ->respondWithError('Unknown device'WebService::CODE_ACCOUNT_SUSPENDED);
  1813.                     }
  1814.                     $statusArryMsg = [];
  1815.                     $statusArryMsg['status'] = WebService::CODE_SUCCESS;
  1816.                     $statusArryMsg['msg'] = '';
  1817.                     if (isset($data['NO_DATA'])) {
  1818.                         $statusArryMsg['msg'] = 'Empty file delivered for Android!!!! ...closing sync...';
  1819.                         $this->createFileJson($path'Empty file delivered for Android!!!! ...closing sync...' " O.o!  \r");
  1820.                         // $registerStatus = Util::updateWebSyncUploadResponseFile($em, $readFilesDataEntityByLicense[0], $data['NO_DATA']);
  1821.                         $theUrlTrSt = new UploadSyncJsonNotifyTransformer($this->realContainer$statusArryMsg);
  1822.                         $jsonTransform $theUrlTrSt->transform();
  1823.                         $jsonContent json_encode($jsonTransform);
  1824.                         return $this->respondWithItem($jsonContent$theUrlTrSt);
  1825.                     }
  1826.                     if ($accountLicenseData[0]->getAlLicenseStatus() == AccountLicense::LICENSE_STATUS_ACTIVE) {
  1827.                         $pushSentArray = [];
  1828.                         $readFilesDataEntityByLicense $em->getRepository('App\Entity\ReadFilesDataWeb')->findBy(['rfwLicenseId' => $accountLicenseData[0]->getId(), 'rfwStatus' => ReadFilesDataWeb::STATUS_READED_DELIVERED], ['rfwDateSincAsk' => 'ASC'], 2);
  1829.                         if (isset($readFilesDataEntityByLicense[0]) && $readFilesDataEntityByLicense[0]->getRfwStatus() == ReadFilesDataWeb::STATUS_READED_DELIVERED) {
  1830.                             $this->createFileJson($path'Encontrada la ' $readFilesDataEntityByLicense[0]->getId() . " :)  \r");
  1831.                             $masterSyncForWebResponse $em->getRepository('App\Entity\MasterSync')->findBy(['msSyncWebRecord' => $readFilesDataEntityByLicense[0]->getId()]);
  1832.                             if (isset($masterSyncForWebResponse[0])) {
  1833.                                 $this->createFileJson($path'Into push validation response ' $masterSyncForWebResponse[0]->getId() . " :)  \r");
  1834.                                 $pushWebPushSend $masterSyncForWebResponse[0]->getMsPushRecord();
  1835.                                 if ($pushWebPushSend) {
  1836.                                     if ($pushWebPushSend->getPushStatus() == PushSent::STATUS_PUSH_PENDING) {
  1837.                                         $pushWebPushSend->setPushStatus(PushSent::STATUS_PUSH_READED);
  1838.                                         $actualDate Util::getCurrentDate();
  1839.                                         $pushWebPushSend->setRespondDate($actualDate);
  1840.                                         $em->persist($pushWebPushSend);
  1841.                                         $em->flush();
  1842.                                         $this->createFileJson($path'Updated push status by sync response for ' $pushWebPushSend->getId() . " ;)  \r");
  1843.                                     } else {
  1844.                                         $this->createFileJson($path'Already responded by Android server XD' "\r");
  1845.                                     }
  1846.                                 } else {
  1847.                                     $this->createFileJson($path'Not related push, it may be an initial login... ' "\r");
  1848.                                 }
  1849.                             }
  1850.                             $isDirectoryReady Util::createLicenseDirectory($this->realContainer$accountLicenseData[0], $data['nickname']);
  1851.                             $theAccountLicenseDirector $isDirectoryReady['directory'];
  1852.                             if (!isset($isDirectoryReady['result']) || $isDirectoryReady['result'] == '__KO__') {
  1853.                                 $this->createFileJson($path'No existe el directorio de la licensia coño! o.O' "\r");
  1854.                                 $msnError 'An error occurred while creating your directory in server ';
  1855.                                 return $this->setStatusCode(WebService::CODE_INTERNAL_ERROR)
  1856.                                                 ->respondWithError($msnErrorWebService::CODE_INTERNAL_ERROR);
  1857.                             }
  1858.                             $uploadFileResponse Utilx::uploadFileTo($request$theAccountLicenseDirector$path);
  1859.                             if (!isset($uploadFileResponse['result']) || !isset($uploadFileResponse['msg'])) {
  1860.                                 $this->createFileJson($path'Unknown error uploading file ' "\r");
  1861.                                 return $this->setStatusCode(WebService::HTTP_CODE_INTERNAL_ERROR)
  1862.                                                 ->respondWithError('Unknown error uploading file'WebService::CODE_INTERNAL_ERROR);
  1863.                             }
  1864.                             if (isset($uploadFileResponse['result']) && isset($uploadFileResponse['msg']) && $uploadFileResponse['result'] == '__KO__') {
  1865.                                 $this->createFileJson($path$uploadFileResponse['msg'] . "\r");
  1866.                                 return $this->setStatusCode(WebService::HTTP_CODE_INTERNAL_ERROR)
  1867.                                                 ->respondWithError($uploadFileResponse['msg'], WebService::CODE_INTERNAL_ERROR);
  1868.                             }
  1869.                             $bucketFileLocation Util::uploadSyncFileToS3Service($this->realContainer$accountLicenseData[0], $uploadFileResponse['fileName'], $uploadFileResponse['fileDir'], $path);
  1870.                             $syncResponseFileS3URI 'https://' $this->realContainer->getParameter('s3_bucket_name') . '.' $this->realContainer->getParameter('s3_default_bucket_domain') . '/' $bucketFileLocation;
  1871.                             $registerStatus Util::updateWebSyncUploadResponseFile($em$readFilesDataEntityByLicense[0], $uploadFileResponse['fileName'], $syncResponseFileS3URI);
  1872. //////////// validacion para determinar si se puede marcar la licencia con login inicial exitoso
  1873.                             $theProcessedUploadedFile $readFilesDataEntityByLicense[0]->getRfwNameProcessedFile();
  1874.                             if (($readFilesDataEntityByLicense[0]->getSplitLoginIndex() == && count(explode('_'$theProcessedUploadedFile)) == && strpos($theProcessedUploadedFile'heInitialData') === 1) ||
  1875.                                     ($readFilesDataEntityByLicense[0]->getSplitLoginIndex() == && count(explode('_'$theProcessedUploadedFile)) == && strpos($theProcessedUploadedFile'heInitialData_user') === 1)) {
  1876.                                 $accountLicenseData[0]->setLastLoginWasOk(true);
  1877.                                 $em->persist($accountLicenseData[0]);
  1878.                                 $em->flush();
  1879.                             }
  1880.                             if ($registerStatus) {
  1881.                                 $statusArryMsg['msg'] = 'File has been uploaded and the record updated';
  1882.                                 $this->createFileJson($path':D 6' "\r");
  1883.                             } else {
  1884.                                 $this->createFileJson($path'Error actualizando el MasterSync coño! o.O' "\r");
  1885.                                 return $this->setStatusCode(WebService::HTTP_CODE_NOT_FOUND)
  1886.                                                 ->respondWithError('Error updating syncronization control record'WebService::CODE_OBJECT_NOT_FOUND);
  1887.                             }
  1888.                             $this->createFileJson($path'Hay Chingada!?' "\r");
  1889.                             $licenseDataBaseEntity $em->getRepository('App\Entity\LicenseDataBase')->findBy(['license' => $accountLicenseData[0]->getId()]);
  1890.                             $this->createFileJson($path'O No Hay!?' "\r");
  1891.                             if (!empty($licenseDataBaseEntity)) {
  1892.                                 $this->createFileJson($path'Entro Trigger' "\r");
  1893.                                 $usernameByNickname $licenseDataBaseEntity[0]->getLicense();
  1894.                                 $theAccountPath $this->realContainer->getParameter('level_directory_data_android') . $usernameByNickname->getAlAccountLicense()->getAcName() . '/' $usernameByNickname->getAlLicenseUsername();
  1895.                                 $theAccountPath str_replace(' ''_'$theAccountPath);
  1896.                                 $dataOptionsRoot = [
  1897.                                     'dbname' => $licenseDataBaseEntity[0]->getDbname(),
  1898.                                     'user' => $licenseDataBaseEntity[0]->getDbuser(),
  1899.                                     'password' => $licenseDataBaseEntity[0]->getDbpass(),
  1900.                                     'host' => $licenseDataBaseEntity[0]->getDbhost(),
  1901.                                     'driver' => 'pdo_mysql',
  1902.                                 ];
  1903.                                 $msg = [
  1904.                                     'id' => $readFilesDataEntityByLicense[0]->getId(),
  1905.                                     'dataOptionsRoot' => $dataOptionsRoot,
  1906.                                     'path' => $theAccountPath,
  1907.                                     'filename' => $readFilesDataEntityByLicense[0]->getRfwClientResponseFile(),
  1908.                                     'AccountLicense' => $usernameByNickname->getAlAccountLicense()->getAcName()
  1909.                                 ];
  1910.                                 $this->get('incoming_web_android_sync_response_producer')->setContentType('application/json');
  1911.                                 $this->get('incoming_web_android_sync_response_producer')->setDeliveryMode(2);
  1912.                                 $this->get('incoming_web_android_sync_response_producer')->publish(json_encode($msg));
  1913.                                 $statusArryMsg['msg'] = 'File has been uploaded and the sync web response process is ready to consume';
  1914.                                 $holdTheComsume $request->request->get('hold');
  1915.                                 if (null == $holdTheComsume) {
  1916.                                     $statusArryMsg['msg'] = 'File has been uploaded and the sync web response process triggered';
  1917.                                     sleep(5);
  1918.                                     $this->createFileJson($path'Instant parameter sended to consumer command -> ' $readFilesDataEntityByLicense[0]->getId() . "\r");
  1919.                                     $data['syncRecord'] = $readFilesDataEntityByLicense[0]->getId();
  1920.                                     ForcedAsynchronousCommandsUtil::consumeUpDownSyncResponseCommand($this->realContainer$datatrue);
  1921.                                     $this->createFileJson($path'Corrio Trigger? ' "\r");
  1922.                                 }
  1923.                             }
  1924.                             $this->createFileJson($path':D 7' "\r");
  1925.                             if (null != $request->request->get('code')) {
  1926.                                 $arrayEncryptResult Util::decryptDataForUploadsFiles($this->realContainer$request->request->get('code'));
  1927.                                 $data['code'] = $arrayEncryptResult['data'];
  1928.                                 $pushSendRecords $em->getRepository('App\Entity\PushSent')->findBy(['verificationCode' => $data['code'], 'pushStatus' => PushSent::STATUS_PUSH_PENDING]);
  1929.                                 if (!empty($pushSendRecords)) {
  1930.                                     $this->updateRegistPushSend($pushSendRecords[0]);
  1931.                                 }
  1932.                             }
  1933.                             $this->createFileJson($path':D 8' "\r");
  1934.                             $theUrlTrSt = new UploadSyncJsonNotifyTransformer($this->realContainer$statusArryMsg);
  1935.                             $jsonTransform $theUrlTrSt->transform();
  1936.                             $jsonContent json_encode($jsonTransform);
  1937.                             return $this->respondWithItem($jsonContent$theUrlTrSt);
  1938.                         } else {
  1939.                             $this->createFileJson($path'No encontro el registro de la sincronizacion web coño! o.O' "\r");
  1940.                             return $this->setStatusCode(WebService::HTTP_CODE_NOT_FOUND)
  1941.                                             ->respondWithError('No syncronization data registered'WebService::CODE_OBJECT_NOT_FOUND);
  1942.                         }
  1943.                     } else {
  1944.                         $this->createFileJson($path'Licensia inactiva! o.O' "\r");
  1945.                         return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  1946.                                         ->respondWithError('Inactive License'WebService::CODE_ACCOUNT_SUSPENDED);
  1947.                     }
  1948.                 } else {
  1949.                     $this->createFileJson($path'No encontro la licencia! o.O' "\r");
  1950.                     return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  1951.                                     ->respondWithError('Invalid nickname or file not uploaded properly'WebService::CODE_COULD_NOT_AUTHENTICATE);
  1952.                 }
  1953.             } catch (\Exception $ex) {
  1954.                 $this->createFileJson($path'Error on request: -> ' $ex->getMessage() . "\r");
  1955.             }
  1956.         } else {
  1957.             return $this->errorNotAllowedMethod('Method not allowed. Use ' WebService::REQUEST_METHOD_POST " method");
  1958.         }
  1959.     }
  1960.     /**
  1961.      * WS generico para que el cliente andorid responda todos los push enviados a los clientes
  1962.      * @author Aealan Z <lrobledo@kijho.com> 18/06/15
  1963.      * @param \Symfony\Component\HttpFoundation\Request $request datos de la solicitud
  1964.      * @return Response Json con la informacion de respuesta
  1965.      */
  1966.     public function respondedReadedPush(Request $request) {
  1967.     
  1968.         $path Util::getValidActiveLogByBaseName($this->realContainer'pushResponseFromAndroid''pushResponseFromAndroid0.txt');
  1969.         $this->createFileJson($path'Push Responded: ' $request->getContent() . "\r");
  1970.         $arrayEncryptResult Util::decryptDataForAndroid($this->realContainer$request->getContent());
  1971.         $params json_decode($arrayEncryptResult['data'], true);
  1972.         $this->createFileJson($path'Push Responded decode params: ' $arrayEncryptResult['data'] . "\r");
  1973.         if (!isset($params['code'])) {
  1974.             $this->createFileJson($path'No code argument send' "\r");
  1975.             return $this->errorWrongArgs('No code argument send'WebService::CODE_WRONG_ARGUMENTS);
  1976.         }
  1977.         $em $this->realContainer->get('doctrine')->getManager();
  1978.         $accountLicenseData $em->getRepository('App\Entity\AccountLicense')->validateRestauratAndAccountActive($params['nickname']);
  1979.         $pushSendRepository $em->getRepository('App\Entity\PushSent');
  1980.         $firstBy null;
  1981.         if (isset($params['pushProvider']) && $params['pushProvider'] == 'Pushy') {
  1982.             $firstBy PushSent::SENDED_FIRST_BY_PUSHY;
  1983.         } elseif (isset($params['pushProvider']) && $params['pushProvider'] == 'Pubnub') {
  1984.             $firstBy PushSent::SENDED_FIRST_BY_PUBNUB;
  1985.         } elseif (isset($params['pushProvider']) && $params['pushProvider'] == 'Level') {
  1986.             $firstBy PushSent::SENDED_FIRST_BY_LICENSOR;
  1987.         }
  1988.         $this->createFileJson($path"step 1 \r");
  1989.         $response null;
  1990.         if (isset($params['response'])) {
  1991.             $response = (int) $params['response'];
  1992.         }
  1993.         $responsePushType $pushSendRepository->selectPushTypeByCode($params['code']);
  1994.         $this->createFileJson($path"step 2 \r");
  1995.         if (!$responsePushType) {
  1996.             $msnError 'Push record not found! ';
  1997.             $this->createFileJson($path"$msnError \r");
  1998.             return $this->setStatusCode(WebService::CODE_INTERNAL_ERROR)
  1999.                             ->respondWithError($msnErrorWebService::CODE_INTERNAL_ERROR);
  2000.         }
  2001.         $responseUpdate $pushSendRepository->updateReadedPush($params['code'], $firstBy$response);
  2002.         if (PushSent::PUSH_TYPE_UPLOAD_S3_BACKUP == $responsePushType) {
  2003.             $pushSendRepository->updateLicenseRecordByPush($params['code']);
  2004.         }
  2005.         $pushSendRepository->respondOldPushesForLicense($responsePushType$accountLicenseData);
  2006.         $pushSendRepository->closeUnansweredS3Pushes($accountLicenseData);
  2007.         $this->createFileJson($path"step 3 \r");
  2008.         if (!$responseUpdate) {
  2009.             $msnError 'An error occurred while updatin the push send record or push already answered.';
  2010.             $this->createFileJson($path"$msnError \r");
  2011.             return $this->setStatusCode(WebService::CODE_INTERNAL_ERROR)
  2012.                             ->respondWithError($msnErrorWebService::CODE_INTERNAL_ERROR);
  2013.         }
  2014.         $responseArray['status'] = WebService::CODE_SUCCESS;
  2015.         $responseArray['msg'] = 'Server notified';
  2016.         $this->createFileJson($path"step 4 \r");
  2017.         $theUrlTrSt = new RespondedNotificationPushTransformer($responseArray);
  2018.         $jsonTransform $theUrlTrSt->transform();
  2019.         $this->createFileJson($path"step 5 \r");
  2020.         $jsonContent json_encode($jsonTransform);
  2021.         $this->createFileJson($path"$jsonContent \r");
  2022.         return $this->respondWithItem($jsonContent$theUrlTrSt);
  2023.     }
  2024.     /**
  2025.      * WS generico para que el servidor andorid responda una pregunta realizada en un push
  2026.      * @author Aealan Z <lrobledo@kijho.com> 15/06/16
  2027.      * @param \Symfony\Component\HttpFoundation\Request $request datos de la solicitud
  2028.      * @return Response Json con la informacion de respuesta
  2029.      */
  2030.     public function respondedAskInPush(Request $request) {
  2031.         if ($request->getMethod() === WebService::REQUEST_METHOD_POST) {
  2032.             if (=== strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_TEXT) || === strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_STRUCTURE)) {
  2033.                 $path Util::getValidActiveLogByBaseName($this->realContainer'requestEncriptedFromAndroid''requestEncriptedFromAndroid0.txt');
  2034.                 $this->createFileJson($path"\r" 'Push Ask: ' $request->getContent() . "\r");
  2035.                 $arrayEncryptResult Util::decryptDataForAndroid($this->realContainer$request->getContent());
  2036.                 $params json_decode($arrayEncryptResult['data'], true);
  2037.                 $this->createFileJson($path'Push Responded decode params: ' $arrayEncryptResult['data'] . "\r");
  2038.                 if (!isset($params['nickname']) || !isset($params['code'])) {
  2039.                     return $this->errorWrongArgs('Wrong Arguments'WebService::CODE_WRONG_ARGUMENTS);
  2040.                 }
  2041.                 $em $this->getDoctrine()->getManager();
  2042.                 $data = ['alLicenseUsername' => $params['nickname']];
  2043.                 $accountLicenseData $em->getRepository('App\Entity\AccountLicense')->findByAlLicenseUsername($data);
  2044.                 $data = ['channelName' => $params['nickname']];
  2045.                 $subLicenseData $em->getRepository('App\Entity\SubLicense')->findBy($data);
  2046.                 $countResult count($accountLicenseData) + count($subLicenseData);
  2047.                 if ($countResult 0) {
  2048.                     if (!empty($accountLicenseData)) {
  2049.                         if ($accountLicenseData[0]->getAlAccountLicense()->getDeleted()) {
  2050.                             return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  2051.                                             ->respondWithError('Account is inactive'WebService::CODE_ACCOUNT_SUSPENDED);
  2052.                         }
  2053.                         if ($accountLicenseData[0]->getAlLicenseStatus() == AccountLicense::LICENSE_STATUS_INACTIVE) {
  2054.                             return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  2055.                                             ->respondWithError('Inactive License'WebService::CODE_ACCOUNT_SUSPENDED);
  2056.                         }
  2057.                     }
  2058.                     $pushSendRecords $em->getRepository('App\Entity\PushSent')->searchPushSendRecords($params['code']);
  2059.                     $responseArray = [];
  2060.                     $responseUpdate false;
  2061.                     if (!empty($pushSendRecords)) {
  2062.                         if (isset($params['response'])) {
  2063.                             $pushSendRecords[0]->setAskedResponse((boolean) $params['response']);
  2064.                         }
  2065.                         $responseUpdate $this->updateRegistPushSend($pushSendRecords[0]);
  2066.                     } else {
  2067.                         $msnError 'Push send record not found ';
  2068.                         return $this->setStatusCode(WebService::CODE_INTERNAL_ERROR)
  2069.                                         ->respondWithError($msnErrorWebService::CODE_INTERNAL_ERROR);
  2070.                     }
  2071.                     if (!$responseUpdate) {
  2072.                         $msnError 'An error occurred while updatin the push send record..';
  2073.                         return $this->setStatusCode(WebService::CODE_INTERNAL_ERROR)
  2074.                                         ->respondWithError($msnErrorWebService::CODE_INTERNAL_ERROR);
  2075.                     }
  2076.                     $responseArray['status'] = WebService::CODE_SUCCESS;
  2077.                     $responseArray['msg'] = 'Push ask response notified';
  2078.                     $theUrlTrSt = new RespondedNotificationPushTransformer($responseArray);
  2079.                     $jsonTransform $theUrlTrSt->transform();
  2080.                     $jsonContent json_encode($jsonTransform);
  2081.                     return $this->respondWithItem($jsonContent$theUrlTrSt);
  2082.                 } else {
  2083.                     return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  2084.                                     ->respondWithError('Invalid nickname or channelname'WebService::CODE_COULD_NOT_AUTHENTICATE);
  2085.                 }
  2086.             } else {
  2087.                 return $this->errorWrongArgs('Wrong Arguments'WebService::CODE_WRONG_ARGUMENTS);
  2088.             }
  2089.         } else {
  2090.             return $this->errorNotAllowedMethod('Method not allowed. Use ' WebService::REQUEST_METHOD_POST " method");
  2091.         }
  2092.     }
  2093.     /**
  2094.      * WS generico para que los dispositivos android notifique de un error por correo
  2095.      * @author Aealan Z <lrobledo@kijho.com> 13/07/15
  2096.      * @param \Symfony\Component\HttpFoundation\Request $request datos de la solicitud
  2097.      * @return Response Json con la informacion de respuesta
  2098.      */
  2099.     public function notifyAndroidError(Request $request) {
  2100.         if ($request->getMethod() === WebService::REQUEST_METHOD_POST) {
  2101.             if (=== strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_TEXT) || === strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_STRUCTURE)) {
  2102.                 /////////////////////// Otra sospecha de caida del servidor de licensor prod
  2103.                 $path Util::getValidActiveLogByBaseName($this->realContainer'notifyErrorAndroid''notifyErrorAndroid0.txt');
  2104.                 $this->createFileJson($path"\r" 'The content: ' $request->getContent() . "\r");
  2105.                 $responseArray['status'] = WebService::CODE_SUCCESS;
  2106.                 $responseArray['msg'] = 'Server notified';
  2107.                 $theUrlTrSt = new RespondedNotificationPushTransformer($responseArray);
  2108.                 $jsonTransform $theUrlTrSt->transform();
  2109.                 $this->createFileJson($path'The encoded ws response: ' json_encode($responseArray) . "\r");
  2110.                 $jsonContent json_encode($jsonTransform);
  2111.                 $this->createFileJson($path'The transform: ' $jsonContent "\r");
  2112.                 return $this->respondWithItem($jsonContent$theUrlTrSt);
  2113.                 ///////////////////
  2114.                 $arrayEncryptResult Util::decryptDataForAndroid($this->realContainer$request->getContent());
  2115.                 $this->createFileJson($path'The decrypted content: ' $request->getContent() . "\r");
  2116.                 $params json_decode($arrayEncryptResult['data'], true);
  2117.                 $this->createFileJson($path'The request array: ' $arrayEncryptResult['data'] . "\r");
  2118.                 if (!isset($params['nickname']) || !isset($params['msg']) || !isset($params['uid'])) {
  2119.                     return $this->errorWrongArgs('Wrong Arguments.'WebService::CODE_WRONG_ARGUMENTS);
  2120.                 }
  2121.                 $data = ['alLicenseUsername' => $params['nickname']];
  2122.                 $em $this->getDoctrine()->getManager();
  2123.                 $accountLicenseData $em->getRepository('App\Entity\AccountLicense')->findByAlLicenseUsername($data);
  2124.                 $data = ['channelName' => $params['nickname']];
  2125.                 $subLicenseData $em->getRepository('App\Entity\SubLicense')->findBy($data);
  2126.                 $countResult count($accountLicenseData) + count($subLicenseData);
  2127.                 if ($countResult 0) {
  2128.                     if (!empty($accountLicenseData)) {
  2129.                         if ($accountLicenseData[0]->getAlAccountLicense()->getDeleted()) {
  2130.                             return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  2131.                                             ->respondWithError('Account is inactive'WebService::CODE_ACCOUNT_SUSPENDED);
  2132.                         }
  2133.                         if ($accountLicenseData[0]->getAlLicenseStatus() == AccountLicense::LICENSE_STATUS_INACTIVE) {
  2134.                             return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  2135.                                             ->respondWithError('Inactive License'WebService::CODE_ACCOUNT_SUSPENDED);
  2136.                         }
  2137.                         if ($accountLicenseData[0]->getDeviceUid() != $params['uid']) {
  2138.                             $emLev Util::emLicenseConnection($this->realContainer$em$accountLicenseData[0]);
  2139.                             $subLicenseData $emLev->getRepository('App\Structure\Stations')->findBy(['staDeviceCode' => $params['uid']]);
  2140.                             if (empty($subLicenseData)) {
  2141.                                 $emLev->close();
  2142.                                 $this->createFileJson($path'Error: Unknown device' "\r");
  2143.                                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  2144.                                                 ->respondWithError('Unknown device'WebService::CODE_UNAUTHORIZED);
  2145.                             } else {
  2146.                                 $emLev->close();
  2147.                             }
  2148.                         }
  2149.                     }
  2150.                     $sendEmail $this->realContainer->getParameter('level_emails_syncs_errors');
  2151.                     if (isset($params['msg']) && $params['msg'] == '') {
  2152.                         return $this->setStatusCode(WebService::CODE_WRONG_ARGUMENTS)
  2153.                                         ->respondWithError('Empty error message'WebService::CODE_ACCOUNT_SUSPENDED);
  2154.                     }
  2155.                     
  2156.                     $errors $em->getRepository('App\Entity\ErrorAndroidEmailSent')->getAllErrorMsg();
  2157.                     list($errorMsg) = explode("->"$params['msg']);
  2158.                     $theErrorEmailEntity=null;
  2159.                     
  2160.                     $countErrors count($errors);
  2161.                     for ($i=0$i $countErrors ; ++$i) { 
  2162.                         $error=$errors[$i]["errorMsg"];
  2163.                         $pos strpos($errorMsg$error);
  2164.                         if ($pos !== false) {
  2165.                             $theErrorEmailEntity $em->getRepository('App\Entity\ErrorAndroidEmailSent')->findBy(['errorMsg' => $error]);
  2166.                             $theErrorEmailEntity $theErrorEmailEntity[0];
  2167.                             break;
  2168.                         }
  2169.                     }
  2170.                     
  2171.                     $body "<p><label>Server: <strong>http://" $this->realContainer->getParameter("licensor_base_url") . "/licensor/login</strong></label><br></p>";
  2172.                     $body .= "<p><label>" $params['nickname'] . "</label></p><br>";
  2173.                     $body .= "<p><label><strong>Error: </strong></label><br></p><p><label>" nl2br($params['msg']) . "</label></p><br>";
  2174.                     $actualDate Utilx::getCurrentDate();
  2175.                     if(!empty($theErrorEmailEntity)){
  2176.                         $theErrorEmailEntity->setDateErrorLastReport($actualDate);
  2177.                         $theErrorEmailEntity->setErrorCounter(+ (int) $theErrorEmailEntity->getErrorCounter());
  2178.                         $em->persist($theErrorEmailEntity);
  2179.                         $em->flush();
  2180.                     } else {
  2181.                         $androidErrorCode $em->getRepository('App\Entity\ErrorAndroidEmailSent')->findRegisteredErrorCodeLicense();
  2182.                         ++$androidErrorCode;
  2183.                         if (!empty($accountLicenseData)) {
  2184.                             $theErrorEmailEntity $this->setRegistErrorEmail($accountLicenseData[0], $sendEmail[0], $errorMsg$params['uid'], $androidErrorCode);
  2185.                         } else {
  2186.                             $theErrorEmailEntity $this->setRegistErrorEmail(null$sendEmail[0], $errorMsg$params['uid'], $androidErrorCode$subLicenseData[0]);
  2187.                         }
  2188.                         $body .= "<p><label><strong>Error Code: </strong></label><br></p><p><label>" $theErrorEmailEntity->getErrorCode() . "</label></p>";
  2189.                         
  2190.                         if ($accountLicenseData[0]) {
  2191.                             $respArray['subject'] = 'Error In ' $params['nickname'] . ' ' $theErrorEmailEntity->getErrorCode();
  2192.                         } else {
  2193.                             $respArray['subject'] = 'Error ' $theErrorEmailEntity->getErrorCode();
  2194.                         }
  2195.                         $respArray['message'] = "";
  2196.                         $this->createFileJson($path"Mail to -> " $sendEmail[0] . "\r");
  2197.                         $respArray['to'] = $sendEmail[0];
  2198.                         Utilx::sendMailInfo($this->realContainer$respArray$path$body);
  2199.                         $theErrorEmailEntity->setDateErrorEmailSent($actualDate);
  2200.                         $em->persist($theErrorEmailEntity);
  2201.                         $em->flush();
  2202.                     }
  2203.                     
  2204.                     if (!empty($accountLicenseData)) {
  2205.                         $theAndroidErrorEntity $this->setRegistAndroidError($theErrorEmailEntity,$accountLicenseData[0], $sendEmail[0], $params['msg'], $params['uid']);
  2206.                     } else {
  2207.                         $theAndroidErrorEntity $this->setRegistAndroidError($theErrorEmailEntity,null$sendEmail[0], $params['msg'], $params['uid'], $subLicenseData[0]);
  2208.                     }
  2209.                     if(!is_null($theErrorEmailEntity->getErrorQualifier())){
  2210.                         if($theErrorEmailEntity->getErrorQualifier() >= ErrorAndroidEmailSent::ERROR_QUALIFIER_COMPARISON ){
  2211.                             if ($accountLicenseData[0]) {
  2212.                                 $respArray['subject'] = 'Error In ' $params['nickname'] . ' ' $theErrorEmailEntity->getErrorCode();
  2213.                             } else {
  2214.                                 $respArray['subject'] = 'Error ' $theErrorEmailEntity->getErrorCode();
  2215.                             }
  2216.                                                         
  2217.                             $body .= "<p><label><strong>Error Code: </strong></label><br></p><p><label>" $theErrorEmailEntity->getErrorCode() . "</label></p>";
  2218.                             
  2219.                             $respArray['message'] = "";
  2220.                             $this->createFileJson($path"Mail to -> " $sendEmail[0] . "\r");
  2221.                             $respArray['to'] = $sendEmail[0];
  2222.         
  2223.                             Utilx::sendMailInfo($this->realContainer$respArray$path$body);
  2224.                             $theAndroidErrorEntity->setDateErrorEmailSent($actualDate);
  2225.                             $em->persist($theAndroidErrorEntity);
  2226.                             $em->flush();
  2227.                         }
  2228.                     }
  2229.                                         
  2230.                     $responseArray['status'] = WebService::CODE_SUCCESS;
  2231.                     $responseArray['msg'] = 'Server notified';
  2232.                     $theUrlTrSt = new RespondedNotificationPushTransformer($responseArray);
  2233.                     $jsonTransform $theUrlTrSt->transform();
  2234.                     $this->createFileJson($path'The encoded ws response: ' json_encode($responseArray) . "\r");
  2235.                     $jsonContent json_encode($jsonTransform);
  2236.                     $this->createFileJson($path'The transform: ' $jsonContent "\r");
  2237.                     return $this->respondWithItem($jsonContent$theUrlTrSt);
  2238.                 } else {
  2239.                     return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  2240.                                     ->respondWithError('Invalid nickname'WebService::CODE_COULD_NOT_AUTHENTICATE);
  2241.                 }
  2242.             } else {
  2243.                 return $this->errorWrongArgs('Wrong Arguments.'WebService::CODE_WRONG_ARGUMENTS);
  2244.             }
  2245.         } else {
  2246.             return $this->errorNotAllowedMethod('Method not allowed. Use ' WebService::REQUEST_METHOD_POST " method");
  2247.         }
  2248.     }
  2249.     /**
  2250.      * WS generico para que los dispositivos android envien su
  2251.      * log por correo a los administradores del sistema
  2252.      * @author Aealan Z <lrobledo@kijho.com> 13/07/15
  2253.      * @param \Symfony\Component\HttpFoundation\Request $request datos de la solicitud
  2254.      * @return Response Json con la informacion de respuesta
  2255.      */
  2256.     public function notifyAndroidLog(Request $request) {
  2257.         if ($request->getMethod() === WebService::REQUEST_METHOD_POST) {
  2258.             if (=== strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_TEXT) || === strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_STRUCTURE)) {
  2259.                 $path Util::getValidActiveLogByBaseName($this->realContainer'notifyAndroidLog''notifyAndroidLog0.txt');
  2260.                 $this->createFileJson($path'Notify Android Log: ' $request->getContent() . "\r");
  2261.                 $arrayEncryptResult Util::decryptDataForAndroid($this->realContainer$request->getContent());
  2262.                 $this->createFileJson($path'The decrypted content: ' $request->getContent() . "\r");
  2263.                 $params json_decode($arrayEncryptResult['data'], true);
  2264.                 $this->createFileJson($path'The request array: ' $arrayEncryptResult['data'] . "\r");
  2265.                 if (!isset($params['nickname']) || !isset($params['log']) || !isset($params['uid'])) {
  2266.                     return $this->errorWrongArgs('Wrong Arguments.'WebService::CODE_WRONG_ARGUMENTS);
  2267.                 }
  2268.                 $data = ['alLicenseUsername' => $params['nickname']];
  2269.                 $em $this->getDoctrine()->getManager();
  2270.                 $accountLicenseData $em->getRepository('App\Entity\AccountLicense')->findBy($data);
  2271.                 $data = ['channelName' => $params['nickname']];
  2272.                 $subLicenseData $em->getRepository('App\Entity\SubLicense')->findBy($data);
  2273.                 $countResult count($accountLicenseData) + count($subLicenseData);
  2274.                 if ($countResult 0) {
  2275.                     if (!empty($accountLicenseData)) {
  2276.                         $theLicenses $accountLicenseData[0];
  2277.                         $theUID $accountLicenseData[0]->getDeviceUid();
  2278.                     } elseif (!empty($subLicenseData)) {
  2279.                         $theLicenses $subLicenseData[0]->getLicense();
  2280.                         $theUID $subLicenseData[0]->getDeviceUid();
  2281.                     }
  2282.                     if ($theLicenses->getAlAccountLicense()->getDeleted()) {
  2283.                         return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  2284.                                         ->respondWithError('Account is inactive'WebService::CODE_ACCOUNT_SUSPENDED);
  2285.                     }
  2286.                     if ($theLicenses->getAlLicenseStatus() == AccountLicense::LICENSE_STATUS_INACTIVE) {
  2287.                         return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  2288.                                         ->respondWithError('Inactive License'WebService::CODE_ACCOUNT_SUSPENDED);
  2289.                     }
  2290.                     if ($theUID != $params['uid']) {
  2291.                         return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  2292.                                         ->respondWithError('Unknown device'WebService::CODE_ACCOUNT_SUSPENDED);
  2293.                     }
  2294.                     if ($params['log'] == '') {
  2295.                         return $this->setStatusCode(WebService::CODE_WRONG_ARGUMENTS)
  2296.                                         ->respondWithError('Empty log content'WebService::CODE_WRONG_ARGUMENTS);
  2297.                     }
  2298.                     $sendEmail $this->realContainer->getParameter('level_emails_syncs_errors');
  2299.                     $isSameLog false;
  2300.                     $sameLogs $em->getRepository('App\Entity\LogAndroidEmailSent')->findBy(['logMsg' => $params['log']]);
  2301.                     if (!empty($sameLogs)) {
  2302.                         $isSameLog true;
  2303.                         $theLogEmailEntity $sameLogs[0];
  2304.                     } else {
  2305.                         $androidLogCode $em->getRepository('App\Entity\LogAndroidEmailSent')->findRegisteredLogCodeLicense();
  2306.                         ++$androidLogCode;
  2307.                         $numEmails count($sendEmail);
  2308.                         for ($i 0$i $numEmails; ++$i) {
  2309.                             if (!empty($accountLicenseData)) {
  2310.                                 $theLogEmailEntity $this->setRegistLogEmail($accountLicenseData[0], $sendEmail[$i], $params['log'], $params['uid'], $androidLogCode);
  2311.                             } else {
  2312.                                 $theLogEmailEntity $this->setRegistLogEmail(null$sendEmail[$i], $params['log'], $params['uid'], $androidLogCode$subLicenseData[0]);
  2313.                             }
  2314.                         }
  2315.                     }
  2316.                     $body "<p><label>Server: <strong>http://" $this->realContainer->getParameter("licensor_base_url") . "/login</strong></label><br></p>";
  2317.                     $body .= "<p><label>" $params['nickname'] . "</label></p><br>";
  2318.                     $body .= "<p><label><strong>Log: </strong></label><br></p><p><label>" nl2br($params['log']) . "</label></p><br>";
  2319.                     $respArray['subject'] = 'Android device log ' $params['nickname'];
  2320.                     $respArray['message'] = "";
  2321.                     foreach ($sendEmail as $mailTo) {
  2322.                         $this->createFileJson($path"Mail to -> " $mailTo "\r");
  2323.                         $respArray['to'] = $mailTo;
  2324.                         Utilx::sendMailInfo($this->realContainer$respArray$path$body);
  2325.                     }
  2326.                     $responseArray['status'] = WebService::CODE_SUCCESS;
  2327.                     $responseArray['msg'] = 'Android log notified';
  2328.                     $theUrlTrSt = new RespondedNotificationPushTransformer($responseArray);
  2329.                     $jsonTransform $theUrlTrSt->transform();
  2330.                     $this->createFileJson($path'The encoded ws response: ' json_encode($responseArray) . "\r");
  2331.                     $jsonContent json_encode($jsonTransform);
  2332.                     $this->createFileJson($path'The transform: ' $jsonContent "\r");
  2333.                     return $this->respondWithItem($jsonContent$theUrlTrSt);
  2334.                 } else {
  2335.                     return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  2336.                                     ->respondWithError('Invalid nickname'WebService::CODE_COULD_NOT_AUTHENTICATE);
  2337.                 }
  2338.             } else {
  2339.                 return $this->errorWrongArgs('Wrong Arguments.'WebService::CODE_WRONG_ARGUMENTS);
  2340.             }
  2341.         } else {
  2342.             return $this->errorNotAllowedMethod('Method not allowed. Use ' WebService::REQUEST_METHOD_POST " method");
  2343.         }
  2344.     }
  2345.     /**
  2346.      * WS Para validar el logue de dispositivos tanto de licencias como de sublicencias,
  2347.      * dado el caso de que sea necesario actualizar el dispositivo logueado,
  2348.      * este sera notificado mediante la validacion de su logueo en este ws
  2349.      * necesario para toda la aplicacion movil
  2350.      * @author Aealan Z <lrobledo@kijho.com> 20/12/15
  2351.      * @param \Symfony\Component\HttpFoundation\Request $request datos de la solicitud
  2352.      * @return Response Json con la informacion de respuesta
  2353.      */
  2354.     public function validateLogin(Request $request) {
  2355.         $path Util::getValidActiveLogByBaseName($this->realContainer'validateLogin''validateLogin0.txt');
  2356.         $this->createFileJson($path"\r" 'Validate Login: ' $request->getContent() . "\r");
  2357.         if ($request->getMethod() === WebService::REQUEST_METHOD_POST) {
  2358.             if (=== strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_STRUCTURE) || === strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_TEXT)) {
  2359.                 $arrayEncryptResult Util::decryptDataForAndroid($this->realContainer$request->getContent());
  2360.                 $this->createFileJson($path"\r" 'arrayEncryptResult: ' json_encode($arrayEncryptResult) . "\r");
  2361.                 $data json_decode($arrayEncryptResult['data'], true);
  2362.                 if (!isset($data['version']) || !isset($data['uid'])) {
  2363.                     return $this->errorWrongArgs('Wrong Arguments!'WebService::CODE_WRONG_ARGUMENTS);
  2364.                 }
  2365.                 $this->createFileJson($path'The Client IP -> ' $request->getClientIp() . "\r");
  2366.                 $dataToSearch = ['deviceUid' => $data['uid']];
  2367.                 $em $this->getDoctrine()->getManager();
  2368.                 $accountLicenseData $em->getRepository('App\Entity\AccountLicense')->findBy($dataToSearch);
  2369.                 if (empty($accountLicenseData)) {
  2370.                     return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  2371.                                     ->respondWithError('Invalid UID'WebService::CODE_COULD_NOT_AUTHENTICATE);
  2372.                 }
  2373.                 if (isset($data['channelname'])) {
  2374.                     $dataToSearch = ['deviceUid' => $data['uid']];
  2375.                     $subLicenseData $em->getRepository('App\Entity\SubLicense')->findBy($dataToSearch);
  2376.                     $countResult count($accountLicenseData) + count($subLicenseData);
  2377.                 } else {
  2378.                     $countResult count($accountLicenseData);
  2379.                 }
  2380.                 if ($countResult 0) {
  2381.                     if ($accountLicenseData[0]->getAlAccountLicense()->getDeleted()) {
  2382.                         return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  2383.                                         ->respondWithError('Account is inactive'WebService::CODE_ACCOUNT_SUSPENDED);
  2384.                     }
  2385.                     if ($accountLicenseData[0]->getAlLicenseStatus() != AccountLicense::LICENSE_STATUS_ACTIVE) {
  2386.                         return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  2387.                                         ->respondWithError('License is inactive'WebService::CODE_ACCOUNT_SUSPENDED);
  2388.                     }
  2389.                     if (isset($data['channelname']) && !empty($subLicenseData)) {
  2390.                         $licenseOrSublicenseToValidate $subLicenseData[0];
  2391.                     } elseif (empty($subLicenseData) && isset($data['channelname'])) {
  2392.                         return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  2393.                                         ->respondWithError('Invalid channelname'WebService::CODE_COULD_NOT_AUTHENTICATE);
  2394.                     } else {
  2395.                         $licenseOrSublicenseToValidate $accountLicenseData[0];
  2396.                     }
  2397.                     if ((int) $this->realContainer->getParameter('device_recognition_by_ip_enabled') && $licenseOrSublicenseToValidate->getAndroidIP() == $request->getClientIp()) {
  2398.                         $licenseOrSublicenseToValidate->setTimesCheckedIP($licenseOrSublicenseToValidate->getTimesCheckedIP() + 1);
  2399.                     } else {
  2400.                         $licenseOrSublicenseToValidate->setAndroidIP($request->getClientIp());
  2401.                         $licenseOrSublicenseToValidate->setTimesCheckedIP(0);
  2402.                     }
  2403.                     if (isset($data['databaseSize'])) {
  2404.                         $licenseOrSublicenseToValidate->setAndroidDatabaseSize((int) $data['databaseSize']);
  2405.                         $licenseOrSublicenseToValidate->setLastUpdateOfDatabaseSize(new DateTime("now"));
  2406.                         if ((int) $data['databaseSize'] > (int) $this->realContainer->getParameter('max_android_database_size_to_consider_cleanse')) {
  2407.                             //  $body = "<p><label>Server: <strong>http://" . $this->realContainer->getParameter("licensor_base_url") . "/licensor/login</strong></label><br></p>";
  2408.                             //  $body .= "<p><label>License: <strong>" . $accountLicenseData[0] . "</strong></label></p>";
  2409.                             //  $body .= "<p><label>Message: Database has a size of <strong>'" . Util::humanFilesize($data['databaseSize']) . "' </strong> and the Android server could be having an slow performance for this reason</label><br></p>";
  2410.                             // $respArray['subject'] = "Android database cleanse is needed for '" . $accountLicenseData[0]->getAlLicenseUsername() . "' license";
  2411.                             // $respArray['message'] = "";
  2412.                             // $sendEmail = $this->realContainer->getParameter('level_emails_support_warnings');
  2413.                             // foreach ($sendEmail as $mailTo) {
  2414.                             //     $this->createFileJson($path, "Mail to -> " . $mailTo . "\r");
  2415.                             //     $respArray['to'] = $mailTo;
  2416.                             //     Utilx::sendMailInfo($this->realContainer, $respArray, $path, $body);
  2417.                             // }
  2418.                             
  2419.                             // Inicio de lógica, validación de notificación.
  2420.                             $currentDate Utilx::getCurrentDate();
  2421.                             $seed $em->getRepository("App\Entity\NotificationInLicensorBell")->findOneBy(["context"=>NotificationInLicensorBell::CONTEXT_NOTIFICATION_ANDROID_DATABASE_CLEANSE_NEEDED"license"=>$accountLicenseData[0]]);
  2422.                             if(!is_null($seed)){
  2423.                                 $dateMinusOneWeek = clone $currentDate;
  2424.                                 $dateMinusOneWeek->modify('-1 week');
  2425.                                 if ($dateMinusOneWeek>=$seed->getPickedtByValidatingCronDate()) {
  2426.                                     $seed->setDateCreated($currentDate);
  2427.                                     $seed->setPickedtByValidatingCronDate(null);
  2428.                                     $seed->setNotificationMsg("License:" $accountLicenseData[0] . "Database has a size of " Util::humanFilesize($data['databaseSize']) . "  and the Android server could be having an slow performance for this reason");
  2429.                                     $em->persist($seed);
  2430.                                     $em->flush();
  2431.                                 }
  2432.                             }else{
  2433.                                 $currentDate Utilx::getCurrentDate();
  2434.                                 $seed = new NotificationInLicensorBell();
  2435.                                 $seed->setNotificationTitle('Android database cleanse is needed for ' $accountLicenseData[0]->getAlLicenseUsername() . ' license');
  2436.                                 $seed->setNotificationLabel(NotificationInLicensorBell::NOTIFICATION_TYPE_WARNING);
  2437.                                 $seed->setNotificationMsg("License:" $accountLicenseData[0] . "Database has a size of " Util::humanFilesize($data['databaseSize']) . "  and the Android server could be having an slow performance for this reason");
  2438.                                 $seed->setDateCreated($currentDate);
  2439.                                 $seed->setContext(NotificationInLicensorBell::CONTEXT_NOTIFICATION_ANDROID_DATABASE_CLEANSE_NEEDED);
  2440.                                 $seed->setLicense($accountLicenseData[0]);
  2441.                                 $seed->setTypeRoleToNotify(NotificationInLicensorBell::ROLE_ADMINISTRATOR);
  2442.                                 $em->persist($seed);
  2443.                                 $em->flush();
  2444.                             }
  2445.                             // Fin de lógica, validación de notificación.
  2446.                         }
  2447.                     }
  2448.                     if(isset($data['numberOfSyncDataRecords']) || (isset($data["validateLogin"]) && $data["validateLogin"] == true)){
  2449.                         $licenseDataBaseEntity $em->getRepository('App\Entity\LicenseDataBase')->findOneBy(['license' => $licenseOrSublicenseToValidate->getId()]);
  2450.                         $dataOptionsRoot = [
  2451.                             'dbname' => $licenseDataBaseEntity->getDbname(),
  2452.                             'user' => $licenseDataBaseEntity->getDbuser(),
  2453.                             'password' => $licenseDataBaseEntity->getDbpass(),
  2454.                             'host' => $licenseDataBaseEntity->getDbhost(),
  2455.                             'driver' => 'pdo_mysql',
  2456.                         ];
  2457.                         $emLev Util::emCreateConfiguration($this->realContainer$dataOptionsRoot);
  2458.                         
  2459.                         
  2460.                         if (isset($data['numberOfSyncDataRecords'])) {
  2461.                             $licenseOrSublicenseToValidate->setNumberOfSyncDataRecords((int) $data['numberOfSyncDataRecords']);
  2462.     
  2463.                             // $licenseDataBaseEntity = $em->getRepository('App\Entity\LicenseDataBase')->findOneBy(['license' => $licenseOrSublicenseToValidate->getId()]);
  2464.     
  2465.                             // $dataOptionsRoot = [
  2466.                             //     'dbname' => $licenseDataBaseEntity->getDbname(),
  2467.                             //     'user' => $licenseDataBaseEntity->getDbuser(),
  2468.                             //     'password' => $licenseDataBaseEntity->getDbpass(),
  2469.                             //     'host' => $licenseDataBaseEntity->getDbhost(),
  2470.                             //     'driver' => 'pdo_mysql',
  2471.                             // ];
  2472.     
  2473.                             // $emLev = Util::emCreateConfiguration($this->realContainer, $dataOptionsRoot);
  2474.                             $configuracion $emLev->getRepository('App\Structure\Configuracion')->find(1);
  2475.                             $configuracion->setNumberOfSyncDataRecords((int) $data['numberOfSyncDataRecords']);
  2476.                             $configuracion->setMaxRecordsSyncUpDown((int) $this->realContainer->getParameter('max_records_sync_up_down'));
  2477.                             $configuracion->setMaxRecordsSyncDownUp((int) $this->realContainer->getParameter('max_records_sync_down_up'));
  2478.                             $emLev->persist($configuracion);
  2479.                             $emLev->flush();
  2480.                         }
  2481.                     }
  2482.                     $em->persist($licenseOrSublicenseToValidate);
  2483.                     $em->flush();
  2484.                     try {
  2485.                         $theRespArray Util::getLastVersionByJsonVersionFile($this->realContainer$data['version'], true$path);
  2486.                     } catch (\Exception $ex) {
  2487.                         $theRespArray['updateAppError'] = true;
  2488.                     }
  2489.                     try {
  2490.                         $theRespArrayTwo Util::getLastVersionByDirAvailableVersions($this->realContainer$data['version'], true$path);
  2491.                     } catch (\Exception $ex) {
  2492.                         $theRespArrayTwo['updateAppError'] = true;
  2493.                     }
  2494.                     if (isset($theRespArray['updateAppError']) && $theRespArray['updateAppError'] && isset($theRespArrayTwo['updateAppError']) && $theRespArrayTwo['updateAppError']) {
  2495.                         return $this->setStatusCode(WebService::HTTP_CODE_SERVICE_UNAVAILABLE)
  2496.                                         ->respondWithError('Error finding last version'WebService::CODE_OBJECT_NOT_FOUND);
  2497.                     }
  2498.                     if (isset($theRespArray["newVersion"]) && isset($theRespArrayTwo["newVersion"])) {
  2499.                         if ($theRespArray["newVersion"] < $theRespArrayTwo["newVersion"]) {
  2500.                             $theRespArray $theRespArrayTwo;
  2501.                         }
  2502.                     } elseif (!isset($theRespArray["newVersion"]) && isset($theRespArrayTwo["newVersion"])) {
  2503.                         $theRespArray $theRespArrayTwo;
  2504.                     }
  2505.                     if (isset($data['version'])) {
  2506.                         if (strpos($data['version'], '-')) {
  2507.                             $this->createFileJson($path'Is a testing version...?  ' $data['version'] . "\r");
  2508.                             $data['version'] = explode('-'$data['version'])[0];
  2509.                         }
  2510.                     }
  2511.                     ForcedAsynchronousCommandsUtil::recoveryInformationInProyects($this->realContainer, ['licenseId' => $accountLicenseData[0]->getId(), 'mode' => 0]);
  2512.                     if (isset($theRespArray['newVersion'])) {
  2513.                         $newVersionString Util::validateNewerVersion($data['version'], $theRespArray['newVersion']);
  2514.                         if ($newVersionString == $theRespArray['newVersion'] && $newVersionString != $data['version']) {
  2515.                             $country $accountLicenseData[0]->getCity()->getCiState()->getStCountry()->getCoVal();
  2516.                             $isCallCenter $accountLicenseData[0]->getIsCallCenter();
  2517.                             $theRespArray['success'] = WebService::CODE_SUCCESS;
  2518.                             $theRespArray['country'] = $country;
  2519.                             $theRespArray['iscallcenter'] = (int) $isCallCenter;
  2520.                             $theUrlTrSt = new UpdateAndroidCommandTransformer($this->realContainer$theRespArray);
  2521.                             $xxArray $theUrlTrSt->transform();
  2522.                             $jsonContent json_encode($xxArray);
  2523.                             return $this->respondWithItem($jsonContent$theUrlTrSt);
  2524.                         }
  2525.                     }
  2526.                     $newVersionString Util::validateNewerVersion($accountLicenseData[0]->getAndroidVersionName(), $data['version']);
  2527.                     if (!isset($theRespArray["newVersion"]) && $newVersionString != $accountLicenseData[0]->getAndroidVersionName() && preg_match('/^(\d+\.)(\d+\.)(\d+)$/'$data['version'])) {
  2528.                         $body "<p><label>Server: <strong>http://" $this->realContainer->getParameter("licensor_base_url") . "/licensor/login</strong></label><br></p>";
  2529.                         $body .= "<p><label><strong>" $accountLicenseData[0]->getAlLicenseUsername() . "</strong></label></p>";
  2530.                         $body .= "<p><label>The server has been updated from version: <strong>" $accountLicenseData[0]->getAndroidVersionName() . "</strong>  to version: <strong>" $data['version'] . "</strong></label><br></p>";
  2531.                         $respArray['subject'] = 'Android APK version updated ' $accountLicenseData[0]->getAlLicenseUsername();
  2532.                         $respArray['message'] = "";
  2533.                         $accountLicenseData[0]->setAndroidVersionName($data['version']);
  2534.                         $accountLicenseData[0]->setVersionUpdatedDate(Util::getCurrentDate());
  2535.                         $em->persist($accountLicenseData[0]);
  2536.                         $em->flush();
  2537.                         $sendEmail $this->realContainer->getParameter('level_emails_syncs_errors');
  2538.                         foreach ($sendEmail as $mailTo) {
  2539.                             $this->createFileJson($path"Mail to -> " $mailTo "\r");
  2540.                             $respArray['to'] = $mailTo;
  2541.                             Utilx::sendMailInfo($this->realContainer$respArray$path$body);
  2542.                         }
  2543.                         $pushSendRepository $em->getRepository('App\Entity\PushSent');
  2544.                         $pushSendRepository->respondOldPushesForLicense(PushSent::PUSH_TYPE_APK_UPDATE$accountLicenseData[0]->getId());
  2545.                     }
  2546.                     if ($data['version']) {
  2547.                         $connectionRecord $em->getRepository('App\Entity\AccountLicense')->getTheLastesVersionRegisteredInDataBaseByWorkingAPKs();
  2548.                         $newVersionString Util::getDifferenceBetweenVersion($this->realContainer->getParameter('max_difference_in_APK_server_version_allowed'), $data['version'], $connectionRecord['androidVersionName']);
  2549.                         if (is_array($newVersionString) && isset($newVersionString['needsEmail']) && $newVersionString['needsEmail']) {
  2550.                             // $body = "<p><label>Server: <strong>http://" . $this->realContainer->getParameter("licensor_base_url") . "/licensor/login</strong></label><br></p>";
  2551.                             // $body .= "<p><label>License: <strong>" . $accountLicenseData[0] . "</strong></label></p>";
  2552.                             // $body .= "<p><label>License Version: <strong>" . $data['version'] . "</strong></label></p>";
  2553.                             // $body .= "<p><label>Newer Version In Use: <strong>" . $connectionRecord['androidVersionName'] . "</strong></label></p>";
  2554.                             // $body .= "<p><label>Message: <strong>" . sprintf($newVersionString['versionResult'], "'" . $accountLicenseData[0] . "'") . "</strong></label><br></p>";
  2555.                             // $respArray['subject'] = "Android APK needs an immediate update for '" . $accountLicenseData[0]->getAlLicenseUsername() . "' license";
  2556.                             // $respArray['message'] = "";
  2557.                             // $sendEmail = $this->realContainer->getParameter('level_emails_support_warnings');
  2558.                             // foreach ($sendEmail as $mailTo) {
  2559.                             //     $this->createFileJson($path, "Mail to -> " . $mailTo . "\r");
  2560.                             //     $respArray['to'] = $mailTo;
  2561.                             //     Utilx::sendMailInfo($this->realContainer, $respArray, $path, $body);
  2562.                             // }
  2563.                             // Inicio de lógica, validación de notificación.
  2564.                             if(!$accountLicenseData[0]->getIsTesting()){
  2565.                                 $currentDate Utilx::getCurrentDate();
  2566.                                 $seed $em->getRepository("App\Entity\NotificationInLicensorBell")->findOneBy(["context" => NotificationInLicensorBell::CONTEXT_NOTIFICATION_ANDROID_UPDATE_NEEDED"license" => $accountLicenseData[0]]);
  2567.     
  2568.                                 if(!is_null($seed)){
  2569.                                     $dateMinusOneWeek = clone $currentDate;
  2570.                                     $dateMinusOneWeek->modify('-1 week');
  2571.     
  2572.                                     if ($dateMinusOneWeek >= $seed->getPickedtByValidatingCronDate()) {
  2573.                                         $seed->setDateCreated($currentDate);
  2574.                                         $seed->setPickedtByValidatingCronDate(null);
  2575.                                         $seed->setNotificationMsg("License:" $accountLicenseData[0] . "License Version:".$data['version'] ."Newer Version In Use:" .$connectionRecord['androidVersionName'] ."Message:" sprintf($newVersionString['versionResult'], "'" $accountLicenseData[0] . "'"));
  2576.     
  2577.                                         $em->persist($seed);
  2578.                                         $em->flush();
  2579.                                     }
  2580.                                 }else{
  2581.                                     $seed = new NotificationInLicensorBell();
  2582.     
  2583.                                     $seed->setNotificationTitle('Android APK needs update for ' $accountLicenseData[0]->getAlLicenseUsername() . ' license');
  2584.                                     $seed->setNotificationLabel(NotificationInLicensorBell::NOTIFICATION_TYPE_WARNING);
  2585.                                     $seed->setNotificationMsg("License:" $accountLicenseData[0] . "License Version:".$data['version'] ."Newer Version In Use:" .$connectionRecord['androidVersionName'] ."Message:" sprintf($newVersionString['versionResult'], "'" $accountLicenseData[0] . "'"));
  2586.                                     $seed->setDateCreated($currentDate);
  2587.                                     $seed->setContext(NotificationInLicensorBell::CONTEXT_NOTIFICATION_ANDROID_UPDATE_NEEDED);
  2588.                                     $seed->setLicense($accountLicenseData[0]);
  2589.                                     $seed->setTypeRoleToNotify(NotificationInLicensorBell::ROLE_ADMINISTRATOR);
  2590.     
  2591.                                     $em->persist($seed);
  2592.                                     $em->flush();
  2593.                                 }
  2594.                             }
  2595.                         }
  2596.                         // Fin de lógica, validación de notificación por una semana.
  2597.                     }
  2598.                     if(isset($data["debug"]) && $data["debug"]){
  2599.                         dump((isset($emLev) && !empty($emLev)));
  2600.                         dump(isset($emLev) && $emLev);
  2601.                         dump($emLev, isset($emLev), !empty($emLev));
  2602.                     } 
  2603.                     if (isset($emLev) && !empty($emLev)) {
  2604.                         $clienteForWebAndroidLogin $emLev->getRepository('App\Structure\Usuario')->findBy(['usuLogin' => 'admin']);
  2605.                         $auxArrayUserAndroidWebLogin = [];
  2606.                         if (isset($clienteForWebAndroidLogin[0])) {
  2607.                             $auxArrayUserAndroidWebLogin['user'] = 'admin';
  2608.                             $auxArrayUserAndroidWebLogin['pass'] = $clienteForWebAndroidLogin[0]->getUsuPass();
  2609.                             $auxArrayUserAndroidWebLogin['nickname'] = $accountLicenseData[0]->getAlLicenseUsername();
  2610.                         }
  2611.                         $pushServicesKeysArray Util::buildTheServicesKeysArray($this->realContainer$accountLicenseData[0], $auxArrayUserAndroidWebLogin);
  2612.                     } else {
  2613.                         $pushServicesKeysArray Util::buildTheServicesKeysArray($this->realContainer$accountLicenseData[0]);
  2614.                     }
  2615.                     if ($accountLicenseData[0]->getLevelLightUser()) {
  2616.                         $userData $accountLicenseData[0]->getLevelLightUser();
  2617.                         /**
  2618.                          * Allows to add the apikey to the user of lite level this exported in OMT
  2619.                          */
  2620.                         if ($accountLicenseData[0]->getHasLogedOMT() == true) {
  2621.                             $apikey Util::doOMTDashboardLoginToGetToken($this->realContainer$userData$path$accountLicenseData[0]->getLoginType());
  2622.                             
  2623.                             if (!empty($apikey)) {
  2624.                                 $userData['apikey'] = $apikey;
  2625.                                 $responseArr['userToOmt']['apikey'] = $apikey;
  2626.                             } else {
  2627.                                 $responseArr['userToOmt']['apikey'] = '';
  2628.                             }
  2629.                             $accountLicenseData[0]->setLevelLightUser($userData);
  2630.                             $em->persist($accountLicenseData[0]);
  2631.                             $em->flush();
  2632.                         } else {
  2633.                             $responseArr['userToOmt']['apikey'] = '';
  2634.                         }
  2635.                         $responseArr['userToOmt']['username'] = $userData['username'];
  2636.                         $responseArr['userToOmt']['password'] = $userData['realPass'];
  2637.                     }
  2638.                     if ($accountLicenseData[0]->getAwsTopicARN() && $accountLicenseData[0]->getAwsTopicARN() != '' && $accountLicenseData[0]->getAwsTopicARN() != "" ) {
  2639.                         if (isset($pushServicesKeysArray['awsPush'])) {
  2640.                             $pushServicesKeysArray['awsPush']['TopicArn'] = $accountLicenseData[0]->getAwsTopicARN();
  2641.                         }
  2642.                     }
  2643.                     ///////
  2644.                     if ($accountLicenseData[0]->getNeedsOneUpdaownSync()) {
  2645.                         ForcedAsynchronousCommandsUtil::callPriorityUpDownSync($this->realContainer, ['license' => $accountLicenseData[0]->getId()], true);
  2646.                         //// podria ser el llamdo con prioridad que se haga desde aca, toca verificar la prioridad en cuanto al funcionamiento general de sync
  2647.                     }
  2648.                     ///////
  2649.                     $responseArr['status'] = WebService::CODE_SUCCESS;
  2650.                     $responseArr['push_services'] = $pushServicesKeysArray;
  2651.                     $responseArr['msg'] = 'Valid login and actual apk version installed!';
  2652.                     $responseArr['url'] = '';
  2653.                     $responseArr['directoryOmtS3'] = [
  2654.                         'directoryImageProduct' => $this->realContainer->getParameter('AWS_ENVIRONMENT_FOLDER') . 'images/product',
  2655.                         'directoryImageRestaurant' => $this->realContainer->getParameter('AWS_ENVIRONMENT_FOLDER') . 'images/restaurant'
  2656.                     ];
  2657.                     $accountLicenseData[0]->setLastValidatedLoginDate(Util::getCurrentDate());
  2658.                     if ($accountLicenseData[0]->getLoginType() == AccountLicense::LOGGED_OUT) {
  2659.                         $accountLicenseData[0]->setLoginType(AccountLicense::LOGGED_BY_LEVEL_ANDROID);
  2660.                     } else if ($accountLicenseData[0]->getLoginType() == AccountLicense::LOGGED_BY_LEVEL_LITE) {
  2661.                         $accountLicenseData[0]->setLoginType(AccountLicense::LOGGED_BY_LEVEL_LITE_AND_ANDROID);
  2662.                     }
  2663.                     $em->persist($accountLicenseData[0]);
  2664.                     $em->flush();
  2665.                     // Se valida que el parametro timeZone exista para guardarlo en las Tablas Configuracion y AccountLicense
  2666.                     if (isset($data['timeZone']) && trim($data['timeZone']) !== '') {
  2667.                         $timeZone trim($data['timeZone']);
  2668.                         $configuracion $emLev->getRepository('App\Structure\Configuracion')->findAll();
  2669.                         if (isset($configuracion[0])) {
  2670.                             $configuracion[0]->setTimeZoneRes($timeZone);
  2671.                             $emLev->persist($configuracion[0]);
  2672.                             $emLev->flush();
  2673.                         }
  2674.                         $accountLicenseData[0]->setTimeZoneRes($timeZone);
  2675.                         $em->persist($accountLicenseData[0]);
  2676.                         $em->flush();
  2677.                     }
  2678.                     $theUrlTrSt = new DemoForLoginTransformer($this->realContainer$responseArr);
  2679.                     $xxArray $theUrlTrSt->transform();
  2680.                     $jsonContent json_encode($xxArray);
  2681.                     return $this->respondWithItem($jsonContent$theUrlTrSt);
  2682.                 } else {
  2683.                     return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  2684.                                     ->respondWithError('Invalid UID'WebService::CODE_COULD_NOT_AUTHENTICATE);
  2685.                 }
  2686.             } else {
  2687.                 $this->createFileJson($path"\r" 'Wrong Content.'WebService::CODE_WRONG_ARGUMENTS "\r");
  2688.                 return $this->errorWrongArgs('Wrong Content.'WebService::CODE_WRONG_ARGUMENTS);
  2689.             }
  2690.         } else {
  2691.             $this->createFileJson($path"\r" 'Method not allowed. Use ' WebService::REQUEST_METHOD_POST " method" "\r");
  2692.             return $this->errorNotAllowedMethod('Method not allowed. Use ' WebService::REQUEST_METHOD_POST " method");
  2693.         }
  2694.     }
  2695.     /**
  2696.      * WS Para validar giftcards segun la licencia, el estado de esta y el
  2697.      * saldo registrado en licensor
  2698.      * @author Aealan Z <lrobledo@kijho.com> 02/02/16
  2699.      * @param \Symfony\Component\HttpFoundation\Request $request datos de la solicitud
  2700.      * @return Response Json con la informacion de respuesta
  2701.      */
  2702.     public function giftCardTransaction(Request $requestArmorService $armorLog $log) {
  2703.         $path Util::getValidActiveLogByBaseName($this->realContainer'GiftCardTransaction''GiftCardTransaction0.txt');
  2704.         // validacion del metodo de peticion POST
  2705.         if ($request->getMethod() === WebService::REQUEST_METHOD_POST) {
  2706.             // Validacion de tamaño en contenido, validacion de datos nulos - vacios
  2707.             if (=== strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_STRUCTURE) || === strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_TEXT)) {
  2708.                 $this->createFileJson($path"\r" 'Validate GiftCard: ' $request->getContent() . "\r");
  2709.                 $arrayEncryptResult Util::decryptDataForAndroid($this->realContainer$request->getContent());
  2710.                 // Datos desencriptados
  2711.                 $data json_decode($arrayEncryptResult['data'], true);
  2712.                 $em $this->getDoctrine()->getManager();
  2713.                 $worksWithArmor false;
  2714.                 //////
  2715.                 /*
  2716.                  *
  2717.                     {
  2718.                     "nickname": "noonansb_206",
  2719.                     "uid": "5ad093af8070f25f",
  2720.                     "type": 1,
  2721.                     "order_id": "720b4297-90df-4c2a-b06b-d9c0815390f5",
  2722.                     "amount": 25,
  2723.                     "gift_code": "8814"
  2724.                     }
  2725.                     {
  2726.                     "nickname":"blackdoc_28",
  2727.                     "uid":"coquitoXX",
  2728.                     "token":"ElTokenCochinoEse"
  2729.                     }
  2730.                     *
  2731.                     *
  2732.                     {
  2733.                     "gift_card_id":"3b02add2-e376-11e8-853e-0242ac130004",  // primaria en la bd de licensor
  2734.                     "issuing": "406b63b7-9ad6-4327-9af9-bdbca33ee637",      // usuario al que pertenece la giftCard
  2735.                     "number": "6",
  2736.                     "balance": "4800",
  2737.                     "activation_date": "1409175049",
  2738.                     "deactivation_date": "1509175049",
  2739.                     "identifier": "b07b77b7-7ad7-7777-7af7-bdbca77ee77",    // no se sabe para que putas, me la invento y ya
  2740.                     "status": "1"
  2741.                     }
  2742.                  *
  2743.                  */
  2744.                 if (isset($data['token']) && base64_encode(base64_decode($data['token'])) === $data['token']) {
  2745.                     $decodeJWT json_decode(Encryptor::decodeInfo($data['token'], 5), true);
  2746.                     $armorGiftCodeToSearch $decodeJWT['number'];
  2747.                     $data['amount'] = Encryptor::decodeInfo($decodeJWT['balance'], 5);
  2748.                     $data['gift_code'] = Encryptor::decodeInfo($decodeJWT['number'], 5);
  2749.                     $data['order_id'] = $decodeJWT['order_id'];
  2750.                     $data['type'] = $decodeJWT['type'];
  2751.                     $data['identifier'] = $decodeJWT['identifier'];
  2752.                     $data['activation_date'] = $decodeJWT['activation_date'];
  2753.                     $client $em->getRepository('App\Entity\OmtClient')->find($decodeJWT['issuing']);
  2754.                     if (!$client) {
  2755.                         return $this->errorWrongArgs('Customer not found!'WebService::CODE_OBJECT_NOT_FOUND);
  2756.                     }
  2757.                     $worksWithArmor true;
  2758.                 }
  2759.                 if (((!isset($data['nickname']) || !isset($data['uid']) || !isset($data['type']) 
  2760.                 || !isset($data['amount']) || !isset($data['gift_code'])) && !$worksWithArmor
  2761.                 || ($worksWithArmor && !isset($data['token']))) {
  2762.                     $this->createFileJson($path'Error: Wrong Arguments!' "\r");
  2763.                     return $this->errorWrongArgs('Wrong Arguments!'WebService::CODE_WRONG_ARGUMENTS);
  2764.                 }
  2765.                 if (!is_numeric($data['amount']) || !is_numeric($data['type']) || $data['gift_code'] == '') {
  2766.                     $this->createFileJson($path'Error: Wrong Type Arguments!' "\r");
  2767.                     return $this->errorWrongArgs('Wrong Type Arguments!'WebService::CODE_WRONG_ARGUMENTS);
  2768.                 }
  2769.                 $dataToSearch = ['alLicenseUsername' => $data['nickname']];
  2770.                 $accountLicenseData $em->getRepository('App\Entity\AccountLicense')->findBy($dataToSearch);
  2771.                 if (empty($accountLicenseData)) {
  2772.                     $this->createFileJson($path'Error: Invalid nickname' "\r");
  2773.                     return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  2774.                     ->respondWithError('Invalid nickname'WebService::CODE_COULD_NOT_AUTHENTICATE);
  2775.                 } else {
  2776.                     $gcStatus $accountLicenseData[0]->getGiftCardStatus();
  2777.                     if (!$gcStatus) {
  2778.                         $this->createFileJson($path"The restaurant has no active gift card payments \r");
  2779.                         return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  2780.                                     ->respondWithError('The restaurant has no active gift card payments'WebService::CODE_ACCOUNT_SUSPENDED);
  2781.                     }
  2782.                     if ($accountLicenseData[0]->getAlAccountLicense()->getDeleted()) {
  2783.                         $this->createFileJson($path'Error: Account is inactive' "\r");
  2784.                         return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  2785.                         ->respondWithError('Account is inactive'WebService::CODE_ACCOUNT_SUSPENDED);
  2786.                     }
  2787.                     if ($accountLicenseData[0]->getAlLicenseStatus() != AccountLicense::LICENSE_STATUS_ACTIVE) {
  2788.                         $this->createFileJson($path'Error: License is inactive' "\r");
  2789.                         return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  2790.                         ->respondWithError('License is inactive'WebService::CODE_ACCOUNT_SUSPENDED);
  2791.                     }
  2792.                     $licenseToValidate $accountLicenseData[0];
  2793.                     if ($licenseToValidate->getDeviceUid() != $data['uid']) {
  2794.                         $emLev Util::emLicenseConnection($this->realContainer$em$accountLicenseData[0]);
  2795.                         $registeredClientsByUID $emLev->getRepository('App\Structure\Stations')->findBy(['staDeviceCode' => $data['uid']]);
  2796.                         if (empty($registeredClientsByUID)) {
  2797.                             $emLev->close();
  2798.                             $this->createFileJson($path'Error: Unknown device' "\r");
  2799.                             return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)->respondWithError('Unknown device'WebService::CODE_UNAUTHORIZED);
  2800.                         
  2801.                         } else {
  2802.                             $emLev->close();
  2803.                         }
  2804.                     }
  2805.                     $actualDate Util::getCurrentDate();
  2806.                     $responseArr['bigbag'] = true;
  2807.                     if (isset($data['transaction_id']) && $data['transaction_id'] != '' 
  2808.                     && (GiftCardTransaction::TRANSACTION_TYPE_BUY_WITH_GIFTCARD == (int) $data['type'
  2809.                     || GiftCardTransaction::TRANSACTION_TYPE_REFUND_GIFTCARD == (int) $data['type'])) {
  2810.                         $giftCardTransaction $em->getRepository('App\Entity\GiftCardTransaction')->find($data['transaction_id']);
  2811.                     
  2812.                     } else {
  2813.                         $giftCardTransaction = new GiftCardTransaction();
  2814.                     }
  2815.                     if (!$giftCardTransaction) {
  2816.                         $this->createFileJson($path'GiftCard transaction not found in licensor!' "\r");
  2817.                         return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  2818.                         ->respondWithError('GiftCard transaction not found!'WebService::GIFTCARD_WS_STATUS_GIFTCARD_TRANSACTION_NOT_FOUND_ERROR);
  2819.                     }
  2820.                     $emLev Util::emLicenseConnection($this->realContainer$em$accountLicenseData[0]);
  2821.                     $theTransactionType $data['type'];
  2822.                     $levelWebGiftCardRepo $emLev->getRepository('App\Structure\GiftCard');
  2823.                     $doGiftCardLogRecord true;
  2824.                     if ($worksWithArmor && GiftCardTransaction::TRANSACTION_TYPE_NEW_GIFTCARD != (int) $data['type']) {
  2825.                         $log->createChannel('gift_card');
  2826.                         $url $this->getParameter('armor_host') . "gift/gift-cards/" $decodeJWT['number'] . "/number";
  2827.                         $dataResponse $armor->armorGet($request$url$log);
  2828.                         if (!isset($dataResponse['id'])) {
  2829.                             return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  2830.                             ->respondWithError('Giftcard not found in Armor!'WebService::GIFTCARD_WS_STATUS_GIFTCARDNOTFOUND_ERROR);
  2831.                         }
  2832.                         $giftCardRecord $em->getRepository('App\Entity\GiftCard')->findBy(['gcVerificationCode' => $dataResponse['id']]);
  2833.                         if (empty($giftCardRecord)) {
  2834.                             $giftCardRecord $em->getRepository('App\Entity\GiftCard')->findBy(['gcVerificationCode' => $data['nickname'] .'-'$dataResponse['id']]);
  2835.                         }
  2836.                         $amountInArmor Encryptor::decodeInfo($dataResponse['balance'], 5);
  2837.                         if (isset($giftCardRecord[0]) && $amountInArmor != $giftCardRecord[0]->getGcAmount()) {
  2838.                             $this->createFileJson($path'Different GT amount error!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!' "\r");
  2839.                             $this->createFileJson($path'Armor amount -> ' $amountInArmor "\r");
  2840.                             $this->createFileJson($path'Licensor amount -> ' $giftCardRecord[0]->getGcAmount() . "\r");
  2841.                             $giftCardRecord[0]->setGcAmount($amountInArmor);
  2842.                             $em->persist($giftCardRecord[0]);
  2843.                             $em->flush();
  2844.                         } elseif (!isset($giftCardRecord[0])) {
  2845.                             $this->createFileJson($path'GiftCard not found in Licensor A!!!' $giftCardRecord[0]->getGcAmount() . "\r");
  2846.                             return $this->errorWrongArgs('GiftCard not found!'WebService::CODE_OBJECT_NOT_FOUND);
  2847.                         }
  2848.                         $data['gift_code'] = $dataResponse['id'];
  2849.                     } else {
  2850.                         $otherAuxGiftcardCode $data['nickname'] .'-'$data['gift_code'];
  2851.                         $giftCardRecord $em->getRepository('App\Entity\GiftCard')->findBy(['gcVerificationCode' => $otherAuxGiftcardCode]);
  2852.                         if (empty($giftCardRecord)) {
  2853.                             $giftCardRecord $em->getRepository('App\Entity\GiftCard')->findOneBy(['gcVerificationCode' => $data['gift_code']]);
  2854.                             if ($giftCardRecord && $giftCardRecord->getGcCreatorLicense()->getId() != $accountLicenseData[0]->getId()) {
  2855.                                 
  2856.                                 $giftCardRecord null;
  2857.                                 $this->createFileJson($path'New giftcard with same base code as other licence ' $data['gift_code'] . "\r");
  2858.                             
  2859.                             } else {
  2860.                                 $this->createFileJson($path'Redy for a very new giftcard with base code ' $data['gift_code'] . "\r");
  2861.                             }
  2862.                         }
  2863.                         if (isset($data['debug'])) {
  2864.                             dump($giftCardRecord);
  2865.                         }
  2866.                     }
  2867.                     if (GiftCardTransaction::TRANSACTION_TYPE_NEW_GIFTCARD == (int) $data['type'] && empty($giftCardRecord)) {
  2868.                         $this->createFileJson($path'New GiftCard to licensor ' "\r");
  2869.                         $theGiftCard = new GiftCard();
  2870.                         $theGiftCard->setGcAmount($data['amount']);
  2871.                         $theGiftCard->setGcVerificationCode($data['nickname'] .'-'$data['gift_code']);
  2872.                         $theGiftCard->setGcReleaseDate($actualDate);
  2873.                         if (isset($data['activation_date'])) {
  2874.                             try {
  2875.                                 $theGiftCard->setGcActivateDate(new DateTime($data['activation_date']));
  2876.                             } catch (\Exception $ex) {
  2877.                                 $theGiftCard->setGcActivateDate(new DateTime('now'));
  2878.                             }
  2879.                         } else {
  2880.                             $theGiftCard->setGcActivateDate(new DateTime('now'));
  2881.                         }
  2882.                         if (isset($data['status'])) {
  2883.                             $theGiftCard->setGcStatus(GiftCard::STATUS_DEACTIVATE);
  2884.                         } else {
  2885.                             $theGiftCard->setGcStatus(GiftCard::STATUS_ACTIVE);
  2886.                         }
  2887.                         $theGiftCard->setGcCreatorLicense($licenseToValidate);
  2888.                         $theGiftCard->setGcAccount($licenseToValidate->getAlAccountLicense());
  2889.                         $em->persist($theGiftCard);
  2890.                         $em->flush();
  2891.                         if ($worksWithArmor) {
  2892.                             $decodeJWT['gift_card_id'] = $theGiftCard->getId();
  2893.                             $decodeJWT['identifier'] = $theGiftCard->getId();
  2894.                             $decodeJWT['balance'] = Encryptor::encodeInfo($data['amount'], 5);
  2895.                             $token Encryptor::encodeInfo(json_encode($decodeJWT));
  2896.                             $request $armor->duplicateRequestWithOverwritedContentForArmorServer($request, ['token' => $token]);
  2897.                             $log->createChannel('gift_card');
  2898.                             $url $this->getParameter('armor_host') . "gift/add-gift-card";
  2899.                             $dataResponse $armor->armorPost($request$url$log);
  2900.                             if ($dataResponse instanceof Response) {
  2901.                                 $jsonResponse $dataResponse->getContent();
  2902.                                 $decodedResponse json_decode($jsonResponsetrue);
  2903.                                 $neededArmorId $data['nickname'] .'-'$decodedResponse['data']['gift_card_id'];
  2904.                                 $data['gift_code'] = $neededArmorId;
  2905.                                 $theGiftCard->setGcVerificationCode($neededArmorId);
  2906.                                 $em->persist($theGiftCard);
  2907.                                 $em->flush();
  2908.                             }
  2909.                         }
  2910.                         $giftCardWebData = new stdClass();
  2911.                         $giftCardWebData->gift_status $data['type'];
  2912.                         $giftCardWebData->gift_price $data['amount'];
  2913.                         $giftCardWebData->gift_code $data['gift_code'];
  2914.                         $giftCardWebData->gift_date $actualDate->format('Y-m-d H:i:s');
  2915.                         $giftCardWebData->licId $theGiftCard->getId();
  2916.                         $giftCardWebData->id UUIDGeneratorUtil::getUUIDv4();
  2917.                         $this->createFileJson($path'Ready to insert GiftCard into license database -> ' json_encode($giftCardWebData) . "\r");
  2918.                         $emLevCreatorGiftCard $emLev;
  2919.                         $queryResponse $levelWebGiftCardRepo->setDataUploadOne($this->realContainer$giftCardWebData$path);
  2920.                         if (is_array($queryResponse)) {
  2921.                             $responseArr['msg'] = 'GiftCard registed and activated successfully!!';
  2922.                             $responseArr['status'] = WebService::GIFTCARD_WS_STATUS_NEW_GIFTCARD_SUCCESS;
  2923.                             $this->createFileJson($path'New GiftCard registed successfully!' "\r");
  2924.                         } else {
  2925.                             
  2926.                             if (strpos($queryResponse'1062 Duplicate entry') && strpos($queryResponse$data['nickname'] .'-'$data['gift_code'])) {
  2927.                                 
  2928.                                 $responseArr['msg'] = "GiftCard with '" $data['gift_code'] . "' code already registed in " $accountLicenseData[0] . " restaurant" ;
  2929.                                 $responseArr['status'] = WebService::GIFTCARD_WS_STATUS_GIFTCARD_ALREADY_REGISTED_ERROR;
  2930.                                 
  2931.                                 $this->createFileJson($path"GiftCard with '" $data['gift_code'] . "' code already registed in " $accountLicenseData[0] . " restaurant" "\r");
  2932.                             
  2933.                             } else {
  2934.                                 $this->createFileJson($path'Error in licensor new Giftcard transaction! -> ' $queryResponse "\r");
  2935.                                 
  2936.                                 return $this->setStatusCode(WebService::HTTP_CODE_INTERNAL_ERROR)
  2937.                                 ->respondWithError('Error in transaction!'WebService::GIFTCARD_WS_STATUS_TRANSACTION_ERROR);
  2938.                             }
  2939.                         }
  2940.                     } elseif (GiftCardTransaction::TRANSACTION_TYPE_NEW_GIFTCARD == (int) $data['type'] && !empty($giftCardRecord)) {
  2941.                         
  2942.                         $this->createFileJson($path'Error: GiftCard already registed in licensor' "\r");
  2943.                         
  2944.                         return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  2945.                         ->respondWithError('GiftCard already registed!'WebService::GIFTCARD_WS_STATUS_GIFTCARD_ALREADY_REGISTED_ERROR);
  2946.                     
  2947.                     } elseif (!empty($giftCardRecord) && $giftCardRecord[0]->getGcStatus() != GiftCard::STATUS_DEACTIVATE) {
  2948.                         
  2949.                         $this->createFileJson($path'Searching old licensor giftcard...' "\r");
  2950.                         if (!empty($giftCardRecord)) {
  2951.                             $this->createFileJson($path'Licensor giftcard found!' "\r");
  2952.                             $theGiftCard $giftCardRecord[0];
  2953.                             // if ($licenseToValidate->getAlAccountLicense()->getId() != $theGiftCard->getGcAccount()->getId()) {
  2954.                             //  $this->createFileJson($path, 'Error: Giftcard of another franchise!' . "\r");
  2955.                             //  return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  2956.                             //  ->respondWithError('Giftcard of another franchise!', WebService::GIFTCARD_WS_STATUS_GIFTCARD_OTHER_FRANCHISE_ERROR);
  2957.                             // }
  2958.                             if ($theGiftCard->getGcCreatorLicense()->getId() != $licenseToValidate->getId()) {
  2959.                                 
  2960.                                 $emLevCreatorGiftCard Util::emLicenseConnection($this->realContainer$em$licenseToValidate);
  2961.                                 $levelWebGiftCardCreatorRepo $emLevCreatorGiftCard->getRepository('App\Structure\GiftCard');
  2962.                             
  2963.                             } else {
  2964.                                 $emLevCreatorGiftCard $emLev;
  2965.                                 $levelWebGiftCardCreatorRepo $levelWebGiftCardRepo;
  2966.                             }
  2967.                             switch ($data['type']) {
  2968.                                 case GiftCardTransaction::TRANSACTION_TYPE_BUY_WITH_GIFTCARD:
  2969.                                     $this->createFileJson($path'Transaction successfully!' "\r");
  2970.                                     if (isset($data['transaction_id'])) {
  2971.                                         $theGiftCard->setGcLastTransactionDate($actualDate);
  2972.                                     } else {
  2973.                                         if (($theGiftCard->getGcAmount() - (double) $data['amount']) < 0.0) {
  2974.                                             
  2975.                                             $this->createFileJson($path'Not eunogh founds in giftcard, transaction declined!' "\r");
  2976.                                             
  2977.                                             $responseArr['msg'] = 'Not eunogh founds in giftcard, transaction declined!';
  2978.                                             $responseArr['status'] = WebService::GIFTCARD_WS_STATUS_TRANSACTION_ERROR;
  2979.                                             $responseArr['amount'] = $theGiftCard->getGcAmount();
  2980.                                             $responseArr['requestedAmount'] = $data['amount'];
  2981.                                             $responseArr['isActive'] = (int) ((boolean) ($theGiftCard->getGcStatus() % GiftCard::STATUS_DEACTIVATE));
  2982.                                             
  2983.                                             $responseArr['activationDate'] = "";
  2984.                                             if ($theGiftCard->getGcActivateDate()) {
  2985.                                                 $responseArr['activationDate'] = $theGiftCard->getGcActivateDate()->format('Y-m-dTH:i:s');
  2986.                                             }
  2987.                                             $responseArr['lastTransactionDate'] = "";
  2988.                                             if ($theGiftCard->getGcLastTransactionDate()) {
  2989.                                                 $responseArr['lastTransactionDate'] = $theGiftCard->getGcLastTransactionDate()->format('Y-m-dTH:i:s');
  2990.                                             }
  2991.                                             $responseArr['deactivationDate'] = "";
  2992.                                             if ($theGiftCard->getGcDeactivateDate()) {
  2993.                                                 $responseArr['deactivationDate'] = $theGiftCard->getGcDeactivateDate()->format('Y-m-dTH:i:s');
  2994.                                             }
  2995.                                             $theUrlTrSt = new LicensorGenericTransformer($this->realContainer$responseArr);
  2996.                                             $xxArray $theUrlTrSt->transform();
  2997.                                             $jsonContent json_encode($xxArray);
  2998.                                             $this->createFileJson($path'The WS Response -> ' $jsonContent "\r");
  2999.                                             return $this->respondWithItem($jsonContent$theUrlTrSt);
  3000.                                         } else {
  3001.                                             $theGiftCard->setGcAmount($theGiftCard->getGcAmount() - (double) $data['amount']);
  3002.                                         }
  3003.                                     }
  3004.                                     $responseArr['msg'] = 'Transaction successfully!';
  3005.                                     $responseArr['status'] = WebService::GIFTCARD_WS_STATUS_TRANSACTION_SUCCESS;
  3006.                                     break;
  3007.                                 case GiftCardTransaction::TRANSACTION_TYPE_RECHARGE_GIFTCARD:
  3008.                                     $this->createFileJson($path'Recharge successfully!' "\r");
  3009.                                     
  3010.                                     $theGiftCard->setGcLastTransactionDate($actualDate);
  3011.                                     $theGiftCard->setGcAmount($theGiftCard->getGcAmount() + (double) $data['amount']);
  3012.                                     $responseArr['msg'] = 'Recharge successfully!';
  3013.                                     $responseArr['status'] = WebService::GIFTCARD_WS_STATUS_RECHARGE_SUCCESS;
  3014.                                     break;
  3015.                                 case GiftCardTransaction::TRANSACTION_TYPE_REFUND_RECHARGE_GIFTCARD:
  3016.                                     $this->createFileJson($path'Recharge canceled successfully!' "\r");
  3017.                                     $theGiftCard->setGcLastTransactionDate($actualDate);
  3018.                                     $theGiftCard->setGcAmount($theGiftCard->getGcAmount() - (double) $data['amount']);
  3019.                                     $responseArr['msg'] = 'Recharge canceled successfully!';
  3020.                                     $responseArr['status'] = WebService::GIFTCARD_WS_STATUS_REFUND_RECHARGE_SUCCESS;
  3021.                                     break;
  3022.                                 case GiftCardTransaction::TRANSACTION_TYPE_REFUND_GIFTCARD:
  3023.                                     $this->createFileJson($path'Refund successfully!' "\r");
  3024.                                     $theGiftCard->setGcLastTransactionDate($actualDate);
  3025.                                     if (isset($data['transaction_id'])) {
  3026.                                         $this->createFileJson($path'GiftCard if Refund!' "\r");
  3027.                                         $theGiftCard->setGcLastTransactionDate($actualDate);
  3028.                                         $theRealTransactionAmount $theGiftCard->getGcAmount() + (double) $data['amount'];
  3029.                                         $giftCardTransaction->setGtTransactionAmount($data['amount']);
  3030.                                         $theGiftCard->setGcAmount($theRealTransactionAmount);
  3031.                                     } else {
  3032.                                         $this->createFileJson($path'GiftCard else Refund!' "\r");
  3033.                                         $theGiftCard->setGcAmount($theGiftCard->getGcAmount() + (double) $data['amount']);
  3034.                                     }
  3035.                                     $responseArr['msg'] = 'Refund successfully!';
  3036.                                     $responseArr['status'] = WebService::GIFTCARD_WS_STATUS_REFUND_SUCCESS;
  3037.                                     break;
  3038.                                 case GiftCardTransaction::TRANSACTION_TYPE_ADJUST_TRANSACTION:
  3039.                                     $this->createFileJson($path'Try adjust order!' "\r");
  3040.                                     $theGiftCard->setGcLastTransactionDate($actualDate);
  3041.                                     if (isset($data['transaction_id'])) {
  3042.                                         $oldGiftCardTransaction $em->getRepository('App\Entity\GiftCardTransaction')->find($data['transaction_id']);
  3043.                                         $theRealTransactionAmount $theGiftCard->getGcAmount() + $oldGiftCardTransaction->getGtTransactionAmount() - (double) $data['amount'];
  3044.                                         $giftCardTransaction->setGtTransactionAmount($data['amount']);
  3045.                                         $theGiftCard->setGcAmount($theRealTransactionAmount);
  3046.                                         $responseArr['msg'] = 'Adjust successfully!';
  3047.                                         $responseArr['status'] = WebService::GIFTCARD_WS_STATUS_ADJUST_SUCCESS;
  3048.                                     }
  3049.                                     break;
  3050.                                 case GiftCardTransaction::TRANSACTION_TYPE_BUY_DEVOLUTION_GIFTCARD:
  3051.                                     $this->createFileJson($path'Devolution successfully!' "\r");
  3052.                                     $theGiftCard->setGcLastTransactionDate($actualDate);
  3053.                                     $theGiftCard->setGcAmount($theGiftCard->getGcAmount() + (double) $data['amount']);
  3054.                                     $responseArr['msg'] = 'Devolution successfully!';
  3055.                                     $responseArr['status'] = WebService::GIFTCARD_WS_STATUS_DEVOLUTION_SUCCESS;
  3056.                                     break;
  3057.                                 case GiftCardTransaction::TRANSACTION_TYPE_BUY_CANCELED_GIFTCARD:
  3058.                                     $this->createFileJson($path'Cancelation successfully!' "\r");
  3059.                                     $theGiftCard->setGcLastTransactionDate($actualDate);
  3060.                                     $theGiftCard->setGcAmount($theGiftCard->getGcAmount() + (double) $data['amount']);
  3061.                                     $responseArr['msg'] = 'Cancelation successfully!';
  3062.                                     $responseArr['status'] = WebService::GIFTCARD_WS_STATUS_CANCELATION_SUCCESS;
  3063.                                     break;
  3064.                                 case GiftCardTransaction::TRANSACTION_TYPE_INFORMATION_GIFTCARD:
  3065.                                     $this->createFileJson($path'Information request!' "\r");
  3066.                                     $responseArr['msg'] = 'Information request!';
  3067.                                     $responseArr['status'] = WebService::GIFTCARD_WS_STATUS_INFORMATION_SUCCESS;
  3068.                                     break;
  3069.                                 case GiftCardTransaction::TRANSACTION_TYPE_DISABLE_GIFTCARD
  3070.                                     $this->createFileJson($path'GiftCard Disabled...' "\r");
  3071.                                     $theGiftCard->setGcDeactivateDate($actualDate);
  3072.                                     $theGiftCard->setIsDeactivationNotified(true);
  3073.                                     $theGiftCard->setGcStatus(GiftCard::STATUS_DEACTIVATE);
  3074.                                     $responseArr['msg'] = 'GiftCard Disabled!';
  3075.                                     $responseArr['status'] = WebService::GIFTCARD_WS_STATUS_DISABLED_SUCCESS;
  3076.                                     break;
  3077.                                 default:
  3078.                                     $data['type'] = GiftCardTransaction::TRANSACTION_TYPE_UNKNOWN_TRANSACTION;
  3079.                                     $theTransactionType $data['type'];
  3080.                                     $this->createFileJson($path'Unknown Transaction...' "\r");
  3081.                                     $theGiftCard->setGcDeactivateDate($actualDate);
  3082.                                     $theGiftCard->setIsDeactivationNotified(true);
  3083.                                     $theGiftCard->setGcStatus(GiftCard::STATUS_DEACTIVATE);
  3084.                                     $responseArr['msg'] = 'Unknown Transaction!';
  3085.                                     $responseArr['status'] = WebService::GIFTCARD_WS_STATUS_UNKNOWN_TRANSACTION;
  3086.                                     break;
  3087.                             }
  3088.                             
  3089.                         } else {
  3090.                             $this->createFileJson($path'Error: Licensor Giftcard not found!' "\r");
  3091.                             return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  3092.                             ->respondWithError('Giftcard not found!'WebService::GIFTCARD_WS_STATUS_GIFTCARDNOTFOUND_ERROR);
  3093.                         }
  3094.                         $auxSearchingCode $data['nickname'] . '-' $data['gift_code'];
  3095.                         $this->createFileJson($path'Searching level GiftCard with code -> ' $auxSearchingCode "\r");
  3096.                         $levelGiftCard $levelWebGiftCardCreatorRepo->findBy(['gcVerificationCode' => $auxSearchingCode]);
  3097.                         if (empty($levelGiftCard)) {
  3098.                             $this->createFileJson($path'Searching old level GiftCard with code -> ' $data['gift_code'] . "\r");
  3099.                             $levelGiftCard $levelWebGiftCardCreatorRepo->findBy(['gcVerificationCode' => $data['gift_code']]);
  3100.                         }
  3101.                         if (isset($data['debug'])) {
  3102.                             dump($theGiftCard);
  3103.                             dump($levelGiftCard);
  3104.                         }
  3105.                         if (empty($levelGiftCard)) {
  3106.                             $this->createFileJson($path'Level GiftCard not found, geting GiftCard from Licensor!' "\r");
  3107.                             
  3108.                             $giftCardWebData Util::getStdClassForGiftCard($theGiftCardtrue);
  3109.                             $giftCardWebData->id UUIDGeneratorUtil::getUUIDv4();
  3110.                             $queryResponse $levelWebGiftCardCreatorRepo->setDataUploadOne($this->realContainer$giftCardWebData$path);
  3111.                         } else {
  3112.                             $this->createFileJson($path'Level web GiftCard found!' "\r");
  3113.                             
  3114.                             $giftCardWebData Util::getStdClassForGiftCard($theGiftCardtrue);
  3115.                             $giftCardWebData->id $levelGiftCard[0]->getId();
  3116.                             
  3117.                             $this->createFileJson($path'Level web GiftCard id found -> ' $levelGiftCard[0]->getId() . "\r");
  3118.                             $queryResponse $levelWebGiftCardCreatorRepo->setDataUpdateUploadOne($this->realContainer$levelGiftCard[0], $giftCardWebData$path);
  3119.                         }
  3120.                         if (isset($data['debug'])) {
  3121.                             dump($queryResponse);
  3122.                             die;
  3123.                         }
  3124.                         if (!is_array($queryResponse) && GiftCardTransaction::TRANSACTION_TYPE_REFUND_RECHARGE_GIFTCARD != (int) $data['type']) {
  3125.                             
  3126.                             // dump(strpos($queryResponse, '1062 Duplicate entry'));
  3127.                             // dump(strpos($queryResponse, $data['nickname'] .'-'. $data['gift_code']));
  3128.                             // die;
  3129.                             if (strpos($queryResponse'1062 Duplicate entry') && strpos($queryResponse$data['nickname'] .'-'$data['gift_code'])) {
  3130.                                 
  3131.                                 $responseArr['msg'] = "GiftCard with '" $data['gift_code'] . "' code already registed in " $accountLicenseData[0] . " restaurant" ;
  3132.                                 $responseArr['status'] = WebService::GIFTCARD_WS_STATUS_GIFTCARD_ALREADY_REGISTED_ERROR;
  3133.                                 
  3134.                                 $this->createFileJson($path"GiftCard with '" $data['gift_code'] . "' code already registed in " $accountLicenseData[0] . " restaurant" "\r");
  3135.                             
  3136.                             } else {
  3137.                                 $this->createFileJson($path'Error in licensor Giftcard transaction! -> ' $queryResponse "\r");
  3138.                                 
  3139.                                 return $this->setStatusCode(WebService::HTTP_CODE_INTERNAL_ERROR)
  3140.                                 ->respondWithError('Error in transaction!'WebService::GIFTCARD_WS_STATUS_TRANSACTION_ERROR);
  3141.                             
  3142.                             }
  3143.                         } elseif (!is_array($queryResponse)) {
  3144.                             $this->createFileJson($path'Error in licensor Giftcard recharge cancelation! -> ' $queryResponse "\r");
  3145.                             return $this->setStatusCode(WebService::HTTP_CODE_INTERNAL_ERROR)
  3146.                                             ->respondWithError('Error in recharge cancelation!'WebService::GIFTCARD_WS_STATUS_GIFTCARD_RECHARGE_CANCELATION_ERROR);
  3147.                         }
  3148.                     } elseif (!empty($giftCardRecord) && $giftCardRecord[0]->getGcStatus() == GiftCard::STATUS_DEACTIVATE) {
  3149.                         
  3150.                         $doGiftCardLogRecord false;
  3151.                         $theGiftCard $giftCardRecord[0];
  3152.                         $responseArr['msg'] = 'GiftCard Disabled!';
  3153.                         $responseArr['status'] = WebService::GIFTCARD_WS_STATUS_DISABLED_SUCCESS;
  3154.                         
  3155.                         $this->createFileJson($path'Deactivated GiftCard request found!' "\r");
  3156.                     } elseif (empty($giftCardRecord) && GiftCardTransaction::TRANSACTION_TYPE_DISABLE_GIFTCARD == (int) $data['type']) {
  3157.                         
  3158.                         $this->createFileJson($path'Error trying to disabled an unknown giftcard -> ' "\r");
  3159.                         
  3160.                         return $this->setStatusCode(WebService::CODE_ERR_CONFLICT)
  3161.                         ->respondWithError('Error trying to disabled an unknown giftcard!'WebService::GIFTCARD_WS_STATUS_TRANSACTION_ERROR);
  3162.                     }
  3163.                     // else {
  3164.                     //     $this->createFileJson($path, 'Error in licensor Giftcard recharge cancelation! -> ' . $queryResponse . "\r");
  3165.                     //     return $this->setStatusCode(WebService::HTTP_CODE_INTERNAL_ERROR)
  3166.                     //                     ->respondWithError('Error in recharge cancelation!', WebService::GIFTCARD_WS_STATUS_GIFTCARD_RECHARGE_CANCELATION_ERROR);
  3167.                     // }
  3168.                     if (isset($data['debug'])) {
  3169.                         die;
  3170.                     }
  3171.                     if (GiftCardTransaction::TRANSACTION_TYPE_NEW_GIFTCARD != (int) $data['type']) {
  3172.                         $em->persist($theGiftCard);
  3173.                         $this->createFileJson($path'Licensor Giftcard updated!' "\r");
  3174.                         if ($worksWithArmor) {
  3175.                             $log->createChannel('gift_card');
  3176.                             $urlData = [
  3177.                                 'gift_card_id' => $theGiftCard->getGcVerificationCode(),
  3178.                                 'identifier' => $theGiftCard->getId()
  3179.                             ];
  3180.                             $paramToken $armor->token($urlData);
  3181.                             $decodeJWT['gift_card_id'] = $theGiftCard->getId();
  3182.                             $decodeJWT['identifier'] = $theGiftCard->getId();
  3183.                             $decodeJWT['balance'] = Encryptor::encodeInfo($theGiftCard->getGcAmount(), 5);
  3184.                             $decodeJWT['status'] = $theGiftCard->getGcStatus();
  3185.                             $token Encryptor::encodeInfo(json_encode($decodeJWT));
  3186.                             $request $armor->duplicateRequestWithOverwritedContentForArmorServer($request, ['token' => $token]);
  3187.                             $url $this->getParameter('armor_host') . 'gift/gift-cards/' $paramToken '/update';
  3188.                             $dataResponse $armor->armorPut($request$url$log);
  3189.                             if ($dataResponse instanceof Response && $dataResponse->getStatusCode() != WebService::HTTP_CODE_SUCCESS) {
  3190.                                 $jsonResponse $dataResponse->getContent();
  3191.                                 $decodedResponse json_decode($jsonResponsetrue);
  3192.                                 $this->createFileJson($path'Unknown Armor error!!!! -> ' $decodedResponse['data'] . "\r");
  3193.                             }
  3194.                         }
  3195.                     }
  3196.                     if ($doGiftCardLogRecord) {
  3197.                         $giftCardTransaction->setGtType($data['type']);
  3198.                         if (isset($data['order_id']) && $data['order_id'] != '') {
  3199.                             $giftCardTransaction->setGtOrder($data['order_id']);
  3200.                         }
  3201.                         if (isset($data['inv_id']) && $data['inv_id'] != '') {
  3202.                             $giftCardTransaction->setGtInvoice($data['inv_id']);
  3203.                         }
  3204.                         $giftCardTransaction->setGtTransactionAmount($data['amount']);
  3205.                         $giftCardTransaction->setGtGiftCard($theGiftCard);
  3206.                         $giftCardTransaction->setGtTransactionDate($actualDate);
  3207.                         $giftCardTransaction->setGtCreatorLicense($licenseToValidate);
  3208.                         $giftCardTransaction->setGtTotalAmount($theGiftCard->getGcAmount());
  3209.                         $em->persist($giftCardTransaction);
  3210.                         $this->createFileJson($path'Licensor GiftCardTransaction registed!' "\r");
  3211.                     }
  3212.                     $em->flush();
  3213.                     if ($doGiftCardLogRecord && is_array($queryResponse)) {
  3214.                         $this->createFileJson($path'Preparing new GiftCardLog to level!' "\r");
  3215.                         $levelGiftCardLogData = new stdClass();
  3216.                         $levelGiftCardLogData->gift_id array_keys($queryResponse)[0];
  3217.                         $levelGiftCardLogData->licId $giftCardTransaction->getId();
  3218.                         $levelGiftCardLogData->gifl_total $theGiftCard->getGcAmount();
  3219.                         $levelGiftCardLogData->gifl_type $theTransactionType;
  3220.                         $levelGiftCardLogData->gifl_price $data['amount'];
  3221.                         if (isset($data['order_id']) && $data['order_id'] != '' ) {
  3222.                             $levelGiftCardLogData->ord_id $data['order_id'];
  3223.                         }
  3224.                         if (isset($data['inv_id']) && $data['inv_id'] != '') {
  3225.                             $levelGiftCardLogData->inv_id $data['inv_id'];
  3226.                         }
  3227.                         $levelGiftCardLogData->gift_code $data['gift_code'];
  3228.                         $levelGiftCardLogData->gifl_date $actualDate->format('Y-m-d H:i:s');
  3229.                         if (isset($data['transaction_id']) && (GiftCardTransaction::TRANSACTION_TYPE_BUY_WITH_GIFTCARD == (int) $data['type'] || GiftCardTransaction::TRANSACTION_TYPE_REFUND_GIFTCARD == (int) $data['type'])) {
  3230.                             
  3231.                             $licesneGiftCardLogRecordToUpdate $emLevCreatorGiftCard->getRepository('App\Structure\GiftCardLog')->findBy(['gclLicFk' => $giftCardTransaction->getId()]);
  3232.                             if (empty($licesneGiftCardLogRecordToUpdate)) {
  3233.                                 
  3234.                                 $this->createFileJson($path'GiftCard log not found in license!' "\r");
  3235.                                 
  3236.                                 return $this->setStatusCode(WebService::HTTP_CODE_INTERNAL_ERROR)
  3237.                                 ->respondWithError('GiftCard log not found!'WebService::GIFTCARD_WS_STATUS_GIFTCARD_LOG_NOT_FOUND_ERROR);
  3238.                             
  3239.                             } else {
  3240.                                 $licenseGiftCardLogOldRecord $licesneGiftCardLogRecordToUpdate[0];
  3241.                                 $queryResponse $emLevCreatorGiftCard->getRepository('App\Structure\GiftCardLog')->setDataUpdateUploadOne($this->realContainer$licenseGiftCardLogOldRecord$levelGiftCardLogData$path);
  3242.                             
  3243.                             }
  3244.                         } else {
  3245.                             $levelGiftCardLogData->id UUIDGeneratorUtil::getUUIDv4();
  3246.                             $queryResponse $emLevCreatorGiftCard->getRepository('App\Structure\GiftCardLog')->setDataUploadOne($this->realContainer$levelGiftCardLogData$path);
  3247.                         }
  3248.                         $responseArr['gift_id'] = '';
  3249.                         if (!is_array($queryResponse)) {
  3250.                             $this->createFileJson($path'Error in level GiftCardLog transaction! -> ' $queryResponse "\r");
  3251.                             
  3252.                             return $this->setStatusCode(WebService::HTTP_CODE_INTERNAL_ERROR)
  3253.                             ->respondWithError('Error registering GiftCardLog!'WebService::GIFTCARD_WS_STATUS_GIFTCARDLOG_ERROR);
  3254.                         
  3255.                         } else {
  3256.                             $this->createFileJson($path'The actual $queryResponse  -> ' json_encode($queryResponse) . "\r");
  3257.                             
  3258.                             $responseArr['gift_id'] = array_keys($queryResponse)[0];
  3259.                             $this->createFileJson($path'GiftCardLog id to android -> ' $responseArr['gift_id'] . "\r");
  3260.                         }
  3261.                     }
  3262.                     $responseArr['amount'] = $theGiftCard->getGcAmount();
  3263.                     $responseArr['transaction_id'] = $giftCardTransaction->getId();
  3264.                     $responseArr['isActive'] = (int) ((boolean) ($theGiftCard->getGcStatus() % GiftCard::STATUS_DEACTIVATE));
  3265.                     
  3266.                     $responseArr['activationDate'] = "";
  3267.                     if ($theGiftCard->getGcActivateDate()) {
  3268.                         $responseArr['activationDate'] = $theGiftCard->getGcActivateDate()->format('Y-m-dTH:i:s');
  3269.                     }
  3270.                     $responseArr['lastTransactionDate'] = "";
  3271.                     if ($theGiftCard->getGcLastTransactionDate()) {
  3272.                         $responseArr['lastTransactionDate'] = $theGiftCard->getGcLastTransactionDate()->format('Y-m-dTH:i:s');
  3273.                     }
  3274.                     $responseArr['deactivationDate'] = "";
  3275.                     if ($theGiftCard->getGcDeactivateDate()) {
  3276.                         $responseArr['deactivationDate'] = $theGiftCard->getGcDeactivateDate()->format('Y-m-dTH:i:s');
  3277.                     }
  3278.                     $theUrlTrSt = new LicensorGenericTransformer($this->realContainer$responseArr);
  3279.                     $xxArray $theUrlTrSt->transform();
  3280.                     $jsonContent json_encode($xxArray);
  3281.                     $this->createFileJson($path'The WS Response -> ' $jsonContent "\r");
  3282.                     return $this->respondWithItem($jsonContent$theUrlTrSt);
  3283.                 }
  3284.             } else {
  3285.                 $this->createFileJson($path'Error: Wrong Content' "\r");
  3286.                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  3287.                 ->respondWithError('Wrong Content.'WebService::CODE_WRONG_ARGUMENTS);
  3288.             }
  3289.         } else {
  3290.             $this->createFileJson($path'Error: Method not allowed. Use ' WebService::REQUEST_METHOD_POST "\r");
  3291.             return $this->errorNotAllowedMethod('Method not allowed. Use ' WebService::REQUEST_METHOD_POST " method");
  3292.         }
  3293.     }
  3294.     /**
  3295.      * WS para notificar por correo electronico a los encargados de administrar el
  3296.      * sistema y dar soporte con el fin de identificar si dicho dispositivo tiene
  3297.      * algun inconveniente en el logueo ya sea licencia o sublicencia
  3298.      * @author Aealan Z <lrobledo@kijho.com> 21/12/15
  3299.      * @param \Symfony\Component\HttpFoundation\Request $request datos de la solicitud
  3300.      * @return Response Json con la informacion de respuesta
  3301.      */
  3302.     public function notifyDeviceInfo(Request $request) {
  3303.         if ($request->getMethod() === WebService::REQUEST_METHOD_POST) {
  3304.             if (=== strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_STRUCTURE) || === strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_TEXT)) {
  3305.                 $path Util::getValidActiveLogByBaseName($this->realContainer'notifyDeviceInfo''notifyDeviceInfo0.txt');
  3306.                 $this->createFileJson($path'Notify Device Info: ' $request->getContent() . "\r");
  3307.                 $arrayEncryptResult Util::decryptDataForAndroid($this->realContainer$request->getContent());
  3308.                 $data json_decode($arrayEncryptResult['data'], true);
  3309.                 if (!isset($data['version']) || !isset($data['uid'])) {
  3310.                     return $this->errorWrongArgs('Wrong Arguments!'WebService::CODE_WRONG_ARGUMENTS);
  3311.                 }
  3312.                 $dataToSearch = ['deviceUid' => $data['uid']];
  3313.                 $em $this->getDoctrine()->getManager();
  3314.                 $accountLicenseData $em->getRepository('App\Entity\AccountLicense')->findBy($dataToSearch);
  3315.                 $generalInfo "<label>General Info: </label><br><br>";
  3316.                 $generalInfo .= "<label>Server: <strong>http://" $this->realContainer->getParameter("licensor_base_url") . "/licensor/login</strong></label><br>";
  3317.                 $generalInfo .= "<label>Device UID: <strong>" $data['uid'] . "</strong></label><br>";
  3318.                 if (!empty($accountLicenseData)) {
  3319.                     $generalInfo .= "<label>Last time used in: <strong>" $accountLicenseData[0]->getAlLicenseUsername() . "</strong> license</label><br>";
  3320.                     if ($accountLicenseData[0]->getAlAccountLicense()->getDeleted()) {
  3321.                         $generalInfo .= "<label>Account <strong>" $accountLicenseData[0]->getAlAccountLicense()->getAcName() . " </strong>incative</label><br>";
  3322.                     } else {
  3323.                         $generalInfo .= "<label>Account <strong>" $accountLicenseData[0]->getAlAccountLicense()->getAcName() . " </strong>active</label><br>";
  3324.                     }
  3325.                     if ($accountLicenseData[0]->getAlLicenseStatus() == AccountLicense::LICENSE_STATUS_ACTIVE) {
  3326.                         $generalInfo .= "<label>License <strong>active</strong><br></label>";
  3327.                     } else {
  3328.                         $generalInfo .= "<label>License <strong>incative</strong><br></label>";
  3329.                     }
  3330.                 } else {
  3331.                     $dataToSearch = ['deviceUid' => $data['uid']];
  3332.                     $subLicenseData $em->getRepository('App\Entity\SubLicense')->findBy($dataToSearch);
  3333.                     if (!empty($subLicenseData)) {
  3334.                         $generalInfo .= "<label>Last time used in: <strong>" $subLicenseData[0]->getChannelName() . "</strong> sublicense</label><br>";
  3335.                         if ($subLicenseData[0]->getLicense()->getAlAccountLicense()->getDeleted()) {
  3336.                             $generalInfo .= "<label>Account <strong>" $subLicenseData[0]->getLicense()->getAlAccountLicense()->getAcName() . " </strong>incative</label><br>";
  3337.                         } else {
  3338.                             $generalInfo .= "<label>Account <strong>" $subLicenseData[0]->getLicense()->getAlAccountLicense()->getAcName() . " </strong>active</label><br>";
  3339.                         }
  3340.                         if ($subLicenseData[0]->getLicense()->getAlLicenseStatus() == AccountLicense::LICENSE_STATUS_ACTIVE) {
  3341.                             $generalInfo .= "<label>License <strong>" $subLicenseData[0]->getLicense()->getAlLicenseUsername() . " </strong>active</label><br>";
  3342.                         } else {
  3343.                             $generalInfo .= "<label>License <strong>" $subLicenseData[0]->getLicense()->getAlLicenseUsername() . " </strong>incative</label><br>";
  3344.                         }
  3345.                     }
  3346.                 }
  3347.                 try {
  3348.                     $theRespArray Util::getLastVersionByJsonVersionFile($this->realContainer$data['version'], true$path);
  3349.                 } catch (\Exception $ex) {
  3350.                     $theRespArray['updateAppError'] = true;
  3351.                 }
  3352.                 try {
  3353.                     $theRespArrayTwo Util::getLastVersionByDirAvailableVersions($this->realContainer$data['version'], true$path);
  3354.                 } catch (\Exception $ex) {
  3355.                     $theRespArrayTwo['updateAppError'] = true;
  3356.                 }
  3357.                 if (isset($theRespArray['updateAppError']) && $theRespArray['updateAppError'] && isset($theRespArrayTwo['updateAppError']) && $theRespArrayTwo['updateAppError']) {
  3358.                     return $this->setStatusCode(WebService::HTTP_CODE_SERVICE_UNAVAILABLE)
  3359.                                     ->respondWithError('Error finding last version'WebService::CODE_OBJECT_NOT_FOUND);
  3360.                 }
  3361.                 if (isset($theRespArray["newVersion"]) && isset($theRespArrayTwo["newVersion"])) {
  3362.                     if ($theRespArray["newVersion"] < $theRespArrayTwo["newVersion"]) {
  3363.                         $theRespArray $theRespArrayTwo;
  3364.                     }
  3365.                 } elseif (!isset($theRespArray["newVersion"]) && isset($theRespArrayTwo["newVersion"])) {
  3366.                     $theRespArray $theRespArrayTwo;
  3367.                 }
  3368.                 $generalInfo .= "<label>APK version: <strong>" $data['version'] . "</strong></label><br>";
  3369.                 if (isset($theRespArray['newVersion'])) {
  3370.                     $generalInfo .= "<label>New version available: <strong>" $theRespArray['newVersion'] . "</strong></label><br>";
  3371.                 }
  3372.                 $emailsToNotify $this->realContainer->getParameter('level_emails_syncs_errors');
  3373.                 $respArray['subject'] = "Device info request " $data['uid'];
  3374.                 $respArray['message'] = "";
  3375.                 foreach ($emailsToNotify as $mailTo) {
  3376.                     $this->createFileJson($path"Mail to -> " $mailTo "\r");
  3377.                     $respArray['to'] = $mailTo;
  3378.                     $emailSuccess Utilx::sendMailInfo($this->realContainer$respArray$path$generalInfo);
  3379.                 }
  3380.                 if (isset($emailSuccess['success']) && $emailSuccess['success']) {
  3381.                     $responseArr['status'] = WebService::CODE_SUCCESS;
  3382.                     $responseArr['msg'] = 'Info device data send!';
  3383.                     $responseArr['bigbag'] = true;
  3384.                     $responseArr['url'] = '';
  3385.                     $theUrlTrSt = new LicensorGenericTransformer($this->realContainer$responseArr);
  3386.                     $xxArray $theUrlTrSt->transform();
  3387.                     $jsonContent json_encode($xxArray);
  3388.                     return $this->respondWithItem($jsonContent$theUrlTrSt);
  3389.                 } else {
  3390.                     return $this->setStatusCode(WebService::HTTP_CODE_INTERNAL_ERROR)
  3391.                                     ->respondWithError('Erro notifiying device info by email!'WebService::CODE_INTERNAL_ERROR);
  3392.                 }
  3393.             } else {
  3394.                 return $this->errorWrongArgs('Wrong Content.'WebService::CODE_WRONG_ARGUMENTS);
  3395.             }
  3396.         } else {
  3397.             return $this->errorNotAllowedMethod('Method not allowed. Use ' WebService::REQUEST_METHOD_POST " method");
  3398.         }
  3399.     }
  3400.     /**
  3401.      * WS para el boton de sincronizacion de arriba a abajo desde android
  3402.      * @author Aealan Z <lrobledo@kijho.com> 30/10/15
  3403.      * @param \Symfony\Component\HttpFoundation\Request $request datos de la solicitud
  3404.      * @return Response Json con la informacion de respuestaa
  3405.      */
  3406.     public function syncUpDownFromAndroid(Request $request) {
  3407.         if ($request->getMethod() === WebService::REQUEST_METHOD_POST) {
  3408.             if (=== strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_STRUCTURE) || === strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_TEXT)) {
  3409.                 $path Util::getValidActiveLogByBaseName($this->realContainer'syncUpDownFromAndroid''syncUpDownFromAndroid0.txt');
  3410.                 $this->createFileJson($path'Request content: ' $request->getContent() . "\r");
  3411.                 $arrayEncryptResult Util::decryptDataForAndroid($this->realContainer$request->getContent());
  3412.                 $data json_decode($arrayEncryptResult['data'], true);
  3413.                 if (!isset($data['nickname']) || !isset($data['uid'])) {
  3414.                     return $this->errorWrongArgs('Wrong arguments'WebService::CODE_COULD_NOT_AUTHENTICATE);
  3415.                 }
  3416.                 $licenseUserName = ['alLicenseUsername' => $data['nickname']];
  3417.                 $em $this->getDoctrine()->getManager();
  3418.                 $accountLicenseData $em->getRepository('App\Entity\AccountLicense')->findBy($licenseUserName);
  3419.                 $countResult count($accountLicenseData);
  3420.                 $this->createFileJson($path'Request content: license count ' $countResult "\r");
  3421.                 if ($countResult 0) {
  3422.                     $this->createFileJson($path'Request content: entro el chingo! ' "\r");
  3423.                     if ($accountLicenseData[0]->getAlAccountLicense()->getDeleted()) {
  3424.                         return $this->errorWrongArgs('Account inactive, please contact your system manager'WebService::CODE_UNAUTHORIZED);
  3425.                     }
  3426.                     if (!$accountLicenseData[0]->getAlLicenseStatus()) {
  3427.                         return $this->errorWrongArgs('License inactive, please contact your system manager'WebService::CODE_UNAUTHORIZED);
  3428.                     }
  3429.                     if ($accountLicenseData[0]->getDeviceUid() != $data['uid']) {
  3430.                         return $this->errorWrongArgs('Unauthorized device'WebService::CODE_UNAUTHORIZED);
  3431.                     }
  3432.                     $arrHead = ['Content-Type: application/json'];
  3433.                     $dataToRequest = ["nickname" => Util::encodeInfo($data['nickname']), 'waitTime' => 0];
  3434.                     $dataPost json_encode($dataToRequest);
  3435.                     $this->createFileJson($path'Request content: request to -> ' $dataPost "\r");
  3436.                     $url $this->realContainer->getParameter('level_scheme') . '://' $this->realContainer->getParameter('level_host') . $this->generateUrl('level_web_service_sync_data_web');
  3437.                     $this->createFileJson($path'Request content: request url -> ' $url "\r");
  3438.                     $ch curl_init($url);
  3439.                     curl_setopt($chCURLOPT_POSTtrue);
  3440.                     curl_setopt($chCURLOPT_HTTPHEADER$arrHead);
  3441.                     curl_setopt($chCURLOPT_POSTFIELDS$dataPost);
  3442.                     curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
  3443.                     $response curl_exec($ch);
  3444.                     curl_close($ch);
  3445.                     $this->createFileJson($path'Request Response: ' $response "\r");
  3446.                     $responseData Util::decryptDataForAndroid($this->realContainer$response);
  3447.                     $responseDecData json_decode($responseData['data']);
  3448.                     $responseArr['status'] = WebService::CODE_SUCCESS;
  3449.                     if (!empty($responseDecData->result) && $responseDecData->result == '__OK__') {
  3450.                         if (empty($responseDecData->msg)) {
  3451.                             $responseArr['status'] = 70;
  3452.                             $responseArr['msg'] = 'Synchronization triggered..';
  3453.                         } else {
  3454.                             $responseArr['status'] = 60;
  3455.                             $responseArr['msg'] = $responseDecData->msg;
  3456.                         }
  3457.                         $this->createFileJson($path'Request answered msg: ' $responseArr['msg'] . "\r");
  3458.                         $idToWebSyncConsumer $responseDecData->syncid;
  3459.                         $this->createFileJson($path'Searching sync with id: ' $idToWebSyncConsumer "\r");
  3460.                         $syncWebRecord $em->getRepository('App\Entity\ReadFilesDataWeb')->find($idToWebSyncConsumer);
  3461.                         if ($syncWebRecord) {
  3462.                             sleep(4);
  3463.                             $this->createFileJson($path'Instant Request pre if -> ' $syncWebRecord->getIsReadedByServer() . ' | ' $syncWebRecord->getRfwStatus() . "\r");
  3464.                             if ($syncWebRecord->getIsReadedByServer() && ReadFilesDataWeb::STATUS_NOTIFIED == $syncWebRecord->getRfwStatus()) {
  3465.                                 $em->clear();
  3466.                                 $data['rwid'] = $syncWebRecord->getId();
  3467.                                 ForcedAsynchronousCommandsUtil::consumeUpDownSyncCommand($this->realContainer$datatrue);
  3468.                                 $this->createFileJson($path'Instant Request Proccessed!' "\r");
  3469.                                 $responseArr['status'] = WebService::CODE_SUCCESS;
  3470.                                 $responseArr['msg'] = 'Server processing new data, please check for the new data in a few seconds!';
  3471.                             } else {
  3472.                                 $responseArr['status'] = 80;
  3473.                                 $responseArr['msg'] = 'Server is working... Please try 20 seconds latter!';
  3474.                             }
  3475.                         } else {
  3476.                             if ($idToWebSyncConsumer == 0) {
  3477.                                 $this->createFileJson($path'Instant Request Push Resend.....' "\r");
  3478.                                 $responseArr['status'] = 90;
  3479.                                 $responseArr['msg'] = 'Unanswered push by android server....';
  3480.                             } else {
  3481.                                 $this->createFileJson($path'Instant Request Auch -> License sync web record not found!' "\r");
  3482.                                 return $this->setStatusCode(WebService::CODE_OBJECT_NOT_FOUND)
  3483.                                                 ->respondWithError('License sync web record not found!'WebService::CODE_OBJECT_NOT_FOUND);
  3484.                             }
  3485.                         }
  3486.                     } else {
  3487.                         if (isset($response->error->message)) {
  3488.                             $responseArr['msg'] = $response->error->message;
  3489.                         } else {
  3490.                             $responseArr['status'] = 100;
  3491.                             $responseArr['msg'] = 'Nothing to synchronize';
  3492.                         }
  3493.                     }
  3494.                     $theUrlTrSt = new RespondedNotificationPushTransformer($responseArr);
  3495.                     $xxArray $theUrlTrSt->transform();
  3496.                     $jsonContent json_encode($xxArray);
  3497.                     return $this->respondWithItem($jsonContent$theUrlTrSt);
  3498.                 } else {
  3499.                     return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  3500.                                     ->respondWithError('Invalid nickname'WebService::CODE_UNAUTHORIZED);
  3501.                 }
  3502.             } else {
  3503.                 return $this->errorWrongArgs('Bad request'WebService::CODE_UNAUTHORIZED);
  3504.             }
  3505.         } else {
  3506.             return $this->errorNotAllowedMethod('Method not allowed. Use ' WebService::REQUEST_METHOD_POST " method");
  3507.         }
  3508.     }
  3509.     /**
  3510.      * WS que permite verificar el login de level lite
  3511.      * @author Felipe Bautista <aarango@uva3.com> 10/04/2019
  3512.      * @param \Symfony\Component\HttpFoundation\Request $request datos de la solicitud
  3513.      * @return Response Json con la informacion de respuesta
  3514.      */
  3515.     public function checkLoginLevel(Request $request) {
  3516.         $em $this->getDoctrine()->getManager();
  3517.         $path Util::getValidActiveLogByBaseName($this->realContainer'checkLoginLevel''requestFromWebYYY0.txt');
  3518.         $paramsIdLicense $request->request->get('id_license');
  3519.         if ($paramsIdLicense == null) {
  3520.             $paramsIdLicense $request->query->get('id_license');
  3521.         }
  3522.         $accountLicenseData $em->getRepository('App\Entity\AccountLicense')->find($paramsIdLicense);
  3523.         if (isset($accountLicenseData)) {
  3524.             if ($accountLicenseData->getLevelLightUser() !== "" && $accountLicenseData->getLevelLightUser() !== []) {
  3525.                 $userData $accountLicenseData->getLevelLightUser();
  3526.                 $apikey Util::doOMTDashboardLoginToGetToken($this->realContainer$userData$path$accountLicenseData->getLoginType());
  3527.                 if (!empty($apikey)) {
  3528.                     $userData['apikey'] = $apikey;
  3529.                     $responseArr['apikey'] = $apikey;
  3530.                 } else {
  3531.                     $responseArr['apikey'] = '';
  3532.                 }
  3533.                 if (isset($responseArr['apikey']) || $accountLicenseData->getHasLogedOMT() == false) {
  3534.                     // $createDefaultUserOmt = Util::makeOMTDefaultDashboardsUserInsertRequest($this->realContainer, $userData, $path);
  3535.                     /**
  3536.                      * Allows to add the apikey to the user of lite level this exported in OMT
  3537.                      */
  3538.                     if ($accountLicenseData->getHasLogedOMT() == true || $accountLicenseData->getIsLevelLight() == true) {
  3539.                         $accountLicenseData->setLevelLightUser($userData);
  3540.                         $em->persist($accountLicenseData);
  3541.                         $em->flush();
  3542.                         $responseToAjax['msg'] = 'Login successfull';
  3543.                         $responseToAjax['result'] = '__OK__';
  3544.                     }
  3545.                     $auxRepository $em->getRepository('App\Entity\AccountLicense');
  3546.                     $connectionRecord $auxRepository->find($paramsIdLicense);
  3547.                     $emLev Util::emLicenseConnection($this->realContainer$em$connectionRecord);
  3548.                     $userLevelLite $emLev->getRepository('App\Structure\Usuario')->findBy(['usuLogin' => $userData['username']]);
  3549.                     if (!isset($userLevelLite[0])) {
  3550.                         $responseToAjax['msg'] = (isset($responseToAjax['msg'])) ? $responseToAjax['msg'] . " and user level lite create" "User level lite created";
  3551.                         $responseToAjax['result'] = '__OK__';
  3552.                         $levelUser = new Usuario();
  3553.                         $levelUser->setUsuNombre($userData['username']);
  3554.                         $levelUser->setUsuApellido($userData['username']);
  3555.                         $levelUser->setUsuTelefono($accountLicenseData->getAlPhoneNumber());
  3556.                         $levelUser->setUsuEmail($accountLicenseData->getAlLicenseEmail());
  3557.                         $levelUser->setUsuTipo(Usuario::USU_TYPE_MANAGER);
  3558.                         $levelUser->setUsuEstado(Usuario::STATUS_IS_ACTIVE);
  3559.                         $levelUser->setUsuLogin($userData['username']);
  3560.                         $levelUser->setUsuSalary(0.000000);
  3561.                         $actualDate Util::getCurrentDate();
  3562.                         $levelUser->setUsuCreation($actualDate);
  3563.                         $encodeLevelWebPass Util::encryptOwnReverseMD5($userData['realPass']);
  3564.                         $levelUser->setUsuPass($encodeLevelWebPass);
  3565.                         $levelUser->setUsuAccessCode($encodeLevelWebPass);
  3566.                         $levelUser->setUsuAcccessCode2($encodeLevelWebPass);
  3567.                         $levelUser->setUsuEmployecard($encodeLevelWebPass);
  3568.                         $levelUser->setUsuFirstLogin(1);
  3569.                         $emLev->persist($levelUser);
  3570.                         $emLev->flush();
  3571.                     } else if ($accountLicenseData->getHasLogedOMT() == false) {
  3572.                         $responseToAjax['msg'] = 'The level lite user exists on levelweb!';
  3573.                         $responseToAjax['result'] = '__OK__';
  3574.                     }
  3575.                 } else {
  3576.                     $responseToAjax['msg'] = 'Error in the login level lite!';
  3577.                     $responseToAjax['result'] = '__KO__';
  3578.                 }
  3579.             } else {
  3580.                 $responseToAjax['msg'] = 'Level lite user not found!';
  3581.                 $responseToAjax['result'] = '__KO__';
  3582.             }
  3583.         } else {
  3584.             $responseToAjax['msg'] = 'License Not Found!';
  3585.             $responseToAjax['result'] = '__KO__';
  3586.         }
  3587.         return $this->respondJsonAjax($responseToAjax);
  3588.     }
  3589.     /**
  3590.      * WS para el boton de sincronizacion all in one que realiza todas las
  3591.      * en el orden correspondiente en cascada
  3592.      * @author Aealan Zulalecius <lrobledo@kijho.com> 01/06/16
  3593.      * @param \Symfony\Component\HttpFoundation\Request $request datos de la solicitud
  3594.      * @return Response Json con la informacion de respuesta
  3595.      */
  3596.     public function theUltimateSyncAllOneButton(Request $request) {
  3597.         // dump($request);die;
  3598.         // $start = microtime(true);
  3599.         // while (false) {
  3600.         // }
  3601.         // $time_elapsed_secs = microtime(true) - $start;
  3602.         //////////////
  3603.         // $start = hrtime(true);
  3604.         // sleep(5); // do something, in your case a loop
  3605.         // $end = hrtime(true);
  3606.         // $eta = $end - $start;
  3607.         // // convert nanoseconds to milliseconds
  3608.         // $eta /= 1e+6;
  3609.         if ($request->getMethod() !== WebService::REQUEST_METHOD_POST) {
  3610.             return $this->errorNotAllowedMethod('Method not allowed. Use ' WebService::REQUEST_METHOD_POST " method");
  3611.         }
  3612.             
  3613.         if (!== strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_STRUCTURE) && !== strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_TEXT)) {
  3614.             return $this->errorWrongArgs('Bad request'WebService::CODE_UNAUTHORIZED);
  3615.         }
  3616.         $path Util::getValidActiveLogByBaseName($this->realContainer'UltimateSyncAllOneButton''UltimateSyncAllOneButton0.txt');
  3617.         $this->createFileJson($path"\r" 'Sync all showtime! ' "\r");
  3618.         $this->createFileJson($path'The request -> ' $request->getContent() . "\r");
  3619.         $arrayEncryptResult Util::decryptDataForAndroid($this->realContainer$request->getContent());
  3620.         
  3621.         $data json_decode($arrayEncryptResult['data'], true);
  3622.         if (!isset($data['nickname']) || !isset($data['uid'])) {
  3623.             return $this->errorWrongArgs('Wrong arguments'WebService::CODE_COULD_NOT_AUTHENTICATE);
  3624.         }
  3625.         $licenseUserName = ['alLicenseUsername' => $data['nickname']];
  3626.         $em $this->getDoctrine()->getManager();
  3627.         $accountLicenseData $em->getRepository('App\Entity\AccountLicense')->findBy($licenseUserName);
  3628.         
  3629.         $countResult count($accountLicenseData);
  3630.         $this->createFileJson($path'License count -> ' $countResult "\r");
  3631.         if ($countResult <= 0) {
  3632.             return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  3633.                             ->respondWithError('Invalid nickname'WebService::CODE_UNAUTHORIZED);
  3634.         }
  3635.         $license $accountLicenseData[0];
  3636.         if ($license->getAlAccountLicense()->getDeleted()) {
  3637.             $this->createFileJson($path'Deleted license! ' "\r");
  3638.             return $this->errorWrongArgs('Account inactive, please contact your system manager'WebService::CODE_UNAUTHORIZED);
  3639.         }
  3640.         if (!$license->getAlLicenseStatus()) {
  3641.             $this->createFileJson($path'Incative license! ' "\r");
  3642.             return $this->errorWrongArgs('License inactive, please contact your system manager'WebService::CODE_UNAUTHORIZED);
  3643.         }
  3644.         if ($license->getDeviceUid() != $data['uid']) {
  3645.             $this->createFileJson($path'Wrong UID -> espected:  ' $license->getDeviceUid() . ' found: ' $data['uid'] . "\r");
  3646.             return $this->errorWrongArgs('Unauthorized device'WebService::CODE_UNAUTHORIZED);
  3647.         }
  3648.         $syncAllCallStatus $em->getRepository('App\Entity\SyncAllCallStatus')->syncCallStatusPerLicense($license);
  3649.         if(!is_null($syncAllCallStatus) && $syncAllCallStatus->getPublishMessageStatus() == SyncAllCallStatus::SYNC_MESSAGE_ERROR && is_null($syncAllCallStatus->getDateNotified())){
  3650.             $responseArr json_decode($syncAllCallStatus->getErrorMessage(), true);
  3651.             $syncAllCallStatus->setDateNotified(Utilx::getCurrentDate());
  3652.             $em->persist($syncAllCallStatus);
  3653.             $em->flush();
  3654.             if (!isset($responseArr['status'])) {
  3655.                 $responseArr['status'] = WebService::CODE_OBJECT_NOT_FOUND;
  3656.             }
  3657.             return $this->setStatusCode($responseArr['status'])
  3658.                                     ->respondWithError($responseArr['msg'], $responseArr['status']);
  3659.         } else if(!is_null($syncAllCallStatus) && $syncAllCallStatus->getPublishMessageStatus() == SyncAllCallStatus::SYNC_MESSAGE_FINISHED && is_null($syncAllCallStatus->getDateNotified())){
  3660.             $responseArr json_decode($syncAllCallStatus->getResponseBySync(), true);
  3661.             $syncAllCallStatus->setDateNotified(Utilx::getCurrentDate());
  3662.             $em->persist($syncAllCallStatus);
  3663.             $em->flush();
  3664.             $responseArr['msjTwo'] = $this->resultAndNewSync($path$license$data$syncAllCallStatus$em);
  3665.             if (!isset($responseArr['status'])) {
  3666.                 $responseArr['status'] = WebService::CODE_SUCCESS;
  3667.             }
  3668.         } else if (is_null($syncAllCallStatus) || (!is_null($syncAllCallStatus) && ($syncAllCallStatus->getPublishMessageStatus() == SyncAllCallStatus::SYNC_MESSAGE_ERROR || $syncAllCallStatus->getPublishMessageStatus() == SyncAllCallStatus::SYNC_MESSAGE_FINISHED))) {
  3669.             $responseArr $this->resultAndNewSync($path$license$data$syncAllCallStatus$em); 
  3670.         } else if(!is_null($syncAllCallStatus) && ($syncAllCallStatus->getPublishMessageStatus() == SyncAllCallStatus::SYNC_MESSAGE_PROCESSING || $syncAllCallStatus->getPublishMessageStatus() == SyncAllCallStatus::SYNC_MESSAGE_PUBLISHED)){
  3671.             $responseArr = ['msg' => 'You have a synchronization process running''status' => WebService::CODE_SUCCESS'result' => '__OK__''response_code' => WebService::CODE_SUCCESS];
  3672.         } else {
  3673.             if (!is_null($syncAllCallStatus)) {
  3674.                 $this->createFileJson($path"wata fack, que estado tiiene sabiendo que abarque todas las condiciones, checar datos:
  3675.                                                 id: {$syncAllCallStatus->getId()} \n
  3676.                                                 publishMessageStatus: {$syncAllCallStatus->getPublishMessageStatus()} \n
  3677.                                                 errorMessage: {$syncAllCallStatus->getErrorMessage()} \n
  3678.                                                 responseBySync: {$syncAllCallStatus->getResponseBySync()} \n
  3679.                                             \r");
  3680.             } else {
  3681.                 $this->createFileJson($path"wata fack, que estado tiiene sabiendo que abarque todas las condiciones, sync all call status es nulo !!!! \r");
  3682.             }
  3683.             $responseArr = ['msg' => 'Please contact with support''status' => WebService::HTTP_CODE_NOT_FOUND'result' => '__KO__'];
  3684.         }
  3685.         $theUrlTrSt = new LicensorGenericTransformer($this->realContainer$responseArr);
  3686.         $xxArray $theUrlTrSt->transform();
  3687.         $jsonContent json_encode($xxArray);
  3688.         $this->createFileJson($path'The theUltimateSyncAllOneButton response -> ' $jsonContent "\r");
  3689.         return $this->respondWithItem($jsonContent$theUrlTrSt);
  3690.     }
  3691.     function resultAndNewSync($path$license$data$syncAllCallStatus$em) {
  3692.         $dataToProducer = ['path' => $path'id' => $license->getId(), 'data' => $data'syncFullVersion' => SyncFullCallConsumer::SYNC_FULL_WEB_SERVICE_VERSION];
  3693.         $this->realContainer->get('old_sound_rabbit_mq.sync_full_call_producer')->setContentType('application/json');
  3694.         $this->realContainer->get('old_sound_rabbit_mq.sync_full_call_producer')->setDeliveryMode(2);
  3695.         $this->realContainer->get('old_sound_rabbit_mq.sync_full_call_producer')->publish(json_encode($dataToProducer));
  3696.         $counterNewPetition 1;
  3697.         if (is_null($syncAllCallStatus)) {
  3698.             $syncAllCallStatus = new SyncAllCallStatus();
  3699.             $syncAllCallStatus->setLicense($license->getId());
  3700.         }else{
  3701.             $counterNewPetition $syncAllCallStatus->getCounterPetitions() + $counterNewPetition;
  3702.         }
  3703.         
  3704.         $syncAllCallStatus->setCounterPetitions($counterNewPetition);
  3705.         $syncAllCallStatus->setPublishMessageStatus(SyncAllCallStatus::SYNC_MESSAGE_PUBLISHED);
  3706.         $syncAllCallStatus->setDateChangeStatus(Utilx::getCurrentDate());
  3707.         $syncAllCallStatus->setDateNotified(null); // Reiniciamos el campo desde el principio para que en realidad notifique
  3708.         
  3709.         $em->persist($syncAllCallStatus);
  3710.         $em->flush();
  3711.         $command "php "$this->realContainer->getParameter('kernel.project_dir') ."/bin/console sync:call:consumer";
  3712.         shell_exec("$command > /dev/null & echo!");
  3713.         return ['msg' => 'You have a synchronization process running''status' => WebService::CODE_SUCCESS'result' => '__OK__''response_code' => WebService::CODE_SUCCESS];
  3714.     }
  3715.     /**
  3716.      * @author Felipe Arango <aarango@uva3.com> 28/01/2021
  3717.      * @param type $masterSyncRecord
  3718.      * @param type $responseArr
  3719.      * @param type $path
  3720.      */
  3721.     public function resetSyncAll(Request $request) {
  3722.         try {
  3723.             if ($request->getMethod() === WebService::REQUEST_METHOD_GET || $request->getMethod() === WebService::REQUEST_METHOD_POST) {
  3724.                 $path Util::getValidActiveLogByBaseName($this->realContainer'resetSync''resetSync0.txt');
  3725.                 $em $this->getDoctrine()->getManager();
  3726.                 
  3727.                 if ($request->getMethod() === WebService::REQUEST_METHOD_GET){
  3728.                     $this->createFileJson($path'get parameters => 'json_encode($request->query->all()) . "\r");
  3729.                     $nickname $request->query->get("nickname");
  3730.                 }
  3731.                 if ($request->getMethod() === WebService::REQUEST_METHOD_POST) {
  3732.                     $this->createFileJson($path'post parameters => '$request->getContent() . "\r");
  3733.                     $arrayEncryptResult Util::decryptDataForAndroid($this->realContainer$request->getContent());
  3734.                     $data json_decode($arrayEncryptResult['data'], true);
  3735.                     $nickname $data['nickname'];
  3736.                 }
  3737.     
  3738.                 if ($nickname == null) {
  3739.                     $this->createFileJson($path'NicknName Undefined! ' "\r");
  3740.                     return $this->errorWrongArgs('NicknName Undefined!'WebService::CODE_UNAUTHORIZED);
  3741.                 }
  3742.     
  3743.                 $accountLicenseData $em->getRepository('App\Entity\AccountLicense')->findOneBy(["alLicenseUsername" => $nickname]);
  3744.     
  3745.                 if (isset($accountLicenseData)) {
  3746.     
  3747.                     if ($accountLicenseData->getAlAccountLicense()->getDeleted()) {
  3748.                         $this->createFileJson($path'Deleted license! ' "\r");
  3749.                         return $this->errorWrongArgs('Account inactive, please contact your system manager'WebService::CODE_UNAUTHORIZED);
  3750.                     }
  3751.     
  3752.                     if (!$accountLicenseData->getAlLicenseStatus()) {
  3753.                         $this->createFileJson($path'Inactive license! ' "\r");
  3754.                         return $this->errorWrongArgs('License inactive, please contact your system manager'WebService::CODE_UNAUTHORIZED);
  3755.                     }
  3756.     
  3757.                     $resultResetSync $em->getRepository('App\Entity\MasterSync')->resetSyncByLicense($accountLicenseData->getId(), $accountLicenseData->getHasLogedOMT());
  3758.     
  3759.                     $licenseDataBaseEntity $em->getRepository('App\Entity\LicenseDataBase')->findOneBy(['license' => $accountLicenseData->getId()]);
  3760.     
  3761.                     $dataOptionsRoot = [
  3762.                         'dbname' => $licenseDataBaseEntity->getDbname(),
  3763.                         'user' => $licenseDataBaseEntity->getDbuser(),
  3764.                         'password' => $licenseDataBaseEntity->getDbpass(),
  3765.                         'host' => $licenseDataBaseEntity->getDbhost(),
  3766.                         'driver' => 'pdo_mysql',
  3767.                     ];
  3768.     
  3769.                     $emLev Util::emCreateConfiguration($this->realContainer$dataOptionsRoot);
  3770.     
  3771.                     $resultResetSync += $emLev->getRepository('App\Structure\RegistActions')->resetDataRegistAction();
  3772.                     $resultResetSync += $emLev->getRepository('App\Structure\Configuracion')->resetDataConfiguration();
  3773.                     $this->createFileJson($path"rows affected -> $resultResetSync \r");
  3774.     
  3775.                     $responseArr['bigbag'] = true;
  3776.                     $responseArr['result'] = '__OK__';
  3777.                     $responseArr['msg'] = 'Successful synchronization reset';
  3778.                     $responseArr['status'] = WebService::CODE_SUCCESS;
  3779.     
  3780.                     $theUrlTrSt = new LicensorGenericTransformer($this->realContainer$responseArr);
  3781.                     $xxArray $theUrlTrSt->transform();
  3782.     
  3783.                     $jsonContent json_encode($xxArray);
  3784.     
  3785.                     return $this->respondWithItem($jsonContent$theUrlTrSt);
  3786.                 } else {
  3787.                     $this->createFileJson($path'Invalid nickname ' "\r");
  3788.                     return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  3789.                                     ->respondWithError('Invalid nickname'WebService::CODE_UNAUTHORIZED);
  3790.                 }
  3791.             } else {
  3792.                 return $this->errorNotAllowedMethod('Method not allowed. Use ' WebService::REQUEST_METHOD_GET " method or " WebService::REQUEST_METHOD_POST " method");
  3793.             }
  3794.         } catch (\Throwable $th) {
  3795.             $err = ['Error message' => $th->getMessage(), 'Error Line' => $th->getLine(), 'Error File' => $th->getFile(), 'Error Trance' => $th->getTrace()];
  3796.             $this->createFileJson($path"error detected "json_encode($err) ." \r");
  3797.             return $this->setStatusCode(WebService::HTTP_CODE_INTERNAL_ERROR)
  3798.                                     ->respondWithError($errWebService::HTTP_CODE_INTERNAL_ERROR);
  3799.         }
  3800.     }
  3801.     /**
  3802.      * @author Aealan Z <lrobledo@kijho.com> 11/06/2016
  3803.      * @param type $masterSyncRecord
  3804.      * @param type $responseArr
  3805.      * @param type $path 
  3806.      */
  3807.     public function sendMailForUnansweredSyncPush($masterSyncRecord$responseArr$license$path) {
  3808.         $body "<p><label>Server: <strong>http://" $this->realContainer->getParameter("licensor_base_url") . "/licensor/login</strong></label><br></p>";
  3809.         $theUnansweredPush $masterSyncRecord[0]['msPushRecord'];
  3810.         $type 1;
  3811.         if (!$theUnansweredPush) {
  3812.             $type 2;
  3813.         }
  3814.         if ($type == 1) {
  3815.             $body .= "<label>Unanswered sync push detected...</label><br>";
  3816.             $body .= "<label>Unanswered push id:  <strong>" $theUnansweredPush "</strong></label><br>";
  3817.         } else {
  3818.             $body .= "<label>Unabled to send push...</label><br>";
  3819.         }
  3820.         $body .= "<label>Message delivered to android server <strong>" $responseArr['msg'] . "</strong></label><br>";
  3821.         $body .= "<label>Master Sync Number: <strong>" $masterSyncRecord[0]['id'] . "</strong></label><br>";
  3822.         $body .= "<label>License: <strong>" $license "</strong></label><br>";
  3823.         $emailsToNotify $this->realContainer->getParameter('level_emails_syncs_errors');
  3824.         if ($type == 1) {
  3825.             $respArray['subject'] = "Unanswered Sync Push In " $license->getAlLicenseUsername() . " License";
  3826.         } else {
  3827.             $respArray['subject'] = "Unabled To Send Push To " $license->getAlLicenseUsername() . " License Requested Sync";
  3828.         }
  3829.         $this->createFileJson($path"The subject: " $respArray['subject'] . "\r");
  3830.         $respArray['message'] = "";
  3831.         foreach ($emailsToNotify as $mailTo) {
  3832.             $this->createFileJson($path"Mail to -> " $mailTo "\r");
  3833.             $respArray['to'] = $mailTo;
  3834.             // Utilx::sendMailInfo($this->realContainer, $respArray, $path, $body);
  3835.         }
  3836.     }
  3837.     /**
  3838.      * Funcion polling que verifica si el push de sincronizacion de arriba a
  3839.      * abajo fue enviado
  3840.      * @author Aealan Z <lrobledo@kijho.com> 11/06/2016
  3841.      * @param type $masterSyncRecord registro maestro de la sincronizacion
  3842.      * @return boolean indicando que el push de de la sincronizacion fue enviado
  3843.      */
  3844.     public function checkForWebPushSend($masterSyncRecord$path null) {
  3845.         $responseToPolling = [];
  3846.         $auxCounter 0;
  3847.         $keepInWhile true;
  3848.         $masterSyncId $masterSyncRecord['id'];
  3849.         if (!is_null($path)) {
  3850.             $this->createFileJson($path'Checking push send....' "\r");
  3851.         }
  3852.         $em $this->getDoctrine()->getManager();
  3853.         do {
  3854.             sleep(3);
  3855.             ++$auxCounter;
  3856.             $masterSyncRecord $em->getRepository('App\Entity\ReadFilesDataWeb')->getTheMasterSyncArrayRecordById($masterSyncIdtrue);
  3857.             if (!is_null($path) && !empty($masterSyncRecord)) {
  3858.                 $this->createFileJson($path"Checking push in'" $masterSyncId "' master sync record...  \r");
  3859.                 $this->createFileJson($path".. and the push...? " json_encode($masterSyncRecord[0]['msPushRecord']) . "\r");
  3860.             }
  3861.             if (!empty($masterSyncRecord) && is_null($masterSyncRecord[0]['msPushRecord']) && $auxCounter 7) {
  3862.                 sleep(1);
  3863.                 $keepInWhile true;
  3864.                 $responseToPolling['msg'] = 'Awaiting for push send....';
  3865.                 $responseToPolling['response_code'] = WebService::SYNC_RESPONSE_PROCESSED;
  3866.                 $responseToPolling['wasAnswered'] = true;
  3867.                 $responseToPolling['masterRecord'] = $masterSyncRecord[0];
  3868.             } else {
  3869.                 if ($masterSyncRecord[0]['msPushRecord']) {
  3870.                     $keepInWhile false;
  3871.                     $responseToPolling['msg'] = 'Push send... going forward whith the synchronization!';
  3872.                     $responseToPolling['response_code'] = WebService::SYNC_RESPONSE_PROCESSED;
  3873.                     $responseToPolling['wasAnswered'] = true;
  3874.                     $responseToPolling['masterRecord'] = $masterSyncRecord[0];
  3875.                 } elseif ($auxCounter >= 14) {
  3876.                     $keepInWhile false;
  3877.                     if (!$masterSyncRecord[0]['msPushRecord']) {
  3878.                         $responseToPolling['msg'] = 'Waiting maximum time has been reached for push send.. Please try again later!';
  3879.                         $responseToPolling['response_code'] = WebService::MAXIMUM_WAIT_TIME_REACHED;
  3880.                         $responseToPolling['wasAnswered'] = false;
  3881.                         $responseToPolling['masterRecord'] = $masterSyncRecord[0];
  3882.                     }
  3883.                 } elseif ($masterSyncRecord[0]['loginType'] == AccountLicense::LOGGED_BY_LEVEL_LITE && $masterSyncRecord[0]['hasLogedOMT']) {
  3884.                     $keepInWhile false;
  3885.                     if ($masterSyncRecord[0]['msPushRecord']) {
  3886.                         $pushArray $em->getRepository('App\Entity\PushSent')->getThePushSentArrayRecordById($masterSyncRecord[0]['msPushRecord']);
  3887.                         if (!empty($pushArray) && $pushArray[0]['omtCurlStatus'] == PushSent::STATUS_CURL_FINISHED) {
  3888.                             $responseToPolling['msg'] = 'Sync no needed..';
  3889.                             $responseToPolling['response_code'] = WebService::SYNC_DONE_SUCCESSFULLY;
  3890.                             $responseToPolling['wasAnswered'] = true;
  3891.                             $responseToPolling['masterRecord'] = $masterSyncRecord[0];
  3892.                         }
  3893.                     }
  3894.                 }
  3895.             }
  3896.             $em->clear();
  3897.         } while ($keepInWhile && $auxCounter 14);
  3898.         return $responseToPolling;
  3899.     }
  3900.     /**
  3901.      * Funcion polling que verifica si el push de sincronizacion de arriba a
  3902.      * abajo fue enviado
  3903.      * @author Aealan Z <lrobledo@kijho.com> 11/06/2016
  3904.      * @param type $masterSyncRecord registro maestro de la sincronizacion
  3905.      * @return boolean indicando que el push de de la sincronizacion fue enviado
  3906.      */
  3907.     public function checkForWebPushSendOMT($masterSyncRecord$path null) {
  3908.         $responseToPolling = [];
  3909.         $auxCounter 0;
  3910.         $keepInWhile true;
  3911.         $masterSyncId $masterSyncRecord->getId();
  3912.         if (!is_null($path)) {
  3913.             $this->createFileJson($path'Checking push send....' "\r");
  3914.         }
  3915.         $em $this->getDoctrine()->getManager();
  3916.         do {
  3917.             sleep(3);
  3918.             ++$auxCounter;
  3919.             $masterSyncRecord $em->getRepository('App\Entity\MasterSync')->find($masterSyncId);
  3920.             if (!is_null($path) && $masterSyncRecord) {
  3921.                 $this->createFileJson($path"Checking push in'" $masterSyncId "' master sync record...  \r");
  3922.                 $this->createFileJson($path".. and the push...? " json_encode($masterSyncRecord->getMsPushRecord()) . "\r");
  3923.             }
  3924.             if ($masterSyncRecord && (is_null($masterSyncRecord->getMsPushRecord()) || is_null($masterSyncRecord->getMsPushRecord()->getOmtCurlStatus()))) {
  3925.                 sleep(1);
  3926.                 $keepInWhile true;
  3927.                 $responseToPolling['msg'] = 'Awaiting response from the curl!!!!!!!!!!';
  3928.                 $responseToPolling['response_code'] = WebService::SYNC_RESPONSE_PROCESSED;
  3929.                 $responseToPolling['wasAnswered'] = true;
  3930.                 $responseToPolling['masterRecord'] = $masterSyncRecord;
  3931.             } else {
  3932.                 if ($masterSyncRecord->getMsPushRecord()->getOmtCurlStatus() == PushSent::STATUS_CURL_PENDING) {
  3933.                     $keepInWhile false;
  3934.                     $responseToPolling['msg'] = 'Push send... going forward whith the synchronization!';
  3935.                     $responseToPolling['response_code'] = WebService::SYNC_RESPONSE_PROCESSED;
  3936.                     $responseToPolling['wasAnswered'] = true;
  3937.                     $responseToPolling['masterRecord'] = $masterSyncRecord;
  3938.                 } elseif ($auxCounter >= 14) {
  3939.                     $keepInWhile false;
  3940.                     if ($masterSyncRecord->getMsPushRecord()->getOmtCurlStatus() == PushSent::STATUS_CURL_PENDING || $masterSyncRecord->getMsPushRecord()->getOmtCurlStatus() == PushSent::STATUS_CURL_RESPONDED) {
  3941.                         $responseToPolling['msg'] = 'Waiting maximum time has been reached for push send.. Please try again later!';
  3942.                         $responseToPolling['response_code'] = WebService::MAXIMUM_WAIT_TIME_REACHED;
  3943.                         $responseToPolling['wasAnswered'] = false;
  3944.                         $responseToPolling['masterRecord'] = $masterSyncRecord;
  3945.                     }
  3946.                 } elseif ($masterSyncRecord->getMsLicense()->getLoginType() == AccountLicense::LOGGED_BY_LEVEL_LITE && $masterSyncRecord->getMsLicense()->getHasLogedOMT()) {
  3947.                     $keepInWhile false;
  3948.                     if ($masterSyncRecord->getMsPushRecord()->getOmtCurlStatus() == PushSent::STATUS_CURL_FINISHED) {
  3949.                         $responseToPolling['msg'] = 'Sync no needed..';
  3950.                         $responseToPolling['response_code'] = WebService::SYNC_DONE_SUCCESSFULLY;
  3951.                         $responseToPolling['wasAnswered'] = true;
  3952.                         $responseToPolling['masterRecord'] = $masterSyncRecord;
  3953.                     }
  3954.                 }
  3955.             }
  3956.             $em->clear();
  3957.         } while ($keepInWhile && $auxCounter 14);
  3958.         return $responseToPolling;
  3959.     }
  3960.     /**
  3961.      * Funcion polling para verificar si el push de la sincronizacion de arriba
  3962.      * a abajo fue respondido
  3963.      * @author Aealan Z <lrobledo@kijho.com> 11/06/2016
  3964.      * @param type $unrespondedPush registro del push de sincronizacion de arriba a abajo enviado
  3965.      * @return boolean que indica si fue respondido o no el push
  3966.      */
  3967.     public function checkForWebPushResponse($unrespondedPush$path) {
  3968.         $responseToPolling = [];
  3969.         $auxCounter 0;
  3970.         $keepInWhile true;
  3971.         $this->createFileJson($path'Checking push response....' "\r");
  3972.         $this->createFileJson($path'Checking push -> ' $unrespondedPush[0]['id'] . "\r");
  3973.         $em $this->getDoctrine()->getManager();
  3974.         do {
  3975.             sleep(3);
  3976.             ++$auxCounter;
  3977.             $pushArray $em->getRepository('App\Entity\PushSent')->getThePushSentArrayRecordById($unrespondedPush[0]['id']);
  3978.             // $unrespondedPush = $em->getRepository('App\Entity\PushSent')->find($unrespondedPush->getId());
  3979.             if ($pushArray[0]['pushStatus'] == PushSent::STATUS_PUSH_READED) {
  3980.                 $keepInWhile false;
  3981.                 $responseToPolling['msg'] = 'Push answered.. going forward whith the synchronization!';
  3982.                 $responseToPolling['response_code'] = WebService::SYNC_RESPONSE_PROCESSED;
  3983.                 $responseToPolling['wasAnswered'] = true;
  3984.             } elseif ($auxCounter >= 14) {
  3985.                 $keepInWhile false;
  3986.                 if ($pushArray[0]['pushStatus'] == PushSent::STATUS_PUSH_PENDING) {
  3987.                     $responseToPolling['msg'] = 'Waiting maximum time has been reached for push answer.. Please try again later!';
  3988.                     $responseToPolling['response_code'] = WebService::MAXIMUM_WAIT_TIME_REACHED;
  3989.                     $responseToPolling['wasAnswered'] = false;
  3990.                 }
  3991.             } elseif ($pushArray[0]['loginType'] == AccountLicense::LOGGED_BY_LEVEL_LITE && $pushArray[0]['hasLogedOMT']) {
  3992.                 $unrespondedPushEntity $em->getRepository('App\Entity\PushSent')->find($unrespondedPush[0]['id']);
  3993.                 $unrespondedPushEntity->setPushStatus(PushSent::STATUS_PUSH_READED);
  3994.                 $unrespondedPushEntity->setRespondDate($unrespondedPushEntity->getRespondDate());
  3995.                 $em->persist($unrespondedPushEntity);
  3996.                 $em->flush();
  3997.                 $responseToPolling['msg'] = 'Automatic closure for unprocedent push!';
  3998.                 $responseToPolling['response_code'] = WebService::SYNC_RESPONSE_PROCESSED;
  3999.                 $responseToPolling['wasAnswered'] = true;
  4000.                 $keepInWhile false;
  4001.             } else {
  4002.                 $em->clear();
  4003.             }
  4004.         } while ($keepInWhile && $auxCounter 14);
  4005.         return $responseToPolling;
  4006.     }
  4007.     /**
  4008.      * Funcion polling para determinar si fue respondida la sincronizacion de arriba
  4009.      * a abajo por el servidor android
  4010.      * @author Aealan Z <lrobledo@kijho.com> 11/06/2016
  4011.      * @param type $syncWebRecord registro de la sincronizacion web
  4012.      * @return boolean que indica si fue respondida o no la sincronizacion web
  4013.      */
  4014.     public function checkForWebResponse($syncWebRecord$path) {
  4015.         $responseToPolling = [];
  4016.         $auxCounter 0;
  4017.         $keepInWhile true;
  4018.         $this->createFileJson($path'Checking sync web response....' "\r");
  4019.         $em $this->getDoctrine()->getManager();
  4020.         do {
  4021.             sleep(3);
  4022.             ++$auxCounter;
  4023.             $syncWebRecord $em->getRepository('App\Entity\ReadFilesDataWeb')->getTheWebSyncArrayRecordById($syncWebRecord);
  4024.             if ($syncWebRecord[0]['rfwStatus'] == ReadFilesDataWeb::STATUS_RESPONSE_READED) {
  4025.                 $keepInWhile false;
  4026.                 $responseToPolling['msg'] = 'Web sync answered.. going forward whith the down up synchronization!';
  4027.                 $responseToPolling['response_code'] = WebService::SYNC_RESPONSE_PROCESSED;
  4028.                 $responseToPolling['wasAnswered'] = true;
  4029.             } elseif ($auxCounter >= 14) {
  4030.                 $keepInWhile false;
  4031.                 if ($syncWebRecord[0]['rfwStatus'] < ReadFilesDataWeb::STATUS_RESPONSE_READED) {
  4032.                     $responseToPolling['msg'] = 'Waiting maximum time has been reached for web sync answer.. Please try again later!';
  4033.                     $responseToPolling['response_code'] = WebService::MAXIMUM_WAIT_TIME_REACHED;
  4034.                     $responseToPolling['wasAnswered'] = false;
  4035.                 }
  4036.             } else {
  4037.                 $em->clear();
  4038.             }
  4039.         } while ($keepInWhile);
  4040.         return $responseToPolling;
  4041.     }
  4042.     /**
  4043.      * Funcion polling para verificar si termino con exito la sincronizacion de arriba a abajo
  4044.      * @author Aealan Z <lrobledo@kijho.com> 11/06/2016
  4045.      * @param type $masterSyncRecord registro maestro de la sincronizacion en proceso
  4046.      * @return boolean indicando si la sincronizacion de arriba a abajo termino con exito
  4047.      */
  4048.     public function checkForWebSyncClose($masterSyncRecord$path) {
  4049.         $responseToPolling = [];
  4050.         $auxCounter 0;
  4051.         $keepInWhile true;
  4052.         $this->createFileJson($path'Checking sync web finish....' "\r");
  4053.         if (!$masterSyncRecord['id']) {
  4054.             $responseToPolling['msg'] = 'Waiting maximum time has been reached for web sync answer.. Please try again later!';
  4055.             $responseToPolling['response_code'] = WebService::MAXIMUM_WAIT_TIME_REACHED;
  4056.             $responseToPolling['wasAnswered'] = false;
  4057.             return $responseToPolling;
  4058.         }
  4059.         $em $this->getDoctrine()->getManager();
  4060.         do {
  4061.             sleep(3);
  4062.             ++$auxCounter;
  4063.             $masterSyncRecord $em->getRepository('App\Entity\ReadFilesDataWeb')->getTheMasterSyncArrayRecordById($masterSyncRecord['id'], true);
  4064.             if ($masterSyncRecord[0]['msStatus'] == MasterSync::MASTER_STATUS_CLOSED) {
  4065.                 $keepInWhile false;
  4066.                 $responseToPolling['msg'] = 'Web sync finished.. going forward whith the down up synchronization!';
  4067.                 $responseToPolling['response_code'] = WebService::SYNC_RESPONSE_PROCESSED;
  4068.                 $responseToPolling['wasAnswered'] = true;
  4069.             } elseif ($auxCounter >= 14) {
  4070.                 $keepInWhile false;
  4071.                 if ($masterSyncRecord[0]['msStatus'] <= MasterSync::MASTER_STATUS_CLOSED) {
  4072.                     $responseToPolling['msg'] = 'Waiting maximum time has been reached for web sync finish.. Please try again later!';
  4073.                     $responseToPolling['response_code'] = WebService::MAXIMUM_WAIT_TIME_REACHED;
  4074.                     $responseToPolling['wasAnswered'] = false;
  4075.                 }
  4076.             } else {
  4077.                 $em->clear();
  4078.             }
  4079.         } while ($keepInWhile);
  4080.         return $responseToPolling;
  4081.     }
  4082.     /**
  4083.      * Funcion polling para verificar la respuesta de una sincronizacion de abajo
  4084.      * a arriba, este funcion verifica en un tiempo maximo de 56 segundos
  4085.      * @author Aealan Z <lrobledo@kijho.com> 11/06/2016
  4086.      * @param type $id id de lalicencia a la cual se verificara la respuesta
  4087.      * @param type $paramLastId id de la ultima sincronizacion de abajo a arriba respondido
  4088.      * @return boolean indica si se respondio o no la solicitud en el tiempo establecido
  4089.      */
  4090.     public function checkForDownUpPolling($id$paramLastId$path) {
  4091.         $checkResponse = [];
  4092.         $auxCounter 0;
  4093.         $keepInWhile true;
  4094.         $this->createFileJson($path'Checking sync response for ' $id " license \r");
  4095.         $em $this->getDoctrine()->getManager();
  4096.         do {
  4097.             sleep(4);
  4098.             ++$auxCounter;
  4099.             $lastReadDataForLicense $em->getRepository('App\Entity\ReadFilesData')->checkForNewSyncPetitionByLicense($id$paramLastIdtrue);
  4100.             if (count($lastReadDataForLicense) > 0) {
  4101.                 $this->createFileJson($path'Count For Polling Status: -> ' $paramLastId ' -> ' $lastReadDataForLicense[0]['id'] . ' => ' $lastReadDataForLicense[0]['rfStatus'] . "\r");
  4102.             } else {
  4103.                 $this->createFileJson($path'Count For Polling: -> ' $paramLastId ' => ' count($lastReadDataForLicense) . "\r");
  4104.             }
  4105.             $askingSyncPushRecordArray $em->getRepository('App\Entity\PushSent')->findLastAskingSyncPushToLicense($idtrue);
  4106.             $askingSyncPushRecord $askingSyncPushRecordArray[0];
  4107.             $this->createFileJson($path'Push Record Found In Polling: -> ' $askingSyncPushRecord['id'] . "\r");
  4108.             if (isset($askingSyncPushRecord['newPushSendedStage']) && $askingSyncPushRecord['newPushSendedStage'] == PushSent::SENDED_STAGE_OMT_SOCKET_PUSH) {
  4109.                 $keepInWhile false;
  4110.                 $this->createFileJson($path"push omt type detected!! \r");
  4111.                 $checkResponse['newPushSendedStage'] = PushSent::SENDED_STAGE_OMT_SOCKET_PUSH;
  4112.                 $checkResponse['wasAnswered'] = true;
  4113.                 $checkResponse['msg'] = 'Android server sync processed.. Please check for the new data!';
  4114.                 $checkResponse['response_code'] = WebService::SYNC_DONE_SUCCESSFULLY;
  4115.             } elseif (!empty($lastReadDataForLicense) && $lastReadDataForLicense[0]['rfStatus'] > ReadFilesData::STATUS_UPLOADED) {
  4116.                 $keepInWhile false;
  4117.                 $checkResponse['status'] = SyncAllWebsocketVersionCommand::ANDROID_SYNC_SUCCESS;
  4118.                 $checkResponse['msg'] = 'Android server sync processed.. Please check for the new data!';
  4119.                 $checkResponse['response_code'] = WebService::SYNC_DONE_SUCCESSFULLY;
  4120.                 $checkResponse['wasAnswered'] = true;
  4121.             } elseif (!empty($askingSyncPushRecord) && $askingSyncPushRecord['askedResponse'] === false) {
  4122.                 $keepInWhile false;
  4123.                 $checkResponse['status'] = SyncAllWebsocketVersionCommand::ANDROID_HAVE_NOTHING_TO_SYNC;
  4124.                 $checkResponse['msg'] = 'Android server have nothing to synchronize... finishing synchronization!';
  4125.                 $checkResponse['response_code'] = WebService::NOTHING_TO_WEB_SYNCHRONIZE;
  4126.                 $checkResponse['wasAnswered'] = true;
  4127.             } elseif ($auxCounter 7) {
  4128.                 $keepInWhile false;
  4129.                 if (count($lastReadDataForLicense) > 0) {
  4130.                     $checkResponse['status'] = SyncAllWebsocketVersionCommand::ANDROID_SYNC_SUCCESS;
  4131.                     $checkResponse['msg'] = 'Android server sync processed.. Please check for the new data!';
  4132.                     $checkResponse['response_code'] = WebService::SYNC_DONE_SUCCESSFULLY;
  4133.                     $checkResponse['wasAnswered'] = true;
  4134.                 } else {
  4135.                     $checkResponse['status'] = SyncAllWebsocketVersionCommand::ANDROID_WAITING_MAXIMUM_TIME;
  4136.                     $checkResponse['msg'] = 'Waiting maximum time has been reached for Android new data.. Please try again later!';
  4137.                     $checkResponse['response_code'] = WebService::MAXIMUM_WAIT_TIME_REACHED;
  4138.                     $checkResponse['wasAnswered'] = false;
  4139.                 }
  4140.             } elseif ($askingSyncPushRecord['loginType'] == AccountLicense::LOGGED_BY_LEVEL_LITE && $askingSyncPushRecord['hasLogedOMT']) {
  4141.                 $askingSyncPushRecord $em->getRepository('App\Entity\PushSent')->find($askingSyncPushRecord['id']);
  4142.                 
  4143.                 $askingSyncPushRecord->setPushStatus(PushSent::STATUS_PUSH_READED);
  4144.                 $askingSyncPushRecord->setRespondDate($askingSyncPushRecord->getRespondDate());
  4145.                 $askingSyncPushRecord->setAskedResponse(false);
  4146.                 $em->persist($askingSyncPushRecord);
  4147.                 $em->flush();
  4148.                 $checkResponse['status'] = SyncAllWebsocketVersionCommand::SYNC_DONE;
  4149.                 $checkResponse['msg'] = 'Sync done.. Please check for the new data!';
  4150.                 $checkResponse['response_code'] = WebService::SYNC_RESPONSE_PROCESSED;
  4151.                 $checkResponse['wasAnswered'] = true;
  4152.                 $keepInWhile false;
  4153.             } else {
  4154.                 $em->clear();
  4155.             }
  4156.         } while ($keepInWhile);
  4157.         return $checkResponse;
  4158.     }
  4159.     public function checkForDownUp(AccountLicense $licensebool $pushAskedResponse$path) {
  4160.         $this->createFileJson($path"Checking sync response for {$license->getId()} license \r");
  4161.         $em $this->getDoctrine()->getManager();
  4162.         $lastReadDataForLicense $em->getRepository('App\Entity\ReadFilesData')->findLastSyncPetitionIdByLicense($license->getId());
  4163.         $lastReadDataForLicense $em->getRepository('App\Entity\ReadFilesData')->checkForNewSyncPetitionByLicense($license->getId(), $lastReadDataForLicensetrue);
  4164.         $checkResponse = [];
  4165.         if (!empty($lastReadDataForLicense) && $lastReadDataForLicense[0]['rfStatus'] > ReadFilesData::STATUS_UPLOADED) {
  4166.             $this->createFileJson($path"Android server sync processed.. Please check for the new data! \r");
  4167.             $checkResponse['status'] = SyncAllWebsocketVersionCommand::ANDROID_SYNC_SUCCESS;
  4168.         }else if(!$pushAskedResponse){
  4169.             $this->createFileJson($path"Android server have nothing to synchronize... finishing synchronization! \r");
  4170.             $checkResponse['status'] = SyncAllWebsocketVersionCommand::ANDROID_HAVE_NOTHING_TO_SYNC;
  4171.         }else{
  4172.             $this->createFileJson($path"clear \r");
  4173.             $em->clear();
  4174.         }
  4175.         $this->createFileJson($path"check response => "json_encode($checkResponse) ." \r");
  4176.         return $checkResponse;
  4177.     }
  4178.     /**
  4179.      * WS generico experimental para la codificacion y decodificacion del encriptado
  4180.      * utilizado entre licensor y android
  4181.      * @author Aealan Z <lrobledo@kijho.com> 18/06/15
  4182.      * @param \Symfony\Component\HttpFoundation\Request $request datos de la solicitud
  4183.      * @return Response Json con la informacion de respuesta
  4184.      */
  4185.     public function cosito(Request $request) {
  4186.         if ($request->getMethod() === WebService::REQUEST_METHOD_GET) {
  4187.             $path $this->realContainer->getParameter('level_directory_data_android') . 'TestiDecodePath.txt';
  4188.             $jsn $this->realContainer->getParameter('level_directory_data_android') . 'TresChangos.txt';
  4189.             $arrData Util::getAllDecryptedJsonContent($this->realContainer$jsntrue$pathtruefalse);
  4190.             $r = new Response($arrData);
  4191.             $r->headers->set('Content-Type''application/json');
  4192.             return $r;
  4193.         } else {
  4194.             return $this->errorNotAllowedMethod('Method not allowed. Use ' WebService::REQUEST_METHOD_GET " method");
  4195.         }
  4196.     }
  4197.     /**
  4198.      * WS generico para que el cliente andorid responda todos los push enviados a los clientes
  4199.      * @author Aealan Z <lrobledo@kijho.com> 18/06/15
  4200.      * @param \Symfony\Component\HttpFoundation\Request $request datos de la solicitud
  4201.      * @return Response Json con la informacion de respuesta
  4202.      */
  4203.     public function cositoDos(Request $request) {
  4204.         if ($request->getMethod() === WebService::REQUEST_METHOD_GET) {
  4205.             $jsn file_get_contents($this->realContainer->getParameter('level_directory_data_android') . 'UnChangoDos.txt');
  4206.             $responseToAjax['content'] = trim($jsn" \t\n\r\0\x0B");
  4207.             return $this->respondJsonAjax($responseToAjax);
  4208.         } else {
  4209.             return $this->errorNotAllowedMethod('Method not allowed. Use ' WebService::REQUEST_METHOD_POST " method");
  4210.         }
  4211.     }
  4212.     /**
  4213.      * WS generico para que el cliente andorid responda todos los push enviados a los clientes
  4214.      * @author Aealan Z <lrobledo@kijho.com> 18/06/15
  4215.      * @param \Symfony\Component\HttpFoundation\Request $request datos de la solicitud
  4216.      * @return Response Json con la informacion de respuesta
  4217.      */
  4218.     public function cositoTres(Request $request) {
  4219.         if ($request->getMethod() === WebService::REQUEST_METHOD_GET) {
  4220. //            $jsn = file_get_contents($this->realContainer->getParameter('level_directory_data_android') . 'UnChangoTres.txt');
  4221.             $cipher "rijndael-128";
  4222.             $mode "cbc";
  4223.             $secret_key "D4:6E:AC:3F:F0:BE";
  4224. //iv length should be 16 bytes
  4225.             $iv "fedcba9876543210";
  4226.             $key_len strlen($secret_key);
  4227.             if ($key_len 16) {
  4228.                 $addS 16 $key_len;
  4229.                 for ($i 0$i $addS; ++$i) {
  4230.                     $secret_key .= " ";
  4231.                 }
  4232.             } else {
  4233.                 $secret_key substr($secret_key016);
  4234.             }
  4235.             $td mcrypt_module_open($cipher""$mode$iv);
  4236.             mcrypt_generic_init($td$secret_key$iv);
  4237.             var_dump($this->realContainer->getParameter('level_directory_data_android') . 'UnChangoTres.txt');
  4238.             die();
  4239.             $getText file_get_contents($this->realContainer->getParameter('level_directory_data_android') . 'UnChangoTres.txt');
  4240.             $textArray explode('\r'$getText);
  4241.             $textCount count($textArray);
  4242.             for ($i 0$i $textCount; ++$i) {
  4243.                 $cyper_text mcrypt_generic($td$textArray[$i]);
  4244.                 mcrypt_generic_deinit($td);
  4245.                 mcrypt_module_close($td);
  4246.                 $textEncrypt bin2hex($cyper_text);
  4247.                 $setText base64_encode($textEncrypt);
  4248.                 $fp fopen($this->realContainer->getParameter('level_directory_data_android') . 'UnChangoTresResponse.txt'"a+");
  4249.                 fwrite($fp$setText);
  4250.                 fclose($fp);
  4251.             }
  4252. //            $path = $this->realContainer->getParameter('level_directory_data_android') . 'UnChangoTresResponse.txt';
  4253. //            $pathXD = $this->realContainer->getParameter('level_directory_data_android') . 'UnChangoTresTest.txt';
  4254. //            Util::putAllEncryptedJsonContent($this->realContainer, trim($jsn, " \t\n\r\0\x0B"), $path, true, $pathXD);
  4255.             $responseToAjax['content'] = 'Si encripto...?';
  4256.             return $this->respondJsonAjax($responseToAjax);
  4257.         } else {
  4258.             return $this->errorNotAllowedMethod('Method not allowed. Use ' WebService::REQUEST_METHOD_POST " method");
  4259.         }
  4260.     }
  4261.     /**
  4262.      * Esta funcion permite notificar por correo, un error persistente dentro
  4263.      * de los registros de sincronizacion de determinada licencia
  4264.      * @author Aealan Z <lrobledo@kijho.com> 18/12/15
  4265.      * @param \Symfony\Component\HttpFoundation\Request $request datos de la solicitud
  4266.      * @return Response Json con la informacion de respuesta
  4267.      */
  4268.     public function notifySyncRecurrentError(Request $request) {
  4269.         if ($request->getMethod() === WebService::REQUEST_METHOD_POST) {
  4270.             $data = [];
  4271.             $dataForTrack = [];
  4272.             $parameters $request->request->all();
  4273.             $path Util::getValidActiveLogByBaseName($this->realContainer'notifyRecurrentSyncError''notifyRecurrentSyncError0.txt');
  4274.             $this->createFileJson($path"The Request -> " json_encode($parameters) . "\r");
  4275.             $arrayEncryptResult Util::decryptDataForUploadsFiles($this->realContainer$parameters['nickname']);
  4276.             $data['nickname'] = $arrayEncryptResult['data'];
  4277.             $dataForTrack['nickname'] = $parameters['nickname'];
  4278.             $arrayEncryptResult Util::decryptDataForUploadsFiles($this->realContainer$parameters['uid']);
  4279.             $data['uid'] = $arrayEncryptResult['data'];
  4280.             $dataForTrack['uid'] = $parameters['uid'];
  4281.             $em $this->getDoctrine()->getManager();
  4282.             $search = ['alLicenseUsername' => $data['nickname']];
  4283.             $accountLicenseData $em->getRepository('App\Entity\AccountLicense')->findBy($search);
  4284.             if (empty($accountLicenseData)) {
  4285.                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  4286.                                 ->respondWithError('Invalid nickname'WebService::CODE_UNAUTHORIZED);
  4287.             } elseif ($accountLicenseData[0]->getDeviceUid() != $data['uid']) {
  4288.                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  4289.                                 ->respondWithError('Unknown device'WebService::CODE_UNAUTHORIZED);
  4290.             }
  4291.             $respArray = [];
  4292.             $respArray['result'] = '__OK__';
  4293.             $respArray['msg'] = '';
  4294.             if (isset($parameters['idsync'])) {
  4295.                 $arrayEncryptResult Util::decryptDataForUploadsFiles($this->realContainer$parameters['idsync']);
  4296.                 $data['idsync'] = $arrayEncryptResult['data'];
  4297.                 $dataForTrack['idsync'] = $arrayEncryptResult['data'];
  4298.                 $errorsToEmail $em->getRepository('App\Entity\SyncReportedError')->find($data['idsync']);
  4299.                 if (!$errorsToEmail) {
  4300.                     return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  4301.                                     ->respondWithError('Error record not found!'WebService::CODE_UNAUTHORIZED);
  4302.                 }
  4303.             } else {
  4304.                 $responseArrayWithUrl Util::createLicenseDirectory($this->realContainer$accountLicenseData[0], $data['nickname']);
  4305.                 $theAccountDirector $responseArrayWithUrl['directory'];
  4306.                 $uploadFileResponse Utilx::uploadFileTo($request$theAccountDirector$path);
  4307.                 if (!isset($uploadFileResponse['result']) || !isset($uploadFileResponse['msg'])) {
  4308.                     $this->createFileJson($path'Unknown error uploading file ' "\r");
  4309.                     return $this->setStatusCode(WebService::HTTP_CODE_INTERNAL_ERROR)
  4310.                                     ->respondWithError('Unknown error uploading file'WebService::CODE_INTERNAL_ERROR);
  4311.                 }
  4312.                 if (isset($uploadFileResponse['result']) && isset($uploadFileResponse['msg']) && $uploadFileResponse['result'] == '__KO__') {
  4313.                     $this->createFileJson($path$uploadFileResponse['msg'] . "\r");
  4314.                     return $this->setStatusCode(WebService::HTTP_CODE_INTERNAL_ERROR)
  4315.                                     ->respondWithError($uploadFileResponse['msg'], WebService::CODE_INTERNAL_ERROR);
  4316.                 }
  4317.                 $errorsToEmail = new SyncReportedError();
  4318.                 $errorsToEmail->setStatus(SyncReportedError::STATUS_CREATED);
  4319.                 $errorsToEmail->setLicense($accountLicenseData[0]);
  4320.                 $actualDate Util::getCurrentDate();
  4321.                 $errorsToEmail->setDateErrorCreated($actualDate);
  4322.                 $errorsToEmail->setErrorFile($uploadFileResponse['fileName']);
  4323.                 $currentUrl $request->getUri();
  4324. //                if (strpos($currentUrl, 'app_dev.php') !== false) {
  4325.                 $errorsToEmail->setApplicationMode(false);
  4326. //                } else {
  4327. //                    $errorsToEmail->setApplicationMode(true);
  4328. //                }
  4329.                 $em->persist($errorsToEmail);
  4330.                 $em->flush();
  4331.                 $this->createFileJson($path"File uploaded -> " $uploadFileResponse['fileName'] . "\r");
  4332.             }
  4333.             $this->createFileJson($pathjson_encode($dataForTrack) . "\r");
  4334.             $emailsToNotify $this->realContainer->getParameter('level_emails_syncs_errors');
  4335.             $responseArrayWithUrl Util::createLicenseDirectory($this->realContainer$accountLicenseData[0], $data['nickname']);
  4336.             $urlToErrorFile $responseArrayWithUrl['directory'] . '/' $errorsToEmail->getErrorFile();
  4337.             $this->createFileJson($path"Ya casi! -> " $urlToErrorFile "\r");
  4338.             if (isset($parameters['isIgnored'])) {
  4339.                 $theSubject $data['nickname'] . ' ignored records sync error ';
  4340.             } else {
  4341.                 $theSubject $data['nickname'] . ' recurrent sync error ';
  4342.             }
  4343.             $respArray['subject'] = $theSubject;
  4344.             $respArray['message'] = "";
  4345.             $body "<html><body><div><p><label><strong>" $data['nickname'] . "</strong>   Uuppss... -_-!</label></p><br></div></body></html>";
  4346.             foreach ($emailsToNotify as $mailTo) {
  4347.                 $this->createFileJson($path"Mail to -> " $mailTo "\r");
  4348.                 $emailSuccess true;
  4349.                 $respArray['to'] = $mailTo;
  4350.                 Utilx::sendMailInfo($this->realContainer$respArray$path$body$urlToErrorFile);
  4351.             }
  4352.             $this->createFileJson($path"Si llego? -> " $urlToErrorFile "\r");
  4353.             $statusArryMsg = [];
  4354.             $statusArryMsg['status'] = WebService::CODE_SUCCESS;
  4355.             if ($emailSuccess) {
  4356.                 $errorsToEmail->setStatus(SyncReportedError::STATUS_NOTIFIED);
  4357.                 $actualDate Util::getCurrentDate();
  4358.                 $errorsToEmail->setDateErrorNotified($actualDate);
  4359.                 $em->persist($errorsToEmail);
  4360.                 $em->flush();
  4361.                 $statusArryMsg['msg'] = 'Recurrent sync errors notified!';
  4362.             } else {
  4363.                 return $this->setStatusCode(WebService::HTTP_CODE_INTERNAL_ERROR)
  4364.                                 ->respondWithError('Erro notifiying recurrent errors by email!'WebService::CODE_INTERNAL_ERROR);
  4365.             }
  4366.             $theUrlTrSt = new UploadSyncJsonNotifyTransformer($this->realContainer$statusArryMsg);
  4367.             $jsonTransform $theUrlTrSt->transform();
  4368.             $jsonContent json_encode($jsonTransform);
  4369.             return $this->respondWithItem($jsonContent$theUrlTrSt);
  4370.         } else {
  4371.             return $this->errorNotAllowedMethod('Method not allowed. Use ' WebService::REQUEST_METHOD_POST " method");
  4372.         }
  4373.     }
  4374.     /**
  4375.      * Funcion para actualizar el registro de un push marcandolo como leido
  4376.      * @author Aealan Z <lrobledo@kijho.com> 11/06/2016
  4377.      * @param type $pushEntity registro de push a actualizar
  4378.      * @return boolean booleano que indica si se actualizo el registro con exito
  4379.      */
  4380.     public function updateRegistPushSend($pushEntity) {
  4381.         $em $this->getDoctrine()->getManager();
  4382.         $pushEntity->setPushStatus(PushSent::STATUS_PUSH_READED);
  4383.         $actualDate Util::getCurrentDate();
  4384.         $pushEntity->setRespondDate($actualDate);
  4385.         $em->persist($pushEntity);
  4386.         try {
  4387.             $em->flush();
  4388.             return true;
  4389.         } catch (\Exception $ex) {
  4390.             return false;
  4391.         }
  4392.     }
  4393.     /**
  4394.      * Funcion para crear un nuevo registro de sincronizacion de abajo a arriba
  4395.      * @author Aealan Z <lrobledo@kijho.com> 11/06/2016
  4396.      * @param type $license licencia a la cual se le creara el nuevo registro
  4397.      * de sincronizacion
  4398.      * @return boolean|ReadFilesData retorna el nuevo registro de sincronizacion
  4399.      * si este fue creado correctamente, de lo contrario retorna un booleano (false)
  4400.      */
  4401.     public function setRegistNewFile($license) {
  4402.         $em $this->getDoctrine()->getManager();
  4403.         $masterSync Utilx::setRegistNewMasterSyncRecordFile($em$licenseMasterSync::MASTER_SYNC_TYPE_DOWUP);
  4404.         $entity = new ReadFilesData();
  4405.         $entity->setRfLicenseId($license);
  4406.         $entity->setRfStatus(ReadFilesData::STATUS_STANDBY);
  4407.         $actualDate Util::getCurrentDate();
  4408.         $entity->setRfDateSincAsk($actualDate);
  4409.         $entity->setIsReadedByServer(false);
  4410.         $appMode $this->realContainer->getParameter('kernel.environment');
  4411.         if ($appMode == 'dev') {
  4412.             $entity->setApplicationMode(false);
  4413.         } else {
  4414.             $entity->setApplicationMode(true);
  4415.         }
  4416.         $em->persist($entity);
  4417.         try {
  4418.             $em->flush();
  4419.             $masterSync->setMsSyncRecord($entity);
  4420.             $em->persist($masterSync);
  4421.             $em->flush();
  4422.             return $entity;
  4423.         } catch (\Exception $ex) {
  4424.             return false;
  4425.         }
  4426.     }
  4427.     /**
  4428.      * Funcion en donde se crea el registro de una notificacion de error
  4429.      * por email junto con el error adjunto, en este funcion se notifican
  4430.      * tanto licencias como sublicencias
  4431.      * @author Aealan Z <lrobledo@kijho.com> 11/06/2016
  4432.      * @param type $license registro de la licencia a la que se notificara el error
  4433.      * @param type $mailedTo email al que se el enviara el correo del error
  4434.      * @param type $msgError mensaje de error a notificar
  4435.      * @param type $deviceUid UID del dispositivo que reporta el error
  4436.      * @param type $errorCode codigo que identifica a cada error distinto en el sistema
  4437.      * @param type $subLicense registro de sublicencia a la que se le notificara el error
  4438.      * @return boolean|ErrorAndroidEmailSent registro de la notificacion del error por email
  4439.      * si se creo exitosamente, de lo contrario retorna un booleano (false)
  4440.      */
  4441.     public function setRegistErrorEmail($license$mailedTo$msgError$deviceUid$errorCode$subLicense null) {
  4442.         $em $this->getDoctrine()->getManager();
  4443.         $entity = new ErrorAndroidEmailSent();
  4444.         if ($license) {
  4445.             $entity->setLiceseError($license);
  4446.         } else {
  4447.             $entity->setSubLicenseError($subLicense);
  4448.         }
  4449.         $entity->setEmailRecordStatus(ErrorAndroidEmailSent::STATUS_SERVER_NOTIFIED);
  4450.         $actualDate Util::getCurrentDate();
  4451.         $entity->setDateErrorReported($actualDate);
  4452.         $entity->setErrorMsg($msgError);
  4453.         $entity->setMailedTo($mailedTo);
  4454.         $entity->setUidErrorDevice($deviceUid);
  4455.         $entity->setErrorCode($errorCode);
  4456.         $entity->setDateErrorLastReport($actualDate);
  4457.         $entity->setErrorCounter(1);
  4458.         $em->persist($entity);
  4459.         try {
  4460.             $em->flush();
  4461.             return $entity;
  4462.         } catch (\Exception $ex) {
  4463.             return false;
  4464.         }
  4465.     }
  4466.     /**
  4467.      * Funcion en donde se crea el registro en el historico de errores de Android,
  4468.      * en este funcion se registran tanto licencias como sublicencias.
  4469.      * Basada en la función setRegistErrorEmail
  4470.      * @author Jhonan V <jsmith@openmytab.com> 29/10/2021
  4471.      * @param type $license registro de la licencia a la que se va a notificara el error
  4472.      * @param type $mailedTo email al que se el enviara el correo del error
  4473.      * @param type $msgError mensaje de error a notificar
  4474.      * @param type $deviceUid UID del dispositivo que reporta el error
  4475.      * @param type $errorCode codigo que identifica a cada error distinto en el sistema
  4476.      * @param type $subLicense registro de sublicencia a la que se le notificara el error
  4477.      * @return boolean|AndroidErrorsHistory registro de la notificacion del error por email
  4478.      * si se creo exitosamente, de lo contrario retorna un booleano (false)
  4479.      */
  4480.     public function setRegistAndroidError($error$license$mailedTo$msgError$deviceUid$subLicense null) {
  4481.         $em $this->getDoctrine()->getManager();
  4482.         $entity = new AndroidErrorsHistory();
  4483.         if ($license) {
  4484.             $entity->setLiceseError($license);
  4485.         } else {
  4486.             $entity->setSubLicenseError($subLicense);
  4487.         }
  4488.         $entity->setErrorCode($error);
  4489.         $entity->setEmailRecordStatus(ErrorAndroidEmailSent::STATUS_SERVER_NOTIFIED);
  4490.         $actualDate Util::getCurrentDate();
  4491.         $entity->setDateErrorReported($actualDate);
  4492.         $entity->setErrorMsg($msgError);
  4493.         $entity->setMailedTo($mailedTo);
  4494.         $entity->setUidErrorDevice($deviceUid);
  4495.                 
  4496.         $em->persist($entity);
  4497.         try {
  4498.             $em->flush();
  4499.             return $entity;
  4500.         } catch (\Exception $ex) {
  4501.             return false;
  4502.         }
  4503.     }
  4504.     /**
  4505.      * Funcion en donde se actualiza el registro de notificacion de error enviado
  4506.      * por email indicando que ya fue enviado dicho correo
  4507.      * @author Aealan Z <lrobledo@kijho.com> 11/06/2016
  4508.      * @param type $errorAndroidEmailRecord registro de notificacion de error
  4509.      * por email
  4510.      * @return boolean booleano que indica si el registro
  4511.      * fue actualizado correctamente
  4512.      */
  4513.     public function updateRegistErrorEmail($errorAndroidEmailRecord) {
  4514.         $em $this->getDoctrine()->getManager();
  4515.         $errorAndroidEmailRecord->setEmailRecordStatus(ErrorAndroidEmailSent::STATUS_EMAIL_SENT);
  4516.         $actualDate Util::getCurrentDate();
  4517.         $errorAndroidEmailRecord->setDateErrorEmailSent($actualDate);
  4518.         $em->persist($errorAndroidEmailRecord);
  4519.         try {
  4520.             $em->flush();
  4521.             return $errorAndroidEmailRecord;
  4522.         } catch (\Exception $ex) {
  4523.             return false;
  4524.         }
  4525.     }
  4526.     /**
  4527.      * Funcion en donde se crea el registro de notificacion de log por email
  4528.      * junto con el log adjunto, esta funcion se notifica tanto licencias
  4529.      * como sublicencias
  4530.      * @author Aealan Z <lrobledo@kijho.com> 11/06/2016
  4531.      * @param type $license registro de la licencia a la que se solicito el log
  4532.      * @param type $mailedTo email al que se el enviara el correo con el log
  4533.      * @param type $msgError log del servidor a ser notificado por email
  4534.      * @param type $deviceUid UID del dispositivo al que se le solicita el log
  4535.      * @param type $errorCode codigo unico del log solicitado
  4536.      * @param type $subLicense registro de sublicencia
  4537.      * a la que se le solicito el log
  4538.      * @return boolean|LogAndroidEmailSent registro
  4539.      * de nitificacion de log por correo si este se genero exitosamente,
  4540.      * un booleano (false) de lo contrario
  4541.      */
  4542.     public function setRegistLogEmail($license$mailedTo$msgError$deviceUid$errorCode$subLicense null) {
  4543.         $em $this->getDoctrine()->getManager();
  4544.         $entity = new LogAndroidEmailSent();
  4545.         if ($license) {
  4546.             $entity->setLiceseLog($license);
  4547.         } else {
  4548.             $entity->setSubLicenseLog($subLicense);
  4549.         }
  4550.         $entity->setEmailRecordStatus(LogAndroidEmailSent::STATUS_SERVER_NOTIFIED);
  4551.         $actualDate Util::getCurrentDate();
  4552.         $entity->setDateLogAsked($actualDate);
  4553.         $entity->setLogMsg($msgError);
  4554.         $entity->setMailedTo($mailedTo);
  4555.         $entity->setUidLogDevice($deviceUid);
  4556.         $entity->setLogCode($errorCode);
  4557.         $em->persist($entity);
  4558.         try {
  4559.             $em->flush();
  4560.             return $entity;
  4561.         } catch (\Exception $ex) {
  4562.             return false;
  4563.         }
  4564.     }
  4565.     /**
  4566.      * Funcion en donde se actualiza el registro de error notificado por email
  4567.      * , en este funcion se actualiza el registro indicando que se envio
  4568.      * exitosamente el correo con el error
  4569.      * @author Aealan Z <lrobledo@kijho.com> 11/06/2016
  4570.      * @param type $errorAndroidEmailRecord registro del error
  4571.      * notificado por email
  4572.      * @return boolean booleano que indica si se actualizo
  4573.      * el registro correctamente
  4574.      */
  4575.     public function updateRegistLogEmail($errorAndroidEmailRecord) {
  4576.         $em $this->getDoctrine()->getManager();
  4577.         $errorAndroidEmailRecord->setEmailRecordStatus(LogAndroidEmailSent::STATUS_EMAIL_SENT);
  4578.         $actualDate Util::getCurrentDate();
  4579.         $errorAndroidEmailRecord->setDateLogEmailSent($actualDate);
  4580.         $em->persist($errorAndroidEmailRecord);
  4581.         try {
  4582.             $em->flush();
  4583.             return $errorAndroidEmailRecord;
  4584.         } catch (\Exception $ex) {
  4585.             return false;
  4586.         }
  4587.     }
  4588.     /**
  4589.      * @author Aealan Z <lrobledo@kijho.com> 29/07/2016
  4590.      * @param type $readFileData
  4591.      * @param type $fileName
  4592.      * @return boolean
  4593.      */
  4594.     public function updateRegistUploadFile($readFileData$fileName$fileInS3URI '') {
  4595.         $em $this->getDoctrine()->getManager();
  4596.         $masterSyncRecords $em->getRepository('App\Entity\MasterSync')->findBy(['msSyncRecord' => $readFileData->getId()]);
  4597.         $masterSyncRecords[0]->setMsStatus(MasterSync::MASTER_STATUS_PROCESSED);
  4598.         $readFileData->setRfStatus(ReadFilesData::STATUS_UPLOADED);
  4599.         $readFileData->setRfNameFile($fileName);
  4600.         $actualDate Util::getCurrentDate();
  4601.         $readFileData->setRfDateUpload($actualDate);
  4602.         $readFileData->setIsReadedByServer(false);
  4603.         if ($fileInS3URI != '') {
  4604.             $readFileData->setFileInS3URI($fileInS3URI);
  4605.         }
  4606.         $em->persist($masterSyncRecords[0]);
  4607.         $em->persist($readFileData);
  4608.         try {
  4609.             $em->flush();
  4610.             return true;
  4611.         } catch (\Exception $ex) {
  4612.             return false;
  4613.         }
  4614.     }
  4615.     /**
  4616.      * Funcion para limpiar el estatus de error en una sincronizacion para
  4617.      * poder reencolarla de nuevo
  4618.      * @author Aealan Z <lrobledo@kijho.com> 11/06/2016
  4619.      * @param type $readFileDataWeb registro de la sincronizacion
  4620.      * web a reencolar
  4621.      * @return boolean booleano que indica si se actualizo
  4622.      * correctamente el registro
  4623.      */
  4624.     public function cleanErrorStatusToRetryWebSync($readFileDataWeb) {
  4625.         $em $this->getDoctrine()->getManager();
  4626.         $masterSyncRecords $em->getRepository('App\Entity\MasterSync')->findBy(['msSyncWebRecord' => $readFileDataWeb->getId()]);
  4627.         $masterSyncRecords[0]->setMsHasPersistentError(false);
  4628.         $readFileDataWeb->setHasPersistentError(false);
  4629.         $em->persist($masterSyncRecords[0]);
  4630.         $em->persist($readFileDataWeb);
  4631.         try {
  4632.             $em->flush();
  4633.             return true;
  4634.         } catch (\Exception $ex) {
  4635.             return false;
  4636.         }
  4637.     }
  4638.     /**
  4639.      * Funcion para actualizar el registro de sincronizacion de abajo a arriba
  4640.      * marcandolo como entregado por licensor
  4641.      * @author Aealan Z <lrobledo@kijho.com> 11/06/2016
  4642.      * @param type $readFileData registro de la sincronizacion de abajo
  4643.      * a arriba
  4644.      * @return boolean booleano indicando si se actualizo el registro
  4645.      * correctamente
  4646.      */
  4647.     public function updateRegistDeliveredFile($readFileData) {
  4648.         $em $this->getDoctrine()->getManager();
  4649.         $masterSyncRecords $em->getRepository('App\Entity\MasterSync')->findBy(['msSyncRecord' => $readFileData->getId()]);
  4650.         $masterSyncRecords[0]->setMsStatus(MasterSync::MASTER_STATUS_RESPONDED);
  4651.         $readFileData->setRfStatus(ReadFilesData::STATUS_DELIVERED);
  4652.         $actualDate Util::getCurrentDate();
  4653.         $readFileData->setRfDateDelivered($actualDate);
  4654.         $em->persist($masterSyncRecords[0]);
  4655.         $em->persist($readFileData);
  4656.         try {
  4657.             $em->flush();
  4658.             return true;
  4659.         } catch (\Exception $ex) {
  4660.             return false;
  4661.         }
  4662.     }
  4663.     /**
  4664.      * WS para desbloquear sincronizaciones no terminadas por errores
  4665.      * @author Aealan Z <lrobledo@kijho.com> 11/11/15
  4666.      * @param \Symfony\Component\HttpFoundation\Request $request datos
  4667.      * de la solicitud
  4668.      * @return Response Json con la informacion de respuesta
  4669.      */
  4670.     public function clearBlockedSyncsByLicense(Request $request) {
  4671.         if ($request->getMethod() === WebService::REQUEST_METHOD_POST) {
  4672.             if (=== strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_STRUCTURE) || === strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_TEXT)) {
  4673.                 $path Util::getValidActiveLogByBaseName($this->realContainer'unblockSyncs''unblockSyncs0.txt');
  4674.                 $this->createFileJson($path'Clear blocked syncs: ' $request->getContent() . "\r");
  4675.                 $arrayEncryptResult Util::decryptDataForAndroid($this->realContainer$request->getContent());
  4676.                 $data json_decode($arrayEncryptResult['data'], true);
  4677.                 if (!isset($data['nickname']) || !isset($data['uid'])) {
  4678.                     return $this->errorWrongArgs('Wrong Arguments.'WebService::CODE_WRONG_ARGUMENTS);
  4679.                 }
  4680.                 $licenseUserName = ['alLicenseUsername' => $data['nickname']];
  4681.                 $em $this->getDoctrine()->getManager();
  4682.                 $accountLicenseData $em->getRepository('App\Entity\AccountLicense')->findBy($licenseUserName);
  4683.                 $countResult count($accountLicenseData);
  4684.                 if ($countResult 0) {
  4685.                     if ($accountLicenseData[0]->getDeviceUid() != $data['uid']) {
  4686.                         return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  4687.                                         ->respondWithError('Unknown device'WebService::HTTP_CODE_UNAUTHORIZED);
  4688.                     }
  4689.                     $masterSyncRecords $em->getRepository('App\Entity\MasterSync')->findMastersSyncsInProcessToBlockNewSyncs($accountLicenseData[0]->getId());
  4690.                     if (!empty($masterSyncRecords)) {
  4691.                         foreach ($masterSyncRecords as $masterSync) {
  4692.                             if ($masterSync->getMsType() == MasterSync::MASTER_SYNC_TYPE_DOWUP) {
  4693.                                 $masterSync->setMsStatus(MasterSync::MASTER_STATUS_RESPONDED);
  4694.                                 $downUpSyncRecord $masterSync->getMsSyncRecord();
  4695.                                 $downUpSyncRecord->setRfStatus(ReadFilesData::STATUS_DELIVERED);
  4696.                             } else {
  4697.                                 $masterSync->setMsStatus(MasterSync::MASTER_STATUS_CLOSED);
  4698.                                 $downUpSyncRecord $masterSync->getMsSyncWebRecord();
  4699.                                 $downUpSyncRecord->setRfwStatus(ReadFilesDataWeb::STATUS_RESPONSE_READED);
  4700.                             }
  4701.                             $em->persist($downUpSyncRecord);
  4702.                             $em->persist($masterSync);
  4703.                         }
  4704.                         $em->flush();
  4705.                     }
  4706.                     $responseArr['status'] = WebService::CODE_SUCCESS;
  4707.                     $responseArr['msg'] = 'All blocking syncs are closed!';
  4708.                     $responseArr['bigbag'] = false;
  4709.                     $theUrlTrSt = new LicensorGenericTransformer($this->realContainer$responseArr);
  4710.                     $xxArray $theUrlTrSt->transform();
  4711.                     $jsonContent json_encode($xxArray);
  4712.                     return $this->respondWithItem($jsonContent$theUrlTrSt);
  4713.                 } else {
  4714.                     return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  4715.                                     ->respondWithError('Invalid nickname'WebService::CODE_COULD_NOT_AUTHENTICATE);
  4716.                 }
  4717.             } else {
  4718.                 return $this->errorWrongArgs('Wrong Content!'WebService::CODE_WRONG_ARGUMENTS);
  4719.             }
  4720.         } else {
  4721.             return $this->errorNotAllowedMethod('Method not allowed. Use ' WebService::REQUEST_METHOD_POST " method");
  4722.         }
  4723.     }
  4724.     /**
  4725.      * Funcion para obtener el ultimo error encontrado generico
  4726.      * a la hora de decodificar un json
  4727.      * @author Aealan Z <lrobledo@kijho.com> 11/06/2016
  4728.      * @return string
  4729.      */
  4730.     public function findErrorJsonDecode() {
  4731.         $r '- No error';
  4732.         switch (json_last_error()) {
  4733.             case JSON_ERROR_NONE:
  4734.                 return $r;
  4735.             case JSON_ERROR_DEPTH:
  4736.                 return ' - Maximum stack depth exceeded';
  4737.             case JSON_ERROR_STATE_MISMATCH:
  4738.                 return ' - Underflow or the modes mismatch';
  4739.             case JSON_ERROR_CTRL_CHAR:
  4740.                 return ' - Unexpected control character found';
  4741.             case JSON_ERROR_SYNTAX:
  4742.                 return ' - Syntax error, malformed JSON';
  4743.             case JSON_ERROR_UTF8:
  4744.                 return ' - Malformed UTF-8 characters, possibly incorrectly encoded';
  4745.             default:
  4746.                 return ' - Unknown error';
  4747.         }
  4748.         return $r;
  4749.     }
  4750.     /**
  4751.      * WS para obtener un listado con todas las sublicencias registradas para
  4752.      * una licencia de tipo call center para que el servidor android les asocie
  4753.      * un dispositivo y las sincronice en licensor
  4754.      * @author Aealan Z <lrobledo@kijho.com> 08/10/15
  4755.      * @param \Symfony\Component\HttpFoundation\Request $request datos
  4756.      * de la solicitud
  4757.      * @return Response Json con la informacion de respuesta
  4758.      */
  4759.     public function getSublicenseByLicense(Request $request) {
  4760.         if ($request->getMethod() === WebService::REQUEST_METHOD_POST) {
  4761.             if (=== strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_STRUCTURE) || === strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_TEXT)) {
  4762.                 $path Util::getValidActiveLogByBaseName($this->realContainer'demoLogin''demoLogin0.txt');
  4763.                 $this->createFileJson($path'Login Mobile: ' $request->getContent() . "\r");
  4764.                 $arrayEncryptResult Util::decryptDataForAndroid($this->realContainer$request->getContent());
  4765.                 $data json_decode($arrayEncryptResult['data'], true);
  4766.                 if (!isset($data['nickname']) || !isset($data['uid'])) {
  4767.                     return $this->errorWrongArgs('Wrong Arguments!'WebService::CODE_WRONG_ARGUMENTS);
  4768.                 }
  4769.                 $licenseUserName = ['alLicenseUsername' => $data['nickname']];
  4770.                 $em $this->getDoctrine()->getManager();
  4771.                 $accountLicenseData $em->getRepository('App\Entity\AccountLicense')->findByAlLicenseUsername($licenseUserName);
  4772.                 $countResult count($accountLicenseData);
  4773.                 if ($countResult 0) {
  4774.                     if (!$accountLicenseData[0]->getIsCallCenter()) {
  4775.                         return $this->errorWrongArgs('Invalid license type!'WebService::CODE_WRONG_ARGUMENTS);
  4776.                     }
  4777.                     if ($accountLicenseData[0]->getDeviceUid() == '' || null == $accountLicenseData[0]->getDeviceUid()) {
  4778.                         $accountLicenseByUID $em->getRepository('App\Entity\AccountLicense')->findBy(array('deviceUid' => $data['uid']));
  4779.                         if (!empty($accountLicenseByUID)) {
  4780.                             if ($accountLicenseData[0]->getAlLicenseUsername() != $accountLicenseByUID[0]->getAlLicenseUsername()) {
  4781.                                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  4782.                                                 ->respondWithError('Device already registed with another license!'WebService::CODE_ACCOUNT_SUSPENDED);
  4783.                             }
  4784.                         }
  4785.                         $accountLicenseData[0]->setDeviceUid($data['uid']);
  4786.                     } else {
  4787.                         if ($accountLicenseData[0]->getDeviceUid() != $data['uid']) {
  4788.                             return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  4789.                                             ->respondWithError('Unknown device'WebService::CODE_ACCOUNT_SUSPENDED);
  4790.                         }
  4791.                     }
  4792.                     $arraySubLicense = [];
  4793.                     $sublicensesByLicense $em->getRepository('App\Entity\SubLicense')->findBy(['license' => $accountLicenseData[0]->getId()]);
  4794.                     if (empty($sublicensesByLicense)) {
  4795.                         return $this->errorWrongArgs('No sub-licenses registerede for this license!'WebService::CODE_WRONG_ARGUMENTS);
  4796.                     } else {
  4797.                         foreach ($sublicensesByLicense as $subL) {
  4798.                             $arraySubLicense[] = $subL->getChannelName();
  4799.                         }
  4800.                     }
  4801.                     $em->persist($accountLicenseData[0]);
  4802.                     $em->flush();
  4803.                     $responseArr['status'] = WebService::CODE_SUCCESS;
  4804.                     $responseArr['list'] = json_encode($arraySubLicense);
  4805.                     $theUrlTrSt = new SublicensesListTransformer($this->realContainer$responseArr);
  4806.                     $xxArray $theUrlTrSt->transform();
  4807.                     $jsonContent json_encode($xxArray);
  4808.                     return $this->respondWithItem($jsonContent$theUrlTrSt);
  4809.                 } else {
  4810.                     return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  4811.                                     ->respondWithError('Invalid channel'WebService::CODE_COULD_NOT_AUTHENTICATE);
  4812.                 }
  4813.             } else {
  4814.                 return $this->errorWrongArgs('Wrong Content!'WebService::CODE_WRONG_ARGUMENTS);
  4815.             }
  4816.         } else {
  4817.             return $this->errorNotAllowedMethod('Method not allowed. Use ' WebService::REQUEST_METHOD_POST " method");
  4818.         }
  4819.     }
  4820.     /**
  4821.      * WS para registrar la pushy key del dispositivo de una sublicencia
  4822.      * @author Aealan Z <lrobledo@kijho.com> 03/11/15
  4823.      * @param \Symfony\Component\HttpFoundation\Request $request datos
  4824.      * de la solicitud
  4825.      * @return Response Json con la informacion de respuesta
  4826.      */
  4827.     public function registerPushyKeyToSublicense(Request $request) {
  4828.         if ($request->getMethod() === WebService::REQUEST_METHOD_POST) {
  4829.             if (=== strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_STRUCTURE) || === strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_TEXT)) {
  4830.                 $path Util::getValidActiveLogByBaseName($this->realContainer'subLRegisterPushy''subLRegisterPushy0.txt');
  4831.                 $this->createFileJson($path'Request Sub Pushy: ' $request->getContent() . "\r");
  4832.                 try {
  4833.                     $arrayEncryptResult Util::decryptDataForAndroid($this->realContainer$request->getContent());
  4834.                     $data json_decode($arrayEncryptResult['data'], true);
  4835.                     $this->createFileJson($path'Decrypted: ' $request->getContent() . "\r");
  4836.                     if (!isset($data['channelname']) || !isset($data['uid']) || !isset($data['pushy'])) {
  4837.                         return $this->errorWrongArgs('Wrong Arguments.'WebService::CODE_WRONG_ARGUMENTS);
  4838.                     }
  4839.                     $em $this->getDoctrine()->getManager();
  4840.                     $accountLicenseData $em->getRepository('App\Entity\SubLicense')
  4841.                             ->findBy(['channelName' => $data['channelname']]);
  4842.                     $countResult count($accountLicenseData);
  4843.                     $this->createFileJson($path'Lic Sub Count: ' $countResult "\r");
  4844.                     if ($countResult 0) {
  4845.                         if ($accountLicenseData[0]->getDeviceUid() == '' || null == $accountLicenseData[0]->getDeviceUid()) {
  4846.                             $this->createFileJson($path'Into IF 1: ' "\r");
  4847.                             $accountLicenseByUID $em->getRepository('App\Entity\SubLicense')->findBy(['deviceUid' => $data['uid']]);
  4848.                             if (!empty($accountLicenseByUID)) {
  4849.                                 $this->createFileJson($path'IF 2: cha ' $accountLicenseData[0]->getChannelName() . ' chaByUID ' $accountLicenseByUID[0]->getChannelName() . "\r");
  4850.                                 if ($accountLicenseData[0]->getChannelName() != $accountLicenseByUID[0]->getChannelName()) {
  4851.                                     $this->createFileJson($path'Error IF 2: ' "\r");
  4852.                                     return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  4853.                                                     ->respondWithError('Device already registed with another license!'WebService::HTTP_CODE_UNAUTHORIZED);
  4854.                                 }
  4855.                             }
  4856.                             $accountLicenseData[0]->setDeviceUid($data['uid']);
  4857.                         } else {
  4858.                             $this->createFileJson($path'IF 3: UID ' $accountLicenseData[0]->getDeviceUid() . ' requeUID ' $data['uid'] . "\r");
  4859.                             if ($accountLicenseData[0]->getDeviceUid() != $data['uid']) {
  4860.                                 $this->createFileJson($path'Error IF 3: ' "\r");
  4861.                                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  4862.                                                 ->respondWithError('Unknown device'WebService::HTTP_CODE_UNAUTHORIZED);
  4863.                             }
  4864.                         }
  4865.                         if ($accountLicenseData[0]->getPushyKey() == '' || null == $accountLicenseData[0]->getPushyKey()) {
  4866.                             $accountLicenseByPushy $em->getRepository('App\Entity\SubLicense')->findBy(['pushyKey' => $data['pushy']]);
  4867.                             if (!empty($accountLicenseByPushy)) {
  4868.                                 $this->createFileJson($path'IF 4: cha ' $accountLicenseData[0]->getChannelName() . ' chaPushy ' $accountLicenseByPushy[0]->getChannelName() . "\r");
  4869.                                 if ($accountLicenseData[0]->getChannelName() != $accountLicenseByPushy[0]->getChannelName()) {
  4870.                                     $this->createFileJson($path'Error IF 4: ' "\r");
  4871.                                     return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  4872.                                                     ->respondWithError('Push key registed with another license!'WebService::HTTP_CODE_UNAUTHORIZED);
  4873.                                 }
  4874.                             }
  4875.                             $accountLicenseData[0]->setPushyKey($data['pushy']);
  4876.                         } else {
  4877.                             $this->createFileJson($path'IF 5: Pushy ' $accountLicenseData[0]->getPushyKey() . ' requePushy ' $data['pushy'] . "\r");
  4878.                             if ($accountLicenseData[0]->getPushyKey() != $data['pushy']) {
  4879.                                 $this->createFileJson($path'Error IF 5: ' "\r");
  4880.                                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  4881.                                                 ->respondWithError('Unknown device'WebService::HTTP_CODE_UNAUTHORIZED);
  4882.                             }
  4883.                         }
  4884.                         $em->persist($accountLicenseData[0]);
  4885.                         $em->flush();
  4886.                         Util::updateAllPushKey([
  4887.                             "nickname"              => $accountLicenseData[0]->getAlLicenseUsername(),
  4888.                             "pushyKey"              => $data['pushy'],
  4889.                             "awsPushEndPoint"       => $accountLicenseData[0]->getAwsPushEndPoint(),
  4890.                             "awsTopicARN"           => $accountLicenseData[0]->getAwsTopicARN(),
  4891.                             "awsSubscriptionARN"    => $accountLicenseData[0]->getAwsSubscriptionARN(),
  4892.                             "awsDeviceToken"        => $accountLicenseData[0]->getAwsDeviceToken(),
  4893.                         ], $this->realContainer);
  4894.                         $em Util::emLicenseConnection($this->realContainer$em$accountLicenseData[0]->getLicense());
  4895.                         $remoteStation $em->getRepository('App\Structure\RemoteStation')->findBy(['parse' => $data['channelname']]);
  4896.                         if (empty($remoteStation)) {
  4897.                             $this->createFileJson($path'Error IF 6: ' "\r");
  4898.                             return $this->setStatusCode(WebService::HTTP_CODE_FORBIDDEN)
  4899.                                             ->respondWithError('Sublicense device record not found!'WebService::CODE_OBJECT_NOT_FOUND);
  4900.                         } else {
  4901.                             $this->createFileJson($path':D' "\r");
  4902.                             $remoteStation[0]->setPushy($data['pushy']);
  4903.                             $registActions = new RegistActions();
  4904.                             $registActions->setReacTableName('remote_stations');
  4905.                             $registActions->setReacTableId($remoteStation[0]->getId());
  4906.                             $registActions->setReacTableAction('U');
  4907.                             $registActions->setReacRegistFk(0);
  4908.                             $registActions->setReacAndroidId($remoteStation[0]->getAndroidSync());
  4909.                             $actualDate Util::getCurrentDate();
  4910.                             $registActions->setReacDateTime($actualDate);
  4911.                             $registActions->setReacEstatus(RegistActions::STATUS_NOTREADED);
  4912.                             $em->persist($remoteStation[0]);
  4913.                             $em->persist($registActions);
  4914.                             $em->flush();
  4915.                         }
  4916.                         $responseArr['status'] = WebService::CODE_SUCCESS;
  4917.                         $responseArr['msg'] = 'Valid license channel and pushy key registered!';
  4918.                         $responseArr['bigbag'] = false;
  4919.                         $theUrlTrSt = new LicensorGenericTransformer($this->realContainer$responseArr);
  4920.                         $xxArray $theUrlTrSt->transform();
  4921.                         $jsonContent json_encode($xxArray);
  4922.                         return $this->respondWithItem($jsonContent$theUrlTrSt);
  4923.                     } else {
  4924.                         return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  4925.                                         ->respondWithError('Invalid channel'WebService::CODE_COULD_NOT_AUTHENTICATE);
  4926.                     }
  4927.                 } catch (\Throwable $th) {
  4928.                     $err = ['Error message' => $th->getMessage(), 'Error line' => $th->getLine(), 'Error file' => $th->getFile(), 'Error trance' => $th->getTrace()];
  4929.                     $this->createFileJson($path'Alert Error: ' json_encode($err) . "\r");
  4930.                     return $this->errorWrongArgs('Wrong Content!'WebService::CODE_WRONG_ARGUMENTS);
  4931.                 }
  4932.             } else {
  4933.                 return $this->errorWrongArgs('Wrong Content!'WebService::CODE_WRONG_ARGUMENTS);
  4934.             }
  4935.         } else {
  4936.             return $this->errorNotAllowedMethod('Method not allowed. Use ' WebService::REQUEST_METHOD_POST " method");
  4937.         }
  4938.     }
  4939.     /**
  4940.      * WS para registrar la pushy key de un dispositivo de una licencia
  4941.      * @author Aealan Z <lrobledo@kijho.com> 05/11/15
  4942.      * @param \Symfony\Component\HttpFoundation\Request $request datos
  4943.      * de la solicitud
  4944.      * @return Response Json con la informacion de respuesta
  4945.      */
  4946.     public function registerPushyKeyToLicense(Request $request) {
  4947.         if ($request->getMethod() === WebService::REQUEST_METHOD_POST) {
  4948.             if (=== strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_STRUCTURE) || === strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_TEXT)) {
  4949.                 $path Util::getValidActiveLogByBaseName($this->realContainer'pushyRegist''pushyRegist0.txt');
  4950.                 $this->createFileJson($path"\r" 'Register Pushy Key: ' $request->getContent() . "\r");
  4951.                 try {
  4952.                     $arrayEncryptResult Util::decryptDataForAndroid($this->realContainer$request->getContent());
  4953.                     $data json_decode($arrayEncryptResult['data'], true);
  4954.                     if (!isset($data['nickname']) || !isset($data['uid']) || !isset($data['pushy'])) {
  4955.                         return $this->errorWrongArgs('Wrong Arguments.'WebService::CODE_WRONG_ARGUMENTS);
  4956.                     }
  4957.                     $this->createFileJson($path'Decrypted: ' $arrayEncryptResult['data'] . "\r");
  4958.                     if ($data['nickname'] == '' || $data['uid'] == '' || $data['pushy'] == '') {
  4959.                         return $this->errorWrongArgs('Empty Arguments.'WebService::CODE_WRONG_ARGUMENTS);
  4960.                     }
  4961.                     $licenseUserName = ['alLicenseUsername' => $data['nickname']];
  4962.                     $em $this->getDoctrine()->getManager();
  4963.                     $accountLicenseData $em->getRepository('App\Entity\AccountLicense')->findBy($licenseUserName);
  4964.                     $countResult count($accountLicenseData);
  4965.                     
  4966.                     if ($countResult 0) {
  4967.                         $accountLicenseByPushy $em->getRepository('App\Entity\AccountLicense')->findBy(['pushyKey' => $data['pushy']]);
  4968.                         // $accountLicenseByPushy = $em->getRepository('App\Entity\AccountLicense')->getLicenseByPushy($data['pushy'], $data['nickname']);
  4969.                         // function internaSaveInRegistAction($container, $em, $license){
  4970.                         //     $emLev = Util::emLicenseConnection($container, $em, $license);
  4971.                         //     $registAction = $emLev->getRepository('App\Structure\RegistActions')->findOneBy(['reacTableName' => 'licensor1', 'reacTableAction' => RegistActions::ACTION_UPDATE, 'reacStatus' => RegistActions::STATUS_NOTREADED]);
  4972.                         //     if(is_null($registAction)){
  4973.                         //         $registAction = new RegistActions();
  4974.                         //         $registAction->setReacTableName('licensor1');
  4975.                         //         $registAction->setReacTableId($license->getId());
  4976.                         //         $registAction->setReacTableAction(RegistActions::ACTION_UPDATE);
  4977.                         //         $registAction->setReacAndroidId($license->getId());
  4978.                         //         $actualDate = Util::getCurrentDate();
  4979.                         //         $registAction->setReacDateTime($actualDate);
  4980.                         //         $emLev->persist($registAction);
  4981.                         //         $emLev->flush();
  4982.                         //     }
  4983.                         // }
  4984.                         if ($accountLicenseData[0]->getPushyKey() == '' || null == $accountLicenseData[0]->getPushyKey()) {
  4985.                             if (!empty($accountLicenseByPushy)) {
  4986.                                 if ($accountLicenseData[0]->getAlLicenseUsername() != $accountLicenseByPushy[0]->getAlLicenseUsername()) {
  4987.                                     $this->createFileJson($path'Error: push key registed with -> ' $accountLicenseByPushy[0]->getAlLicenseUsername() . ' license!' "\r");
  4988.                                     return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  4989.                                                     ->respondWithError('Push key registed with '.$accountLicenseByPushy[0]->getAlLicenseUsername().' license!'WebService::HTTP_CODE_UNAUTHORIZED);
  4990.                                 }
  4991.                             }
  4992.                             $accountLicenseData[0]->setPushyKey($data['pushy']);
  4993.                             // $this->createFileJson($path, 'New regist action before insert new pushy key '. "\r");
  4994.                             // internaSaveInRegistAction($this->realContainer, $em, $accountLicenseData[0]);
  4995.                         } else {
  4996.                             if ($accountLicenseData[0]->getPushyKey() != $data['pushy']) {
  4997.                                 if (empty($accountLicenseByPushy)) {
  4998.                                     $accountLicenseData[0]->setPushyKey($data['pushy']);
  4999.                                     
  5000.                                     // $this->createFileJson($path, 'New regist action before insert new pushy key '. "\r");
  5001.                                     // internaSaveInRegistAction($this->realContainer, $em, $accountLicenseData[0]);
  5002.                                 } else {
  5003.                                     return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  5004.                                                     ->respondWithError('Unknown device'WebService::HTTP_CODE_UNAUTHORIZED);
  5005.                                 }
  5006.                             }
  5007.                         }
  5008.                         $em->persist($accountLicenseData[0]);
  5009.                         $em->flush();
  5010.                         Util::updateAllPushKey([
  5011.                             "nickname"              => $accountLicenseData[0]->getAlLicenseUsername(),
  5012.                             "pushyKey"              => $data['pushy'],
  5013.                             "awsPushEndPoint"       => $accountLicenseData[0]->getAwsPushEndPoint(),
  5014.                             "awsTopicARN"           => $accountLicenseData[0]->getAwsTopicARN(),
  5015.                             "awsSubscriptionARN"    => $accountLicenseData[0]->getAwsSubscriptionARN(),
  5016.                             "awsDeviceToken"        => $accountLicenseData[0]->getAwsDeviceToken(),
  5017.                         ], $this->realContainer);
  5018.                         $responseArr['status'] = WebService::CODE_SUCCESS;
  5019.                         $responseArr['msg'] = 'Valid license and push key registered!';
  5020.                         $responseArr['bigbag'] = false;
  5021.                         $theUrlTrSt = new LicensorGenericTransformer($this->realContainer$responseArr);
  5022.                         $xxArray $theUrlTrSt->transform();
  5023.                         $jsonContent json_encode($xxArray);
  5024.                         $this->createFileJson($path'Response to Android: ' $jsonContent "\r");
  5025.                         return $this->respondWithItem($jsonContent$theUrlTrSt);
  5026.                     } else {
  5027.                         return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  5028.                                         ->respondWithError('Invalid channel'WebService::CODE_COULD_NOT_AUTHENTICATE);
  5029.                     }
  5030.                 } catch (\Throwable $th) {
  5031.                     $err = ['Error message' => $th->getMessage(), 'Error line' => $th->getLine(), 'Error file' => $th->getFile(), 'Error trance' => $th->getTrace()];
  5032.                     $this->createFileJson($path'Alert Error: ' json_encode($err) . "\r");
  5033.                     return $this->errorWrongArgs('Service error, please contact support.'WebService::CODE_WRONG_ARGUMENTS);
  5034.                 }
  5035.             } else {
  5036.                 return $this->errorWrongArgs('Wrong content format, please contact support.'WebService::CODE_WRONG_ARGUMENTS);
  5037.             }
  5038.         } else {
  5039.             return $this->errorNotAllowedMethod('Method not allowed. Use ' WebService::REQUEST_METHOD_POST " method");
  5040.         }
  5041.     }
  5042.     /**
  5043.      * WS para registrar la pushy key de un dispositivo de una licencia
  5044.      * @author Aealan Z <lrobledo@kijho.com> 05/11/15
  5045.      * @param \Symfony\Component\HttpFoundation\Request $request datos
  5046.      * de la solicitud
  5047.      * @return Response Json con la informacion de respuesta
  5048.      */
  5049.     public function createAndSendPusherVerificationPush(Request $request) {
  5050.         // if ($request->getMethod() !== WebService::REQUEST_METHOD_POST) {
  5051.         //     return $this->errorNotAllowedMethod('Method not allowed. Use ' . WebService::REQUEST_METHOD_POST . " method");
  5052.         // }
  5053.         // if (0 !== strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_STRUCTURE) && 0 !== strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_STRUCTURE)) {
  5054.         //     return $this->errorWrongArgs('Wrong Content!', WebService::CODE_WRONG_ARGUMENTS);
  5055.         // }
  5056.             
  5057.         $response       false;
  5058.         $statusCode     200;
  5059.         $msg "Valid license and pusher validation push send!";
  5060.         $path Util::getValidActiveLogByBaseName($this->realContainer'createAndSendPusherVerificationPush''createAndSendPusherVerificationPush0.txt');
  5061.         $this->createFileJson($path"\r" 'Register Pusher Key: ' $request->getContent() . "\r");
  5062.         $channelName    $request->get('channel_name');
  5063.         $socketId       $request->get('socket_id');
  5064.         try {
  5065.             $arrayEncryptResult Util::decryptDataForAndroid($this->realContainer$request->getContent());
  5066.             $data json_decode($arrayEncryptResult['data'], true);
  5067.             if (!isset($data['nickname']) || !isset($data['uid']) || !isset($socketId) || !isset($channelName)) {
  5068.                 return $this->errorWrongArgs('Wrong Arguments.'WebService::CODE_WRONG_ARGUMENTS);
  5069.             }
  5070.             $this->createFileJson($path'Decrypted: ' $arrayEncryptResult['data'] . "\r");
  5071.             if ($data['nickname'] == '' || $data['uid'] == '' || $socketId == '' || $channelName == '') {
  5072.                 return $this->errorWrongArgs('Empty Arguments.'WebService::CODE_WRONG_ARGUMENTS);
  5073.             }
  5074.             $licenseUserName = ['alLicenseUsername' => $data['nickname']];
  5075.             $em $this->getDoctrine()->getManager();
  5076.             $accountLicenseData $em->getRepository('App\Entity\AccountLicense')->findBy($licenseUserName);
  5077.             $countResult count($accountLicenseData);
  5078.             if ($countResult <= 0) {
  5079.                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  5080.                     ->respondWithError('Invalid nickname'WebService::CODE_COULD_NOT_AUTHENTICATE);
  5081.             }
  5082.             if ($accountLicenseData[0]->getDeviceUid() != $data['uid']) {
  5083.                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  5084.                     ->respondWithError('Wrong device UID'WebService::CODE_COULD_NOT_AUTHENTICATE);
  5085.             }
  5086.             // function internalSaveInRegistAction($container, $em, $license) {
  5087.             //     $emLev = Util::emLicenseConnection($container, $em, $license);
  5088.             //     $registAction = $emLev->getRepository('App\Structure\RegistActions')->findOneBy(['reacTableName' => 'licensor1', 'reacTableAction' => RegistActions::ACTION_UPDATE, 'reacStatus' => RegistActions::STATUS_NOTREADED]);
  5089.             //     if(is_null($registAction)){
  5090.             //         $registAction = new RegistActions();
  5091.             //         $registAction->setReacTableName('licensor1');
  5092.             //         $registAction->setReacTableId($license->getId());
  5093.             //         $registAction->setReacTableAction(RegistActions::ACTION_UPDATE);
  5094.             //         $registAction->setReacAndroidId($license->getId());
  5095.             //         $actualDate = Util::getCurrentDate();
  5096.             //         $registAction->setReacDateTime($actualDate);
  5097.             //         $emLev->persist($registAction);
  5098.             //         $emLev->flush();
  5099.             //     }
  5100.             // }
  5101.             if($channelName === 'presence-'.$data['nickname']){
  5102.                 if(strpos($channelName'presence-') !== false) {
  5103.                     $user = array(
  5104.                         "user_id" => $data['uid'],
  5105.                         "user_info" => [
  5106.                             "name" => $data['nickname']
  5107.                         ]
  5108.                     );
  5109.                     $ownAPIsKeys $em->getRepository('App\Entity\ThirdPartyAPIRecords')->getOwnPushServicesByLicense($accountLicenseData[0]->getId(), ThirdPartyAPIRecords::API_PUSHER);
  5110.                     if (!empty($ownAPIsKeys)) {
  5111.                         $pusher = new PusherManager($ownAPIsKeys[ThirdPartyAPIRecords::API_PUSHER]);
  5112.                     } else {
  5113.                         $pusher = new PusherManager();
  5114.                     }
  5115.                     $response $pusher->authorizeChannel($channelName$socketId$user);
  5116.                     if(!empty($response)){
  5117.                         $newPusherTokenCallResult NewUtil::generateNewPusherVerificationToken($this->realContainer$em$accountLicenseData[0], $path);
  5118.                         if (is_string($newPusherTokenCallResult)) {
  5119.                             $this->createFileJson($path'Error creating new pusher token -> ' $newPusherTokenCallResult "\r");
  5120.                         } else {
  5121.                             $msg 'New pusher token created!';
  5122.                             $statusCode     200;
  5123.                             $this->createFileJson($path'New pusher token created!'"\r");
  5124.                         }
  5125.                         $pushWithSameKey true;
  5126.                         $thePushKey false;
  5127.         
  5128.                         while (!empty($pushWithSameKey)) {
  5129.                             $thePushKey Util::randomPushKey();
  5130.                             $pushWithSameKey $em->getRepository('App\Entity\PushSent')->searchPushSendRecords($thePushKey);
  5131.                         }
  5132.         
  5133.                         $pushEntity = new PushSent();
  5134.         
  5135.                         $pushVerificationCode Util::createRegistPushSend($em$pushEntityPushSent::PUSH_TYPE_COMFIRM_PUSHER_LICENSE_CHANNEL$thePushKey$accountLicenseData[0], truefalse$path);
  5136.         
  5137.                         $response json_decode($responsetrue);
  5138.                         $token["actions"] = 'ping';
  5139.                         $token["nickname"] = $accountLicenseData[0]->getAlLicenseUsername();
  5140.                         $token["pusherToken"] = $accountLicenseData[0]->getPusherOwnVerificationToken();
  5141.         
  5142.                         if ($pushVerificationCode && $pushVerificationCode != '') {
  5143.                             $this->createFileJson($path'Push send record created!' "\r");
  5144.                             $token["code"] = $pushVerificationCode;
  5145.                         }
  5146.                         // $response['verify'] = $token;
  5147.                         ForcedAsynchronousCommandsUtil::sendPusherPushNotification($this->realContainer,  'presence-'.$accountLicenseData[0]->getAlLicenseUsername(), $token0$pathtrue);
  5148.                         $em->persist($accountLicenseData[0]);
  5149.                         $em->flush();
  5150.                     }else {
  5151.                         $msg "Not authorized channel!";
  5152.                         $statusCode     403;
  5153.                         throw new Exception('Not authorized channel! 1');
  5154.                     }
  5155.                 } else {
  5156.                     $msg "Not authorized channel!";
  5157.                     $statusCode     403;
  5158.                     throw new Exception('Not authorized channel! 2');
  5159.                 }
  5160.             }else {
  5161.                 $msg "Not authorized channel!";
  5162.                 $statusCode     403;
  5163.                 throw new Exception('Not authorized channel! 3');
  5164.             }
  5165.             // return $this->respondWithItem($jsonContent, $theUrlTrSt);
  5166.             return new JsonResponse($response$statusCode);
  5167.         } catch (\Throwable $th) {
  5168.             $err = ['Error message' => $th->getMessage(), 'Error line' => $th->getLine(), 'Error file' => $th->getFile(), 'Error trance' => $th->getTrace()];
  5169.             $this->createFileJson($path'Alert Error: ' json_encode($err) . "\r");
  5170.             return $this->errorWrongArgs('Wrong Content!'WebService::CODE_WRONG_ARGUMENTS);
  5171.         }
  5172.     }
  5173.     /**
  5174.      * WS para registrar el device token de una licencia para los push de AWS
  5175.      * @author Aealan Z <lrobledo@openmytab.com> 21/10/22
  5176.      * @param \Symfony\Component\HttpFoundation\Request $request datos
  5177.      * de la solicitud
  5178.      * @return Response Json con la informacion de respuesta
  5179.      */
  5180.     public function registerAWSDeviceTokenToPushService(Request $request) {
  5181.         if ($request->getMethod() !== WebService::REQUEST_METHOD_POST) {
  5182.             return $this->errorNotAllowedMethod('Method not allowed. Use ' WebService::REQUEST_METHOD_POST " method");
  5183.         }
  5184.         if (!== strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_STRUCTURE) && !== strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_TEXT)) {
  5185.             return $this->errorWrongArgs('Wrong Content!'WebService::CODE_WRONG_ARGUMENTS);
  5186.         }
  5187.         $path Util::getValidActiveLogByBaseName($this->realContainer'registerAWSDeviceTokenToPushService''registerAWSDeviceTokenToPushService0.txt');
  5188.         $this->createFileJson($path"\r" 'Register AWS Device Token: ' $request->getContent() . "\r");
  5189.         $arrayEncryptResult Util::decryptDataForAndroid($this->realContainer$request->getContent());
  5190.         $data json_decode($arrayEncryptResult['data'], true);
  5191.         if (!isset($data['nickname']) || !isset($data['uid']) || !isset($data['deviceToken'])) {
  5192.             return $this->errorWrongArgs('Wrong Arguments.'WebService::CODE_WRONG_ARGUMENTS);
  5193.         }
  5194.         $this->createFileJson($path'Decrypted: ' $arrayEncryptResult['data'] . "\r");
  5195.         if ($data['nickname'] == '' || $data['uid'] == '' || $data['deviceToken'] == '') {
  5196.             return $this->errorWrongArgs('Empty Arguments.'WebService::CODE_WRONG_ARGUMENTS);
  5197.         }
  5198.         $licenseUserName = ['alLicenseUsername' => $data['nickname']];
  5199.         $em $this->getDoctrine()->getManager();
  5200.         $accountLicenseData $em->getRepository('App\Entity\AccountLicense')->findBy($licenseUserName);
  5201.         $countResult count($accountLicenseData);
  5202.         if ($countResult <= 0) {
  5203.             return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  5204.                             ->respondWithError('Invalid nickname'WebService::CODE_COULD_NOT_AUTHENTICATE);
  5205.         }
  5206.         $accountLicenseByPushy $em->getRepository('App\Entity\AccountLicense')->findBy(['awsDeviceToken' => $data['deviceToken']]);
  5207.         if ($accountLicenseData[0]->getPushyKey() == '' || null == $accountLicenseData[0]->getPushyKey()) {
  5208.             if (!empty($accountLicenseByPushy)) {
  5209.                 if ($accountLicenseData[0]->getAlLicenseUsername() != $accountLicenseByPushy[0]->getAlLicenseUsername()) {
  5210.                     return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  5211.                                     ->respondWithError('DeviceToken registed with another license!'WebService::HTTP_CODE_UNAUTHORIZED);
  5212.                 }
  5213.             }
  5214.             $accountLicenseData[0]->setAwsDeviceToken($data['deviceToken']);
  5215.         } else {
  5216.             if ($accountLicenseData[0]->getAwsDeviceToken() != $data['deviceToken']) {
  5217.                 if (empty($accountLicenseByPushy)) {
  5218.                     $accountLicenseData[0]->setAwsDeviceToken($data['deviceToken']);
  5219.                 } else {
  5220.                     return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  5221.                                     ->respondWithError('Unknown device'WebService::HTTP_CODE_UNAUTHORIZED);
  5222.                 }
  5223.             }
  5224.         }
  5225.         if (!$accountLicenseData[0]->getAwsTopicARN()) {
  5226.             $creationTopicARNResult NewUtil::registerAlternateNewDeviceToAWSSNSPushService($this->realContainer$em$accountLicenseData[0], $data['deviceToken'], $path);
  5227.             $this->createFileJson($path'Creation of TopicARN result: ' json_encode($creationTopicARNResult) . "\r");
  5228.         }
  5229.         $arrayResult NewUtil::registerAlternateCreateAppEndpointForDeviceSNSPushService($this->realContainer$em$accountLicenseData[0], $data['deviceToken'], $path);
  5230.         if (is_array($arrayResult) && isset($arrayResult['licenseEntity'])) {
  5231.             $accountLicenseData[0] = $arrayResult['licenseEntity'];
  5232.         }
  5233.         if (is_array($arrayResult) && isset($arrayResult['EndpointArn'])) {
  5234.             $responseArr['endpointArn'] = $arrayResult['EndpointArn'];
  5235.         } else {
  5236.             $responseArr['endpointArn'] = $arrayResult;
  5237.         }
  5238.         $arraySecondResult NewUtil::registerAlternateSubscriptionToTopicForDeviceSNSPushService($this->realContainer$em$accountLicenseData[0], $path);
  5239.         if (is_array($arraySecondResult) && isset($arraySecondResult['SubscriptionArn'])) {
  5240.             $responseArr['subscriptionArn'] = $arraySecondResult['SubscriptionArn'];
  5241.         } else {
  5242.             $responseArr['subscriptionArn'] = $arraySecondResult;
  5243.         }
  5244.         $responseArr['status'] = WebService::CODE_SUCCESS;
  5245.         $responseArr['msg'] = "Valid license and AWS token registered with it's endpoint and topic subscription!";
  5246.         $responseArr['topicArn'] = $accountLicenseData[0]->getAwsTopicARN();
  5247.         $responseArr['bigbag'] = true;
  5248.                 
  5249.         Util::updateAllPushKey([
  5250.             "nickname"              => $accountLicenseData[0]->getAlLicenseUsername(),
  5251.             "awsPushEndPoint"       => $accountLicenseData[0]->getAwsPushEndPoint(),
  5252.             "awsTopicARN"           => $accountLicenseData[0]->getAwsTopicARN(),
  5253.             "awsSubscriptionARN"    => $accountLicenseData[0]->getAwsSubscriptionARN(),
  5254.             "awsDeviceToken"        => $accountLicenseData[0]->getAwsDeviceToken(),
  5255.         ], $this->realContainer);
  5256.         $theUrlTrSt = new LicensorGenericTransformer($this->realContainer$responseArr);
  5257.         $xxArray $theUrlTrSt->transform();
  5258.         $jsonContent json_encode($xxArray);
  5259.         return $this->respondWithItem($jsonContent$theUrlTrSt);
  5260.     }
  5261.     /**
  5262.      * WS para registrar la pushy key de un dispositivo de una licencia
  5263.      * @author Aealan Z <lrobledo@kijho.com> 05/11/15
  5264.      * @param \Symfony\Component\HttpFoundation\Request $request datos
  5265.      * de la solicitud
  5266.      * @return Response Json con la informacion de respuesta
  5267.      */
  5268.     public function registerCodeInstallToLicense(Request $request) {
  5269.         if ($request->getMethod() === WebService::REQUEST_METHOD_POST) {
  5270.             if (=== strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_STRUCTURE) || === strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_TEXT)) {
  5271.                 $path Util::getValidActiveLogByBaseName($this->realContainer'codeInstallRegist''codeInstallRegist0.txt');
  5272.                 $this->createFileJson($path"\r" 'Register Code Install: ' $request->getContent() . "\r");
  5273.                 $arrayEncryptResult Util::decryptDataForAndroid($this->realContainer$request->getContent());
  5274.                 $data json_decode($arrayEncryptResult['data'], true);
  5275.                 if (!isset($data['nickname']) || !isset($data['uid']) || !isset($data['codeInstall'])) {
  5276.                     return $this->errorWrongArgs('Wrong Arguments.'WebService::CODE_WRONG_ARGUMENTS);
  5277.                 }
  5278.                 $this->createFileJson($path'Decrypted: ' $arrayEncryptResult['data'] . "\r");
  5279.                 if ($data['nickname'] == '' || $data['uid'] == '' || $data['codeInstall'] == '') {
  5280.                     return $this->errorWrongArgs('Empty Arguments.'WebService::CODE_WRONG_ARGUMENTS);
  5281.                 }
  5282.                 $licenseUserName = ['alLicenseUsername' => $data['nickname']];
  5283.                 $em $this->getDoctrine()->getManager();
  5284.                 $accountLicenseData $em->getRepository('App\Entity\AccountLicense')->findBy($licenseUserName);
  5285.                 $countResult count($accountLicenseData);
  5286.                 if ($countResult 0) {
  5287.                     if ($accountLicenseData[0]->getAlAccountLicense()->getDeleted()) {
  5288.                         return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  5289.                                         ->respondWithError('Account is inactive'WebService::CODE_ACCOUNT_SUSPENDED);
  5290.                     }
  5291.                     if ($accountLicenseData[0]->getAlLicenseStatus() != AccountLicense::LICENSE_STATUS_ACTIVE) {
  5292.                         return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  5293.                                         ->respondWithError('License is inactive'WebService::CODE_ACCOUNT_SUSPENDED);
  5294.                     }
  5295.                     $accountLicenseData[0]->setApkInstallCode($data['codeInstall']);
  5296.                     $em->persist($accountLicenseData[0]);
  5297.                     $em->flush();
  5298.                     $responseArr['status'] = WebService::CODE_SUCCESS;
  5299.                     $responseArr['msg'] = 'Code install registered!';
  5300.                     $responseArr['bigbag'] = false;
  5301.                     $theUrlTrSt = new LicensorGenericTransformer($this->realContainer$responseArr);
  5302.                     $xxArray $theUrlTrSt->transform();
  5303.                     $jsonContent json_encode($xxArray);
  5304.                     return $this->respondWithItem($jsonContent$theUrlTrSt);
  5305.                 } else {
  5306.                     return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  5307.                                     ->respondWithError('Invalid channel'WebService::CODE_COULD_NOT_AUTHENTICATE);
  5308.                 }
  5309.             } else {
  5310.                 return $this->errorWrongArgs('Wrong Content!'WebService::CODE_WRONG_ARGUMENTS);
  5311.             }
  5312.         } else {
  5313.             return $this->errorNotAllowedMethod('Method not allowed. Use ' WebService::REQUEST_METHOD_POST " method");
  5314.         }
  5315.     }
  5316.     /**
  5317.      * WS para registrar la pushy key de un dispositivo de una licencia
  5318.      * @author Aealan Z <lrobledo@kijho.com> 05/11/15
  5319.      * @param \Symfony\Component\HttpFoundation\Request $request datos
  5320.      * de la solicitud
  5321.      * @return Response Json con la informacion de respuesta
  5322.      */
  5323.     public function notifyFattyAndroidDatabase(Request $request) {
  5324.         if ($request->getMethod() === WebService::REQUEST_METHOD_POST) {
  5325.             if (=== strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_STRUCTURE) || === strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_TEXT)) {
  5326.                 $path Util::getValidActiveLogByBaseName($this->realContainer'notifyFattyAndroidDatabase''notifyFattyAndroidDatabase0.txt');
  5327.                 $this->createFileJson($path"\r" 'Notify Fatty Android Database: ' $request->getContent() . "\r");
  5328.                 $arrayEncryptResult Util::decryptDataForAndroid($this->realContainer$request->getContent());
  5329.                 $data json_decode($arrayEncryptResult['data'], true);
  5330.                 if (!isset($data['nickname']) || !isset($data['uid'])) {
  5331.                     return $this->errorWrongArgs('Wrong Arguments.'WebService::CODE_WRONG_ARGUMENTS);
  5332.                 }
  5333.                 $this->createFileJson($path'Decrypted: ' $arrayEncryptResult['data'] . "\r");
  5334.                 if ($data['nickname'] == '' || $data['uid'] == '') {
  5335.                     return $this->errorWrongArgs('Empty Arguments.'WebService::CODE_WRONG_ARGUMENTS);
  5336.                 }
  5337.                 $licenseUserName = ['alLicenseUsername' => $data['nickname']];
  5338.                 $em $this->getDoctrine()->getManager();
  5339.                 $accountLicenseData $em->getRepository('App\Entity\AccountLicense')->findBy($licenseUserName);
  5340.                 $countResult count($accountLicenseData);
  5341.                 if ($countResult 0) {
  5342.                     if ($accountLicenseData[0]->getAlAccountLicense()->getDeleted()) {
  5343.                         return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  5344.                                         ->respondWithError('Account is inactive'WebService::CODE_ACCOUNT_SUSPENDED);
  5345.                     }
  5346.                     if ($accountLicenseData[0]->getAlLicenseStatus() != AccountLicense::LICENSE_STATUS_ACTIVE) {
  5347.                         return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  5348.                                         ->respondWithError('License is inactive'WebService::CODE_ACCOUNT_SUSPENDED);
  5349.                     }
  5350.                     if (isset($data['days']) && ((int) $data['days']) > 0) {
  5351.                         $emLev Util::emLicenseConnection($this->realContainer$em$accountLicenseData[0]);
  5352.                         $configurationLicenseRecord $emLev->getRepository('App\Structure\Configuracion')->find(1);
  5353.                         $configurationLicenseRecord->setConfAllowAutoCleanseDB(1);
  5354.                         $configurationLicenseRecord->setConfDataSinceLastDays((int) $data['days']);
  5355.                         $emLev->persist($configurationLicenseRecord);
  5356.                         $emLev->flush();
  5357.                         $this->createFileJson($path"Auto cleanse configured with '" $data['days'] . "' ... \r");
  5358.                     }
  5359.                     $this->createFileJson($path'Ready for new cleanse request to be done!' "\r");
  5360.                     $msg = [
  5361.                         'license' => $accountLicenseData[0]->getId()
  5362.                     ];
  5363.                     $this->get('cleanse_for_fatty_android_database_producer')->setContentType('application/json');
  5364.                     $this->get('cleanse_for_fatty_android_database_producer')->setDeliveryMode(2);
  5365.                     $this->get('cleanse_for_fatty_android_database_producer')->publish(json_encode($msg));
  5366.                     $this->createFileJson($path'Rabbit produces message sended!' "\r");
  5367.                     $data['rabbit_consumer'] = 'old_sound_rabbit_mq.operate_fatty_android_database_task_consumer';
  5368.                     $data['rabbit_queue'] = 'operate_fatty_android_database';
  5369.                     sleep(3);
  5370.                     ForcedAsynchronousCommandsUtil::callTheBizarreGenericConsumerCommand($this->realContainer$datatrue);
  5371.                     $this->createFileJson($path'Rabbit async consumer request sended!' "\r");
  5372.                     $responseArr['status'] = WebService::CODE_SUCCESS;
  5373.                     $responseArr['msg'] = "Cleanse database proccess started for '<strong>$accountLicenseData[0]</strong>' license!";
  5374.                     $responseArr['bigbag'] = false;
  5375.                     $theUrlTrSt = new LicensorGenericTransformer($this->realContainer$responseArr);
  5376.                     $xxArray $theUrlTrSt->transform();
  5377.                     $jsonContent json_encode($xxArray);
  5378.                     return $this->respondWithItem($jsonContent$theUrlTrSt);
  5379.                 } else {
  5380.                     return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  5381.                                     ->respondWithError('Invalid nickname.'WebService::CODE_COULD_NOT_AUTHENTICATE);
  5382.                 }
  5383.             } else {
  5384.                 return $this->errorWrongArgs('Wrong Content!'WebService::CODE_WRONG_ARGUMENTS);
  5385.             }
  5386.         } else {
  5387.             return $this->errorNotAllowedMethod('Method not allowed. Use ' WebService::REQUEST_METHOD_POST " method");
  5388.         }
  5389.     }
  5390.     /**
  5391.      * WS para registrar la pushy key de un dispositivo de una licencia
  5392.      * @author Aealan Z <lrobledo@kijho.com> 05/11/15
  5393.      * @param \Symfony\Component\HttpFoundation\Request $request datos
  5394.      * de la solicitud
  5395.      * @return Response Json con la informacion de respuesta
  5396.      */
  5397.     public function experimentalAuthWS(Request $request) {
  5398.         if ($request->getMethod() === WebService::REQUEST_METHOD_POST) {
  5399.             if (=== strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_STRUCTURE) || === strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_TEXT)) {
  5400.                 $path Util::getValidActiveLogByBaseName($this->realContainer'experimentalAuthWS''experimentalAuthWS0.txt');
  5401.                 $this->createFileJson($path"\r" 'Experimental ecurity WS: ' $request->getContent() . "\r");
  5402.                 $arrayEncryptResult Util::decryptDataForAndroid($this->realContainer$request->getContent());
  5403.                 $data json_decode($arrayEncryptResult['data'], true);
  5404.                 if (!isset($data['nickname']) || !isset($data['uid']) || !isset($data['authCode'])) {
  5405.                     return $this->errorWrongArgs('Wrong Arguments.'WebService::CODE_WRONG_ARGUMENTS);
  5406.                 }
  5407.                 $this->createFileJson($path'Decrypted: ' $arrayEncryptResult['data'] . "\r");
  5408.                 if ($data['nickname'] == '' || $data['uid'] == '' || $data['authCode'] == '') {
  5409.                     return $this->errorWrongArgs('Empty Arguments.'WebService::CODE_WRONG_ARGUMENTS);
  5410.                 }
  5411.                 $licenseUserName = ['alLicenseUsername' => $data['nickname']];
  5412.                 $em $this->getDoctrine()->getManager();
  5413.                 $accountLicenseData $em->getRepository('App\Entity\AccountLicense')->findBy($licenseUserName);
  5414.                 $countResult count($accountLicenseData);
  5415.                 if ($countResult 0) {
  5416.                     if ($accountLicenseData[0]->getAlAccountLicense()->getDeleted()) {
  5417.                         return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  5418.                                         ->respondWithError('Account is inactive'WebService::CODE_ACCOUNT_SUSPENDED);
  5419.                     }
  5420.                     if ($accountLicenseData[0]->getAlLicenseStatus() != AccountLicense::LICENSE_STATUS_ACTIVE) {
  5421.                         return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  5422.                                         ->respondWithError('License is inactive'WebService::CODE_ACCOUNT_SUSPENDED);
  5423.                     }
  5424. //                    if (isset($data['authCode'])) {
  5425. //                        $google2fa = new Google2FA();
  5426. //                        $secret = $accountLicenseData[0]->getAuthSeed();
  5427. //                        $wasValid = $google2fa->verifyKey($secret, $data['authCode'], 10);
  5428. //
  5429. //                        if (!$wasValid) {
  5430. //                            return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  5431. //                                            ->respondWithError('Invalid authorization', WebService::CODE_INVALID_SECURITY_HASH);
  5432. //                        } else {
  5433. //                            $responseArr['msg'] = 'Code verified and pass!';
  5434. //                            $this->createFileJson($path, 'Experimental ecurity WS: Good code ;) ' . "\r");
  5435. //                        }
  5436. //                    } else {
  5437. //                        $responseArr['msg'] = 'Code without code verification...';
  5438. //                    }
  5439.                     $authResult $this->validateAuth($accountLicenseData[0], $data);
  5440.                     if (is_string($authResult)) {
  5441.                         return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  5442.                                         ->respondWithError($authResultWebService::CODE_INVALID_SECURITY_HASH);
  5443.                     }
  5444.                     $responseArr['status'] = WebService::CODE_SUCCESS;
  5445.                     $responseArr['msg'] = 'Code verified and pass!';
  5446.                     $responseArr['bigbag'] = false;
  5447.                     $theUrlTrSt = new LicensorGenericTransformer($this->realContainer$responseArr);
  5448.                     $xxArray $theUrlTrSt->transform();
  5449.                     $jsonContent json_encode($xxArray);
  5450.                     return $this->respondWithItem($jsonContent$theUrlTrSt);
  5451.                 } else {
  5452.                     return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  5453.                                     ->respondWithError('Invalid nickname'WebService::CODE_COULD_NOT_AUTHENTICATE);
  5454.                 }
  5455.             } else {
  5456.                 return $this->errorWrongArgs('Wrong content'WebService::CODE_WRONG_ARGUMENTS);
  5457.             }
  5458.         } else {
  5459.             return $this->errorNotAllowedMethod('Method not allowed. Use ' WebService::REQUEST_METHOD_POST " method");
  5460.         }
  5461.     }
  5462.     /**
  5463.      * Esta funcion permite al cliente adroid notificar que termino de
  5464.      * subir el archivo de sincronizacion
  5465.      * @author Aealan Z <lrobledo@kijho.com> 30/04/15
  5466.      * @param \Symfony\Component\HttpFoundation\Request $request datos de la solicitud
  5467.      * @return Response Json con la informacion de respuesta
  5468.      */
  5469.     public function uploadSyncServiceUrlAlternate(Request $request) {
  5470.         if ($request->getMethod() === WebService::REQUEST_METHOD_POST) {
  5471.             $arrayRequestEncripted = [];
  5472.             $arrayRequestEncripted['nickname'] = $request->request->get('nickname');
  5473.             $arrayRequestEncripted['uid'] = $request->request->get('uid');
  5474.             $path Util::getValidActiveLogByBaseName($this->realContainer'syncDownUpWSTest''syncDownUpWSTest0.txt');
  5475.             $this->createFileJson($path"\r" 'The request ' json_encode($arrayRequestEncripted) . "\r");
  5476.             $parameters $request->request->all();
  5477. //            $this->createFileJson($path, 'All parameters in request -> ' . json_encode($parameters) . "\r");
  5478.             $text 'Hola Changoo!!';
  5479.             $file fopen($path"a+");
  5480.             fwrite($file$text);
  5481.             fclose($file);
  5482.             dump($path);
  5483.             dump($text);
  5484.             die;
  5485.             $data = [];
  5486.             $arrayEncryptResult Util::decryptDataForUploadsFiles($this->realContainer$request->request->get('nickname'));
  5487.             $data['nickname'] = $arrayEncryptResult['data'];
  5488.             $arrayEncryptResult Util::decryptDataForUploadsFiles($this->realContainer$request->request->get('uid'));
  5489.             $data['uid'] = $arrayEncryptResult['data'];
  5490.             $this->createFileJson($path'Decripted ' json_encode($data) . "\r");
  5491.             $theTrueNameFile $request->files->get('file')->getClientOriginalName();
  5492.             $this->createFileJson($path'The Client IP -> ' $request->getClientIp() . "\r");
  5493.             $this->createFileJson($path'The File -> ' $theTrueNameFile "\r");
  5494.             $licenseUserName = ['alLicenseUsername' => $data['nickname']];
  5495.             $em $this->getDoctrine()->getManager();
  5496.             $accountLicenseData $em->getRepository('App\Entity\AccountLicense')->findByAlLicenseUsername($licenseUserName);
  5497.             $forcedValidationPassed false;
  5498.             if (empty($accountLicenseData) && (null == $data['nickname'] ||
  5499.                     empty($data['nickname']) || $data['nickname'] == 'null') &&
  5500.                     (int) $this->realContainer->getParameter('device_recognition_by_ip_enabled') &&
  5501.                     !empty($theTrueNameFile) && $theTrueNameFile != '') {
  5502.                 $this->createFileJson($path'Forcing server android autentication... ' "\r");
  5503.                 $accountLicenseData $em->getRepository('App\Entity\AccountLicense')->findBy(['androidIP' => $request->getClientIp()]);
  5504.                 if (empty($accountLicenseData) || (int) $accountLicenseData[0]->getTimesCheckedIP() < (int) $this->realContainer->getParameter('ip_recognition_times_to_valid_check')) {
  5505.                     $accountLicenseData = [];
  5506.                 } else {
  5507.                     $forcedValidationPassed true;
  5508.                     $this->createFileJson($path'Forced autentication succeeded! ' "\r");
  5509.                 }
  5510.             }
  5511.             $countResult count($accountLicenseData);
  5512.             $statusArryMsg['status'] = WebService::CODE_OK_ACCEPTED;
  5513.             $this->createFileJson($path'Number of license found -> ' $countResult "\r");
  5514.             if ($countResult 0) {
  5515.                 if ($accountLicenseData[0]->getAlAccountLicense()->getDeleted()) {
  5516.                     $this->createFileJson($path'Salio 1! ' "\r");
  5517.                     return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  5518.                                     ->respondWithError('Account is inactive'WebService::CODE_ACCOUNT_SUSPENDED);
  5519.                 }
  5520.                 if (!$forcedValidationPassed && $accountLicenseData[0]->getDeviceUid() != $data['uid']) {
  5521.                     $this->createFileJson($path'Salio 2! ' "\r");
  5522.                     return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  5523.                                     ->respondWithError('Unknown device'WebService::CODE_ACCOUNT_SUSPENDED);
  5524.                 }
  5525.                 if ($accountLicenseData[0]->getAlLicenseStatus() == AccountLicense::LICENSE_STATUS_ACTIVE) {
  5526.                     $this->createFileJson($path'License active! ' "\r");
  5527. //                    $masterBlockingByDBUpdate = $em->getRepository('App\Entity\MasterSync')->findBy(['msLicense' => $accountLicenseData[0]->getId(), 'msType' => MasterSync::MASTER_SYNC_TYPE_DB_UPDATE, 'msStatus' => MasterSync::MASTER_STATUS_INITIALIZATED]);
  5528. //
  5529. //                    if (!empty($masterBlockingByDBUpdate)) {
  5530. //                        $this->createFileJson($path, 'Se Fue DB blocked!' . "\r");
  5531. //                        return $this->setStatusCode(WebService::CODE_OBJECT_NOT_FOUND)
  5532. //                                        ->respondWithError('Synchronization blocked by DB update, please wait...', WebService::NOTHING_TO_WEB_SYNCHRONIZE);
  5533. //                    }
  5534.                     $readFilesDataEntity $em->getRepository('App\Entity\ReadFilesData')->findBy(['rfStatus' => ReadFilesData::STATUS_UPLOADED'rfLicenseId' => $accountLicenseData[0]->getId(), 'hasPersistentError' => false]);
  5535.                     if (!empty($readFilesDataEntity)) {
  5536.                         $this->createFileJson($path'There is another sync petition in process, please wait until is finished' "\r");
  5537.                         $statusArryMsg['msg'] = 'There is another sync petition in process, please wait until is finished';
  5538.                         $theUrlTrSt = new UploadSyncJsonNotifyTransformer($this->realContainer$statusArryMsg);
  5539.                         $jsonTransform $theUrlTrSt->transform();
  5540.                         $jsonContent json_encode($jsonTransform);
  5541.                         return $this->respondWithItem($jsonContent$theUrlTrSt);
  5542.                     }
  5543.                     $readFilesDataEntity $em->getRepository('App\Entity\ReadFilesData')->findBy(['rfStatus' => ReadFilesData::STATUS_UPLOADED'rfLicenseId' => $accountLicenseData[0]->getId(), 'hasPersistentError' => true]);
  5544.                     if (!empty($readFilesDataEntity)) {
  5545.                         $this->createFileJson($path'There is another sync petition for this license with a problem in the sever, please contact your system supplier for more information' "\r");
  5546.                         $statusArryMsg['msg'] = 'There is another sync petition for this license with a problem in the sever, please contact your system supplier for more information';
  5547.                         $theUrlTrSt = new UploadSyncJsonNotifyTransformer($this->realContainer$statusArryMsg);
  5548.                         $jsonTransform $theUrlTrSt->transform();
  5549.                         $jsonContent json_encode($jsonTransform);
  5550.                         return $this->respondWithItem($jsonContent$theUrlTrSt);
  5551.                     }
  5552.                     $isDirectoryReady Util::createLicenseDirectory($this->realContainer$accountLicenseData[0], $accountLicenseData[0]->getAlLicenseUsername());
  5553.                     $theAccountLicenseDirector $isDirectoryReady['directory'];
  5554.                     if (!isset($isDirectoryReady['result']) || $isDirectoryReady['result'] == '__KO__') {
  5555.                         $msnError 'An error occurred while creating your directory in server ';
  5556.                         return $this->setStatusCode(WebService::CODE_INTERNAL_ERROR)
  5557.                                         ->respondWithError($msnErrorWebService::CODE_INTERNAL_ERROR);
  5558.                     }
  5559.                     $this->createFileJson($path'The license dir ' $theAccountLicenseDirector "\r");
  5560.                     $uploadFileResponse Utilx::uploadFileTo($request$theAccountLicenseDirector$path);
  5561.                     dump($uploadFileResponse);
  5562.                     die;
  5563.                     ///////////////////
  5564.                     ///////////////////
  5565.                     if (!isset($uploadFileResponse['result']) || !isset($uploadFileResponse['msg'])) {
  5566.                         $this->createFileJson($path'Unknown error uploading file ' "\r");
  5567.                         return $this->setStatusCode(WebService::HTTP_CODE_INTERNAL_ERROR)
  5568.                                         ->respondWithError('Unknown error uploading file'WebService::CODE_INTERNAL_ERROR);
  5569.                     }
  5570.                     if (isset($uploadFileResponse['result']) && isset($uploadFileResponse['msg']) && $uploadFileResponse['result'] == '__KO__') {
  5571.                         $this->createFileJson($path$uploadFileResponse['msg'] . "\r");
  5572.                         return $this->setStatusCode(WebService::HTTP_CODE_INTERNAL_ERROR)
  5573.                                         ->respondWithError($uploadFileResponse['msg'], WebService::CODE_INTERNAL_ERROR);
  5574.                     }
  5575.                     $readFilesDataEntityByLicense $em->getRepository('App\Entity\ReadFilesData')->findBy(['rfLicenseId' => $accountLicenseData[0]->getId(), 'rfStatus' => ReadFilesData::STATUS_STANDBY], ['rfDateSincAsk' => 'DESC']);
  5576.                     $this->createFileJson($path'The ReadFilesData count 1 -> ' count($readFilesDataEntityByLicense) . "\r");
  5577.                     if (empty($readFilesDataEntityByLicense)) {
  5578.                         $readFilesDataEntityByLicense[0] = $this->setRegistNewFile($accountLicenseData[0]);
  5579.                     }
  5580.                     $registerStatus $this->updateRegistUploadFile($readFilesDataEntityByLicense[0], $uploadFileResponse['fileName']);
  5581.                     if ($registerStatus) {
  5582.                         $statusArryMsg['msg'] = 'File has been uploaded and the record updated';
  5583.                         $this->createFileJson($path'File has been uploaded and the record updated' "\r");
  5584.                     } else {
  5585.                         $this->createFileJson($path'Salio 9! ' "\r");
  5586.                         return $this->setStatusCode(WebService::HTTP_CODE_NOT_FOUND)
  5587.                                         ->respondWithError('Error updating syncronization control record'WebService::CODE_OBJECT_NOT_FOUND);
  5588.                     }
  5589.                     $licenseDataBaseEntity $em->getRepository('App\Entity\LicenseDataBase')->findBy(['license' => $accountLicenseData[0]->getId()]);
  5590.                     if (!empty($licenseDataBaseEntity)) {
  5591.                         $pushSendRepository $em->getRepository('App\Entity\PushSent');
  5592.                         $pushSendRepository->respondOldPushesForLicense(PushSent::PUSH_TYPE_SYNC_DOWNUP$accountLicenseData[0]->getId());
  5593.                         $usernameByNickname $licenseDataBaseEntity[0]->getLicense();
  5594.                         $theAccountPath $this->realContainer->getParameter('level_directory_data_android') . $usernameByNickname->getAlAccountLicense()->getAcName() . '/' $usernameByNickname->getAlLicenseUsername();
  5595.                         $theAccountPath str_replace(' ''_'$theAccountPath);
  5596.                         $dataOptionsRoot = [
  5597.                             'dbname' => $licenseDataBaseEntity[0]->getDbname(),
  5598.                             'user' => $licenseDataBaseEntity[0]->getDbuser(),
  5599.                             'password' => $licenseDataBaseEntity[0]->getDbpass(),
  5600.                             'host' => $licenseDataBaseEntity[0]->getDbhost(),
  5601.                             'driver' => 'pdo_mysql',
  5602.                         ];
  5603.                         $msg = [
  5604.                             'id' => $readFilesDataEntityByLicense[0]->getId(),
  5605.                             'dataOptionsRoot' => $dataOptionsRoot,
  5606.                             'path' => $theAccountPath,
  5607.                             'fileName' => $readFilesDataEntityByLicense[0]->getRfNameFile(),
  5608.                             'AccountLicense' => $usernameByNickname->getAlAccountLicense()->getAcName(),
  5609.                             'pushchanel' => $usernameByNickname->getAlLicenseUsername()
  5610.                         ];
  5611.                         $readFilesDataEntityByLicense[0]->setIsReadedByServer(true);
  5612.                         $em->persist($readFilesDataEntityByLicense[0]);
  5613.                         $em->flush();
  5614. //                        $this->get('incoming_android_sync_producer')->setContentType('application/json');
  5615. //                        $this->get('incoming_android_sync_producer')->setDeliveryMode(2);
  5616. //                        $this->get('incoming_android_sync_producer')->publish(json_encode($msg));
  5617.                         if (!$request->request->get('hold')) {
  5618.                             $statusArryMsg['msg'] = 'File has been uploaded and the sync process triggered';
  5619.                             $this->createFileJson($path'File has been uploaded and the sync process triggered' "\r");
  5620.                             $data['readFilesDataId'] = $readFilesDataEntityByLicense[0]->getId();
  5621. //                            ForcedAsynchronousCommandsUtil::consumeDownUpSyncCommand($this->realContainer, $data, true);
  5622.                         } else {
  5623.                             $statusArryMsg['msg'] = 'File has been uploaded and the sync process is ready to start';
  5624.                             $this->createFileJson($path'File has been uploaded and the sync process is ready to start' "\r");
  5625.                         }
  5626.                     }
  5627.                     $this->createFileJson($path'Track 7! ' "\r");
  5628.                     $theUrlTrSt = new UploadSyncJsonNotifyTransformer($this->realContainer$statusArryMsg);
  5629.                     $jsonTransform $theUrlTrSt->transform();
  5630.                     $jsonContent json_encode($jsonTransform);
  5631.                     $this->createFileJson($path'Track 8! ' "\r");
  5632.                     $this->createFileJson($path'UploadSyncJsonNotifyTransformer json to respond' $jsonContent "\r");
  5633.                     return $this->respondWithItem($jsonContent$theUrlTrSt);
  5634.                 } else {
  5635.                     $this->createFileJson($path'Salio 3! ' "\r");
  5636.                     return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  5637.                                     ->respondWithError('Inactive License'WebService::CODE_ACCOUNT_SUSPENDED);
  5638.                 }
  5639.             } else {
  5640.                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  5641.                                 ->respondWithError('Invalid nickname'WebService::CODE_COULD_NOT_AUTHENTICATE);
  5642.             }
  5643.         } else {
  5644.             return $this->errorNotAllowedMethod('Method not allowed. Use ' WebService::REQUEST_METHOD_POST " method");
  5645.         }
  5646.     }
  5647.     public function licensorLicenseLastSync(Request $request){
  5648.         if ($request->getMethod() != WebService::REQUEST_METHOD_GET) {
  5649.             return $this->errorNotAllowedMethod('Method not allowed. Use ' WebService::REQUEST_METHOD_GET " method");
  5650.         }
  5651.         $response=$request->query->get("nicknamelicense");
  5652.         if ($response == '') {
  5653.             return $this->errorWrongArgs('Empty Arguments.'WebService::CODE_WRONG_ARGUMENTS);
  5654.         }
  5655.         $em $this->getDoctrine()->getManager();
  5656.         $lastSync $em->getRepository('App\Entity\MasterSync')->lastSyncForLicenseNickName($response);
  5657.         if (!empty($lastSync)){
  5658.             $date=$lastSync[0]["msDateSyncAsk"];
  5659.             $stringDate $date->format('Y-m-d H:i:s');
  5660.             $lastSync[0]["msDateSyncAsk"]=$stringDate;
  5661.             $lastSync $lastSync[0];
  5662.         }
  5663.         
  5664.         $responseArr['status'] = WebService::CODE_SUCCESS;
  5665.         $responseArr['msg'] = $lastSync;
  5666.         $responseArr['bigbag'] = true;
  5667.         $theUrlTrSt = new LicensorGenericTransformer($this->realContainer$responseArr);
  5668.         $xxArray $theUrlTrSt->transform();
  5669.         $jsonContent json_encode($xxArray);
  5670.         return $this->respondWithItem($jsonContent$theUrlTrSt);
  5671.         } 
  5672.     /**
  5673.      * WS para registrar la pushy key de un dispositivo de una licencia
  5674.      * @author Aealan Z <lrobledo@kijho.com> 05/11/15
  5675.      * @param \Symfony\Component\HttpFoundation\Request $request datos
  5676.      * de la solicitud
  5677.      * @return Response Json con la informacion de respuesta
  5678.      */
  5679.     public function getSQLLiteQueryToCleanBadAndroidSyncDataRecords(Request $request) {
  5680.         if ($request->getMethod() === WebService::REQUEST_METHOD_POST) {
  5681.             if (=== strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_STRUCTURE) || === strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_TEXT)) {
  5682.                 $path Util::getValidActiveLogByBaseName($this->realContainer'getSQLLiteQueryToCleanBadAndroidSyncDataRecords''getSQLLiteQueryToCleanBadAndroidSyncDataRecords0.txt');
  5683.                 $this->createFileJson($path"\r" 'Incoming parameters: ' $request->getContent() . "\r");
  5684.                 $arrayEncryptResult Util::decryptDataForAndroid($this->realContainer$request->getContent());
  5685.                 $data json_decode($arrayEncryptResult['data'], true);
  5686.                 if (!isset($data['nickname']) || !isset($data['data'])) {
  5687.                     return $this->errorWrongArgs('Wrong Arguments.'WebService::CODE_WRONG_ARGUMENTS);
  5688.                 }
  5689.                 $this->createFileJson($path'Decrypted: ' $arrayEncryptResult['data'] . "\r");
  5690.                 if ($data['nickname'] == '' || $data['data'] == '') {
  5691.                     return $this->errorWrongArgs('Empty Arguments.'WebService::CODE_WRONG_ARGUMENTS);
  5692.                 }
  5693.                 $licenseUserName = ['alLicenseUsername' => $data['nickname']];
  5694.                 $em $this->getDoctrine()->getManager();
  5695.                 $accountLicenseData $em->getRepository('App\Entity\AccountLicense')->findBy($licenseUserName);
  5696.                 $countResult count($accountLicenseData);
  5697.                 if ($countResult 0) {
  5698.                     $basicJsonResponseToProcess $data['data'];
  5699.                     $auxJsonDecodeArray json_decode($basicJsonResponseToProcesstrue);
  5700.                     $auxSQLString "SELECT +'+ || syn_id || +'+ || +,+ FROM sync_data WHERE syn_record_id IN (";
  5701.                     foreach ($auxJsonDecodeArray['data'] as $tableIndex) {
  5702.                         foreach ($tableIndex as $tableData) {
  5703.                             if ($tableData) {
  5704.                                 $auxSQLString .= "'$tableData',";
  5705.                             } 
  5706.                         }
  5707.                     }
  5708.                     $auxSQLString .= ");";
  5709.                     $auxSQLString str_replace(",)",")"$auxSQLString);
  5710.                     $auxSQLString str_replace("+",'"'$auxSQLString);
  5711.                     $responseArr['status'] = WebService::CODE_SUCCESS;
  5712.                     $responseArr['msg'] = 'SQLLite Query Obtained!';
  5713.                     $responseArr['sqlliteQuery'] = $auxSQLString;
  5714.                     $responseArr['bigbag'] = true;
  5715.                     $theUrlTrSt = new LicensorGenericTransformer($this->realContainer$responseArr);
  5716.                     $xxArray $theUrlTrSt->transform();
  5717.                     $jsonContent json_encode($xxArray);
  5718.                     return $this->respondWithItem($jsonContent$theUrlTrSt);
  5719.                 } else {
  5720.                     return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  5721.                                     ->respondWithError('Invalid channel'WebService::CODE_COULD_NOT_AUTHENTICATE);
  5722.                 }
  5723.             } else {
  5724.                 return $this->errorWrongArgs('Wrong Content!'WebService::CODE_WRONG_ARGUMENTS);
  5725.             }
  5726.         } else {
  5727.             return $this->errorNotAllowedMethod('Method not allowed. Use ' WebService::REQUEST_METHOD_POST " method");
  5728.         }
  5729.     }
  5730.     /**
  5731.      * WS para registrar la pushy key de un dispositivo de una licencia
  5732.      * @author Aealan Z <lrobledo@kijho.com> 05/11/15
  5733.      * @param \Symfony\Component\HttpFoundation\Request $request datos
  5734.      * de la solicitud
  5735.      * @return Response Json con la informacion de respuesta
  5736.      */
  5737.     public function setBadSyncDataRecordsInRegistActionForCleanse(Request $request) {
  5738.         if ($request->getMethod() === WebService::REQUEST_METHOD_POST) {
  5739.             if (=== strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_STRUCTURE) || === strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_TEXT)) {
  5740.                 $path Util::getValidActiveLogByBaseName($this->realContainer'setBadSyncDataRecordsInRegistActionForCleanse''setBadSyncDataRecordsInRegistActionForCleanse0.txt');
  5741.                 $this->createFileJson($path"\r" 'Incoming parameters: ' $request->getContent() . "\r");
  5742.                 $arrayEncryptResult Util::decryptDataForAndroid($this->realContainer$request->getContent());
  5743.                 $data json_decode($arrayEncryptResult['data'], true);
  5744.                 if (!isset($data['nickname']) || !isset($data['data'])) {
  5745.                     return $this->errorWrongArgs('Wrong Arguments.'WebService::CODE_WRONG_ARGUMENTS);
  5746.                 }
  5747.                 $this->createFileJson($path'Decrypted: ' $arrayEncryptResult['data'] . "\r");
  5748.                 if ($data['nickname'] == '' || $data['data'] == '') {
  5749.                     return $this->errorWrongArgs('Empty Arguments.'WebService::CODE_WRONG_ARGUMENTS);
  5750.                 }
  5751.                 $licenseUserName = ['alLicenseUsername' => $data['nickname']];
  5752.                 $em $this->getDoctrine()->getManager();
  5753.                 $accountLicenseData $em->getRepository('App\Entity\AccountLicense')->findBy($licenseUserName);
  5754.                 $countResult count($accountLicenseData);
  5755.                 if ($countResult 0) {
  5756.                     $auxStringAndroidSyncDataIds $data['data'];
  5757.                     $auxArrayToRegistActionRecord explode(','$auxStringAndroidSyncDataIds);
  5758.                     $emLev Util::emLicenseConnection($this->realContainer$em$accountLicenseData[0]);
  5759.                     $insertCounter 0;
  5760.                     foreach ($auxArrayToRegistActionRecord as $recordToRegistAction) {
  5761.                         if ($recordToRegistAction != '') {
  5762.                             Util::saveUpdateRecordInRegistActionsByDataArray($emLev'sync_data', ['level' => $recordToRegistAction'android' => $recordToRegistAction], 'D');
  5763.                             ++$insertCounter;
  5764.                         }
  5765.                     }
  5766.                     $responseArr['status'] = WebService::CODE_SUCCESS;
  5767.                     $responseArr['msg'] = "$insertCounter records where inserted into regist action! ready to sync?";
  5768.                     $responseArr['bigbag'] = false;
  5769.                     $theUrlTrSt = new LicensorGenericTransformer($this->realContainer$responseArr);
  5770.                     $xxArray $theUrlTrSt->transform();
  5771.                     $jsonContent json_encode($xxArray);
  5772.                     return $this->respondWithItem($jsonContent$theUrlTrSt);
  5773.                 } else {
  5774.                     return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  5775.                                     ->respondWithError('Invalid channel'WebService::CODE_COULD_NOT_AUTHENTICATE);
  5776.                 }
  5777.             } else {
  5778.                 return $this->errorWrongArgs('Wrong Content!'WebService::CODE_WRONG_ARGUMENTS);
  5779.             }
  5780.         } else {
  5781.             return $this->errorNotAllowedMethod('Method not allowed. Use ' WebService::REQUEST_METHOD_POST " method");
  5782.         }
  5783.     }
  5784.     /**
  5785.      * Crea la semilla de notificación para el contexto CONTEXT_NOTIFICATION_ANDROID_LAST_SYNC.
  5786.      * 
  5787.      * Recibe la entidad de AccountLicense, invoca a la función  getDateOfLastSync la cual trae la fecha de la ultima sincronización,
  5788.      * luego se valida si la fecha retornada sea menor a la fecha actual menos una constate de días, si esto se cumple se procede a
  5789.      * crear o actualizar  la semilla, si este ultimo caso lleva mas de una semana de ser notificada.
  5790.      * 
  5791.      * @author Jhonan Vargas <jsmith@openmytab.com> 19/01/2022
  5792.      * @access private
  5793.      * @param type AccountLicense $license
  5794.     */
  5795.     public function notifyLastSyncByLicense($em$license){
  5796.         
  5797.         $dateLastSync $em->getRepository('App\Entity\MasterSync')->getDateOfLastSync($license->getId());
  5798.         
  5799.         if($dateLastSync){
  5800.             $currentDate Utilx::getCurrentDate();
  5801.             $days $this->realContainer->getParameter('max_days_without_android_sync');
  5802.             $dateMinusDays = clone $currentDate;
  5803.             $dateMinusDays->modify("-$days days");    
  5804.             if($dateMinusDays >= $dateLastSync){
  5805.                 $seed $em->getRepository("App\Entity\NotificationInLicensorBell")->findOneBy(["context" => NotificationInLicensorBell::CONTEXT_NOTIFICATION_ANDROID_LAST_SYNC"license" => $license]);
  5806.                 $title 'Android device not synced in ' $license->getAlLicenseUsername() . ' license';
  5807.                 $message "The Android device has not been synced for $days days or more.";
  5808.                 if(!is_null($seed)){
  5809.                     $dateMinusOneWeek = clone $currentDate;
  5810.                     $dateMinusOneWeek->modify('-1 week');
  5811.                     
  5812.                     if($seed->getPickedtByValidatingCronDate()){
  5813.                         
  5814.                         if ($dateMinusOneWeek >= $seed->getPickedtByValidatingCronDate()) {
  5815.                             $seed->setDateCreated($currentDate);
  5816.                             $seed->setPickedtByValidatingCronDate(null);
  5817.                             $seed->setNotificationMsg($message);
  5818.                             
  5819.                             $em->persist($seed);
  5820.                             $em->flush();
  5821.                         }
  5822.                     }
  5823.                 } else {
  5824.                     $seed = new NotificationInLicensorBell();
  5825.                     $seed->setNotificationTitle($title);
  5826.                     $seed->setNotificationLabel(NotificationInLicensorBell::NOTIFICATION_TYPE_WARNING);
  5827.                     $seed->setNotificationMsg($message);
  5828.                     $seed->setDateCreated($currentDate);
  5829.                     $seed->setContext(NotificationInLicensorBell::CONTEXT_NOTIFICATION_ANDROID_LAST_SYNC);
  5830.                     $seed->setLicense($license);
  5831.                     $seed->setTypeRoleToNotify(NotificationInLicensorBell::ROLE_ADMINISTRATOR);
  5832.                     $seed->setNotificationAlt('Android has not synced');
  5833.                     $seed->setNotificationHTMLTitle($title);
  5834.                     $em->persist($seed);
  5835.                     $em->flush();
  5836.                 }
  5837.             }
  5838.         }
  5839.     }
  5840.     // public function 
  5841. }